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