2003-03-31 Havoc Pennington <hp@pobox.com>
[platform/upstream/dbus.git] / dbus / dbus-server.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-server.c DBusServer object
3  *
4  * Copyright (C) 2002, 2003 Red Hat Inc.
5  *
6  * Licensed under the Academic Free License version 1.2
7  * 
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  * 
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  */ 
23
24 #include "dbus-server.h"
25 #include "dbus-server-unix.h"
26 #ifdef DBUS_BUILD_TESTS
27 #include "dbus-server-debug.h"
28 #include "dbus-server-debug-pipe.h"
29 #endif
30 #include "dbus-address.h"
31
32 /**
33  * @defgroup DBusServer DBusServer
34  * @ingroup  DBus
35  * @brief Server that listens for new connections.
36  *
37  * Types and functions related to DBusServer.
38  * A DBusServer represents a server that other applications
39  * can connect to. Each connection from another application
40  * is represented by a DBusConnection.
41  *
42  * @todo Thread safety hasn't been looked at for #DBusServer
43  * @todo Need notification to apps of disconnection, may matter for some transports
44  */
45
46 /**
47  * @defgroup DBusServerInternals DBusServer implementation details
48  * @ingroup  DBusInternals
49  * @brief Implementation details of DBusServer
50  *
51  * @{
52  */
53
54 /**
55  * Initializes the members of the DBusServer base class.
56  * Chained up to by subclass constructors.
57  *
58  * @param server the server.
59  * @param vtable the vtable for the subclass.
60  * @param address the server's address
61  * @returns #TRUE on success.
62  */
63 dbus_bool_t
64 _dbus_server_init_base (DBusServer             *server,
65                         const DBusServerVTable *vtable,
66                         const DBusString       *address)
67 {
68   server->vtable = vtable;
69   server->refcount = 1;
70
71   server->address = NULL;
72   server->watches = NULL;
73   server->timeouts = NULL;
74   server->connection_counter = NULL;
75   
76   if (!_dbus_string_copy_data (address, &server->address))
77     goto failed;
78   
79   server->watches = _dbus_watch_list_new ();
80   if (server->watches == NULL)
81     goto failed;
82
83   server->timeouts = _dbus_timeout_list_new ();
84   if (server->timeouts == NULL)
85     goto failed;
86   
87   server->connection_counter = _dbus_counter_new ();
88   if (server->connection_counter == NULL)
89     goto failed;  
90
91   server->max_connections = 256; /* same as an X server, seems like a nice default */
92
93   _dbus_data_slot_list_init (&server->slot_list);
94
95   _dbus_verbose ("Initialized server on address %s\n", server->address);
96   
97   return TRUE;
98
99  failed:
100   if (server->watches)
101     {
102       _dbus_watch_list_free (server->watches);
103       server->watches = NULL;
104     }
105   if (server->timeouts)
106     {
107       _dbus_timeout_list_free (server->timeouts);
108       server->timeouts = NULL;
109     }
110   if (server->connection_counter)
111     {
112       _dbus_counter_unref (server->connection_counter);
113       server->connection_counter = NULL;
114     }
115   if (server->address)
116     {
117       dbus_free (server->address);
118       server->address = NULL;
119     }
120   
121   return FALSE;
122 }
123
124 /**
125  * Finalizes the members of the DBusServer base class.
126  * Chained up to by subclass finalizers.
127  *
128  * @param server the server.
129  */
130 void
131 _dbus_server_finalize_base (DBusServer *server)
132 {
133   /* calls out to application code... */
134   _dbus_data_slot_list_free (&server->slot_list);
135
136   dbus_server_set_new_connection_function (server, NULL, NULL, NULL);
137
138   if (!server->disconnected)
139     dbus_server_disconnect (server);
140
141   _dbus_watch_list_free (server->watches);
142   _dbus_timeout_list_free (server->timeouts);
143   _dbus_counter_unref (server->connection_counter);
144
145   dbus_free (server->address);
146 }
147
148 /**
149  * Adds a watch for this server, chaining out to application-provided
150  * watch handlers.
151  *
152  * @param server the server.
153  * @param watch the watch to add.
154  */
155 dbus_bool_t
156 _dbus_server_add_watch (DBusServer *server,
157                         DBusWatch  *watch)
158 {
159   return _dbus_watch_list_add_watch (server->watches, watch);
160 }
161
162 /**
163  * Removes a watch previously added with _dbus_server_remove_watch().
164  *
165  * @param server the server.
166  * @param watch the watch to remove.
167  */
168 void
169 _dbus_server_remove_watch  (DBusServer *server,
170                             DBusWatch  *watch)
171 {
172   _dbus_watch_list_remove_watch (server->watches, watch);
173 }
174
175 /**
176  * Toggles a watch and notifies app via server's
177  * DBusWatchToggledFunction if available. It's an error to call this
178  * function on a watch that was not previously added.
179  *
180  * @param server the server.
181  * @param watch the watch to toggle.
182  * @param enabled whether to enable or disable
183  */
184 void
185 _dbus_server_toggle_watch (DBusServer  *server,
186                            DBusWatch   *watch,
187                            dbus_bool_t  enabled)
188 {
189   if (server->watches) /* null during finalize */
190     _dbus_watch_list_toggle_watch (server->watches,
191                                    watch, enabled);
192 }
193
194 /**
195  * Adds a timeout for this server, chaining out to
196  * application-provided timeout handlers. The timeout should be
197  * repeatedly handled with dbus_timeout_handle() at its given interval
198  * until it is removed.
199  *
200  * @param server the server.
201  * @param timeout the timeout to add.
202  */
203 dbus_bool_t
204 _dbus_server_add_timeout (DBusServer  *server,
205                           DBusTimeout *timeout)
206 {
207   return _dbus_timeout_list_add_timeout (server->timeouts, timeout);
208 }
209
210 /**
211  * Removes a timeout previously added with _dbus_server_add_timeout().
212  *
213  * @param server the server.
214  * @param timeout the timeout to remove.
215  */
216 void
217 _dbus_server_remove_timeout (DBusServer  *server,
218                              DBusTimeout *timeout)
219 {
220   _dbus_timeout_list_remove_timeout (server->timeouts, timeout);  
221 }
222
223 /**
224  * Toggles a timeout and notifies app via server's
225  * DBusTimeoutToggledFunction if available. It's an error to call this
226  * function on a timeout that was not previously added.
227  *
228  * @param server the server.
229  * @param timeout the timeout to toggle.
230  * @param enabled whether to enable or disable
231  */
232 void
233 _dbus_server_toggle_timeout (DBusServer  *server,
234                              DBusTimeout *timeout,
235                              dbus_bool_t  enabled)
236 {
237   if (server->timeouts) /* null during finalize */
238     _dbus_timeout_list_toggle_timeout (server->timeouts,
239                                        timeout, enabled);
240 }
241
242
243 /** @} */
244
245 /**
246  * @addtogroup DBusServer
247  *
248  * @{
249  */
250
251
252 /**
253  * @typedef DBusServer
254  *
255  * An opaque object representing a server that listens for
256  * connections from other applications. Each time a connection
257  * is made, a new DBusConnection is created and made available
258  * via an application-provided DBusNewConnectionFunction.
259  * The DBusNewConnectionFunction is provided with
260  * dbus_server_set_new_connection_function().
261  * 
262  */
263
264 /**
265  * Listens for new connections on the given address.
266  * Returns #NULL if listening fails for any reason.
267  * Otherwise returns a new #DBusServer.
268  * dbus_server_set_new_connection_function() and
269  * dbus_server_set_watch_functions() should be called
270  * immediately to render the server fully functional.
271  *
272  * @todo error messages on bad address could really be better.
273  * DBusResultCode is a bit limiting here.
274  *
275  * @param address the address of this server.
276  * @param error location to store rationale for failure.
277  * @returns a new DBusServer, or #NULL on failure.
278  * 
279  */
280 DBusServer*
281 dbus_server_listen (const char     *address,
282                     DBusError      *error)
283 {
284   DBusServer *server;
285   DBusAddressEntry **entries;
286   int len, i;
287   const char *address_problem_type;
288   const char *address_problem_field;
289   const char *address_problem_other;
290
291   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
292   
293   if (!dbus_parse_address (address, &entries, &len, error))
294     return NULL;
295
296   server = NULL;
297   address_problem_type = NULL;
298   address_problem_field = NULL;
299   address_problem_other = NULL;
300   
301   for (i = 0; i < len; i++)
302     {
303       const char *method = dbus_address_entry_get_method (entries[i]);
304
305       if (strcmp (method, "unix") == 0)
306         {
307           const char *path = dbus_address_entry_get_value (entries[i], "path");
308
309           if (path == NULL)
310             {
311               address_problem_type = "unix";
312               address_problem_field = "path";
313               goto bad_address;
314             }
315
316           server = _dbus_server_new_for_domain_socket (path, error);
317
318           if (server)
319             break;
320         }
321       else if (strcmp (method, "tcp") == 0)
322         {
323           const char *host = dbus_address_entry_get_value (entries[i], "host");
324           const char *port = dbus_address_entry_get_value (entries[i], "port");
325           DBusString  str;
326           long lport;
327           dbus_bool_t sresult;
328           
329           if (port == NULL)
330             {
331               address_problem_type = "tcp";
332               address_problem_field = "port";
333               goto bad_address;
334             }
335
336           _dbus_string_init_const (&str, port);
337           sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
338           _dbus_string_free (&str);
339           
340           if (sresult == FALSE || lport <= 0 || lport > 65535)
341             {
342               address_problem_other = "Port is not an integer between 0 and 65535";
343               goto bad_address;
344             }
345           
346           server = _dbus_server_new_for_tcp_socket (host, lport, error);
347
348           if (server)
349             break;
350         }
351 #ifdef DBUS_BUILD_TESTS
352       else if (strcmp (method, "debug") == 0)
353         {
354           const char *name = dbus_address_entry_get_value (entries[i], "name");
355
356           if (name == NULL)
357             {
358               address_problem_type = "debug";
359               address_problem_field = "name";
360               goto bad_address;
361             }
362
363           server = _dbus_server_debug_new (name, error);
364
365           if (server)
366             break;
367         }
368       else if (strcmp (method, "debug-pipe") == 0)
369         {
370           const char *name = dbus_address_entry_get_value (entries[i], "name");
371
372           if (name == NULL)
373             {
374               address_problem_type = "debug-pipe";
375               address_problem_field = "name";
376               goto bad_address;
377             }
378
379           server = _dbus_server_debug_pipe_new (name, error);
380
381           if (server)
382             break;
383         }
384 #endif
385       else
386         {
387           address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
388           goto bad_address;
389         }
390     }
391   
392   dbus_address_entries_free (entries);
393   return server;
394
395  bad_address:
396   dbus_address_entries_free (entries);
397   if (address_problem_type != NULL)
398     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
399                     "Server address of type %s was missing argument %s",
400                     address_problem_type, address_problem_field);
401   else
402     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
403                     "Could not parse server address: %s",
404                     address_problem_other);
405
406   return NULL;
407 }
408
409 /**
410  * Increments the reference count of a DBusServer.
411  *
412  * @param server the server.
413  */
414 void
415 dbus_server_ref (DBusServer *server)
416 {
417   server->refcount += 1;
418 }
419
420 /**
421  * Decrements the reference count of a DBusServer.  Finalizes the
422  * server if the reference count reaches zero. The server connection
423  * will be closed as with dbus_server_disconnect() when the server is
424  * finalized.
425  *
426  * @param server the server.
427  */
428 void
429 dbus_server_unref (DBusServer *server)
430 {
431   _dbus_assert (server != NULL);
432   _dbus_assert (server->refcount > 0);
433
434   server->refcount -= 1;
435   if (server->refcount == 0)
436     {
437       _dbus_assert (server->vtable->finalize != NULL);
438       
439       (* server->vtable->finalize) (server);
440     }
441 }
442
443 /**
444  * Releases the server's address and stops listening for
445  * new clients. If called more than once, only the first
446  * call has an effect. Does not modify the server's
447  * reference count.
448  * 
449  * @param server the server.
450  */
451 void
452 dbus_server_disconnect (DBusServer *server)
453 {
454   _dbus_assert (server->vtable->disconnect != NULL);
455
456   if (server->disconnected)
457     return;
458   
459   (* server->vtable->disconnect) (server);
460   server->disconnected = TRUE;
461 }
462
463 /**
464  * Returns #TRUE if the server is still listening for new connections.
465  *
466  * @param server the server.
467  */
468 dbus_bool_t
469 dbus_server_get_is_connected (DBusServer *server)
470 {
471   return !server->disconnected;
472 }
473
474 /**
475  * Returns the address of the server, as a newly-allocated
476  * string which must be freed by the caller.
477  *
478  * @param server the server
479  * @returns the address or #NULL if no memory
480  */
481 char*
482 dbus_server_get_address (DBusServer *server)
483 {
484   return _dbus_strdup (server->address);
485 }
486
487 /**
488  * Sets a function to be used for handling new connections.  The given
489  * function is passed each new connection as the connection is
490  * created. If the new connection function increments the connection's
491  * reference count, the connection will stay alive. Otherwise, the
492  * connection will be unreferenced and closed.
493  *
494  * @param server the server.
495  * @param function a function to handle new connections.
496  * @param data data to pass to the new connection handler.
497  * @param free_data_function function to free the data.
498  */
499 void
500 dbus_server_set_new_connection_function (DBusServer                *server,
501                                          DBusNewConnectionFunction  function,
502                                          void                      *data,
503                                          DBusFreeFunction           free_data_function)
504 {
505   if (server->new_connection_free_data_function != NULL)
506     (* server->new_connection_free_data_function) (server->new_connection_data);
507   
508   server->new_connection_function = function;
509   server->new_connection_data = data;
510   server->new_connection_free_data_function = free_data_function;
511 }
512
513 /**
514  * Sets the watch functions for the connection. These functions are
515  * responsible for making the application's main loop aware of file
516  * descriptors that need to be monitored for events.
517  *
518  * This function behaves exactly like dbus_connection_set_watch_functions();
519  * see the documentation for that routine.
520  *
521  * @param server the server.
522  * @param add_function function to begin monitoring a new descriptor.
523  * @param remove_function function to stop monitoring a descriptor.
524  * @param toggled_function function to notify when the watch is enabled/disabled
525  * @param data data to pass to add_function and remove_function.
526  * @param free_data_function function to be called to free the data.
527  * @returns #FALSE on failure (no memory)
528  */
529 dbus_bool_t
530 dbus_server_set_watch_functions (DBusServer              *server,
531                                  DBusAddWatchFunction     add_function,
532                                  DBusRemoveWatchFunction  remove_function,
533                                  DBusWatchToggledFunction toggled_function,
534                                  void                    *data,
535                                  DBusFreeFunction         free_data_function)
536 {
537   return _dbus_watch_list_set_functions (server->watches,
538                                          add_function,
539                                          remove_function,
540                                          toggled_function,
541                                          data,
542                                          free_data_function);
543 }
544
545 /**
546  * Sets the timeout functions for the connection. These functions are
547  * responsible for making the application's main loop aware of timeouts.
548  *
549  * This function behaves exactly like dbus_connection_set_timeout_functions();
550  * see the documentation for that routine.
551  *
552  * @param server the server.
553  * @param add_function function to add a timeout.
554  * @param remove_function function to remove a timeout.
555  * @param toggled_function function to notify when the timeout is enabled/disabled
556  * @param data data to pass to add_function and remove_function.
557  * @param free_data_function function to be called to free the data.
558  * @returns #FALSE on failure (no memory)
559  */
560 dbus_bool_t
561 dbus_server_set_timeout_functions (DBusServer                *server,
562                                    DBusAddTimeoutFunction     add_function,
563                                    DBusRemoveTimeoutFunction  remove_function,
564                                    DBusTimeoutToggledFunction toggled_function,
565                                    void                      *data,
566                                    DBusFreeFunction           free_data_function)
567 {
568   return _dbus_timeout_list_set_functions (server->timeouts,
569                                            add_function, remove_function,
570                                            toggled_function,
571                                            data, free_data_function); 
572 }
573
574 /**
575  * Called to notify the server when a previously-added watch
576  * is ready for reading or writing, or has an exception such
577  * as a hangup.
578  * 
579  * If this function returns #FALSE, then the file descriptor may still
580  * be ready for reading or writing, but more memory is needed in order
581  * to do the reading or writing. If you ignore the #FALSE return, your
582  * application may spin in a busy loop on the file descriptor until
583  * memory becomes available, but nothing more catastrophic should
584  * happen.
585  *
586  * @param server the server.
587  * @param watch the watch.
588  * @param condition the current condition of the file descriptors being watched.
589  */
590 dbus_bool_t
591 dbus_server_handle_watch (DBusServer              *server,
592                           DBusWatch               *watch,
593                           unsigned int             condition)
594 {
595   _dbus_assert (server->vtable->handle_watch != NULL);
596
597   _dbus_watch_sanitize_condition (watch, &condition);
598   
599   return (* server->vtable->handle_watch) (server, watch, condition);
600 }
601
602 /**
603  * Sets the maximum number of connections that can be open at one
604  * time for this server. If the maximum is reached, and another
605  * client tries to connect, then the oldest unauthenticated client
606  * will be dropped. If no unauthenticated client exists, then
607  * the new connection will be refused.
608  *
609  * If the maximum is set to a number lower than the current
610  * number of connections, no current connections are
611  * disconnected.
612  *
613  * @todo honoring max_connections has not been implemented
614  * yet. The only real work involved is keeping a list
615  * of live connections on the DBusServer so the oldest
616  * unauthenticated client can be located when required.
617  * 
618  * @todo for a systemwide daemon, we need a max number of connections
619  * per user, since any user can authenticate a bunch of connections
620  * and create a DOS.
621  *
622  * @todo a single process might listen on multiple mechanisms
623  * (multiple DBusServer) and might want the max connections
624  * value to span all those servers. Should consider
625  * changing the API accordingly, though I'm inclined to
626  * punt this to the app that wants to do it instead of
627  * putting it in the library.
628  * 
629  * @param server the server
630  * @param max_connections maximum number of connections allowed
631  */
632 void
633 dbus_server_set_max_connections (DBusServer *server,
634                                  int         max_connections)
635 {
636   server->max_connections = max_connections;
637 }
638
639 /**
640  * Gets the maximum number of connections that can be active
641  * at a time for this server.
642  *
643  * @param server the server
644  * @returns maximum number of connections at once
645  */
646 int
647 dbus_server_get_max_connections (DBusServer *server)
648 {
649   return server->max_connections;
650 }
651
652 /**
653  * Gets the number of #DBusConnection to this server that
654  * have not yet been finalized. i.e. all #DBusConnection that
655  * were passed to #DBusNewConnectionFunction and have not yet been
656  * finalized will count in this total.
657  *
658  * @param server the server
659  * @returns the number of connections
660  */
661 int
662 dbus_server_get_n_connections (DBusServer *server)
663 {
664   return _dbus_counter_get_value (server->connection_counter);
665 }
666
667
668 static DBusDataSlotAllocator slot_allocator;
669 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
670
671 /**
672  * Allocates an integer ID to be used for storing application-specific
673  * data on any DBusServer. The allocated ID may then be used
674  * with dbus_server_set_data() and dbus_server_get_data().
675  * If allocation fails, -1 is returned. Again, the allocated
676  * slot is global, i.e. all DBusServer objects will
677  * have a slot with the given integer ID reserved.
678  *
679  * @returns -1 on failure, otherwise the data slot ID
680  */
681 int
682 dbus_server_allocate_data_slot (void)
683 {
684   return _dbus_data_slot_allocator_alloc (&slot_allocator,
685                                           _DBUS_LOCK_NAME (server_slots));
686 }
687
688 /**
689  * Deallocates a global ID for server data slots.
690  * dbus_server_get_data() and dbus_server_set_data()
691  * may no longer be used with this slot.
692  * Existing data stored on existing DBusServer objects
693  * will be freed when the server is finalized,
694  * but may not be retrieved (and may only be replaced
695  * if someone else reallocates the slot).
696  *
697  * @param slot the slot to deallocate
698  */
699 void
700 dbus_server_free_data_slot (int slot)
701 {
702   _dbus_data_slot_allocator_free (&slot_allocator, slot);
703 }
704
705 /**
706  * Stores a pointer on a DBusServer, along
707  * with an optional function to be used for freeing
708  * the data when the data is set again, or when
709  * the server is finalized. The slot number
710  * must have been allocated with dbus_server_allocate_data_slot().
711  *
712  * @param server the server
713  * @param slot the slot number
714  * @param data the data to store
715  * @param free_data_func finalizer function for the data
716  * @returns #TRUE if there was enough memory to store the data
717  */
718 dbus_bool_t
719 dbus_server_set_data (DBusServer   *server,
720                       int               slot,
721                       void             *data,
722                       DBusFreeFunction  free_data_func)
723 {
724   DBusFreeFunction old_free_func;
725   void *old_data;
726   dbus_bool_t retval;
727
728 #if 0
729   dbus_mutex_lock (server->mutex);
730 #endif
731   
732   retval = _dbus_data_slot_list_set (&slot_allocator,
733                                      &server->slot_list,
734                                      slot, data, free_data_func,
735                                      &old_free_func, &old_data);
736
737 #if 0
738   dbus_mutex_unlock (server->mutex);
739 #endif
740   
741   if (retval)
742     {
743       /* Do the actual free outside the server lock */
744       if (old_free_func)
745         (* old_free_func) (old_data);
746     }
747
748   return retval;
749 }
750
751 /**
752  * Retrieves data previously set with dbus_server_set_data().
753  * The slot must still be allocated (must not have been freed).
754  *
755  * @param server the server
756  * @param slot the slot to get data from
757  * @returns the data, or #NULL if not found
758  */
759 void*
760 dbus_server_get_data (DBusServer   *server,
761                       int               slot)
762 {
763   void *res;
764   
765 #if 0
766   dbus_mutex_lock (server->mutex);
767 #endif
768   
769   res = _dbus_data_slot_list_get (&slot_allocator,
770                                   &server->slot_list,
771                                   slot);
772
773 #if 0
774   dbus_mutex_unlock (server->mutex);
775 #endif
776   
777   return res;
778 }
779
780 /** @} */
781