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