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