2006-10-21 Havoc Pennington <hp@redhat.com>
[platform/upstream/dbus.git] / dbus / dbus-bus.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
2 /* dbus-bus.c  Convenience functions for communicating with the bus.
3  *
4  * Copyright (C) 2003  CodeFactory AB
5  * Copyright (C) 2003  Red Hat, Inc.
6  *
7  * Licensed under the Academic Free License version 2.1
8  * 
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  * 
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #include "dbus-bus.h"
26 #include "dbus-protocol.h"
27 #include "dbus-internals.h"
28 #include "dbus-message.h"
29 #include "dbus-marshal-validate.h"
30 #include "dbus-threads-internal.h"
31 #include "dbus-connection-internal.h"
32 #include <string.h>
33
34 /**
35  * @defgroup DBusBus Message bus APIs
36  * @ingroup DBus
37  * @brief Functions for communicating with the message bus
38  *
39  * dbus_bus_get() allows all modules and libraries in a given
40  * process to share the same connection to the bus daemon by storing
41  * the connection globally.
42  *
43  * All other functions in this module are just convenience functions;
44  * most of them invoke methods on the bus daemon, by sending method
45  * call messages to #DBUS_SERVICE_DBUS. These convenience functions
46  * often make blocking method calls. If you don't want to block,
47  * you can send the method call messages manually in the same way
48  * you would any other method call message.
49  *
50  * This module is the only one in libdbus that's specific to
51  * communicating with the message bus daemon. The rest of the API can
52  * also be used for connecting to another application directly.
53  * 
54  * @todo right now the default address of the system bus is hardcoded,
55  * so if you change it in the global config file suddenly you have to
56  * set DBUS_SYSTEM_BUS_ADDRESS env variable.  Might be nice if the
57  * client lib somehow read the config file, or if the bus on startup
58  * somehow wrote out its address to a well-known spot, but might also
59  * not be worth it.
60  */
61
62 /**
63  * @defgroup DBusBusInternals Message bus APIs internals
64  * @ingroup DBusInternals
65  * @brief Internals of functions for communicating with the message bus
66  *
67  * @{
68  */
69
70 /**
71  * Block of message-bus-related data we attach to each
72  * #DBusConnection used with these convenience functions.
73  *
74  */
75 typedef struct
76 {
77   DBusConnection *connection; /**< Connection we're associated with */
78   char *unique_name; /**< Unique name of this connection */
79
80   unsigned int is_well_known : 1; /**< Is one of the well-known connections in our global array */
81 } BusData;
82
83 /** The slot we have reserved to store BusData.
84  */
85 static dbus_int32_t bus_data_slot = -1;
86
87 /** Number of bus types */
88 #define N_BUS_TYPES 3
89
90 static DBusConnection *bus_connections[N_BUS_TYPES];
91 static char *bus_connection_addresses[N_BUS_TYPES] = { NULL, NULL, NULL };
92
93 static DBusBusType activation_bus_type = DBUS_BUS_STARTER;
94
95 static dbus_bool_t initialized = FALSE;
96
97 /**
98  * Lock for globals in this file
99  */
100 _DBUS_DEFINE_GLOBAL_LOCK (bus);
101
102 static void
103 addresses_shutdown_func (void *data)
104 {
105   int i;
106
107   i = 0;
108   while (i < N_BUS_TYPES)
109     {
110       if (bus_connections[i] != NULL)
111         _dbus_warn_check_failed ("dbus_shutdown() called but connections were still live. This probably means the application did not drop all its references to bus connections.\n");
112       
113       dbus_free (bus_connection_addresses[i]);
114       bus_connection_addresses[i] = NULL;
115       ++i;
116     }
117
118   activation_bus_type = DBUS_BUS_STARTER;
119 }
120
121 static dbus_bool_t
122 get_from_env (char           **connection_p,
123               const char      *env_var)
124 {
125   const char *s;
126   
127   _dbus_assert (*connection_p == NULL);
128   
129   s = _dbus_getenv (env_var);
130   if (s == NULL || *s == '\0')
131     return TRUE; /* successfully didn't use the env var */
132   else
133     {
134       *connection_p = _dbus_strdup (s);
135       return *connection_p != NULL;
136     }
137 }
138
139 static dbus_bool_t
140 init_connections_unlocked (void)
141 {
142   if (!initialized)
143     {
144       const char *s;
145       int i;
146
147       i = 0;
148       while (i < N_BUS_TYPES)
149         {
150           bus_connections[i] = NULL;
151           ++i;
152         }
153
154       /* Don't init these twice, we may run this code twice if
155        * init_connections_unlocked() fails midway through.
156        * In practice, each block below should contain only one
157        * "return FALSE" or running through twice may not
158        * work right.
159        */
160       
161        if (bus_connection_addresses[DBUS_BUS_SYSTEM] == NULL)
162          {
163            _dbus_verbose ("Filling in system bus address...\n");
164            
165            if (!get_from_env (&bus_connection_addresses[DBUS_BUS_SYSTEM],
166                               "DBUS_SYSTEM_BUS_ADDRESS"))
167              return FALSE;
168          }
169
170                   
171        if (bus_connection_addresses[DBUS_BUS_SYSTEM] == NULL)
172          {
173            /* Use default system bus address if none set in environment */
174            bus_connection_addresses[DBUS_BUS_SYSTEM] =
175              _dbus_strdup (DBUS_SYSTEM_BUS_DEFAULT_ADDRESS);
176
177            if (bus_connection_addresses[DBUS_BUS_SYSTEM] == NULL)
178              return FALSE;
179            
180            _dbus_verbose ("  used default system bus \"%s\"\n",
181                           bus_connection_addresses[DBUS_BUS_SYSTEM]);
182          }
183        else
184          _dbus_verbose ("  used env var system bus \"%s\"\n",
185                         bus_connection_addresses[DBUS_BUS_SYSTEM]);
186           
187       if (bus_connection_addresses[DBUS_BUS_SESSION] == NULL)
188         {
189           _dbus_verbose ("Filling in session bus address...\n");
190           
191           if (!get_from_env (&bus_connection_addresses[DBUS_BUS_SESSION],
192                              "DBUS_SESSION_BUS_ADDRESS"))
193             return FALSE;
194
195           if (bus_connection_addresses[DBUS_BUS_SESSION] == NULL)
196             bus_connection_addresses[DBUS_BUS_SESSION] =
197               _dbus_strdup (DBUS_SESSION_BUS_DEFAULT_ADDRESS);
198           
199           if (bus_connection_addresses[DBUS_BUS_SESSION] == NULL)
200              return FALSE;
201
202           _dbus_verbose ("  \"%s\"\n", bus_connection_addresses[DBUS_BUS_SESSION] ?
203                          bus_connection_addresses[DBUS_BUS_SESSION] : "none set");
204         }
205
206       if (bus_connection_addresses[DBUS_BUS_STARTER] == NULL)
207         {
208           _dbus_verbose ("Filling in activation bus address...\n");
209           
210           if (!get_from_env (&bus_connection_addresses[DBUS_BUS_STARTER],
211                              "DBUS_STARTER_ADDRESS"))
212             return FALSE;
213           
214           _dbus_verbose ("  \"%s\"\n", bus_connection_addresses[DBUS_BUS_STARTER] ?
215                          bus_connection_addresses[DBUS_BUS_STARTER] : "none set");
216         }
217
218
219       if (bus_connection_addresses[DBUS_BUS_STARTER] != NULL)
220         {
221           s = _dbus_getenv ("DBUS_STARTER_BUS_TYPE");
222               
223           if (s != NULL)
224             {
225               _dbus_verbose ("Bus activation type was set to \"%s\"\n", s);
226                   
227               if (strcmp (s, "system") == 0)
228                 activation_bus_type = DBUS_BUS_SYSTEM;
229               else if (strcmp (s, "session") == 0)
230                 activation_bus_type = DBUS_BUS_SESSION;
231             }
232         }
233       else
234         {
235           /* Default to the session bus instead if available */
236           if (bus_connection_addresses[DBUS_BUS_SESSION] != NULL)
237             {
238               bus_connection_addresses[DBUS_BUS_STARTER] =
239                 _dbus_strdup (bus_connection_addresses[DBUS_BUS_SESSION]);
240               if (bus_connection_addresses[DBUS_BUS_STARTER] == NULL)
241                 return FALSE;
242             }
243         }
244       
245       /* If we return FALSE we have to be sure that restarting
246        * the above code will work right
247        */
248       
249       if (!_dbus_setenv ("DBUS_ACTIVATION_ADDRESS", NULL))
250         return FALSE;
251
252       if (!_dbus_setenv ("DBUS_ACTIVATION_BUS_TYPE", NULL))
253         return FALSE;
254       
255       if (!_dbus_register_shutdown_func (addresses_shutdown_func,
256                                          NULL))
257         return FALSE;
258       
259       initialized = TRUE;
260     }
261
262   return initialized;
263 }
264
265 static void
266 bus_data_free (void *data)
267 {
268   BusData *bd = data;
269   
270   if (bd->is_well_known)
271     {
272       int i;
273       _DBUS_LOCK (bus);
274       /* We may be stored in more than one slot */
275       /* This should now be impossible - these slots are supposed to
276        * be cleared on disconnect, so should not need to be cleared on
277        * finalize
278        */
279       i = 0;
280       while (i < N_BUS_TYPES)
281         {
282           if (bus_connections[i] == bd->connection)
283             bus_connections[i] = NULL;
284           
285           ++i;
286         }
287       _DBUS_UNLOCK (bus);
288     }
289   
290   dbus_free (bd->unique_name);
291   dbus_free (bd);
292
293   dbus_connection_free_data_slot (&bus_data_slot);
294 }
295
296 static BusData*
297 ensure_bus_data (DBusConnection *connection)
298 {
299   BusData *bd;
300
301   if (!dbus_connection_allocate_data_slot (&bus_data_slot))
302     return NULL;
303
304   bd = dbus_connection_get_data (connection, bus_data_slot);
305   if (bd == NULL)
306     {      
307       bd = dbus_new0 (BusData, 1);
308       if (bd == NULL)
309         {
310           dbus_connection_free_data_slot (&bus_data_slot);
311           return NULL;
312         }
313
314       bd->connection = connection;
315       
316       if (!dbus_connection_set_data (connection, bus_data_slot, bd,
317                                      bus_data_free))
318         {
319           dbus_free (bd);
320           dbus_connection_free_data_slot (&bus_data_slot);
321           return NULL;
322         }
323
324       /* Data slot refcount now held by the BusData */
325     }
326   else
327     {
328       dbus_connection_free_data_slot (&bus_data_slot);
329     }
330
331   return bd;
332 }
333
334 /**
335  * Internal function that checks to see if this
336  * is a shared connection owned by the bus and if it is unref it.
337  *
338  * @param connection a connection that has been disconnected.
339  */
340 void
341 _dbus_bus_notify_shared_connection_disconnected_unlocked (DBusConnection *connection)
342 {
343   int i;
344   
345   _DBUS_LOCK (bus);
346
347   /* We are expecting to have the connection saved in only one of these
348    * slots, but someone could in a pathological case set system and session
349    * bus to the same bus or something. Or set one of them to the starter
350    * bus without setting the starter bus type in the env variable.
351    * So we don't break the loop as soon as we find a match.
352    */
353   for (i = 0; i < N_BUS_TYPES; ++i)
354     {
355       if (bus_connections[i] == connection)
356         {
357           bus_connections[i] = NULL;
358         }
359     }
360
361   _DBUS_UNLOCK (bus);
362 }
363
364 static DBusConnection *
365 internal_bus_get (DBusBusType  type,
366                   dbus_bool_t  private,
367                   DBusError   *error)
368 {
369   const char *address;
370   DBusConnection *connection;
371   BusData *bd;
372   DBusBusType address_type;
373
374   _dbus_return_val_if_fail (type >= 0 && type < N_BUS_TYPES, NULL);
375   _dbus_return_val_if_error_is_set (error, NULL);
376
377   _DBUS_LOCK (bus);
378
379   if (!init_connections_unlocked ())
380     {
381       _DBUS_UNLOCK (bus);
382       _DBUS_SET_OOM (error);
383       return NULL;
384     }
385
386   /* We want to use the activation address even if the
387    * activating bus is the session or system bus,
388    * per the spec.
389    */
390   address_type = type;
391   
392   /* Use the real type of the activation bus for getting its
393    * connection, but only if the real type's address is available. (If
394    * the activating bus isn't a well-known bus then
395    * activation_bus_type == DBUS_BUS_STARTER)
396    */
397   if (type == DBUS_BUS_STARTER &&
398       bus_connection_addresses[activation_bus_type] != NULL)
399     type = activation_bus_type;
400   
401   if (!private && bus_connections[type] != NULL)
402     {
403       connection = bus_connections[type];
404       dbus_connection_ref (connection);
405       
406       _DBUS_UNLOCK (bus);
407       return connection;
408     }
409
410   address = bus_connection_addresses[address_type];
411   if (address == NULL)
412     {
413       dbus_set_error (error, DBUS_ERROR_FAILED,
414                       "Unable to determine the address of the message bus (try 'man dbus-launch' and 'man dbus-daemon' for help)");
415       _DBUS_UNLOCK (bus);
416       return NULL;
417     }
418
419   if (private)
420     connection = dbus_connection_open_private (address, error);
421   else
422     connection = dbus_connection_open (address, error);
423   
424   if (!connection)
425     {
426       _DBUS_ASSERT_ERROR_IS_SET (error);
427       _DBUS_UNLOCK (bus);
428       return NULL;
429     }
430
431   /* By default we're bound to the lifecycle of
432    * the message bus.
433    */
434   dbus_connection_set_exit_on_disconnect (connection,
435                                           TRUE);
436   
437   if (!dbus_bus_register (connection, error))
438     {
439       _DBUS_ASSERT_ERROR_IS_SET (error);
440       _dbus_connection_close_possibly_shared (connection);
441       dbus_connection_unref (connection);
442
443       _DBUS_UNLOCK (bus);
444       return NULL;
445     }
446
447   if (!private)
448     {
449       /* store a weak ref to the connection (dbus-connection.c is
450        * supposed to have a strong ref that it drops on disconnect,
451        * since this is a shared connection)
452        */
453       bus_connections[type] = connection;
454     }
455   
456   bd = ensure_bus_data (connection);
457   _dbus_assert (bd != NULL);
458
459   bd->is_well_known = TRUE;
460
461   _DBUS_UNLOCK (bus);
462
463   /* Return a reference to the caller */
464   return connection;
465 }
466
467
468 /** @} */ /* end of implementation details docs */
469
470 /**
471  * @addtogroup DBusBus
472  * @{
473  */
474
475 /**
476  * Connects to a bus daemon and registers the client with it.  If a
477  * connection to the bus already exists, then that connection is
478  * returned.  The caller of this function owns a reference to the bus.
479  *
480  * The caller may NOT call dbus_connection_close() on this connection;
481  * see dbus_connection_open() and dbus_connection_close() for details
482  * on that.
483  *
484  * If this function obtains a new connection object never before
485  * returned from dbus_bus_get(), it will call
486  * dbus_connection_set_exit_on_disconnect(), so the application
487  * will exit if the connection closes. You can undo this
488  * by calling dbus_connection_set_exit_on_disconnect() yourself
489  * after you get the connection.
490  *
491  * dbus_bus_get() calls dbus_bus_register() for you.
492  * 
493  * If returning a newly-created connection, this function will block
494  * until authentication and bus registration are complete.
495  * 
496  * @param type bus type
497  * @param error address where an error can be returned.
498  * @returns a #DBusConnection with new ref
499  */
500 DBusConnection *
501 dbus_bus_get (DBusBusType  type,
502               DBusError   *error)
503 {
504   return internal_bus_get (type, FALSE, error);
505 }
506
507 /**
508  * Connects to a bus daemon and registers the client with it as with
509  * dbus_bus_register().  Unlike dbus_bus_get(), always creates a new
510  * connection. This connection will not be saved or recycled by
511  * libdbus. Caller owns a reference to the bus and must either close
512  * it or know it to be closed prior to releasing this reference.
513  *
514  * See dbus_connection_open_private() for more details on when to
515  * close and unref this connection.
516  *
517  * This function calls
518  * dbus_connection_set_exit_on_disconnect() on the new connection, so the application
519  * will exit if the connection closes. You can undo this
520  * by calling dbus_connection_set_exit_on_disconnect() yourself
521  * after you get the connection.
522  *
523  * dbus_bus_get_private() calls dbus_bus_register() for you.
524  *
525  * This function will block until authentication and bus registration
526  * are complete.
527  *
528  * @param type bus type
529  * @param error address where an error can be returned.
530  * @returns a DBusConnection with new ref
531  */
532 DBusConnection *
533 dbus_bus_get_private (DBusBusType  type,
534                       DBusError   *error)
535 {
536   return internal_bus_get (type, TRUE, error);
537 }
538
539 /**
540  * Registers a connection with the bus. This must be the first
541  * thing an application does when connecting to the message bus.
542  * If registration succeeds, the unique name will be set,
543  * and can be obtained using dbus_bus_get_unique_name().
544  *
545  * If you use dbus_bus_get() or dbus_bus_get_private() this
546  * function will be called for you.
547  *
548  * If you open a bus connection with dbus_connection_open() or
549  * dbus_connection_open_private() you will have to dbus_bus_register()
550  * yourself, or make the appropriate registration method calls
551  * yourself.
552  *
553  * This function will block until registration is complete.
554  * 
555  * @param connection the connection
556  * @param error place to store errors
557  * @returns #TRUE on success
558  */
559 dbus_bool_t
560 dbus_bus_register (DBusConnection *connection,
561                    DBusError      *error)
562 {
563   DBusMessage *message, *reply;
564   char *name;
565   BusData *bd;
566   dbus_bool_t retval;
567
568   _dbus_return_val_if_fail (connection != NULL, FALSE);
569   _dbus_return_val_if_error_is_set (error, FALSE);
570
571   retval = FALSE;
572   
573   bd = ensure_bus_data (connection);
574   if (bd == NULL)
575     {
576       _DBUS_SET_OOM (error);
577       return FALSE;
578     }
579
580   if (bd->unique_name != NULL)
581     {
582       _dbus_warn_check_failed ("Attempt to register the same DBusConnection %s with the message bus a second time.\n",
583                                bd->unique_name);
584       /* This isn't an error, it's a programming bug. so return TRUE */
585       return TRUE;
586     }
587   
588   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
589                                           DBUS_PATH_DBUS,
590                                           DBUS_INTERFACE_DBUS,
591                                           "Hello"); 
592
593   if (!message)
594     {
595       _DBUS_SET_OOM (error);
596       return FALSE;
597     }
598   
599   reply = dbus_connection_send_with_reply_and_block (connection, message, -1, error);
600
601   dbus_message_unref (message);
602   
603   if (reply == NULL)
604     goto out;
605   else if (dbus_set_error_from_message (error, reply))
606     goto out;
607   else if (!dbus_message_get_args (reply, error,
608                                    DBUS_TYPE_STRING, &name,
609                                    DBUS_TYPE_INVALID))
610     goto out;
611   
612   bd->unique_name = _dbus_strdup (name);
613   if (bd->unique_name == NULL)
614     {
615       _DBUS_SET_OOM (error);
616       goto out;
617     }
618   
619   retval = TRUE;
620   
621  out:
622   if (reply)
623     dbus_message_unref (reply);
624
625   if (!retval)
626     _DBUS_ASSERT_ERROR_IS_SET (error);
627   
628   return retval;
629 }
630
631
632 /**
633  * Sets the unique name of the connection, as assigned by the message
634  * bus.  Can only be used if you registered with the bus manually
635  * (i.e. if you did not call dbus_bus_register()). Can only be called
636  * once per connection.  After the unique name is set, you can get it
637  * with dbus_bus_get_unique_name().
638  *
639  * @param connection the connection
640  * @param unique_name the unique name
641  * @returns #FALSE if not enough memory
642  */
643 dbus_bool_t
644 dbus_bus_set_unique_name (DBusConnection *connection,
645                           const char     *unique_name)
646 {
647   BusData *bd;
648
649   _dbus_return_val_if_fail (connection != NULL, FALSE);
650   _dbus_return_val_if_fail (unique_name != NULL, FALSE);
651   
652   bd = ensure_bus_data (connection);
653   if (bd == NULL)
654     return FALSE;
655
656   _dbus_assert (bd->unique_name == NULL);
657   
658   bd->unique_name = _dbus_strdup (unique_name);
659   return bd->unique_name != NULL;
660 }
661
662 /**
663  * Gets the unique name of the connection as assigned by the message
664  * bus. Only possible after the connection has been registered with
665  * the message bus.
666  *
667  * The name remains valid until the connection is freed, and
668  * should not be freed by the caller.
669  *
670  * There are two ways to set the unique name; one is
671  * dbus_bus_register(), the other is dbus_bus_set_unique_name().
672  * You are responsible for calling dbus_bus_set_unique_name()
673  * if you register by hand instead of using dbus_bus_register().
674  * 
675  * @param connection the connection
676  * @returns the unique name or NULL on error
677  */
678 const char*
679 dbus_bus_get_unique_name (DBusConnection *connection)
680 {
681   BusData *bd;
682
683   _dbus_return_val_if_fail (connection != NULL, NULL);
684   
685   bd = ensure_bus_data (connection);
686   if (bd == NULL)
687     return NULL;
688   
689   return bd->unique_name;
690 }
691
692 /**
693  * Asks the bus to return the uid of the named connection.
694  * Only works on UNIX; only works for connections on the same
695  * machine as the bus. If you are not on the same machine
696  * as the bus, then calling this is probably a bad idea,
697  * since the uid will mean little to your application.
698  *
699  * For the system message bus you're guaranteed to be on the same
700  * machine since it only listens on a UNIX domain socket (at least,
701  * as shipped by default).
702  *
703  * This function will just return an error on Windows.
704  * 
705  * @param connection the connection
706  * @param name a name owned by the connection
707  * @param error location to store the error
708  * @returns the unix user id, or ((unsigned)-1) if error is set
709  */ 
710 unsigned long
711 dbus_bus_get_unix_user (DBusConnection *connection,
712                         const char     *name,
713                         DBusError      *error)
714 {
715   DBusMessage *message, *reply;
716   dbus_uint32_t uid;
717
718   _dbus_return_val_if_fail (connection != NULL, DBUS_UID_UNSET);
719   _dbus_return_val_if_fail (name != NULL, DBUS_UID_UNSET);
720   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), DBUS_UID_UNSET);
721   _dbus_return_val_if_error_is_set (error, DBUS_UID_UNSET);
722   
723   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
724                                           DBUS_PATH_DBUS,
725                                           DBUS_INTERFACE_DBUS,
726                                           "GetConnectionUnixUser");
727
728   if (message == NULL)
729     {
730       _DBUS_SET_OOM (error);
731       return DBUS_UID_UNSET;
732     }
733  
734   if (!dbus_message_append_args (message,
735                                  DBUS_TYPE_STRING, &name,
736                                  DBUS_TYPE_INVALID))
737     {
738       dbus_message_unref (message);
739       _DBUS_SET_OOM (error);
740       return DBUS_UID_UNSET;
741     }
742   
743   reply = dbus_connection_send_with_reply_and_block (connection, message, -1,
744                                                      error);
745   
746   dbus_message_unref (message);
747   
748   if (reply == NULL)
749     {
750       _DBUS_ASSERT_ERROR_IS_SET (error);
751       return DBUS_UID_UNSET;
752     }  
753
754   if (dbus_set_error_from_message (error, reply))
755     {
756       _DBUS_ASSERT_ERROR_IS_SET (error);
757       dbus_message_unref (reply);
758       return DBUS_UID_UNSET;
759     }
760   
761   if (!dbus_message_get_args (reply, error,
762                               DBUS_TYPE_UINT32, &uid,
763                               DBUS_TYPE_INVALID))
764     {
765       _DBUS_ASSERT_ERROR_IS_SET (error);
766       dbus_message_unref (reply);
767       return DBUS_UID_UNSET;
768     }
769
770   dbus_message_unref (reply);
771   
772   return (unsigned long) uid;
773 }
774
775
776 /**
777  * Asks the bus to assign the given name to this connection by invoking
778  * the RequestName method on the bus. This method is fully documented
779  * in the D-Bus specification. For quick reference, the flags and
780  * result codes are discussed here, but the specification is the
781  * canonical version of this information.
782  *
783  * First you should know that for each bus name, the bus stores
784  * a queue of connections that would like to own it. Only
785  * one owns it at a time - called the primary owner. If the primary
786  * owner releases the name or disconnects, then the next owner in the
787  * queue atomically takes over.
788  *
789  * So for example if you have an application org.freedesktop.TextEditor
790  * and multiple instances of it can be run, you can have all of them
791  * sitting in the queue. The first one to start up will receive messages
792  * sent to org.freedesktop.TextEditor, but if that one exits another
793  * will become the primary owner and receive messages.
794  *
795  * The queue means you don't need to manually watch for the current owner to
796  * disappear and then request the name again.
797  *
798  * When requesting a name, you can specify several flags.
799  * 
800  * #DBUS_NAME_FLAG_ALLOW_REPLACEMENT and #DBUS_NAME_FLAG_DO_NOT_QUEUE
801  * are properties stored by the bus for this connection with respect to
802  * each requested bus name. These properties are stored even if the
803  * connection is queued and does not become the primary owner.
804  * You can update these flags by calling RequestName again (even if
805  * you already own the name).
806  *
807  * #DBUS_NAME_FLAG_ALLOW_REPLACEMENT means that another requestor of the
808  * name can take it away from you by specifying #DBUS_NAME_FLAG_REPLACE_EXISTING.
809  *
810  * #DBUS_NAME_FLAG_DO_NOT_QUEUE means that if you aren't the primary owner,
811  * you don't want to be queued up - you only care about being the
812  * primary owner.
813  *
814  * Unlike the other two flags, #DBUS_NAME_FLAG_REPLACE_EXISTING is a property
815  * of the individual RequestName call, i.e. the bus does not persistently
816  * associate it with the connection-name pair. If a RequestName call includes
817  * the #DBUS_NAME_FLAG_REPLACE_EXISTING flag, and the current primary
818  * owner has #DBUS_NAME_FLAG_ALLOW_REPLACEMENT set, then the current primary
819  * owner will be kicked off.
820  *
821  * If no flags are given, an application will receive the requested
822  * name only if the name is currently unowned; and it will NOT give
823  * up the name if another application asks to take it over using
824  * #DBUS_NAME_FLAG_REPLACE_EXISTING.
825  *
826  * This function returns a result code. The possible result codes
827  * are as follows.
828  * 
829  * #DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER means that the name had no
830  * existing owner, and the caller is now the primary owner; or that
831  * the name had an owner, and the caller specified
832  * #DBUS_NAME_FLAG_REPLACE_EXISTING, and the current owner
833  * specified #DBUS_NAME_FLAG_ALLOW_REPLACEMENT.
834  *
835  * #DBUS_REQUEST_NAME_REPLY_IN_QUEUE happens only if the caller does NOT
836  * specify #DBUS_NAME_FLAG_DO_NOT_QUEUE and either the current owner
837  * did NOT specify #DBUS_NAME_FLAG_ALLOW_REPLACEMENT or the caller did NOT
838  * specify #DBUS_NAME_FLAG_REPLACE_EXISTING. In this case the caller ends up 
839  * in a queue to own the name after the current owner gives it up.
840  *
841  * #DBUS_REQUEST_NAME_REPLY_EXISTS happens if the name has an owner
842  * already and the caller specifies #DBUS_NAME_FLAG_DO_NOT_QUEUE
843  * and either the current owner has NOT specified 
844  * #DBUS_NAME_FLAG_ALLOW_REPLACEMENT or the caller did NOT specify 
845  * #DBUS_NAME_FLAG_REPLACE_EXISTING.
846  *
847  * #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER happens if an application
848  * requests a name it already owns. (Re-requesting a name is useful if
849  * you want to change the #DBUS_NAME_FLAG_ALLOW_REPLACEMENT or
850  * #DBUS_NAME_FLAG_DO_NOT_QUEUE settings.)
851  *
852  * When a service represents an application, say "text editor," then
853  * it should specify #DBUS_NAME_FLAG_ALLOW_REPLACEMENT if it wants
854  * the last editor started to be the user's editor vs. the first one
855  * started.  Then any editor that can be the user's editor should
856  * specify #DBUS_NAME_FLAG_REPLACE_EXISTING to either take over
857  * (last-started-wins) or be queued up (first-started-wins) according
858  * to whether #DBUS_NAME_FLAG_ALLOW_REPLACEMENT was given.
859  *
860  * Conventionally, single-instance applications often offer a command
861  * line option called --replace which means to replace the current
862  * instance.  To implement this, always set
863  * #DBUS_NAME_FLAG_ALLOW_REPLACEMENT when you request your
864  * application's bus name.  When you lose ownership of your bus name,
865  * you need to exit.  Look for the signal "NameLost" from
866  * #DBUS_SERVICE_DBUS and #DBUS_INTERFACE_DBUS (the signal's first
867  * argument is the bus name that was lost).  If starting up without
868  * --replace, do not specify #DBUS_NAME_FLAG_REPLACE_EXISTING, and
869  * exit if you fail to become the bus name owner. If --replace is
870  * given, ask to replace the old owner.
871  *
872  * @param connection the connection
873  * @param name the name to request
874  * @param flags flags
875  * @param error location to store the error
876  * @returns a result code, -1 if error is set
877  */ 
878 int
879 dbus_bus_request_name (DBusConnection *connection,
880                        const char     *name,
881                        unsigned int    flags,
882                        DBusError      *error)
883 {
884   DBusMessage *message, *reply;
885   dbus_uint32_t result;
886
887   _dbus_return_val_if_fail (connection != NULL, 0);
888   _dbus_return_val_if_fail (name != NULL, 0);
889   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), 0);
890   _dbus_return_val_if_error_is_set (error, 0);
891   
892   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
893                                           DBUS_PATH_DBUS,
894                                           DBUS_INTERFACE_DBUS,
895                                           "RequestName");
896
897   if (message == NULL)
898     {
899       _DBUS_SET_OOM (error);
900       return -1;
901     }
902  
903   if (!dbus_message_append_args (message,
904                                  DBUS_TYPE_STRING, &name,
905                                  DBUS_TYPE_UINT32, &flags,
906                                  DBUS_TYPE_INVALID))
907     {
908       dbus_message_unref (message);
909       _DBUS_SET_OOM (error);
910       return -1;
911     }
912   
913   reply = dbus_connection_send_with_reply_and_block (connection, message, -1,
914                                                      error);
915   
916   dbus_message_unref (message);
917   
918   if (reply == NULL)
919     {
920       _DBUS_ASSERT_ERROR_IS_SET (error);
921       return -1;
922     }  
923
924   if (dbus_set_error_from_message (error, reply))
925     {
926       _DBUS_ASSERT_ERROR_IS_SET (error);
927       dbus_message_unref (reply);
928       return -1;
929     }
930   
931   if (!dbus_message_get_args (reply, error,
932                               DBUS_TYPE_UINT32, &result,
933                               DBUS_TYPE_INVALID))
934     {
935       _DBUS_ASSERT_ERROR_IS_SET (error);
936       dbus_message_unref (reply);
937       return -1;
938     }
939
940   dbus_message_unref (reply);
941   
942   return result;
943 }
944
945
946 /**
947  * Asks the bus to unassign the given name from this connection by
948  * invoking the ReleaseName method on the bus. The "ReleaseName"
949  * method is canonically documented in the D-Bus specification.
950  *
951  * Possible results are: #DBUS_RELEASE_NAME_REPLY_RELEASED
952  * which means you owned the name or were in the queue to own it,
953  * and and now you don't own it and aren't in the queue.
954  * #DBUS_RELEASE_NAME_REPLY_NOT_OWNER which means someone else
955  * owns the name so you can't release it.
956  * #DBUS_RELEASE_NAME_REPLY_NON_EXISTENT
957  * which means nobody owned the name.
958  * 
959  * @param connection the connection
960  * @param name the name to remove 
961  * @param error location to store the error
962  * @returns a result code, -1 if error is set
963  */ 
964 int
965 dbus_bus_release_name (DBusConnection *connection,
966                        const char     *name,
967                        DBusError      *error)
968 {
969   DBusMessage *message, *reply;
970   dbus_uint32_t result;
971
972   _dbus_return_val_if_fail (connection != NULL, 0);
973   _dbus_return_val_if_fail (name != NULL, 0);
974   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), 0);
975   _dbus_return_val_if_error_is_set (error, 0);
976
977   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
978                                           DBUS_PATH_DBUS,
979                                           DBUS_INTERFACE_DBUS,
980                                           "ReleaseName");
981
982   if (message == NULL)
983     {
984       _DBUS_SET_OOM (error);
985       return -1;
986     }
987
988   if (!dbus_message_append_args (message,
989                                  DBUS_TYPE_STRING, &name,
990                                  DBUS_TYPE_INVALID))
991     {
992       dbus_message_unref (message);
993       _DBUS_SET_OOM (error);
994       return -1;
995     }
996
997   reply = dbus_connection_send_with_reply_and_block (connection, message, -1,
998                                                      error);
999
1000   dbus_message_unref (message);
1001
1002   if (reply == NULL)
1003     {
1004       _DBUS_ASSERT_ERROR_IS_SET (error);
1005       return -1;
1006     }
1007
1008   if (dbus_set_error_from_message (error, reply))
1009     {
1010       _DBUS_ASSERT_ERROR_IS_SET (error);
1011       dbus_message_unref (reply);
1012       return -1;
1013     }
1014
1015   if (!dbus_message_get_args (reply, error,
1016                               DBUS_TYPE_UINT32, &result,
1017                               DBUS_TYPE_INVALID))
1018     {
1019       _DBUS_ASSERT_ERROR_IS_SET (error);
1020       dbus_message_unref (reply);
1021       return -1;
1022     }
1023
1024   dbus_message_unref (reply);
1025
1026   return result;
1027 }
1028
1029 /**
1030  * Asks the bus whether a certain name has an owner.
1031  *
1032  * Using this can easily result in a race condition,
1033  * since an owner can appear or disappear after you
1034  * call this.
1035  *
1036  * If you want to request a name, just request it;
1037  * if you want to avoid replacing a current owner,
1038  * don't specify #DBUS_NAME_FLAG_REPLACE_EXISTING and
1039  * you will get an error if there's already an owner.
1040  * 
1041  * @param connection the connection
1042  * @param name the name
1043  * @param error location to store any errors
1044  * @returns #TRUE if the name exists, #FALSE if not or on error
1045  */
1046 dbus_bool_t
1047 dbus_bus_name_has_owner (DBusConnection *connection,
1048                          const char     *name,
1049                          DBusError      *error)
1050 {
1051   DBusMessage *message, *reply;
1052   dbus_bool_t exists;
1053
1054   _dbus_return_val_if_fail (connection != NULL, FALSE);
1055   _dbus_return_val_if_fail (name != NULL, FALSE);
1056   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), FALSE);
1057   _dbus_return_val_if_error_is_set (error, FALSE);
1058   
1059   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
1060                                           DBUS_PATH_DBUS,
1061                                           DBUS_INTERFACE_DBUS,
1062                                           "NameHasOwner");
1063   if (message == NULL)
1064     {
1065       _DBUS_SET_OOM (error);
1066       return FALSE;
1067     }
1068   
1069   if (!dbus_message_append_args (message,
1070                                  DBUS_TYPE_STRING, &name,
1071                                  DBUS_TYPE_INVALID))
1072     {
1073       dbus_message_unref (message);
1074       _DBUS_SET_OOM (error);
1075       return FALSE;
1076     }
1077   
1078   reply = dbus_connection_send_with_reply_and_block (connection, message, -1, error);
1079   dbus_message_unref (message);
1080
1081   if (reply == NULL)
1082     {
1083       _DBUS_ASSERT_ERROR_IS_SET (error);
1084       return FALSE;
1085     }
1086
1087   if (!dbus_message_get_args (reply, error,
1088                               DBUS_TYPE_BOOLEAN, &exists,
1089                               DBUS_TYPE_INVALID))
1090     {
1091       _DBUS_ASSERT_ERROR_IS_SET (error);
1092       dbus_message_unref (reply);
1093       return FALSE;
1094     }
1095   
1096   dbus_message_unref (reply);
1097   return exists;
1098 }
1099
1100 /**
1101  * Starts a service that will request ownership of the given name.
1102  * The returned result will be one of be one of
1103  * #DBUS_START_REPLY_SUCCESS or #DBUS_START_REPLY_ALREADY_RUNNING if
1104  * successful.  Pass #NULL if you don't care about the result.
1105  * 
1106  * The flags parameter is for future expansion, currently you should
1107  * specify 0.
1108  *
1109  * It's often easier to avoid explicitly starting services, and
1110  * just send a method call to the service's bus name instead.
1111  * Method calls start a service to handle them by default
1112  * unless you call dbus_message_set_auto_start() to disable this
1113  * behavior.
1114  * 
1115  * @param connection the connection
1116  * @param name the name we want the new service to request
1117  * @param flags the flags (should always be 0 for now)
1118  * @param result a place to store the result or #NULL
1119  * @param error location to store any errors
1120  * @returns #TRUE if the activation succeeded, #FALSE if not
1121  */
1122 dbus_bool_t
1123 dbus_bus_start_service_by_name (DBusConnection *connection,
1124                                 const char     *name,
1125                                 dbus_uint32_t   flags,
1126                                 dbus_uint32_t  *result,
1127                                 DBusError      *error)
1128 {
1129   DBusMessage *msg;
1130   DBusMessage *reply;
1131
1132   _dbus_return_val_if_fail (connection != NULL, FALSE);
1133   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), FALSE);
1134   
1135   msg = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
1136                                       DBUS_PATH_DBUS,
1137                                       DBUS_INTERFACE_DBUS,
1138                                       "StartServiceByName");
1139
1140   if (!dbus_message_append_args (msg, DBUS_TYPE_STRING, &name,
1141                                  DBUS_TYPE_UINT32, &flags, DBUS_TYPE_INVALID))
1142     {
1143       dbus_message_unref (msg);
1144       _DBUS_SET_OOM (error);
1145       return FALSE;
1146     }
1147
1148   reply = dbus_connection_send_with_reply_and_block (connection, msg,
1149                                                      -1, error);
1150   dbus_message_unref (msg);
1151
1152   if (reply == NULL)
1153     {
1154       _DBUS_ASSERT_ERROR_IS_SET (error);
1155       return FALSE;
1156     }
1157
1158   if (dbus_set_error_from_message (error, reply))
1159     {
1160       _DBUS_ASSERT_ERROR_IS_SET (error);
1161       dbus_message_unref (reply);
1162       return FALSE;
1163     }
1164
1165   if (result != NULL &&
1166       !dbus_message_get_args (reply, error, DBUS_TYPE_UINT32,
1167                               result, DBUS_TYPE_INVALID))
1168     {
1169       _DBUS_ASSERT_ERROR_IS_SET (error);
1170       dbus_message_unref (reply);
1171       return FALSE;
1172     }
1173   
1174   dbus_message_unref (reply);
1175   return TRUE;
1176 }
1177
1178 static void
1179 send_no_return_values (DBusConnection *connection,
1180                        DBusMessage    *msg,
1181                        DBusError      *error)
1182 {
1183   if (error)
1184     {
1185       /* Block to check success codepath */
1186       DBusMessage *reply;
1187       
1188       reply = dbus_connection_send_with_reply_and_block (connection, msg,
1189                                                          -1, error);
1190       
1191       if (reply == NULL)
1192         _DBUS_ASSERT_ERROR_IS_SET (error);
1193       else
1194         dbus_message_unref (reply);
1195     }
1196   else
1197     {
1198       /* Silently-fail nonblocking codepath */
1199       dbus_message_set_no_reply (msg, TRUE);
1200       dbus_connection_send (connection, msg, NULL);
1201     }
1202 }
1203
1204 /**
1205  * Adds a match rule to match messages going through the message bus.
1206  * The "rule" argument is the string form of a match rule.
1207  *
1208  * If you pass #NULL for the error, this function will not
1209  * block; the match thus won't be added until you flush the
1210  * connection, and if there's an error adding the match
1211  * (only possible error is lack of resources in the bus),
1212  * you won't find out about it.
1213  *
1214  * If you pass non-#NULL for the error this function will
1215  * block until it gets a reply.
1216  *
1217  * Normal API conventions would have the function return
1218  * a boolean value indicating whether the error was set,
1219  * but that would require blocking always to determine
1220  * the return value.
1221  *
1222  * The AddMatch method is fully documented in the D-Bus 
1223  * specification. For quick reference, the format of the 
1224  * match rules is discussed here, but the specification 
1225  * is the canonical version of this information.
1226  *
1227  * Rules are specified as a string of comma separated 
1228  * key/value pairs. An example is 
1229  * "type='signal',sender='org.freedesktop.DBus',
1230  * interface='org.freedesktop.DBus',member='Foo',
1231  * path='/bar/foo',destination=':452345.34'"
1232  *
1233  * Possible keys you can match on are type, sender, 
1234  * interface, member, path, destination and numbered
1235  * keys to match message args (keys are 'arg0', 'arg1', etc.).
1236  * Omitting a key from the rule indicates 
1237  * a wildcard match.  For instance omitting
1238  * the member from a match rule but adding a sender would
1239  * let all messages from that sender through regardless of
1240  * the member.
1241  *
1242  * Matches are inclusive not exclusive so as long as one 
1243  * rule matches the message will get through.  It is important
1244  * to note this because every time a message is received the 
1245  * application will be paged into memory to process it.  This
1246  * can cause performance problems such as draining batteries
1247  * on embedded platforms.
1248  *
1249  * If you match message args ('arg0', 'arg1', and so forth)
1250  * only string arguments will match. That is, arg0='5' means
1251  * match the string "5" not the integer 5.
1252  *
1253  * Currently there is no way to match against non-string arguments.
1254  *
1255  * Matching on interface is tricky because method call
1256  * messages only optionally specify the interface.
1257  * If a message omits the interface, then it will NOT match
1258  * if the rule specifies an interface name. This means match
1259  * rules on method calls should not usually give an interface.
1260  *
1261  * However, signal messages are required to include the interface
1262  * so when matching signals usually you should specify the interface
1263  * in the match rule.
1264  * 
1265  * For security reasons, you can match arguments only up to
1266  * #DBUS_MAXIMUM_MATCH_RULE_ARG_NUMBER.
1267  *
1268  * Match rules have a maximum length of #DBUS_MAXIMUM_MATCH_RULE_LENGTH
1269  * bytes.
1270  *
1271  * Both of these maximums are much higher than you're likely to need,
1272  * they only exist because the D-Bus bus daemon has fixed limits on
1273  * all resource usage.
1274  *
1275  * @param connection connection to the message bus
1276  * @param rule textual form of match rule
1277  * @param error location to store any errors
1278  */
1279 void
1280 dbus_bus_add_match (DBusConnection *connection,
1281                     const char     *rule,
1282                     DBusError      *error)
1283 {
1284   DBusMessage *msg;
1285
1286   _dbus_return_if_fail (rule != NULL);
1287
1288   msg = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
1289                                       DBUS_PATH_DBUS,
1290                                       DBUS_INTERFACE_DBUS,
1291                                       "AddMatch");
1292
1293   if (msg == NULL)
1294     {
1295       _DBUS_SET_OOM (error);
1296       return;
1297     }
1298
1299   if (!dbus_message_append_args (msg, DBUS_TYPE_STRING, &rule,
1300                                  DBUS_TYPE_INVALID))
1301     {
1302       dbus_message_unref (msg);
1303       _DBUS_SET_OOM (error);
1304       return;
1305     }
1306
1307   send_no_return_values (connection, msg, error);
1308
1309   dbus_message_unref (msg);
1310 }
1311
1312 /**
1313  * Removes a previously-added match rule "by value" (the most
1314  * recently-added identical rule gets removed).  The "rule" argument
1315  * is the string form of a match rule.
1316  *
1317  * The bus compares match rules semantically, not textually, so
1318  * whitespace and ordering don't have to be identical to
1319  * the rule you passed to dbus_bus_add_match().
1320  * 
1321  * If you pass #NULL for the error, this function will not
1322  * block; otherwise it will. See detailed explanation in
1323  * docs for dbus_bus_add_match().
1324  * 
1325  * @param connection connection to the message bus
1326  * @param rule textual form of match rule
1327  * @param error location to store any errors
1328  */
1329 void
1330 dbus_bus_remove_match (DBusConnection *connection,
1331                        const char     *rule,
1332                        DBusError      *error)
1333 {
1334   DBusMessage *msg;
1335
1336   _dbus_return_if_fail (rule != NULL);
1337   
1338   msg = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
1339                                       DBUS_PATH_DBUS,
1340                                       DBUS_INTERFACE_DBUS,
1341                                       "RemoveMatch");
1342
1343   if (!dbus_message_append_args (msg, DBUS_TYPE_STRING, &rule,
1344                                  DBUS_TYPE_INVALID))
1345     {
1346       dbus_message_unref (msg);
1347       _DBUS_SET_OOM (error);
1348       return;
1349     }
1350
1351   send_no_return_values (connection, msg, error);
1352
1353   dbus_message_unref (msg);
1354 }
1355
1356 /** @} */