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