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