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