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