2003-03-14 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  * @returns #TRUE on success.
61  */
62 dbus_bool_t
63 _dbus_server_init_base (DBusServer             *server,
64                         const DBusServerVTable *vtable)
65 {
66   server->vtable = vtable;
67   server->refcount = 1;
68
69   server->watches = _dbus_watch_list_new ();
70   if (server->watches == NULL)
71     return FALSE;
72
73   server->timeouts = _dbus_timeout_list_new ();
74   if (server->timeouts == NULL)
75     {
76       _dbus_watch_list_free (server->watches);
77       server->watches = NULL;
78       return FALSE;
79     }
80   
81   server->connection_counter = _dbus_counter_new ();
82   if (server->connection_counter == NULL)
83     {
84       _dbus_watch_list_free (server->watches);
85       server->watches = NULL;
86       _dbus_timeout_list_free (server->timeouts);
87       server->timeouts = NULL;
88       
89       return FALSE;
90     }
91
92   server->max_connections = 256; /* same as an X server, seems like a nice default */
93
94   _dbus_data_slot_list_init (&server->slot_list);
95   
96   return TRUE;
97 }
98
99 /**
100  * Finalizes the members of the DBusServer base class.
101  * Chained up to by subclass finalizers.
102  *
103  * @param server the server.
104  */
105 void
106 _dbus_server_finalize_base (DBusServer *server)
107 {
108   /* calls out to application code... */
109   _dbus_data_slot_list_free (&server->slot_list);
110
111   dbus_server_set_new_connection_function (server, NULL, NULL, NULL);
112
113   if (!server->disconnected)
114     dbus_server_disconnect (server);
115
116   _dbus_watch_list_free (server->watches);
117   _dbus_timeout_list_free (server->timeouts);
118   _dbus_counter_unref (server->connection_counter);
119 }
120
121 /**
122  * Adds a watch for this server, chaining out to application-provided
123  * watch handlers.
124  *
125  * @param server the server.
126  * @param watch the watch to add.
127  */
128 dbus_bool_t
129 _dbus_server_add_watch (DBusServer *server,
130                         DBusWatch  *watch)
131 {
132   return _dbus_watch_list_add_watch (server->watches, watch);
133 }
134
135 /**
136  * Removes a watch previously added with _dbus_server_remove_watch().
137  *
138  * @param server the server.
139  * @param watch the watch to remove.
140  */
141 void
142 _dbus_server_remove_watch  (DBusServer *server,
143                             DBusWatch  *watch)
144 {
145   _dbus_watch_list_remove_watch (server->watches, watch);
146 }
147
148 /**
149  * Adds a timeout for this server, chaining out to
150  * application-provided timeout handlers. The timeout should be
151  * repeatedly handled with dbus_timeout_handle() at its given interval
152  * until it is removed.
153  *
154  * @param server the server.
155  * @param timeout the timeout to add.
156  */
157 dbus_bool_t
158 _dbus_server_add_timeout (DBusServer  *server,
159                           DBusTimeout *timeout)
160 {
161   return _dbus_timeout_list_add_timeout (server->timeouts, timeout);
162 }
163
164 /**
165  * Removes a timeout previously added with _dbus_server_add_timeout().
166  *
167  * @param server the server.
168  * @param timeout the timeout to remove.
169  */
170 void
171 _dbus_server_remove_timeout (DBusServer  *server,
172                              DBusTimeout *timeout)
173 {
174   _dbus_timeout_list_remove_timeout (server->timeouts, timeout);  
175 }
176
177 /** @} */
178
179 /**
180  * @addtogroup DBusServer
181  *
182  * @{
183  */
184
185
186 /**
187  * @typedef DBusServer
188  *
189  * An opaque object representing a server that listens for
190  * connections from other applications. Each time a connection
191  * is made, a new DBusConnection is created and made available
192  * via an application-provided DBusNewConnectionFunction.
193  * The DBusNewConnectionFunction is provided with
194  * dbus_server_set_new_connection_function().
195  * 
196  */
197
198 /**
199  * Listens for new connections on the given address.
200  * Returns #NULL if listening fails for any reason.
201  * Otherwise returns a new #DBusServer.
202  * dbus_server_set_new_connection_function() and
203  * dbus_server_set_watch_functions() should be called
204  * immediately to render the server fully functional.
205  *
206  * @todo error messages on bad address could really be better.
207  * DBusResultCode is a bit limiting here.
208  *
209  * @param address the address of this server.
210  * @param result location to store rationale for failure.
211  * @returns a new DBusServer, or #NULL on failure.
212  * 
213  */
214 DBusServer*
215 dbus_server_listen (const char     *address,
216                     DBusResultCode *result)
217 {
218   DBusServer *server;
219   DBusAddressEntry **entries;
220   int len, i;
221   
222   if (!dbus_parse_address (address, &entries, &len, result))
223     return NULL;
224
225   server = NULL;
226   
227   for (i = 0; i < len; i++)
228     {
229       const char *method = dbus_address_entry_get_method (entries[i]);
230
231       if (strcmp (method, "unix") == 0)
232         {
233           const char *path = dbus_address_entry_get_value (entries[i], "path");
234
235           if (path == NULL)
236             goto bad_address;
237
238           server = _dbus_server_new_for_domain_socket (path, result);
239
240           if (server)
241             break;
242         }
243       else if (strcmp (method, "tcp") == 0)
244         {
245           const char *host = dbus_address_entry_get_value (entries[i], "host");
246           const char *port = dbus_address_entry_get_value (entries[i], "port");
247           DBusString  str;
248           long lport;
249           dbus_bool_t sresult;
250           
251           if (port == NULL)
252             goto bad_address;
253
254           _dbus_string_init_const (&str, port);
255           sresult = _dbus_string_parse_int (&str, 0, &lport, NULL);
256           _dbus_string_free (&str);
257           
258           if (sresult == FALSE || lport <= 0 || lport > 65535)
259             goto bad_address;
260           
261           server = _dbus_server_new_for_tcp_socket (host, lport, result);
262
263           if (server)
264             break;
265         }
266 #ifdef DBUS_BUILD_TESTS
267       else if (strcmp (method, "debug") == 0)
268         {
269           const char *name = dbus_address_entry_get_value (entries[i], "name");
270
271           if (name == NULL)
272             goto bad_address;
273
274           server = _dbus_server_debug_new (name, result);
275
276           if (server)
277             break;
278         }
279       else if (strcmp (method, "debug-pipe") == 0)
280         {
281           const char *name = dbus_address_entry_get_value (entries[i], "name");
282
283           if (name == NULL)
284             goto bad_address;
285
286           server = _dbus_server_debug_pipe_new (name, result);
287
288           if (server)
289             break;
290         }
291 #endif
292       else
293         goto bad_address;
294     }
295   
296   dbus_address_entries_free (entries);
297   return server;
298
299  bad_address:
300   dbus_address_entries_free (entries);
301   dbus_set_result (result, DBUS_RESULT_BAD_ADDRESS);
302
303   return NULL;
304 }
305
306 /**
307  * Increments the reference count of a DBusServer.
308  *
309  * @param server the server.
310  */
311 void
312 dbus_server_ref (DBusServer *server)
313 {
314   server->refcount += 1;
315 }
316
317 /**
318  * Decrements the reference count of a DBusServer.  Finalizes the
319  * server if the reference count reaches zero. The server connection
320  * will be closed as with dbus_server_disconnect() when the server is
321  * finalized.
322  *
323  * @param server the server.
324  */
325 void
326 dbus_server_unref (DBusServer *server)
327 {
328   _dbus_assert (server != NULL);
329   _dbus_assert (server->refcount > 0);
330
331   server->refcount -= 1;
332   if (server->refcount == 0)
333     {
334       _dbus_assert (server->vtable->finalize != NULL);
335       
336       (* server->vtable->finalize) (server);
337     }
338 }
339
340 /**
341  * Releases the server's address and stops listening for
342  * new clients. If called more than once, only the first
343  * call has an effect. Does not modify the server's
344  * reference count.
345  * 
346  * @param server the server.
347  */
348 void
349 dbus_server_disconnect (DBusServer *server)
350 {
351   _dbus_assert (server->vtable->disconnect != NULL);
352
353   if (server->disconnected)
354     return;
355   
356   (* server->vtable->disconnect) (server);
357   server->disconnected = TRUE;
358 }
359
360 /**
361  * Returns #TRUE if the server is still listening for new connections.
362  *
363  * @param server the server.
364  */
365 dbus_bool_t
366 dbus_server_get_is_connected (DBusServer *server)
367 {
368   return !server->disconnected;
369 }
370
371 /**
372  * Sets a function to be used for handling new connections.  The given
373  * function is passed each new connection as the connection is
374  * created. If the new connection function increments the connection's
375  * reference count, the connection will stay alive. Otherwise, the
376  * connection will be unreferenced and closed.
377  *
378  * @param server the server.
379  * @param function a function to handle new connections.
380  * @param data data to pass to the new connection handler.
381  * @param free_data_function function to free the data.
382  */
383 void
384 dbus_server_set_new_connection_function (DBusServer                *server,
385                                          DBusNewConnectionFunction  function,
386                                          void                      *data,
387                                          DBusFreeFunction           free_data_function)
388 {
389   if (server->new_connection_free_data_function != NULL)
390     (* server->new_connection_free_data_function) (server->new_connection_data);
391   
392   server->new_connection_function = function;
393   server->new_connection_data = data;
394   server->new_connection_free_data_function = free_data_function;
395 }
396
397 /**
398  * Sets the watch functions for the connection. These functions are
399  * responsible for making the application's main loop aware of file
400  * descriptors that need to be monitored for events.
401  *
402  * This function behaves exactly like dbus_connection_set_watch_functions();
403  * see the documentation for that routine.
404  *
405  * @param server the server.
406  * @param add_function function to begin monitoring a new descriptor.
407  * @param remove_function function to stop monitoring a descriptor.
408  * @param data data to pass to add_function and remove_function.
409  * @param free_data_function function to be called to free the data.
410  * @returns #FALSE on failure (no memory)
411  */
412 dbus_bool_t
413 dbus_server_set_watch_functions (DBusServer              *server,
414                                  DBusAddWatchFunction     add_function,
415                                  DBusRemoveWatchFunction  remove_function,
416                                  void                    *data,
417                                  DBusFreeFunction         free_data_function)
418 {
419   return _dbus_watch_list_set_functions (server->watches,
420                                          add_function,
421                                          remove_function,
422                                          data,
423                                          free_data_function);
424 }
425
426 /**
427  * Sets the timeout functions for the connection. These functions are
428  * responsible for making the application's main loop aware of timeouts.
429  *
430  * This function behaves exactly like dbus_connection_set_timeout_functions();
431  * see the documentation for that routine.
432  *
433  * @param server the server.
434  * @param add_function function to add a timeout.
435  * @param remove_function function to remove a timeout.
436  * @param data data to pass to add_function and remove_function.
437  * @param free_data_function function to be called to free the data.
438  * @returns #FALSE on failure (no memory)
439  */
440 dbus_bool_t
441 dbus_server_set_timeout_functions (DBusServer                *server,
442                                    DBusAddTimeoutFunction     add_function,
443                                    DBusRemoveTimeoutFunction  remove_function,
444                                    void                      *data,
445                                    DBusFreeFunction           free_data_function)
446 {
447   return _dbus_timeout_list_set_functions (server->timeouts,
448                                            add_function, remove_function,
449                                            data, free_data_function); 
450 }
451
452 /**
453  * Called to notify the server when a previously-added watch
454  * is ready for reading or writing, or has an exception such
455  * as a hangup.
456  *
457  * @param server the server.
458  * @param watch the watch.
459  * @param condition the current condition of the file descriptors being watched.
460  */
461 void
462 dbus_server_handle_watch (DBusServer              *server,
463                           DBusWatch               *watch,
464                           unsigned int             condition)
465 {
466   _dbus_assert (server->vtable->handle_watch != NULL);
467
468   _dbus_watch_sanitize_condition (watch, &condition);
469   
470   (* server->vtable->handle_watch) (server, watch, condition);
471 }
472
473 /**
474  * Sets the maximum number of connections that can be open at one
475  * time for this server. If the maximum is reached, and another
476  * client tries to connect, then the oldest unauthenticated client
477  * will be dropped. If no unauthenticated client exists, then
478  * the new connection will be refused.
479  *
480  * If the maximum is set to a number lower than the current
481  * number of connections, no current connections are
482  * disconnected.
483  *
484  * @todo honoring max_connections has not been implemented
485  * yet. The only real work involved is keeping a list
486  * of live connections on the DBusServer so the oldest
487  * unauthenticated client can be located when required.
488  * 
489  * @todo for a systemwide daemon, we need a max number of connections
490  * per user, since any user can authenticate a bunch of connections
491  * and create a DOS.
492  *
493  * @todo a single process might listen on multiple mechanisms
494  * (multiple DBusServer) and might want the max connections
495  * value to span all those servers. Should consider
496  * changing the API accordingly, though I'm inclined to
497  * punt this to the app that wants to do it instead of
498  * putting it in the library.
499  * 
500  * @param server the server
501  * @param max_connections maximum number of connections allowed
502  */
503 void
504 dbus_server_set_max_connections (DBusServer *server,
505                                  int         max_connections)
506 {
507   server->max_connections = max_connections;
508 }
509
510 /**
511  * Gets the maximum number of connections that can be active
512  * at a time for this server.
513  *
514  * @param server the server
515  * @returns maximum number of connections at once
516  */
517 int
518 dbus_server_get_max_connections (DBusServer *server)
519 {
520   return server->max_connections;
521 }
522
523 /**
524  * Gets the number of #DBusConnection to this server that
525  * have not yet been finalized. i.e. all #DBusConnection that
526  * were passed to #DBusNewConnectionFunction and have not yet been
527  * finalized will count in this total.
528  *
529  * @param server the server
530  * @returns the number of connections
531  */
532 int
533 dbus_server_get_n_connections (DBusServer *server)
534 {
535   return _dbus_counter_get_value (server->connection_counter);
536 }
537
538
539 static DBusDataSlotAllocator slot_allocator;
540
541 /**
542  * Initialize the mutex used for #DBusConnection data
543  * slot reservations.
544  *
545  * @returns the mutex
546  */
547 DBusMutex *
548 _dbus_server_slots_init_lock (void)
549 {
550   if (!_dbus_data_slot_allocator_init (&slot_allocator))
551     return NULL;
552   else
553     return slot_allocator.lock;
554 }
555
556 /**
557  * Allocates an integer ID to be used for storing application-specific
558  * data on any DBusServer. The allocated ID may then be used
559  * with dbus_server_set_data() and dbus_server_get_data().
560  * If allocation fails, -1 is returned. Again, the allocated
561  * slot is global, i.e. all DBusServer objects will
562  * have a slot with the given integer ID reserved.
563  *
564  * @returns -1 on failure, otherwise the data slot ID
565  */
566 int
567 dbus_server_allocate_data_slot (void)
568 {
569   return _dbus_data_slot_allocator_alloc (&slot_allocator);
570 }
571
572 /**
573  * Deallocates a global ID for server data slots.
574  * dbus_server_get_data() and dbus_server_set_data()
575  * may no longer be used with this slot.
576  * Existing data stored on existing DBusServer objects
577  * will be freed when the server is finalized,
578  * but may not be retrieved (and may only be replaced
579  * if someone else reallocates the slot).
580  *
581  * @param slot the slot to deallocate
582  */
583 void
584 dbus_server_free_data_slot (int slot)
585 {
586   _dbus_data_slot_allocator_free (&slot_allocator, slot);
587 }
588
589 /**
590  * Stores a pointer on a DBusServer, along
591  * with an optional function to be used for freeing
592  * the data when the data is set again, or when
593  * the server is finalized. The slot number
594  * must have been allocated with dbus_server_allocate_data_slot().
595  *
596  * @param server the server
597  * @param slot the slot number
598  * @param data the data to store
599  * @param free_data_func finalizer function for the data
600  * @returns #TRUE if there was enough memory to store the data
601  */
602 dbus_bool_t
603 dbus_server_set_data (DBusServer   *server,
604                       int               slot,
605                       void             *data,
606                       DBusFreeFunction  free_data_func)
607 {
608   DBusFreeFunction old_free_func;
609   void *old_data;
610   dbus_bool_t retval;
611
612 #if 0
613   dbus_mutex_lock (server->mutex);
614 #endif
615   
616   retval = _dbus_data_slot_list_set (&slot_allocator,
617                                      &server->slot_list,
618                                      slot, data, free_data_func,
619                                      &old_free_func, &old_data);
620
621 #if 0
622   dbus_mutex_unlock (server->mutex);
623 #endif
624   
625   if (retval)
626     {
627       /* Do the actual free outside the server lock */
628       if (old_free_func)
629         (* old_free_func) (old_data);
630     }
631
632   return retval;
633 }
634
635 /**
636  * Retrieves data previously set with dbus_server_set_data().
637  * The slot must still be allocated (must not have been freed).
638  *
639  * @param server the server
640  * @param slot the slot to get data from
641  * @returns the data, or #NULL if not found
642  */
643 void*
644 dbus_server_get_data (DBusServer   *server,
645                       int               slot)
646 {
647   void *res;
648   
649 #if 0
650   dbus_mutex_lock (server->mutex);
651 #endif
652   
653   res = _dbus_data_slot_list_get (&slot_allocator,
654                                   &server->slot_list,
655                                   slot);
656
657 #if 0
658   dbus_mutex_unlock (server->mutex);
659 #endif
660   
661   return res;
662 }
663
664 /** @} */
665