2003-04-01 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   dbus_free_string_array (server->auth_mechanisms);
148 }
149
150 /**
151  * Adds a watch for this server, chaining out to application-provided
152  * watch handlers.
153  *
154  * @param server the server.
155  * @param watch the watch to add.
156  */
157 dbus_bool_t
158 _dbus_server_add_watch (DBusServer *server,
159                         DBusWatch  *watch)
160 {
161   return _dbus_watch_list_add_watch (server->watches, watch);
162 }
163
164 /**
165  * Removes a watch previously added with _dbus_server_remove_watch().
166  *
167  * @param server the server.
168  * @param watch the watch to remove.
169  */
170 void
171 _dbus_server_remove_watch  (DBusServer *server,
172                             DBusWatch  *watch)
173 {
174   _dbus_watch_list_remove_watch (server->watches, watch);
175 }
176
177 /**
178  * Toggles a watch and notifies app via server's
179  * DBusWatchToggledFunction if available. It's an error to call this
180  * function on a watch that was not previously added.
181  *
182  * @param server the server.
183  * @param watch the watch to toggle.
184  * @param enabled whether to enable or disable
185  */
186 void
187 _dbus_server_toggle_watch (DBusServer  *server,
188                            DBusWatch   *watch,
189                            dbus_bool_t  enabled)
190 {
191   if (server->watches) /* null during finalize */
192     _dbus_watch_list_toggle_watch (server->watches,
193                                    watch, enabled);
194 }
195
196 /**
197  * Adds a timeout for this server, chaining out to
198  * application-provided timeout handlers. The timeout should be
199  * repeatedly handled with dbus_timeout_handle() at its given interval
200  * until it is removed.
201  *
202  * @param server the server.
203  * @param timeout the timeout to add.
204  */
205 dbus_bool_t
206 _dbus_server_add_timeout (DBusServer  *server,
207                           DBusTimeout *timeout)
208 {
209   return _dbus_timeout_list_add_timeout (server->timeouts, timeout);
210 }
211
212 /**
213  * Removes a timeout previously added with _dbus_server_add_timeout().
214  *
215  * @param server the server.
216  * @param timeout the timeout to remove.
217  */
218 void
219 _dbus_server_remove_timeout (DBusServer  *server,
220                              DBusTimeout *timeout)
221 {
222   _dbus_timeout_list_remove_timeout (server->timeouts, timeout);  
223 }
224
225 /**
226  * Toggles a timeout and notifies app via server's
227  * DBusTimeoutToggledFunction if available. It's an error to call this
228  * function on a timeout that was not previously added.
229  *
230  * @param server the server.
231  * @param timeout the timeout to toggle.
232  * @param enabled whether to enable or disable
233  */
234 void
235 _dbus_server_toggle_timeout (DBusServer  *server,
236                              DBusTimeout *timeout,
237                              dbus_bool_t  enabled)
238 {
239   if (server->timeouts) /* null during finalize */
240     _dbus_timeout_list_toggle_timeout (server->timeouts,
241                                        timeout, enabled);
242 }
243
244
245 /** @} */
246
247 /**
248  * @addtogroup DBusServer
249  *
250  * @{
251  */
252
253
254 /**
255  * @typedef DBusServer
256  *
257  * An opaque object representing a server that listens for
258  * connections from other applications. Each time a connection
259  * is made, a new DBusConnection is created and made available
260  * via an application-provided DBusNewConnectionFunction.
261  * The DBusNewConnectionFunction is provided with
262  * dbus_server_set_new_connection_function().
263  * 
264  */
265
266 /**
267  * Listens for new connections on the given address.
268  * Returns #NULL if listening fails for any reason.
269  * Otherwise returns a new #DBusServer.
270  * dbus_server_set_new_connection_function() and
271  * dbus_server_set_watch_functions() should be called
272  * immediately to render the server fully functional.
273  *
274  * @todo error messages on bad address could really be better.
275  * DBusResultCode is a bit limiting here.
276  *
277  * @param address the address of this server.
278  * @param error location to store rationale for failure.
279  * @returns a new DBusServer, or #NULL on failure.
280  * 
281  */
282 DBusServer*
283 dbus_server_listen (const char     *address,
284                     DBusError      *error)
285 {
286   DBusServer *server;
287   DBusAddressEntry **entries;
288   int len, i;
289   const char *address_problem_type;
290   const char *address_problem_field;
291   const char *address_problem_other;
292
293   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
294   
295   if (!dbus_parse_address (address, &entries, &len, error))
296     return NULL;
297
298   server = NULL;
299   address_problem_type = NULL;
300   address_problem_field = NULL;
301   address_problem_other = NULL;
302   
303   for (i = 0; i < len; i++)
304     {
305       const char *method = dbus_address_entry_get_method (entries[i]);
306
307       if (strcmp (method, "unix") == 0)
308         {
309           const char *path = dbus_address_entry_get_value (entries[i], "path");
310
311           if (path == NULL)
312             {
313               address_problem_type = "unix";
314               address_problem_field = "path";
315               goto bad_address;
316             }
317
318           server = _dbus_server_new_for_domain_socket (path, error);
319
320           if (server)
321             break;
322         }
323       else if (strcmp (method, "tcp") == 0)
324         {
325           const char *host = dbus_address_entry_get_value (entries[i], "host");
326           const char *port = dbus_address_entry_get_value (entries[i], "port");
327           DBusString  str;
328           long lport;
329           dbus_bool_t sresult;
330           
331           if (port == NULL)
332             {
333               address_problem_type = "tcp";
334               address_problem_field = "port";
335               goto bad_address;
336             }
337
338           _dbus_string_init_const (&str, port);
339           sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
340           _dbus_string_free (&str);
341           
342           if (sresult == FALSE || lport <= 0 || lport > 65535)
343             {
344               address_problem_other = "Port is not an integer between 0 and 65535";
345               goto bad_address;
346             }
347           
348           server = _dbus_server_new_for_tcp_socket (host, lport, error);
349
350           if (server)
351             break;
352         }
353 #ifdef DBUS_BUILD_TESTS
354       else if (strcmp (method, "debug") == 0)
355         {
356           const char *name = dbus_address_entry_get_value (entries[i], "name");
357
358           if (name == NULL)
359             {
360               address_problem_type = "debug";
361               address_problem_field = "name";
362               goto bad_address;
363             }
364
365           server = _dbus_server_debug_new (name, error);
366
367           if (server)
368             break;
369         }
370       else if (strcmp (method, "debug-pipe") == 0)
371         {
372           const char *name = dbus_address_entry_get_value (entries[i], "name");
373
374           if (name == NULL)
375             {
376               address_problem_type = "debug-pipe";
377               address_problem_field = "name";
378               goto bad_address;
379             }
380
381           server = _dbus_server_debug_pipe_new (name, error);
382
383           if (server)
384             break;
385         }
386 #endif
387       else
388         {
389           address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
390           goto bad_address;
391         }
392     }
393   
394   dbus_address_entries_free (entries);
395   return server;
396
397  bad_address:
398   dbus_address_entries_free (entries);
399   if (address_problem_type != NULL)
400     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
401                     "Server address of type %s was missing argument %s",
402                     address_problem_type, address_problem_field);
403   else
404     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
405                     "Could not parse server address: %s",
406                     address_problem_other);
407
408   return NULL;
409 }
410
411 /**
412  * Increments the reference count of a DBusServer.
413  *
414  * @param server the server.
415  */
416 void
417 dbus_server_ref (DBusServer *server)
418 {
419   server->refcount += 1;
420 }
421
422 /**
423  * Decrements the reference count of a DBusServer.  Finalizes the
424  * server if the reference count reaches zero. The server connection
425  * will be closed as with dbus_server_disconnect() when the server is
426  * finalized.
427  *
428  * @param server the server.
429  */
430 void
431 dbus_server_unref (DBusServer *server)
432 {
433   _dbus_assert (server != NULL);
434   _dbus_assert (server->refcount > 0);
435
436   server->refcount -= 1;
437   if (server->refcount == 0)
438     {
439       _dbus_assert (server->vtable->finalize != NULL);
440       
441       (* server->vtable->finalize) (server);
442     }
443 }
444
445 /**
446  * Releases the server's address and stops listening for
447  * new clients. If called more than once, only the first
448  * call has an effect. Does not modify the server's
449  * reference count.
450  * 
451  * @param server the server.
452  */
453 void
454 dbus_server_disconnect (DBusServer *server)
455 {
456   _dbus_assert (server->vtable->disconnect != NULL);
457
458   if (server->disconnected)
459     return;
460   
461   (* server->vtable->disconnect) (server);
462   server->disconnected = TRUE;
463 }
464
465 /**
466  * Returns #TRUE if the server is still listening for new connections.
467  *
468  * @param server the server.
469  */
470 dbus_bool_t
471 dbus_server_get_is_connected (DBusServer *server)
472 {
473   return !server->disconnected;
474 }
475
476 /**
477  * Returns the address of the server, as a newly-allocated
478  * string which must be freed by the caller.
479  *
480  * @param server the server
481  * @returns the address or #NULL if no memory
482  */
483 char*
484 dbus_server_get_address (DBusServer *server)
485 {
486   return _dbus_strdup (server->address);
487 }
488
489 /**
490  * Sets a function to be used for handling new connections.  The given
491  * function is passed each new connection as the connection is
492  * created. If the new connection function increments the connection's
493  * reference count, the connection will stay alive. Otherwise, the
494  * connection will be unreferenced and closed.
495  *
496  * @param server the server.
497  * @param function a function to handle new connections.
498  * @param data data to pass to the new connection handler.
499  * @param free_data_function function to free the data.
500  */
501 void
502 dbus_server_set_new_connection_function (DBusServer                *server,
503                                          DBusNewConnectionFunction  function,
504                                          void                      *data,
505                                          DBusFreeFunction           free_data_function)
506 {
507   if (server->new_connection_free_data_function != NULL)
508     (* server->new_connection_free_data_function) (server->new_connection_data);
509   
510   server->new_connection_function = function;
511   server->new_connection_data = data;
512   server->new_connection_free_data_function = free_data_function;
513 }
514
515 /**
516  * Sets the watch functions for the connection. These functions are
517  * responsible for making the application's main loop aware of file
518  * descriptors that need to be monitored for events.
519  *
520  * This function behaves exactly like dbus_connection_set_watch_functions();
521  * see the documentation for that routine.
522  *
523  * @param server the server.
524  * @param add_function function to begin monitoring a new descriptor.
525  * @param remove_function function to stop monitoring a descriptor.
526  * @param toggled_function function to notify when the watch is enabled/disabled
527  * @param data data to pass to add_function and remove_function.
528  * @param free_data_function function to be called to free the data.
529  * @returns #FALSE on failure (no memory)
530  */
531 dbus_bool_t
532 dbus_server_set_watch_functions (DBusServer              *server,
533                                  DBusAddWatchFunction     add_function,
534                                  DBusRemoveWatchFunction  remove_function,
535                                  DBusWatchToggledFunction toggled_function,
536                                  void                    *data,
537                                  DBusFreeFunction         free_data_function)
538 {
539   return _dbus_watch_list_set_functions (server->watches,
540                                          add_function,
541                                          remove_function,
542                                          toggled_function,
543                                          data,
544                                          free_data_function);
545 }
546
547 /**
548  * Sets the timeout functions for the connection. These functions are
549  * responsible for making the application's main loop aware of timeouts.
550  *
551  * This function behaves exactly like dbus_connection_set_timeout_functions();
552  * see the documentation for that routine.
553  *
554  * @param server the server.
555  * @param add_function function to add a timeout.
556  * @param remove_function function to remove a timeout.
557  * @param toggled_function function to notify when the timeout is enabled/disabled
558  * @param data data to pass to add_function and remove_function.
559  * @param free_data_function function to be called to free the data.
560  * @returns #FALSE on failure (no memory)
561  */
562 dbus_bool_t
563 dbus_server_set_timeout_functions (DBusServer                *server,
564                                    DBusAddTimeoutFunction     add_function,
565                                    DBusRemoveTimeoutFunction  remove_function,
566                                    DBusTimeoutToggledFunction toggled_function,
567                                    void                      *data,
568                                    DBusFreeFunction           free_data_function)
569 {
570   return _dbus_timeout_list_set_functions (server->timeouts,
571                                            add_function, remove_function,
572                                            toggled_function,
573                                            data, free_data_function); 
574 }
575
576 /**
577  * Called to notify the server when a previously-added watch
578  * is ready for reading or writing, or has an exception such
579  * as a hangup.
580  * 
581  * If this function returns #FALSE, then the file descriptor may still
582  * be ready for reading or writing, but more memory is needed in order
583  * to do the reading or writing. If you ignore the #FALSE return, your
584  * application may spin in a busy loop on the file descriptor until
585  * memory becomes available, but nothing more catastrophic should
586  * happen.
587  *
588  * @param server the server.
589  * @param watch the watch.
590  * @param condition the current condition of the file descriptors being watched.
591  */
592 dbus_bool_t
593 dbus_server_handle_watch (DBusServer              *server,
594                           DBusWatch               *watch,
595                           unsigned int             condition)
596 {
597   _dbus_assert (server->vtable->handle_watch != NULL);
598
599   _dbus_watch_sanitize_condition (watch, &condition);
600   
601   return (* server->vtable->handle_watch) (server, watch, condition);
602 }
603
604 /**
605  * Sets the authentication mechanisms that this server offers
606  * to clients, as a list of SASL mechanisms. This function
607  * only affects connections created *after* it is called.
608  * Pass #NULL instead of an array to use all available mechanisms.
609  *
610  * @param server the server
611  * @param mechanisms #NULL-terminated array of mechanisms
612  * @returns #FALSE if no memory
613  */
614 dbus_bool_t
615 dbus_server_set_auth_mechanisms (DBusServer  *server,
616                                  const char **mechanisms)
617 {
618   char **copy;
619
620   if (mechanisms != NULL)
621     {
622       copy = _dbus_dup_string_array (mechanisms);
623       if (copy == NULL)
624         return FALSE;
625     }
626   else
627     copy = NULL;
628
629   dbus_free_string_array (server->auth_mechanisms);
630   server->auth_mechanisms = copy;
631
632   return TRUE;
633 }
634
635 /**
636  * Sets the maximum number of connections that can be open at one
637  * time for this server. If the maximum is reached, and another
638  * client tries to connect, then the oldest unauthenticated client
639  * will be dropped. If no unauthenticated client exists, then
640  * the new connection will be refused.
641  *
642  * If the maximum is set to a number lower than the current
643  * number of connections, no current connections are
644  * disconnected.
645  *
646  * @todo honoring max_connections has not been implemented
647  * yet. The only real work involved is keeping a list
648  * of live connections on the DBusServer so the oldest
649  * unauthenticated client can be located when required.
650  * 
651  * @todo for a systemwide daemon, we need a max number of connections
652  * per user, since any user can authenticate a bunch of connections
653  * and create a DOS.
654  *
655  * @todo a single process might listen on multiple mechanisms
656  * (multiple DBusServer) and might want the max connections
657  * value to span all those servers. Should consider
658  * changing the API accordingly, though I'm inclined to
659  * punt this to the app that wants to do it instead of
660  * putting it in the library.
661  * 
662  * @param server the server
663  * @param max_connections maximum number of connections allowed
664  */
665 void
666 dbus_server_set_max_connections (DBusServer *server,
667                                  int         max_connections)
668 {
669   server->max_connections = max_connections;
670 }
671
672 /**
673  * Gets the maximum number of connections that can be active
674  * at a time for this server.
675  *
676  * @param server the server
677  * @returns maximum number of connections at once
678  */
679 int
680 dbus_server_get_max_connections (DBusServer *server)
681 {
682   return server->max_connections;
683 }
684
685 /**
686  * Gets the number of #DBusConnection to this server that
687  * have not yet been finalized. i.e. all #DBusConnection that
688  * were passed to #DBusNewConnectionFunction and have not yet been
689  * finalized will count in this total.
690  *
691  * @param server the server
692  * @returns the number of connections
693  */
694 int
695 dbus_server_get_n_connections (DBusServer *server)
696 {
697   return _dbus_counter_get_value (server->connection_counter);
698 }
699
700
701 static DBusDataSlotAllocator slot_allocator;
702 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
703
704 /**
705  * Allocates an integer ID to be used for storing application-specific
706  * data on any DBusServer. The allocated ID may then be used
707  * with dbus_server_set_data() and dbus_server_get_data().
708  * If allocation fails, -1 is returned. Again, the allocated
709  * slot is global, i.e. all DBusServer objects will
710  * have a slot with the given integer ID reserved.
711  *
712  * @returns -1 on failure, otherwise the data slot ID
713  */
714 int
715 dbus_server_allocate_data_slot (void)
716 {
717   return _dbus_data_slot_allocator_alloc (&slot_allocator,
718                                           _DBUS_LOCK_NAME (server_slots));
719 }
720
721 /**
722  * Deallocates a global ID for server data slots.
723  * dbus_server_get_data() and dbus_server_set_data()
724  * may no longer be used with this slot.
725  * Existing data stored on existing DBusServer objects
726  * will be freed when the server is finalized,
727  * but may not be retrieved (and may only be replaced
728  * if someone else reallocates the slot).
729  *
730  * @param slot the slot to deallocate
731  */
732 void
733 dbus_server_free_data_slot (int slot)
734 {
735   _dbus_data_slot_allocator_free (&slot_allocator, slot);
736 }
737
738 /**
739  * Stores a pointer on a DBusServer, along
740  * with an optional function to be used for freeing
741  * the data when the data is set again, or when
742  * the server is finalized. The slot number
743  * must have been allocated with dbus_server_allocate_data_slot().
744  *
745  * @param server the server
746  * @param slot the slot number
747  * @param data the data to store
748  * @param free_data_func finalizer function for the data
749  * @returns #TRUE if there was enough memory to store the data
750  */
751 dbus_bool_t
752 dbus_server_set_data (DBusServer   *server,
753                       int               slot,
754                       void             *data,
755                       DBusFreeFunction  free_data_func)
756 {
757   DBusFreeFunction old_free_func;
758   void *old_data;
759   dbus_bool_t retval;
760
761 #if 0
762   dbus_mutex_lock (server->mutex);
763 #endif
764   
765   retval = _dbus_data_slot_list_set (&slot_allocator,
766                                      &server->slot_list,
767                                      slot, data, free_data_func,
768                                      &old_free_func, &old_data);
769
770 #if 0
771   dbus_mutex_unlock (server->mutex);
772 #endif
773   
774   if (retval)
775     {
776       /* Do the actual free outside the server lock */
777       if (old_free_func)
778         (* old_free_func) (old_data);
779     }
780
781   return retval;
782 }
783
784 /**
785  * Retrieves data previously set with dbus_server_set_data().
786  * The slot must still be allocated (must not have been freed).
787  *
788  * @param server the server
789  * @param slot the slot to get data from
790  * @returns the data, or #NULL if not found
791  */
792 void*
793 dbus_server_get_data (DBusServer   *server,
794                       int               slot)
795 {
796   void *res;
797   
798 #if 0
799   dbus_mutex_lock (server->mutex);
800 #endif
801   
802   res = _dbus_data_slot_list_get (&slot_allocator,
803                                   &server->slot_list,
804                                   slot);
805
806 #if 0
807   dbus_mutex_unlock (server->mutex);
808 #endif
809   
810   return res;
811 }
812
813 /** @} */
814