2003-08-12 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 #include "dbus-string.h"
27 #ifdef DBUS_BUILD_TESTS
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_return_val_if_fail (address != NULL, NULL);
281   _dbus_return_val_if_error_is_set (error, NULL);
282   
283   if (!dbus_parse_address (address, &entries, &len, error))
284     return NULL;
285
286   server = NULL;
287   address_problem_type = NULL;
288   address_problem_field = NULL;
289   address_problem_other = NULL;
290   
291   for (i = 0; i < len; i++)
292     {
293       const char *method = dbus_address_entry_get_method (entries[i]);
294
295       if (strcmp (method, "unix") == 0)
296         {
297           const char *path = dbus_address_entry_get_value (entries[i], "path");
298           const char *tmpdir = dbus_address_entry_get_value (entries[i], "tmpdir");
299           const char *abstract = dbus_address_entry_get_value (entries[i], "abstract");
300           
301           if (path == NULL && tmpdir == NULL && abstract == NULL)
302             {
303               address_problem_type = "unix";
304               address_problem_field = "path or tmpdir or abstract";
305               goto bad_address;
306             }
307
308           if ((path && tmpdir) ||
309               (path && abstract) ||
310               (tmpdir && abstract))
311             {
312               address_problem_other = "cannot specify two of \"path\" and \"tmpdir\" and \"abstract\" at the same time";
313               goto bad_address;
314             }
315
316           if (tmpdir != NULL)
317             {
318               DBusString full_path;
319               DBusString filename;
320               
321               if (!_dbus_string_init (&full_path))
322                 {
323                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
324                   goto out;
325                 }
326                   
327               if (!_dbus_string_init (&filename))
328                 {
329                   _dbus_string_free (&full_path);
330                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
331                   goto out;
332                 }
333               
334               if (!_dbus_string_append (&filename,
335                                         "dbus-") ||
336                   !_dbus_generate_random_ascii (&filename, 10) ||
337                   !_dbus_string_append (&full_path, tmpdir) ||
338                   !_dbus_concat_dir_and_file (&full_path, &filename))
339                 {
340                   _dbus_string_free (&full_path);
341                   _dbus_string_free (&filename);
342                   dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
343                   goto out;
344                 }
345               
346               /* FIXME - we will unconditionally unlink() the path if
347                * we don't support abstract namespace.  unlink() does
348                * not follow symlinks, but would like independent
349                * confirmation this is safe enough. See also
350                * _dbus_listen_unix_socket() and comments therein.
351                */
352
353               /* Always use abstract namespace if possible with tmpdir */
354               
355               server =
356                 _dbus_server_new_for_domain_socket (_dbus_string_get_const_data (&full_path),
357 #ifdef HAVE_ABSTRACT_SOCKETS
358                                                     TRUE,
359 #else
360                                                     FALSE,
361 #endif
362                                                     error);
363
364               _dbus_string_free (&full_path);
365               _dbus_string_free (&filename);
366             }
367           else
368             {
369               if (path)
370                 server = _dbus_server_new_for_domain_socket (path, FALSE, error);
371               else
372                 server = _dbus_server_new_for_domain_socket (abstract, TRUE, error);
373             }
374         }
375       else if (strcmp (method, "tcp") == 0)
376         {
377           const char *host = dbus_address_entry_get_value (entries[i], "host");
378           const char *port = dbus_address_entry_get_value (entries[i], "port");
379           DBusString  str;
380           long lport;
381           dbus_bool_t sresult;
382           
383           if (port == NULL)
384             {
385               address_problem_type = "tcp";
386               address_problem_field = "port";
387               goto bad_address;
388             }
389
390           _dbus_string_init_const (&str, port);
391           sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
392           _dbus_string_free (&str);
393           
394           if (sresult == FALSE || lport <= 0 || lport > 65535)
395             {
396               address_problem_other = "Port is not an integer between 0 and 65535";
397               goto bad_address;
398             }
399           
400           server = _dbus_server_new_for_tcp_socket (host, lport, error);
401
402           if (server)
403             break;
404         }
405 #ifdef DBUS_BUILD_TESTS
406       else if (strcmp (method, "debug-pipe") == 0)
407         {
408           const char *name = dbus_address_entry_get_value (entries[i], "name");
409
410           if (name == NULL)
411             {
412               address_problem_type = "debug-pipe";
413               address_problem_field = "name";
414               goto bad_address;
415             }
416
417           server = _dbus_server_debug_pipe_new (name, error);
418         }
419 #endif
420       else
421         {
422           address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
423           goto bad_address;
424         }
425       
426       if (server)
427         break;
428     }
429
430  out:
431   
432   dbus_address_entries_free (entries);
433   return server;
434
435  bad_address:
436   dbus_address_entries_free (entries);
437   if (address_problem_type != NULL)
438     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
439                     "Server address of type %s was missing argument %s",
440                     address_problem_type, address_problem_field);
441   else
442     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
443                     "Could not parse server address: %s",
444                     address_problem_other);
445
446   return NULL;
447 }
448
449 /**
450  * Increments the reference count of a DBusServer.
451  *
452  * @param server the server.
453  */
454 void
455 dbus_server_ref (DBusServer *server)
456 {
457   _dbus_return_if_fail (server != NULL);
458   
459   server->refcount += 1;
460 }
461
462 /**
463  * Decrements the reference count of a DBusServer.  Finalizes the
464  * server if the reference count reaches zero. The server connection
465  * will be closed as with dbus_server_disconnect() when the server is
466  * finalized.
467  *
468  * @param server the server.
469  */
470 void
471 dbus_server_unref (DBusServer *server)
472 {
473   _dbus_return_if_fail (server != NULL);
474
475   _dbus_assert (server->refcount > 0);
476
477   server->refcount -= 1;
478   if (server->refcount == 0)
479     {
480       _dbus_assert (server->vtable->finalize != NULL);
481       
482       (* server->vtable->finalize) (server);
483     }
484 }
485
486 /**
487  * Releases the server's address and stops listening for
488  * new clients. If called more than once, only the first
489  * call has an effect. Does not modify the server's
490  * reference count.
491  * 
492  * @param server the server.
493  */
494 void
495 dbus_server_disconnect (DBusServer *server)
496 {
497   _dbus_return_if_fail (server != NULL);
498   
499   _dbus_assert (server->vtable->disconnect != NULL);
500
501   if (server->disconnected)
502     return;
503   
504   (* server->vtable->disconnect) (server);
505   server->disconnected = TRUE;
506 }
507
508 /**
509  * Returns #TRUE if the server is still listening for new connections.
510  *
511  * @param server the server.
512  */
513 dbus_bool_t
514 dbus_server_get_is_connected (DBusServer *server)
515 {
516   _dbus_return_val_if_fail (server != NULL, FALSE);
517   
518   return !server->disconnected;
519 }
520
521 /**
522  * Returns the address of the server, as a newly-allocated
523  * string which must be freed by the caller.
524  *
525  * @param server the server
526  * @returns the address or #NULL if no memory
527  */
528 char*
529 dbus_server_get_address (DBusServer *server)
530 {
531   _dbus_return_val_if_fail (server != NULL, NULL);
532   
533   return _dbus_strdup (server->address);
534 }
535
536 /**
537  * Sets a function to be used for handling new connections.  The given
538  * function is passed each new connection as the connection is
539  * created. If the new connection function increments the connection's
540  * reference count, the connection will stay alive. Otherwise, the
541  * connection will be unreferenced and closed.
542  *
543  * @param server the server.
544  * @param function a function to handle new connections.
545  * @param data data to pass to the new connection handler.
546  * @param free_data_function function to free the data.
547  */
548 void
549 dbus_server_set_new_connection_function (DBusServer                *server,
550                                          DBusNewConnectionFunction  function,
551                                          void                      *data,
552                                          DBusFreeFunction           free_data_function)
553 {
554   _dbus_return_if_fail (server != NULL);
555   
556   if (server->new_connection_free_data_function != NULL)
557     (* server->new_connection_free_data_function) (server->new_connection_data);
558   
559   server->new_connection_function = function;
560   server->new_connection_data = data;
561   server->new_connection_free_data_function = free_data_function;
562 }
563
564 /**
565  * Sets the watch functions for the connection. These functions are
566  * responsible for making the application's main loop aware of file
567  * descriptors that need to be monitored for events.
568  *
569  * This function behaves exactly like dbus_connection_set_watch_functions();
570  * see the documentation for that routine.
571  *
572  * @param server the server.
573  * @param add_function function to begin monitoring a new descriptor.
574  * @param remove_function function to stop monitoring a descriptor.
575  * @param toggled_function function to notify when the watch is enabled/disabled
576  * @param data data to pass to add_function and remove_function.
577  * @param free_data_function function to be called to free the data.
578  * @returns #FALSE on failure (no memory)
579  */
580 dbus_bool_t
581 dbus_server_set_watch_functions (DBusServer              *server,
582                                  DBusAddWatchFunction     add_function,
583                                  DBusRemoveWatchFunction  remove_function,
584                                  DBusWatchToggledFunction toggled_function,
585                                  void                    *data,
586                                  DBusFreeFunction         free_data_function)
587 {
588   _dbus_return_val_if_fail (server != NULL, FALSE);
589   
590   return _dbus_watch_list_set_functions (server->watches,
591                                          add_function,
592                                          remove_function,
593                                          toggled_function,
594                                          data,
595                                          free_data_function);
596 }
597
598 /**
599  * Sets the timeout functions for the connection. These functions are
600  * responsible for making the application's main loop aware of timeouts.
601  *
602  * This function behaves exactly like dbus_connection_set_timeout_functions();
603  * see the documentation for that routine.
604  *
605  * @param server the server.
606  * @param add_function function to add a timeout.
607  * @param remove_function function to remove a timeout.
608  * @param toggled_function function to notify when the timeout is enabled/disabled
609  * @param data data to pass to add_function and remove_function.
610  * @param free_data_function function to be called to free the data.
611  * @returns #FALSE on failure (no memory)
612  */
613 dbus_bool_t
614 dbus_server_set_timeout_functions (DBusServer                *server,
615                                    DBusAddTimeoutFunction     add_function,
616                                    DBusRemoveTimeoutFunction  remove_function,
617                                    DBusTimeoutToggledFunction toggled_function,
618                                    void                      *data,
619                                    DBusFreeFunction           free_data_function)
620 {
621   _dbus_return_val_if_fail (server != NULL, FALSE);
622   
623   return _dbus_timeout_list_set_functions (server->timeouts,
624                                            add_function, remove_function,
625                                            toggled_function,
626                                            data, free_data_function); 
627 }
628
629 /**
630  * Sets the authentication mechanisms that this server offers
631  * to clients, as a list of SASL mechanisms. This function
632  * only affects connections created *after* it is called.
633  * Pass #NULL instead of an array to use all available mechanisms.
634  *
635  * @param server the server
636  * @param mechanisms #NULL-terminated array of mechanisms
637  * @returns #FALSE if no memory
638  */
639 dbus_bool_t
640 dbus_server_set_auth_mechanisms (DBusServer  *server,
641                                  const char **mechanisms)
642 {
643   char **copy;
644
645   _dbus_return_val_if_fail (server != NULL, FALSE);
646   
647   if (mechanisms != NULL)
648     {
649       copy = _dbus_dup_string_array (mechanisms);
650       if (copy == NULL)
651         return FALSE;
652     }
653   else
654     copy = NULL;
655
656   dbus_free_string_array (server->auth_mechanisms);
657   server->auth_mechanisms = copy;
658
659   return TRUE;
660 }
661
662
663 static DBusDataSlotAllocator slot_allocator;
664 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
665
666 /**
667  * Allocates an integer ID to be used for storing application-specific
668  * data on any DBusServer. The allocated ID may then be used
669  * with dbus_server_set_data() and dbus_server_get_data().
670  * The slot must be initialized with -1. If a nonnegative
671  * slot is passed in, the refcount is incremented on that
672  * slot, rather than creating a new slot.
673  *  
674  * The allocated slot is global, i.e. all DBusServer objects will have
675  * a slot with the given integer ID reserved.
676  *
677  * @param slot_p address of global variable storing the slot ID
678  * @returns #FALSE on no memory
679  */
680 dbus_bool_t
681 dbus_server_allocate_data_slot (dbus_int32_t *slot_p)
682 {
683   return _dbus_data_slot_allocator_alloc (&slot_allocator,
684                                           _DBUS_LOCK_NAME (server_slots),
685                                           slot_p);
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_p address of the slot to deallocate
698  */
699 void
700 dbus_server_free_data_slot (dbus_int32_t *slot_p)
701 {
702   _dbus_return_if_fail (*slot_p >= 0);
703   
704   _dbus_data_slot_allocator_free (&slot_allocator, slot_p);
705 }
706
707 /**
708  * Stores a pointer on a DBusServer, along
709  * with an optional function to be used for freeing
710  * the data when the data is set again, or when
711  * the server is finalized. The slot number
712  * must have been allocated with dbus_server_allocate_data_slot().
713  *
714  * @param server the server
715  * @param slot the slot number
716  * @param data the data to store
717  * @param free_data_func finalizer function for the data
718  * @returns #TRUE if there was enough memory to store the data
719  */
720 dbus_bool_t
721 dbus_server_set_data (DBusServer       *server,
722                       int               slot,
723                       void             *data,
724                       DBusFreeFunction  free_data_func)
725 {
726   DBusFreeFunction old_free_func;
727   void *old_data;
728   dbus_bool_t retval;
729
730   _dbus_return_val_if_fail (server != NULL, FALSE);
731   
732 #if 0
733   dbus_mutex_lock (server->mutex);
734 #endif
735   
736   retval = _dbus_data_slot_list_set (&slot_allocator,
737                                      &server->slot_list,
738                                      slot, data, free_data_func,
739                                      &old_free_func, &old_data);
740
741 #if 0
742   dbus_mutex_unlock (server->mutex);
743 #endif
744   
745   if (retval)
746     {
747       /* Do the actual free outside the server lock */
748       if (old_free_func)
749         (* old_free_func) (old_data);
750     }
751
752   return retval;
753 }
754
755 /**
756  * Retrieves data previously set with dbus_server_set_data().
757  * The slot must still be allocated (must not have been freed).
758  *
759  * @param server the server
760  * @param slot the slot to get data from
761  * @returns the data, or #NULL if not found
762  */
763 void*
764 dbus_server_get_data (DBusServer   *server,
765                       int           slot)
766 {
767   void *res;
768
769   _dbus_return_val_if_fail (server != NULL, NULL);
770   
771 #if 0
772   dbus_mutex_lock (server->mutex);
773 #endif
774   
775   res = _dbus_data_slot_list_get (&slot_allocator,
776                                   &server->slot_list,
777                                   slot);
778
779 #if 0
780   dbus_mutex_unlock (server->mutex);
781 #endif
782   
783   return res;
784 }
785
786 /** @} */
787