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