2003-04-18 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   
75   if (!_dbus_string_copy_data (address, &server->address))
76     goto failed;
77   
78   server->watches = _dbus_watch_list_new ();
79   if (server->watches == NULL)
80     goto failed;
81
82   server->timeouts = _dbus_timeout_list_new ();
83   if (server->timeouts == NULL)
84     goto failed;
85
86   _dbus_data_slot_list_init (&server->slot_list);
87
88   _dbus_verbose ("Initialized server on address %s\n", server->address);
89   
90   return TRUE;
91
92  failed:
93   if (server->watches)
94     {
95       _dbus_watch_list_free (server->watches);
96       server->watches = NULL;
97     }
98   if (server->timeouts)
99     {
100       _dbus_timeout_list_free (server->timeouts);
101       server->timeouts = NULL;
102     }
103   if (server->address)
104     {
105       dbus_free (server->address);
106       server->address = NULL;
107     }
108   
109   return FALSE;
110 }
111
112 /**
113  * Finalizes the members of the DBusServer base class.
114  * Chained up to by subclass finalizers.
115  *
116  * @param server the server.
117  */
118 void
119 _dbus_server_finalize_base (DBusServer *server)
120 {
121   /* calls out to application code... */
122   _dbus_data_slot_list_free (&server->slot_list);
123
124   dbus_server_set_new_connection_function (server, NULL, NULL, NULL);
125
126   if (!server->disconnected)
127     dbus_server_disconnect (server);
128
129   _dbus_watch_list_free (server->watches);
130   _dbus_timeout_list_free (server->timeouts);
131
132   dbus_free (server->address);
133
134   dbus_free_string_array (server->auth_mechanisms);
135 }
136
137 /**
138  * Adds a watch for this server, chaining out to application-provided
139  * watch handlers.
140  *
141  * @param server the server.
142  * @param watch the watch to add.
143  */
144 dbus_bool_t
145 _dbus_server_add_watch (DBusServer *server,
146                         DBusWatch  *watch)
147 {
148   return _dbus_watch_list_add_watch (server->watches, watch);
149 }
150
151 /**
152  * Removes a watch previously added with _dbus_server_remove_watch().
153  *
154  * @param server the server.
155  * @param watch the watch to remove.
156  */
157 void
158 _dbus_server_remove_watch  (DBusServer *server,
159                             DBusWatch  *watch)
160 {
161   _dbus_watch_list_remove_watch (server->watches, watch);
162 }
163
164 /**
165  * Toggles a watch and notifies app via server's
166  * DBusWatchToggledFunction if available. It's an error to call this
167  * function on a watch that was not previously added.
168  *
169  * @param server the server.
170  * @param watch the watch to toggle.
171  * @param enabled whether to enable or disable
172  */
173 void
174 _dbus_server_toggle_watch (DBusServer  *server,
175                            DBusWatch   *watch,
176                            dbus_bool_t  enabled)
177 {
178   if (server->watches) /* null during finalize */
179     _dbus_watch_list_toggle_watch (server->watches,
180                                    watch, enabled);
181 }
182
183 /**
184  * Adds a timeout for this server, chaining out to
185  * application-provided timeout handlers. The timeout should be
186  * repeatedly handled with dbus_timeout_handle() at its given interval
187  * until it is removed.
188  *
189  * @param server the server.
190  * @param timeout the timeout to add.
191  */
192 dbus_bool_t
193 _dbus_server_add_timeout (DBusServer  *server,
194                           DBusTimeout *timeout)
195 {
196   return _dbus_timeout_list_add_timeout (server->timeouts, timeout);
197 }
198
199 /**
200  * Removes a timeout previously added with _dbus_server_add_timeout().
201  *
202  * @param server the server.
203  * @param timeout the timeout to remove.
204  */
205 void
206 _dbus_server_remove_timeout (DBusServer  *server,
207                              DBusTimeout *timeout)
208 {
209   _dbus_timeout_list_remove_timeout (server->timeouts, timeout);  
210 }
211
212 /**
213  * Toggles a timeout and notifies app via server's
214  * DBusTimeoutToggledFunction if available. It's an error to call this
215  * function on a timeout that was not previously added.
216  *
217  * @param server the server.
218  * @param timeout the timeout to toggle.
219  * @param enabled whether to enable or disable
220  */
221 void
222 _dbus_server_toggle_timeout (DBusServer  *server,
223                              DBusTimeout *timeout,
224                              dbus_bool_t  enabled)
225 {
226   if (server->timeouts) /* null during finalize */
227     _dbus_timeout_list_toggle_timeout (server->timeouts,
228                                        timeout, enabled);
229 }
230
231
232 /** @} */
233
234 /**
235  * @addtogroup DBusServer
236  *
237  * @{
238  */
239
240
241 /**
242  * @typedef DBusServer
243  *
244  * An opaque object representing a server that listens for
245  * connections from other applications. Each time a connection
246  * is made, a new DBusConnection is created and made available
247  * via an application-provided DBusNewConnectionFunction.
248  * The DBusNewConnectionFunction is provided with
249  * dbus_server_set_new_connection_function().
250  * 
251  */
252
253 /**
254  * Listens for new connections on the given address.
255  * Returns #NULL if listening fails for any reason.
256  * Otherwise returns a new #DBusServer.
257  * dbus_server_set_new_connection_function() and
258  * dbus_server_set_watch_functions() should be called
259  * immediately to render the server fully functional.
260  *
261  * @todo error messages on bad address could really be better.
262  * DBusResultCode is a bit limiting here.
263  *
264  * @param address the address of this server.
265  * @param error location to store rationale for failure.
266  * @returns a new DBusServer, or #NULL on failure.
267  * 
268  */
269 DBusServer*
270 dbus_server_listen (const char     *address,
271                     DBusError      *error)
272 {
273   DBusServer *server;
274   DBusAddressEntry **entries;
275   int len, i;
276   const char *address_problem_type;
277   const char *address_problem_field;
278   const char *address_problem_other;
279
280   _DBUS_ASSERT_ERROR_IS_CLEAR (error);
281   
282   if (!dbus_parse_address (address, &entries, &len, error))
283     return NULL;
284
285   server = NULL;
286   address_problem_type = NULL;
287   address_problem_field = NULL;
288   address_problem_other = NULL;
289   
290   for (i = 0; i < len; i++)
291     {
292       const char *method = dbus_address_entry_get_method (entries[i]);
293
294       if (strcmp (method, "unix") == 0)
295         {
296           const char *path = dbus_address_entry_get_value (entries[i], "path");
297           const char *tmpdir = dbus_address_entry_get_value (entries[i], "tmpdir");
298           
299           if (path == NULL && tmpdir == NULL)
300             {
301               address_problem_type = "unix";
302               address_problem_field = "path or tmpdir";
303               goto bad_address;
304             }
305
306           if (path && tmpdir)
307             {
308               address_problem_other = "cannot specify both \"path\" and \"tmpdir\" at the same time";
309               goto bad_address;
310             }
311
312           if (tmpdir != NULL)
313             {
314               DBusString full_path;
315               DBusString filename;
316               
317               if (!_dbus_string_init (&full_path))
318                 {
319                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
320                   goto out;
321                 }
322                   
323               if (!_dbus_string_init (&filename))
324                 {
325                   _dbus_string_free (&full_path);
326                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
327                   goto out;
328                 }
329               
330               if (!_dbus_string_append (&filename,
331                                         "dbus-") ||
332                   !_dbus_generate_random_ascii (&filename, 10) ||
333                   !_dbus_string_append (&full_path, tmpdir) ||
334                   !_dbus_concat_dir_and_file (&full_path, &filename))
335                 {
336                   _dbus_string_free (&full_path);
337                   _dbus_string_free (&filename);
338                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
339                   goto out;
340                 }
341               
342               /* FIXME - we will unconditionally unlink() the path.
343                * unlink() does not follow symlinks, but would like
344                * independent confirmation this is safe enough. See
345                * also _dbus_listen_unix_socket() and comments therein.
346                */
347               
348               server =
349                 _dbus_server_new_for_domain_socket (_dbus_string_get_const_data (&full_path),
350                                                     error);
351
352               _dbus_string_free (&full_path);
353               _dbus_string_free (&filename);
354             }
355           else
356             {
357               server = _dbus_server_new_for_domain_socket (path, error);
358             }
359         }
360       else if (strcmp (method, "tcp") == 0)
361         {
362           const char *host = dbus_address_entry_get_value (entries[i], "host");
363           const char *port = dbus_address_entry_get_value (entries[i], "port");
364           DBusString  str;
365           long lport;
366           dbus_bool_t sresult;
367           
368           if (port == NULL)
369             {
370               address_problem_type = "tcp";
371               address_problem_field = "port";
372               goto bad_address;
373             }
374
375           _dbus_string_init_const (&str, port);
376           sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
377           _dbus_string_free (&str);
378           
379           if (sresult == FALSE || lport <= 0 || lport > 65535)
380             {
381               address_problem_other = "Port is not an integer between 0 and 65535";
382               goto bad_address;
383             }
384           
385           server = _dbus_server_new_for_tcp_socket (host, lport, error);
386
387           if (server)
388             break;
389         }
390 #ifdef DBUS_BUILD_TESTS
391       else if (strcmp (method, "debug") == 0)
392         {
393           const char *name = dbus_address_entry_get_value (entries[i], "name");
394
395           if (name == NULL)
396             {
397               address_problem_type = "debug";
398               address_problem_field = "name";
399               goto bad_address;
400             }
401
402           server = _dbus_server_debug_new (name, error);
403         }
404       else if (strcmp (method, "debug-pipe") == 0)
405         {
406           const char *name = dbus_address_entry_get_value (entries[i], "name");
407
408           if (name == NULL)
409             {
410               address_problem_type = "debug-pipe";
411               address_problem_field = "name";
412               goto bad_address;
413             }
414
415           server = _dbus_server_debug_pipe_new (name, error);
416         }
417 #endif
418       else
419         {
420           address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
421           goto bad_address;
422         }
423       
424       if (server)
425         break;
426     }
427
428  out:
429   
430   dbus_address_entries_free (entries);
431   return server;
432
433  bad_address:
434   dbus_address_entries_free (entries);
435   if (address_problem_type != NULL)
436     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
437                     "Server address of type %s was missing argument %s",
438                     address_problem_type, address_problem_field);
439   else
440     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
441                     "Could not parse server address: %s",
442                     address_problem_other);
443
444   return NULL;
445 }
446
447 /**
448  * Increments the reference count of a DBusServer.
449  *
450  * @param server the server.
451  */
452 void
453 dbus_server_ref (DBusServer *server)
454 {
455   server->refcount += 1;
456 }
457
458 /**
459  * Decrements the reference count of a DBusServer.  Finalizes the
460  * server if the reference count reaches zero. The server connection
461  * will be closed as with dbus_server_disconnect() when the server is
462  * finalized.
463  *
464  * @param server the server.
465  */
466 void
467 dbus_server_unref (DBusServer *server)
468 {
469   _dbus_assert (server != NULL);
470   _dbus_assert (server->refcount > 0);
471
472   server->refcount -= 1;
473   if (server->refcount == 0)
474     {
475       _dbus_assert (server->vtable->finalize != NULL);
476       
477       (* server->vtable->finalize) (server);
478     }
479 }
480
481 /**
482  * Releases the server's address and stops listening for
483  * new clients. If called more than once, only the first
484  * call has an effect. Does not modify the server's
485  * reference count.
486  * 
487  * @param server the server.
488  */
489 void
490 dbus_server_disconnect (DBusServer *server)
491 {
492   _dbus_assert (server->vtable->disconnect != NULL);
493
494   if (server->disconnected)
495     return;
496   
497   (* server->vtable->disconnect) (server);
498   server->disconnected = TRUE;
499 }
500
501 /**
502  * Returns #TRUE if the server is still listening for new connections.
503  *
504  * @param server the server.
505  */
506 dbus_bool_t
507 dbus_server_get_is_connected (DBusServer *server)
508 {
509   return !server->disconnected;
510 }
511
512 /**
513  * Returns the address of the server, as a newly-allocated
514  * string which must be freed by the caller.
515  *
516  * @param server the server
517  * @returns the address or #NULL if no memory
518  */
519 char*
520 dbus_server_get_address (DBusServer *server)
521 {
522   return _dbus_strdup (server->address);
523 }
524
525 /**
526  * Sets a function to be used for handling new connections.  The given
527  * function is passed each new connection as the connection is
528  * created. If the new connection function increments the connection's
529  * reference count, the connection will stay alive. Otherwise, the
530  * connection will be unreferenced and closed.
531  *
532  * @param server the server.
533  * @param function a function to handle new connections.
534  * @param data data to pass to the new connection handler.
535  * @param free_data_function function to free the data.
536  */
537 void
538 dbus_server_set_new_connection_function (DBusServer                *server,
539                                          DBusNewConnectionFunction  function,
540                                          void                      *data,
541                                          DBusFreeFunction           free_data_function)
542 {
543   if (server->new_connection_free_data_function != NULL)
544     (* server->new_connection_free_data_function) (server->new_connection_data);
545   
546   server->new_connection_function = function;
547   server->new_connection_data = data;
548   server->new_connection_free_data_function = free_data_function;
549 }
550
551 /**
552  * Sets the watch functions for the connection. These functions are
553  * responsible for making the application's main loop aware of file
554  * descriptors that need to be monitored for events.
555  *
556  * This function behaves exactly like dbus_connection_set_watch_functions();
557  * see the documentation for that routine.
558  *
559  * @param server the server.
560  * @param add_function function to begin monitoring a new descriptor.
561  * @param remove_function function to stop monitoring a descriptor.
562  * @param toggled_function function to notify when the watch is enabled/disabled
563  * @param data data to pass to add_function and remove_function.
564  * @param free_data_function function to be called to free the data.
565  * @returns #FALSE on failure (no memory)
566  */
567 dbus_bool_t
568 dbus_server_set_watch_functions (DBusServer              *server,
569                                  DBusAddWatchFunction     add_function,
570                                  DBusRemoveWatchFunction  remove_function,
571                                  DBusWatchToggledFunction toggled_function,
572                                  void                    *data,
573                                  DBusFreeFunction         free_data_function)
574 {
575   return _dbus_watch_list_set_functions (server->watches,
576                                          add_function,
577                                          remove_function,
578                                          toggled_function,
579                                          data,
580                                          free_data_function);
581 }
582
583 /**
584  * Sets the timeout functions for the connection. These functions are
585  * responsible for making the application's main loop aware of timeouts.
586  *
587  * This function behaves exactly like dbus_connection_set_timeout_functions();
588  * see the documentation for that routine.
589  *
590  * @param server the server.
591  * @param add_function function to add a timeout.
592  * @param remove_function function to remove a timeout.
593  * @param toggled_function function to notify when the timeout is enabled/disabled
594  * @param data data to pass to add_function and remove_function.
595  * @param free_data_function function to be called to free the data.
596  * @returns #FALSE on failure (no memory)
597  */
598 dbus_bool_t
599 dbus_server_set_timeout_functions (DBusServer                *server,
600                                    DBusAddTimeoutFunction     add_function,
601                                    DBusRemoveTimeoutFunction  remove_function,
602                                    DBusTimeoutToggledFunction toggled_function,
603                                    void                      *data,
604                                    DBusFreeFunction           free_data_function)
605 {
606   return _dbus_timeout_list_set_functions (server->timeouts,
607                                            add_function, remove_function,
608                                            toggled_function,
609                                            data, free_data_function); 
610 }
611
612 /**
613  * Sets the authentication mechanisms that this server offers
614  * to clients, as a list of SASL mechanisms. This function
615  * only affects connections created *after* it is called.
616  * Pass #NULL instead of an array to use all available mechanisms.
617  *
618  * @param server the server
619  * @param mechanisms #NULL-terminated array of mechanisms
620  * @returns #FALSE if no memory
621  */
622 dbus_bool_t
623 dbus_server_set_auth_mechanisms (DBusServer  *server,
624                                  const char **mechanisms)
625 {
626   char **copy;
627
628   if (mechanisms != NULL)
629     {
630       copy = _dbus_dup_string_array (mechanisms);
631       if (copy == NULL)
632         return FALSE;
633     }
634   else
635     copy = NULL;
636
637   dbus_free_string_array (server->auth_mechanisms);
638   server->auth_mechanisms = copy;
639
640   return TRUE;
641 }
642
643
644 static DBusDataSlotAllocator slot_allocator;
645 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
646
647 /**
648  * Allocates an integer ID to be used for storing application-specific
649  * data on any DBusServer. The allocated ID may then be used
650  * with dbus_server_set_data() and dbus_server_get_data().
651  * If allocation fails, -1 is returned. Again, the allocated
652  * slot is global, i.e. all DBusServer objects will
653  * have a slot with the given integer ID reserved.
654  *
655  * @returns -1 on failure, otherwise the data slot ID
656  */
657 int
658 dbus_server_allocate_data_slot (void)
659 {
660   return _dbus_data_slot_allocator_alloc (&slot_allocator,
661                                           _DBUS_LOCK_NAME (server_slots));
662 }
663
664 /**
665  * Deallocates a global ID for server data slots.
666  * dbus_server_get_data() and dbus_server_set_data()
667  * may no longer be used with this slot.
668  * Existing data stored on existing DBusServer objects
669  * will be freed when the server is finalized,
670  * but may not be retrieved (and may only be replaced
671  * if someone else reallocates the slot).
672  *
673  * @param slot the slot to deallocate
674  */
675 void
676 dbus_server_free_data_slot (int slot)
677 {
678   _dbus_data_slot_allocator_free (&slot_allocator, slot);
679 }
680
681 /**
682  * Stores a pointer on a DBusServer, along
683  * with an optional function to be used for freeing
684  * the data when the data is set again, or when
685  * the server is finalized. The slot number
686  * must have been allocated with dbus_server_allocate_data_slot().
687  *
688  * @param server the server
689  * @param slot the slot number
690  * @param data the data to store
691  * @param free_data_func finalizer function for the data
692  * @returns #TRUE if there was enough memory to store the data
693  */
694 dbus_bool_t
695 dbus_server_set_data (DBusServer   *server,
696                       int               slot,
697                       void             *data,
698                       DBusFreeFunction  free_data_func)
699 {
700   DBusFreeFunction old_free_func;
701   void *old_data;
702   dbus_bool_t retval;
703
704 #if 0
705   dbus_mutex_lock (server->mutex);
706 #endif
707   
708   retval = _dbus_data_slot_list_set (&slot_allocator,
709                                      &server->slot_list,
710                                      slot, data, free_data_func,
711                                      &old_free_func, &old_data);
712
713 #if 0
714   dbus_mutex_unlock (server->mutex);
715 #endif
716   
717   if (retval)
718     {
719       /* Do the actual free outside the server lock */
720       if (old_free_func)
721         (* old_free_func) (old_data);
722     }
723
724   return retval;
725 }
726
727 /**
728  * Retrieves data previously set with dbus_server_set_data().
729  * The slot must still be allocated (must not have been freed).
730  *
731  * @param server the server
732  * @param slot the slot to get data from
733  * @returns the data, or #NULL if not found
734  */
735 void*
736 dbus_server_get_data (DBusServer   *server,
737                       int               slot)
738 {
739   void *res;
740   
741 #if 0
742   dbus_mutex_lock (server->mutex);
743 #endif
744   
745   res = _dbus_data_slot_list_get (&slot_allocator,
746                                   &server->slot_list,
747                                   slot);
748
749 #if 0
750   dbus_mutex_unlock (server->mutex);
751 #endif
752   
753   return res;
754 }
755
756 /** @} */
757