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