2003-04-05 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
309           if (path == NULL)
310             {
311               address_problem_type = "unix";
312               address_problem_field = "path";
313               goto bad_address;
314             }
315
316           server = _dbus_server_new_for_domain_socket (path, error);
317
318           if (server)
319             break;
320         }
321       else if (strcmp (method, "tcp") == 0)
322         {
323           const char *host = dbus_address_entry_get_value (entries[i], "host");
324           const char *port = dbus_address_entry_get_value (entries[i], "port");
325           DBusString  str;
326           long lport;
327           dbus_bool_t sresult;
328           
329           if (port == NULL)
330             {
331               address_problem_type = "tcp";
332               address_problem_field = "port";
333               goto bad_address;
334             }
335
336           _dbus_string_init_const (&str, port);
337           sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
338           _dbus_string_free (&str);
339           
340           if (sresult == FALSE || lport <= 0 || lport > 65535)
341             {
342               address_problem_other = "Port is not an integer between 0 and 65535";
343               goto bad_address;
344             }
345           
346           server = _dbus_server_new_for_tcp_socket (host, lport, error);
347
348           if (server)
349             break;
350         }
351 #ifdef DBUS_BUILD_TESTS
352       else if (strcmp (method, "debug") == 0)
353         {
354           const char *name = dbus_address_entry_get_value (entries[i], "name");
355
356           if (name == NULL)
357             {
358               address_problem_type = "debug";
359               address_problem_field = "name";
360               goto bad_address;
361             }
362
363           server = _dbus_server_debug_new (name, error);
364
365           if (server)
366             break;
367         }
368       else if (strcmp (method, "debug-pipe") == 0)
369         {
370           const char *name = dbus_address_entry_get_value (entries[i], "name");
371
372           if (name == NULL)
373             {
374               address_problem_type = "debug-pipe";
375               address_problem_field = "name";
376               goto bad_address;
377             }
378
379           server = _dbus_server_debug_pipe_new (name, error);
380
381           if (server)
382             break;
383         }
384 #endif
385       else
386         {
387           address_problem_other = "Unknown address type (examples of valid types are \"unix\" and \"tcp\")";
388           goto bad_address;
389         }
390     }
391   
392   dbus_address_entries_free (entries);
393   return server;
394
395  bad_address:
396   dbus_address_entries_free (entries);
397   if (address_problem_type != NULL)
398     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
399                     "Server address of type %s was missing argument %s",
400                     address_problem_type, address_problem_field);
401   else
402     dbus_set_error (error, DBUS_ERROR_BAD_ADDRESS,
403                     "Could not parse server address: %s",
404                     address_problem_other);
405
406   return NULL;
407 }
408
409 /**
410  * Increments the reference count of a DBusServer.
411  *
412  * @param server the server.
413  */
414 void
415 dbus_server_ref (DBusServer *server)
416 {
417   server->refcount += 1;
418 }
419
420 /**
421  * Decrements the reference count of a DBusServer.  Finalizes the
422  * server if the reference count reaches zero. The server connection
423  * will be closed as with dbus_server_disconnect() when the server is
424  * finalized.
425  *
426  * @param server the server.
427  */
428 void
429 dbus_server_unref (DBusServer *server)
430 {
431   _dbus_assert (server != NULL);
432   _dbus_assert (server->refcount > 0);
433
434   server->refcount -= 1;
435   if (server->refcount == 0)
436     {
437       _dbus_assert (server->vtable->finalize != NULL);
438       
439       (* server->vtable->finalize) (server);
440     }
441 }
442
443 /**
444  * Releases the server's address and stops listening for
445  * new clients. If called more than once, only the first
446  * call has an effect. Does not modify the server's
447  * reference count.
448  * 
449  * @param server the server.
450  */
451 void
452 dbus_server_disconnect (DBusServer *server)
453 {
454   _dbus_assert (server->vtable->disconnect != NULL);
455
456   if (server->disconnected)
457     return;
458   
459   (* server->vtable->disconnect) (server);
460   server->disconnected = TRUE;
461 }
462
463 /**
464  * Returns #TRUE if the server is still listening for new connections.
465  *
466  * @param server the server.
467  */
468 dbus_bool_t
469 dbus_server_get_is_connected (DBusServer *server)
470 {
471   return !server->disconnected;
472 }
473
474 /**
475  * Returns the address of the server, as a newly-allocated
476  * string which must be freed by the caller.
477  *
478  * @param server the server
479  * @returns the address or #NULL if no memory
480  */
481 char*
482 dbus_server_get_address (DBusServer *server)
483 {
484   return _dbus_strdup (server->address);
485 }
486
487 /**
488  * Sets a function to be used for handling new connections.  The given
489  * function is passed each new connection as the connection is
490  * created. If the new connection function increments the connection's
491  * reference count, the connection will stay alive. Otherwise, the
492  * connection will be unreferenced and closed.
493  *
494  * @param server the server.
495  * @param function a function to handle new connections.
496  * @param data data to pass to the new connection handler.
497  * @param free_data_function function to free the data.
498  */
499 void
500 dbus_server_set_new_connection_function (DBusServer                *server,
501                                          DBusNewConnectionFunction  function,
502                                          void                      *data,
503                                          DBusFreeFunction           free_data_function)
504 {
505   if (server->new_connection_free_data_function != NULL)
506     (* server->new_connection_free_data_function) (server->new_connection_data);
507   
508   server->new_connection_function = function;
509   server->new_connection_data = data;
510   server->new_connection_free_data_function = free_data_function;
511 }
512
513 /**
514  * Sets the watch functions for the connection. These functions are
515  * responsible for making the application's main loop aware of file
516  * descriptors that need to be monitored for events.
517  *
518  * This function behaves exactly like dbus_connection_set_watch_functions();
519  * see the documentation for that routine.
520  *
521  * @param server the server.
522  * @param add_function function to begin monitoring a new descriptor.
523  * @param remove_function function to stop monitoring a descriptor.
524  * @param toggled_function function to notify when the watch is enabled/disabled
525  * @param data data to pass to add_function and remove_function.
526  * @param free_data_function function to be called to free the data.
527  * @returns #FALSE on failure (no memory)
528  */
529 dbus_bool_t
530 dbus_server_set_watch_functions (DBusServer              *server,
531                                  DBusAddWatchFunction     add_function,
532                                  DBusRemoveWatchFunction  remove_function,
533                                  DBusWatchToggledFunction toggled_function,
534                                  void                    *data,
535                                  DBusFreeFunction         free_data_function)
536 {
537   return _dbus_watch_list_set_functions (server->watches,
538                                          add_function,
539                                          remove_function,
540                                          toggled_function,
541                                          data,
542                                          free_data_function);
543 }
544
545 /**
546  * Sets the timeout functions for the connection. These functions are
547  * responsible for making the application's main loop aware of timeouts.
548  *
549  * This function behaves exactly like dbus_connection_set_timeout_functions();
550  * see the documentation for that routine.
551  *
552  * @param server the server.
553  * @param add_function function to add a timeout.
554  * @param remove_function function to remove a timeout.
555  * @param toggled_function function to notify when the timeout is enabled/disabled
556  * @param data data to pass to add_function and remove_function.
557  * @param free_data_function function to be called to free the data.
558  * @returns #FALSE on failure (no memory)
559  */
560 dbus_bool_t
561 dbus_server_set_timeout_functions (DBusServer                *server,
562                                    DBusAddTimeoutFunction     add_function,
563                                    DBusRemoveTimeoutFunction  remove_function,
564                                    DBusTimeoutToggledFunction toggled_function,
565                                    void                      *data,
566                                    DBusFreeFunction           free_data_function)
567 {
568   return _dbus_timeout_list_set_functions (server->timeouts,
569                                            add_function, remove_function,
570                                            toggled_function,
571                                            data, free_data_function); 
572 }
573
574 /**
575  * Called to notify the server when a previously-added watch
576  * is ready for reading or writing, or has an exception such
577  * as a hangup.
578  * 
579  * If this function returns #FALSE, then the file descriptor may still
580  * be ready for reading or writing, but more memory is needed in order
581  * to do the reading or writing. If you ignore the #FALSE return, your
582  * application may spin in a busy loop on the file descriptor until
583  * memory becomes available, but nothing more catastrophic should
584  * happen.
585  *
586  * @param server the server.
587  * @param watch the watch.
588  * @param condition the current condition of the file descriptors being watched.
589  */
590 dbus_bool_t
591 dbus_server_handle_watch (DBusServer              *server,
592                           DBusWatch               *watch,
593                           unsigned int             condition)
594 {
595   _dbus_assert (server->vtable->handle_watch != NULL);
596
597   _dbus_watch_sanitize_condition (watch, &condition);
598   
599   return (* server->vtable->handle_watch) (server, watch, condition);
600 }
601
602 /**
603  * Sets the authentication mechanisms that this server offers
604  * to clients, as a list of SASL mechanisms. This function
605  * only affects connections created *after* it is called.
606  * Pass #NULL instead of an array to use all available mechanisms.
607  *
608  * @param server the server
609  * @param mechanisms #NULL-terminated array of mechanisms
610  * @returns #FALSE if no memory
611  */
612 dbus_bool_t
613 dbus_server_set_auth_mechanisms (DBusServer  *server,
614                                  const char **mechanisms)
615 {
616   char **copy;
617
618   if (mechanisms != NULL)
619     {
620       copy = _dbus_dup_string_array (mechanisms);
621       if (copy == NULL)
622         return FALSE;
623     }
624   else
625     copy = NULL;
626
627   dbus_free_string_array (server->auth_mechanisms);
628   server->auth_mechanisms = copy;
629
630   return TRUE;
631 }
632
633
634 static DBusDataSlotAllocator slot_allocator;
635 _DBUS_DEFINE_GLOBAL_LOCK (server_slots);
636
637 /**
638  * Allocates an integer ID to be used for storing application-specific
639  * data on any DBusServer. The allocated ID may then be used
640  * with dbus_server_set_data() and dbus_server_get_data().
641  * If allocation fails, -1 is returned. Again, the allocated
642  * slot is global, i.e. all DBusServer objects will
643  * have a slot with the given integer ID reserved.
644  *
645  * @returns -1 on failure, otherwise the data slot ID
646  */
647 int
648 dbus_server_allocate_data_slot (void)
649 {
650   return _dbus_data_slot_allocator_alloc (&slot_allocator,
651                                           _DBUS_LOCK_NAME (server_slots));
652 }
653
654 /**
655  * Deallocates a global ID for server data slots.
656  * dbus_server_get_data() and dbus_server_set_data()
657  * may no longer be used with this slot.
658  * Existing data stored on existing DBusServer objects
659  * will be freed when the server is finalized,
660  * but may not be retrieved (and may only be replaced
661  * if someone else reallocates the slot).
662  *
663  * @param slot the slot to deallocate
664  */
665 void
666 dbus_server_free_data_slot (int slot)
667 {
668   _dbus_data_slot_allocator_free (&slot_allocator, slot);
669 }
670
671 /**
672  * Stores a pointer on a DBusServer, along
673  * with an optional function to be used for freeing
674  * the data when the data is set again, or when
675  * the server is finalized. The slot number
676  * must have been allocated with dbus_server_allocate_data_slot().
677  *
678  * @param server the server
679  * @param slot the slot number
680  * @param data the data to store
681  * @param free_data_func finalizer function for the data
682  * @returns #TRUE if there was enough memory to store the data
683  */
684 dbus_bool_t
685 dbus_server_set_data (DBusServer   *server,
686                       int               slot,
687                       void             *data,
688                       DBusFreeFunction  free_data_func)
689 {
690   DBusFreeFunction old_free_func;
691   void *old_data;
692   dbus_bool_t retval;
693
694 #if 0
695   dbus_mutex_lock (server->mutex);
696 #endif
697   
698   retval = _dbus_data_slot_list_set (&slot_allocator,
699                                      &server->slot_list,
700                                      slot, data, free_data_func,
701                                      &old_free_func, &old_data);
702
703 #if 0
704   dbus_mutex_unlock (server->mutex);
705 #endif
706   
707   if (retval)
708     {
709       /* Do the actual free outside the server lock */
710       if (old_free_func)
711         (* old_free_func) (old_data);
712     }
713
714   return retval;
715 }
716
717 /**
718  * Retrieves data previously set with dbus_server_set_data().
719  * The slot must still be allocated (must not have been freed).
720  *
721  * @param server the server
722  * @param slot the slot to get data from
723  * @returns the data, or #NULL if not found
724  */
725 void*
726 dbus_server_get_data (DBusServer   *server,
727                       int               slot)
728 {
729   void *res;
730   
731 #if 0
732   dbus_mutex_lock (server->mutex);
733 #endif
734   
735   res = _dbus_data_slot_list_get (&slot_allocator,
736                                   &server->slot_list,
737                                   slot);
738
739 #if 0
740   dbus_mutex_unlock (server->mutex);
741 #endif
742   
743   return res;
744 }
745
746 /** @} */
747