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