2003-05-08 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-pipe.h"
28 #endif
29 #include "dbus-address.h"
30
31 /**
32  * @defgroup DBusServer DBusServer
33  * @ingroup  DBus
34  * @brief Server that listens for new connections.
35  *
36  * Types and functions related to DBusServer.
37  * A DBusServer represents a server that other applications
38  * can connect to. Each connection from another application
39  * is represented by a DBusConnection.
40  *
41  * @todo Thread safety hasn't been looked at for #DBusServer
42  * @todo Need notification to apps of disconnection, may matter for some transports
43  */
44
45 /**
46  * @defgroup DBusServerInternals DBusServer implementation details
47  * @ingroup  DBusInternals
48  * @brief Implementation details of DBusServer
49  *
50  * @{
51  */
52
53 /**
54  * Initializes the members of the DBusServer base class.
55  * Chained up to by subclass constructors.
56  *
57  * @param server the server.
58  * @param vtable the vtable for the subclass.
59  * @param address the server's address
60  * @returns #TRUE on success.
61  */
62 dbus_bool_t
63 _dbus_server_init_base (DBusServer             *server,
64                         const DBusServerVTable *vtable,
65                         const DBusString       *address)
66 {
67   server->vtable = vtable;
68   server->refcount = 1;
69
70   server->address = NULL;
71   server->watches = NULL;
72   server->timeouts = NULL;
73   
74   if (!_dbus_string_copy_data (address, &server->address))
75     goto failed;
76   
77   server->watches = _dbus_watch_list_new ();
78   if (server->watches == NULL)
79     goto failed;
80
81   server->timeouts = _dbus_timeout_list_new ();
82   if (server->timeouts == NULL)
83     goto failed;
84
85   _dbus_data_slot_list_init (&server->slot_list);
86
87   _dbus_verbose ("Initialized server on address %s\n", server->address);
88   
89   return TRUE;
90
91  failed:
92   if (server->watches)
93     {
94       _dbus_watch_list_free (server->watches);
95       server->watches = NULL;
96     }
97   if (server->timeouts)
98     {
99       _dbus_timeout_list_free (server->timeouts);
100       server->timeouts = NULL;
101     }
102   if (server->address)
103     {
104       dbus_free (server->address);
105       server->address = NULL;
106     }
107   
108   return FALSE;
109 }
110
111 /**
112  * Finalizes the members of the DBusServer base class.
113  * Chained up to by subclass finalizers.
114  *
115  * @param server the server.
116  */
117 void
118 _dbus_server_finalize_base (DBusServer *server)
119 {
120   /* calls out to application code... */
121   _dbus_data_slot_list_free (&server->slot_list);
122
123   dbus_server_set_new_connection_function (server, NULL, NULL, NULL);
124
125   if (!server->disconnected)
126     dbus_server_disconnect (server);
127
128   _dbus_watch_list_free (server->watches);
129   _dbus_timeout_list_free (server->timeouts);
130
131   dbus_free (server->address);
132
133   dbus_free_string_array (server->auth_mechanisms);
134 }
135
136 /**
137  * Adds a watch for this server, chaining out to application-provided
138  * watch handlers.
139  *
140  * @param server the server.
141  * @param watch the watch to add.
142  */
143 dbus_bool_t
144 _dbus_server_add_watch (DBusServer *server,
145                         DBusWatch  *watch)
146 {
147   return _dbus_watch_list_add_watch (server->watches, watch);
148 }
149
150 /**
151  * Removes a watch previously added with _dbus_server_remove_watch().
152  *
153  * @param server the server.
154  * @param watch the watch to remove.
155  */
156 void
157 _dbus_server_remove_watch  (DBusServer *server,
158                             DBusWatch  *watch)
159 {
160   _dbus_watch_list_remove_watch (server->watches, watch);
161 }
162
163 /**
164  * Toggles a watch and notifies app via server's
165  * DBusWatchToggledFunction if available. It's an error to call this
166  * function on a watch that was not previously added.
167  *
168  * @param server the server.
169  * @param watch the watch to toggle.
170  * @param enabled whether to enable or disable
171  */
172 void
173 _dbus_server_toggle_watch (DBusServer  *server,
174                            DBusWatch   *watch,
175                            dbus_bool_t  enabled)
176 {
177   if (server->watches) /* null during finalize */
178     _dbus_watch_list_toggle_watch (server->watches,
179                                    watch, enabled);
180 }
181
182 /**
183  * Adds a timeout for this server, chaining out to
184  * application-provided timeout handlers. The timeout should be
185  * repeatedly handled with dbus_timeout_handle() at its given interval
186  * until it is removed.
187  *
188  * @param server the server.
189  * @param timeout the timeout to add.
190  */
191 dbus_bool_t
192 _dbus_server_add_timeout (DBusServer  *server,
193                           DBusTimeout *timeout)
194 {
195   return _dbus_timeout_list_add_timeout (server->timeouts, timeout);
196 }
197
198 /**
199  * Removes a timeout previously added with _dbus_server_add_timeout().
200  *
201  * @param server the server.
202  * @param timeout the timeout to remove.
203  */
204 void
205 _dbus_server_remove_timeout (DBusServer  *server,
206                              DBusTimeout *timeout)
207 {
208   _dbus_timeout_list_remove_timeout (server->timeouts, timeout);  
209 }
210
211 /**
212  * Toggles a timeout and notifies app via server's
213  * DBusTimeoutToggledFunction if available. It's an error to call this
214  * function on a timeout that was not previously added.
215  *
216  * @param server the server.
217  * @param timeout the timeout to toggle.
218  * @param enabled whether to enable or disable
219  */
220 void
221 _dbus_server_toggle_timeout (DBusServer  *server,
222                              DBusTimeout *timeout,
223                              dbus_bool_t  enabled)
224 {
225   if (server->timeouts) /* null during finalize */
226     _dbus_timeout_list_toggle_timeout (server->timeouts,
227                                        timeout, enabled);
228 }
229
230
231 /** @} */
232
233 /**
234  * @addtogroup DBusServer
235  *
236  * @{
237  */
238
239
240 /**
241  * @typedef DBusServer
242  *
243  * An opaque object representing a server that listens for
244  * connections from other applications. Each time a connection
245  * is made, a new DBusConnection is created and made available
246  * via an application-provided DBusNewConnectionFunction.
247  * The DBusNewConnectionFunction is provided with
248  * dbus_server_set_new_connection_function().
249  * 
250  */
251
252 /**
253  * Listens for new connections on the given address.
254  * Returns #NULL if listening fails for any reason.
255  * Otherwise returns a new #DBusServer.
256  * dbus_server_set_new_connection_function() and
257  * dbus_server_set_watch_functions() should be called
258  * immediately to render the server fully functional.
259  *
260  * @todo error messages on bad address could really be better.
261  * DBusResultCode is a bit limiting here.
262  *
263  * @param address the address of this server.
264  * @param error location to store rationale for failure.
265  * @returns a new DBusServer, or #NULL on failure.
266  * 
267  */
268 DBusServer*
269 dbus_server_listen (const char     *address,
270                     DBusError      *error)
271 {
272   DBusServer *server;
273   DBusAddressEntry **entries;
274   int len, i;
275   const char *address_problem_type;
276   const char *address_problem_field;
277   const char *address_problem_other;
278
279   _dbus_return_val_if_fail (address != NULL, NULL);
280   _dbus_return_val_if_error_is_set (error, NULL);
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-pipe") == 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-pipe";
398               address_problem_field = "name";
399               goto bad_address;
400             }
401
402           server = _dbus_server_debug_pipe_new (name, error);
403         }
404 #endif
405       else
406         {
407           address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
408           goto bad_address;
409         }
410       
411       if (server)
412         break;
413     }
414
415  out:
416   
417   dbus_address_entries_free (entries);
418   return server;
419
420  bad_address:
421   dbus_address_entries_free (entries);
422   if (address_problem_type != NULL)
423     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
424                     "Server address of type %s was missing argument %s",
425                     address_problem_type, address_problem_field);
426   else
427     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
428                     "Could not parse server address: %s",
429                     address_problem_other);
430
431   return NULL;
432 }
433
434 /**
435  * Increments the reference count of a DBusServer.
436  *
437  * @param server the server.
438  */
439 void
440 dbus_server_ref (DBusServer *server)
441 {
442   _dbus_return_if_fail (server != NULL);
443   
444   server->refcount += 1;
445 }
446
447 /**
448  * Decrements the reference count of a DBusServer.  Finalizes the
449  * server if the reference count reaches zero. The server connection
450  * will be closed as with dbus_server_disconnect() when the server is
451  * finalized.
452  *
453  * @param server the server.
454  */
455 void
456 dbus_server_unref (DBusServer *server)
457 {
458   _dbus_return_if_fail (server != NULL);
459
460   _dbus_assert (server->refcount > 0);
461
462   server->refcount -= 1;
463   if (server->refcount == 0)
464     {
465       _dbus_assert (server->vtable->finalize != NULL);
466       
467       (* server->vtable->finalize) (server);
468     }
469 }
470
471 /**
472  * Releases the server's address and stops listening for
473  * new clients. If called more than once, only the first
474  * call has an effect. Does not modify the server's
475  * reference count.
476  * 
477  * @param server the server.
478  */
479 void
480 dbus_server_disconnect (DBusServer *server)
481 {
482   _dbus_return_if_fail (server != NULL);
483   
484   _dbus_assert (server->vtable->disconnect != NULL);
485
486   if (server->disconnected)
487     return;
488   
489   (* server->vtable->disconnect) (server);
490   server->disconnected = TRUE;
491 }
492
493 /**
494  * Returns #TRUE if the server is still listening for new connections.
495  *
496  * @param server the server.
497  */
498 dbus_bool_t
499 dbus_server_get_is_connected (DBusServer *server)
500 {
501   _dbus_return_val_if_fail (server != NULL, FALSE);
502   
503   return !server->disconnected;
504 }
505
506 /**
507  * Returns the address of the server, as a newly-allocated
508  * string which must be freed by the caller.
509  *
510  * @param server the server
511  * @returns the address or #NULL if no memory
512  */
513 char*
514 dbus_server_get_address (DBusServer *server)
515 {
516   _dbus_return_val_if_fail (server != NULL, NULL);
517   
518   return _dbus_strdup (server->address);
519 }
520
521 /**
522  * Sets a function to be used for handling new connections.  The given
523  * function is passed each new connection as the connection is
524  * created. If the new connection function increments the connection's
525  * reference count, the connection will stay alive. Otherwise, the
526  * connection will be unreferenced and closed.
527  *
528  * @param server the server.
529  * @param function a function to handle new connections.
530  * @param data data to pass to the new connection handler.
531  * @param free_data_function function to free the data.
532  */
533 void
534 dbus_server_set_new_connection_function (DBusServer                *server,
535                                          DBusNewConnectionFunction  function,
536                                          void                      *data,
537                                          DBusFreeFunction           free_data_function)
538 {
539   _dbus_return_if_fail (server != NULL);
540   
541   if (server->new_connection_free_data_function != NULL)
542     (* server->new_connection_free_data_function) (server->new_connection_data);
543   
544   server->new_connection_function = function;
545   server->new_connection_data = data;
546   server->new_connection_free_data_function = free_data_function;
547 }
548
549 /**
550  * Sets the watch functions for the connection. These functions are
551  * responsible for making the application's main loop aware of file
552  * descriptors that need to be monitored for events.
553  *
554  * This function behaves exactly like dbus_connection_set_watch_functions();
555  * see the documentation for that routine.
556  *
557  * @param server the server.
558  * @param add_function function to begin monitoring a new descriptor.
559  * @param remove_function function to stop monitoring a descriptor.
560  * @param toggled_function function to notify when the watch is enabled/disabled
561  * @param data data to pass to add_function and remove_function.
562  * @param free_data_function function to be called to free the data.
563  * @returns #FALSE on failure (no memory)
564  */
565 dbus_bool_t
566 dbus_server_set_watch_functions (DBusServer              *server,
567                                  DBusAddWatchFunction     add_function,
568                                  DBusRemoveWatchFunction  remove_function,
569                                  DBusWatchToggledFunction toggled_function,
570                                  void                    *data,
571                                  DBusFreeFunction         free_data_function)
572 {
573   _dbus_return_val_if_fail (server != NULL, FALSE);
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   _dbus_return_val_if_fail (server != NULL, FALSE);
607   
608   return _dbus_timeout_list_set_functions (server->timeouts,
609                                            add_function, remove_function,
610                                            toggled_function,
611                                            data, free_data_function); 
612 }
613
614 /**
615  * Sets the authentication mechanisms that this server offers
616  * to clients, as a list of SASL mechanisms. This function
617  * only affects connections created *after* it is called.
618  * Pass #NULL instead of an array to use all available mechanisms.
619  *
620  * @param server the server
621  * @param mechanisms #NULL-terminated array of mechanisms
622  * @returns #FALSE if no memory
623  */
624 dbus_bool_t
625 dbus_server_set_auth_mechanisms (DBusServer  *server,
626                                  const char **mechanisms)
627 {
628   char **copy;
629
630   _dbus_return_val_if_fail (server != NULL, FALSE);
631   
632   if (mechanisms != NULL)
633     {
634       copy = _dbus_dup_string_array (mechanisms);
635       if (copy == NULL)
636         return FALSE;
637     }
638   else
639     copy = NULL;
640
641   dbus_free_string_array (server->auth_mechanisms);
642   server->auth_mechanisms = copy;
643
644   return TRUE;
645 }
646
647
648 static DBusDataSlotAllocator slot_allocator;
649 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
650
651 /**
652  * Allocates an integer ID to be used for storing application-specific
653  * data on any DBusServer. The allocated ID may then be used
654  * with dbus_server_set_data() and dbus_server_get_data().
655  * If allocation fails, -1 is returned. Again, the allocated
656  * slot is global, i.e. all DBusServer objects will
657  * have a slot with the given integer ID reserved.
658  *
659  * @returns -1 on failure, otherwise the data slot ID
660  */
661 int
662 dbus_server_allocate_data_slot (void)
663 {
664   return _dbus_data_slot_allocator_alloc (&slot_allocator,
665                                           _DBUS_LOCK_NAME (server_slots));
666 }
667
668 /**
669  * Deallocates a global ID for server data slots.
670  * dbus_server_get_data() and dbus_server_set_data()
671  * may no longer be used with this slot.
672  * Existing data stored on existing DBusServer objects
673  * will be freed when the server is finalized,
674  * but may not be retrieved (and may only be replaced
675  * if someone else reallocates the slot).
676  *
677  * @param slot the slot to deallocate
678  */
679 void
680 dbus_server_free_data_slot (int slot)
681 {
682   _dbus_return_if_fail (slot >= 0);
683   
684   _dbus_data_slot_allocator_free (&slot_allocator, slot);
685 }
686
687 /**
688  * Stores a pointer on a DBusServer, along
689  * with an optional function to be used for freeing
690  * the data when the data is set again, or when
691  * the server is finalized. The slot number
692  * must have been allocated with dbus_server_allocate_data_slot().
693  *
694  * @param server the server
695  * @param slot the slot number
696  * @param data the data to store
697  * @param free_data_func finalizer function for the data
698  * @returns #TRUE if there was enough memory to store the data
699  */
700 dbus_bool_t
701 dbus_server_set_data (DBusServer       *server,
702                       int               slot,
703                       void             *data,
704                       DBusFreeFunction  free_data_func)
705 {
706   DBusFreeFunction old_free_func;
707   void *old_data;
708   dbus_bool_t retval;
709
710   _dbus_return_val_if_fail (server != NULL, FALSE);
711   
712 #if 0
713   dbus_mutex_lock (server->mutex);
714 #endif
715   
716   retval = _dbus_data_slot_list_set (&slot_allocator,
717                                      &server->slot_list,
718                                      slot, data, free_data_func,
719                                      &old_free_func, &old_data);
720
721 #if 0
722   dbus_mutex_unlock (server->mutex);
723 #endif
724   
725   if (retval)
726     {
727       /* Do the actual free outside the server lock */
728       if (old_free_func)
729         (* old_free_func) (old_data);
730     }
731
732   return retval;
733 }
734
735 /**
736  * Retrieves data previously set with dbus_server_set_data().
737  * The slot must still be allocated (must not have been freed).
738  *
739  * @param server the server
740  * @param slot the slot to get data from
741  * @returns the data, or #NULL if not found
742  */
743 void*
744 dbus_server_get_data (DBusServer   *server,
745                       int           slot)
746 {
747   void *res;
748
749   _dbus_return_val_if_fail (server != NULL, NULL);
750   
751 #if 0
752   dbus_mutex_lock (server->mutex);
753 #endif
754   
755   res = _dbus_data_slot_list_get (&slot_allocator,
756                                   &server->slot_list,
757                                   slot);
758
759 #if 0
760   dbus_mutex_unlock (server->mutex);
761 #endif
762   
763   return res;
764 }
765
766 /** @} */
767