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