* configure.in: add DBUS_BINDIR as a #define to C source code.
[platform/upstream/dbus.git] / dbus / dbus-bus.c
1 /* -*- mode: C; c-file-style: "gnu" -*- */
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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  */
24
25 #include "dbus-bus.h"
26 #include "dbus-protocol.h"
27 #include "dbus-internals.h"
28 #include "dbus-message.h"
29 #include "dbus-marshal-validate.h"
30 #include "dbus-threads-internal.h"
31 #include "dbus-connection-internal.h"
32 #include <string.h>
33
34 /**
35  * @defgroup DBusBus Message bus APIs
36  * @ingroup DBus
37  * @brief Functions for communicating with the message bus
38  *
39  * @todo right now the default address of the system bus is hardcoded,
40  * so if you change it in the global config file suddenly you have to
41  * set DBUS_SYSTEM_BUS_ADDRESS env variable.  Might be nice if the
42  * client lib somehow read the config file, or if the bus on startup
43  * somehow wrote out its address to a well-known spot, but might also
44  * not be worth it.
45  */
46
47 /**
48  * @defgroup DBusBusInternals Message bus APIs internals
49  * @ingroup DBusInternals
50  * @brief Internals of functions for communicating with the message bus
51  *
52  * @{
53  */
54
55 /**
56  * Block of message-bus-related data we attach to each
57  * #DBusConnection used with these convenience functions.
58  *
59  */
60 typedef struct
61 {
62   DBusConnection *connection; /**< Connection we're associated with */
63   char *unique_name; /**< Unique name of this connection */
64
65   unsigned int is_well_known : 1; /**< Is one of the well-known connections in our global array */
66 } BusData;
67
68 /** The slot we have reserved to store BusData.
69  */
70 static dbus_int32_t bus_data_slot = -1;
71
72 /** Number of bus types */
73 #define N_BUS_TYPES 3
74
75 static DBusConnection *bus_connections[N_BUS_TYPES];
76 static char *bus_connection_addresses[N_BUS_TYPES] = { NULL, NULL, NULL };
77
78 static DBusBusType activation_bus_type = DBUS_BUS_STARTER;
79
80 static dbus_bool_t initialized = FALSE;
81
82 /**
83  * Lock for globals in this file
84  */
85 _DBUS_DEFINE_GLOBAL_LOCK (bus);
86
87 static void
88 addresses_shutdown_func (void *data)
89 {
90   int i;
91
92   i = 0;
93   while (i < N_BUS_TYPES)
94     {
95       if (bus_connections[i] != NULL)
96         _dbus_warn ("dbus_shutdown() called but connections were still live!");
97       
98       dbus_free (bus_connection_addresses[i]);
99       bus_connection_addresses[i] = NULL;
100       ++i;
101     }
102
103   activation_bus_type = DBUS_BUS_STARTER;
104 }
105
106 static dbus_bool_t
107 get_from_env (char           **connection_p,
108               const char      *env_var)
109 {
110   const char *s;
111   
112   _dbus_assert (*connection_p == NULL);
113   
114   s = _dbus_getenv (env_var);
115   if (s == NULL || *s == '\0')
116     return TRUE; /* successfully didn't use the env var */
117   else
118     {
119       *connection_p = _dbus_strdup (s);
120       return *connection_p != NULL;
121     }
122 }
123
124 static dbus_bool_t
125 init_connections_unlocked (void)
126 {
127   if (!initialized)
128     {
129       const char *s;
130       int i;
131
132       i = 0;
133       while (i < N_BUS_TYPES)
134         {
135           bus_connections[i] = NULL;
136           ++i;
137         }
138
139       /* Don't init these twice, we may run this code twice if
140        * init_connections_unlocked() fails midway through.
141        * In practice, each block below should contain only one
142        * "return FALSE" or running through twice may not
143        * work right.
144        */
145       
146        if (bus_connection_addresses[DBUS_BUS_SYSTEM] == NULL)
147          {
148            _dbus_verbose ("Filling in system bus address...\n");
149            
150            if (!get_from_env (&bus_connection_addresses[DBUS_BUS_SYSTEM],
151                               "DBUS_SYSTEM_BUS_ADDRESS"))
152              return FALSE;
153          }
154
155                   
156        if (bus_connection_addresses[DBUS_BUS_SYSTEM] == NULL)
157          {
158            /* Use default system bus address if none set in environment */
159            bus_connection_addresses[DBUS_BUS_SYSTEM] =
160              _dbus_strdup (DBUS_SYSTEM_BUS_DEFAULT_ADDRESS);
161            if (bus_connection_addresses[DBUS_BUS_SYSTEM] == NULL)
162              return FALSE;
163            
164            _dbus_verbose ("  used default system bus \"%s\"\n",
165                           bus_connection_addresses[DBUS_BUS_SYSTEM]);
166          }
167        else
168          _dbus_verbose ("  used env var system bus \"%s\"\n",
169                         bus_connection_addresses[DBUS_BUS_SYSTEM]);
170           
171       if (bus_connection_addresses[DBUS_BUS_SESSION] == NULL)
172         {
173           _dbus_verbose ("Filling in session bus address...\n");
174           
175           if (!get_from_env (&bus_connection_addresses[DBUS_BUS_SESSION],
176                              "DBUS_SESSION_BUS_ADDRESS"))
177             return FALSE;
178
179           if (bus_connection_addresses[DBUS_BUS_SESSION] == NULL)
180             bus_connection_addresses[DBUS_BUS_SESSION] =
181               _dbus_strdup (DBUS_SESSION_BUS_DEFAULT_ADDRESS);
182            if (bus_connection_addresses[DBUS_BUS_SESSION] == NULL)
183              return FALSE;
184
185           _dbus_verbose ("  \"%s\"\n", bus_connection_addresses[DBUS_BUS_SESSION] ?
186                          bus_connection_addresses[DBUS_BUS_SESSION] : "none set");
187         }
188
189       if (bus_connection_addresses[DBUS_BUS_STARTER] == NULL)
190         {
191           _dbus_verbose ("Filling in activation bus address...\n");
192           
193           if (!get_from_env (&bus_connection_addresses[DBUS_BUS_STARTER],
194                              "DBUS_STARTER_ADDRESS"))
195             return FALSE;
196           
197           _dbus_verbose ("  \"%s\"\n", bus_connection_addresses[DBUS_BUS_STARTER] ?
198                          bus_connection_addresses[DBUS_BUS_STARTER] : "none set");
199         }
200
201
202       if (bus_connection_addresses[DBUS_BUS_STARTER] != NULL)
203         {
204           s = _dbus_getenv ("DBUS_STARTER_BUS_TYPE");
205               
206           if (s != NULL)
207             {
208               _dbus_verbose ("Bus activation type was set to \"%s\"\n", s);
209                   
210               if (strcmp (s, "system") == 0)
211                 activation_bus_type = DBUS_BUS_SYSTEM;
212               else if (strcmp (s, "session") == 0)
213                 activation_bus_type = DBUS_BUS_SESSION;
214             }
215         }
216       else
217         {
218           /* Default to the session bus instead if available */
219           if (bus_connection_addresses[DBUS_BUS_SESSION] != NULL)
220             {
221               bus_connection_addresses[DBUS_BUS_STARTER] =
222                 _dbus_strdup (bus_connection_addresses[DBUS_BUS_SESSION]);
223               if (bus_connection_addresses[DBUS_BUS_STARTER] == NULL)
224                 return FALSE;
225             }
226         }
227       
228       /* If we return FALSE we have to be sure that restarting
229        * the above code will work right
230        */
231       
232       if (!_dbus_setenv ("DBUS_ACTIVATION_ADDRESS", NULL))
233         return FALSE;
234
235       if (!_dbus_setenv ("DBUS_ACTIVATION_BUS_TYPE", NULL))
236         return FALSE;
237       
238       if (!_dbus_register_shutdown_func (addresses_shutdown_func,
239                                          NULL))
240         return FALSE;
241       
242       initialized = TRUE;
243     }
244
245   return initialized;
246 }
247
248 static void
249 bus_data_free (void *data)
250 {
251   BusData *bd = data;
252   
253   if (bd->is_well_known)
254     {
255       int i;
256       _DBUS_LOCK (bus);
257       /* We may be stored in more than one slot */
258       i = 0;
259       while (i < N_BUS_TYPES)
260         {
261           if (bus_connections[i] == bd->connection)
262             bus_connections[i] = NULL;
263           
264           ++i;
265         }
266       _DBUS_UNLOCK (bus);
267     }
268   
269   dbus_free (bd->unique_name);
270   dbus_free (bd);
271
272   dbus_connection_free_data_slot (&bus_data_slot);
273 }
274
275 static BusData*
276 ensure_bus_data (DBusConnection *connection)
277 {
278   BusData *bd;
279
280   if (!dbus_connection_allocate_data_slot (&bus_data_slot))
281     return NULL;
282
283   bd = dbus_connection_get_data (connection, bus_data_slot);
284   if (bd == NULL)
285     {      
286       bd = dbus_new0 (BusData, 1);
287       if (bd == NULL)
288         {
289           dbus_connection_free_data_slot (&bus_data_slot);
290           return NULL;
291         }
292
293       bd->connection = connection;
294       
295       if (!dbus_connection_set_data (connection, bus_data_slot, bd,
296                                      bus_data_free))
297         {
298           dbus_free (bd);
299           dbus_connection_free_data_slot (&bus_data_slot);
300           return NULL;
301         }
302
303       /* Data slot refcount now held by the BusData */
304     }
305   else
306     {
307       dbus_connection_free_data_slot (&bus_data_slot);
308     }
309
310   return bd;
311 }
312
313 /* internal function that checks to see if this
314    is a shared connection owned by the bus and if it is unref it */
315 void
316 _dbus_bus_check_connection_and_unref_unlocked (DBusConnection *connection)
317 {
318   _DBUS_LOCK (bus);
319
320   if (bus_connections[DBUS_BUS_SYSTEM] == connection)
321     {
322       bus_connections[DBUS_BUS_SYSTEM] = NULL;
323       _dbus_connection_unref_unlocked (connection);
324     }
325   else if (bus_connections[DBUS_BUS_SESSION] == connection)
326     {
327       bus_connections[DBUS_BUS_SESSION] = NULL;
328       _dbus_connection_unref_unlocked (connection);
329     }
330   else if (bus_connections[DBUS_BUS_STARTER] == connection)
331     {
332       bus_connections[DBUS_BUS_STARTER] = NULL;
333       _dbus_connection_unref_unlocked (connection);
334     }
335
336   _DBUS_UNLOCK (bus);
337 }
338
339 static DBusConnection *
340 internal_bus_get (DBusBusType  type,
341               DBusError   *error, dbus_bool_t private)
342 {
343   const char *address;
344   DBusConnection *connection;
345   BusData *bd;
346   DBusBusType address_type;
347
348   _dbus_return_val_if_fail (type >= 0 && type < N_BUS_TYPES, NULL);
349   _dbus_return_val_if_error_is_set (error, NULL);
350
351   _DBUS_LOCK (bus);
352
353   if (!init_connections_unlocked ())
354     {
355       _DBUS_UNLOCK (bus);
356       _DBUS_SET_OOM (error);
357       return NULL;
358     }
359
360   /* We want to use the activation address even if the
361    * activating bus is the session or system bus,
362    * per the spec.
363    */
364   address_type = type;
365   
366   /* Use the real type of the activation bus for getting its
367    * connection, but only if the real type's address is available. (If
368    * the activating bus isn't a well-known bus then
369    * activation_bus_type == DBUS_BUS_STARTER)
370    */
371   if (type == DBUS_BUS_STARTER &&
372       bus_connection_addresses[activation_bus_type] != NULL)
373     type = activation_bus_type;
374   
375   if (!private && bus_connections[type] != NULL)
376     {
377       connection = bus_connections[type];
378       dbus_connection_ref (connection);
379       
380       _DBUS_UNLOCK (bus);
381       return connection;
382     }
383
384   address = bus_connection_addresses[address_type];
385   if (address == NULL)
386     {
387       dbus_set_error (error, DBUS_ERROR_FAILED,
388                       "Unable to determine the address of the message bus (try 'man dbus-launch' and 'man dbus-daemon' for help)");
389       _DBUS_UNLOCK (bus);
390       return NULL;
391     }
392
393   if (private)
394     connection = dbus_connection_open_private(address, error);
395   else
396     connection = dbus_connection_open (address, error);
397   
398   if (!connection)
399     {
400       _DBUS_ASSERT_ERROR_IS_SET (error);
401       _DBUS_UNLOCK (bus);
402       return NULL;
403     }
404
405   /* By default we're bound to the lifecycle of
406    * the message bus.
407    */
408   dbus_connection_set_exit_on_disconnect (connection,
409                                           TRUE);
410   
411   if (!dbus_bus_register (connection, error))
412     {
413       _DBUS_ASSERT_ERROR_IS_SET (error);
414       _dbus_connection_close_internal (connection);
415       dbus_connection_unref (connection);
416
417       _DBUS_UNLOCK (bus);
418       return NULL;
419     }
420
421   if (!private)
422     {
423       /* get a hard ref to the connection */
424       bus_connections[type] = connection;
425       dbus_connection_ref (bus_connections[type]);
426     }
427   
428   bd = ensure_bus_data (connection);
429   _dbus_assert (bd != NULL);
430
431   bd->is_well_known = TRUE;
432
433   _DBUS_UNLOCK (bus);
434   return connection;
435 }
436
437
438 /** @} */ /* end of implementation details docs */
439
440 /**
441  * @addtogroup DBusBus
442  * @{
443  */
444
445 /**
446  * Connects to a bus daemon and registers the client with it.  If a
447  * connection to the bus already exists, then that connection is
448  * returned.  Caller owns a reference to the bus.
449  *
450  * @param type bus type
451  * @param error address where an error can be returned.
452  * @returns a DBusConnection with new ref
453  */
454 DBusConnection *
455 dbus_bus_get (DBusBusType  type,
456               DBusError   *error) {
457   return internal_bus_get(type, error, FALSE);
458 }
459
460 /**
461  * Connects to a bus daemon and registers the client with it.  Unlike
462  * dbus_bus_get(), always creates a new connection. This connection
463  * will not be saved or recycled by libdbus. Caller owns a reference
464  * to the bus.
465  *
466  * @param type bus type
467  * @param error address where an error can be returned.
468  * @returns a DBusConnection with new ref
469  */
470 DBusConnection *
471 dbus_bus_get_private (DBusBusType  type,
472               DBusError   *error) {
473   return internal_bus_get(type, error, TRUE);
474 }
475
476 /**
477  * Registers a connection with the bus. This must be the first
478  * thing an application does when connecting to the message bus.
479  * If registration succeeds, the unique name will be set,
480  * and can be obtained using dbus_bus_get_unique_name().
481  * 
482  * @param connection the connection
483  * @param error place to store errors
484  * @returns #TRUE on success
485  */
486 dbus_bool_t
487 dbus_bus_register (DBusConnection *connection,
488                    DBusError      *error)
489 {
490   DBusMessage *message, *reply;
491   char *name;
492   BusData *bd;
493   dbus_bool_t retval;
494
495   _dbus_return_val_if_fail (connection != NULL, FALSE);
496   _dbus_return_val_if_error_is_set (error, FALSE);
497
498   retval = FALSE;
499   
500   bd = ensure_bus_data (connection);
501   if (bd == NULL)
502     {
503       _DBUS_SET_OOM (error);
504       return FALSE;
505     }
506
507   if (bd->unique_name != NULL)
508     {
509       _dbus_warn ("Attempt to register the same DBusConnection with the message bus, but it is already registered\n");
510       /* This isn't an error, it's a programming bug. We'll be nice
511        * and not _dbus_assert_not_reached()
512        */
513       return TRUE;
514     }
515   
516   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
517                                           DBUS_PATH_DBUS,
518                                           DBUS_INTERFACE_DBUS,
519                                           "Hello"); 
520
521   if (!message)
522     {
523       _DBUS_SET_OOM (error);
524       return FALSE;
525     }
526   
527   reply = dbus_connection_send_with_reply_and_block (connection, message, -1, error);
528
529   dbus_message_unref (message);
530   
531   if (reply == NULL)
532     goto out;
533   else if (dbus_set_error_from_message (error, reply))
534     goto out;
535   else if (!dbus_message_get_args (reply, error,
536                                    DBUS_TYPE_STRING, &name,
537                                    DBUS_TYPE_INVALID))
538     goto out;
539   
540   bd->unique_name = _dbus_strdup (name);
541   if (bd->unique_name == NULL)
542     {
543       _DBUS_SET_OOM (error);
544       goto out;
545     }
546   
547   retval = TRUE;
548   
549  out:
550   if (reply)
551     dbus_message_unref (reply);
552
553   if (!retval)
554     _DBUS_ASSERT_ERROR_IS_SET (error);
555   
556   return retval;
557 }
558
559
560 /**
561  * Sets the unique name of the connection.  Can only be used if you
562  * registered with the bus manually (i.e. if you did not call
563  * dbus_bus_register()). Can only be called once per connection.
564  *
565  * @param connection the connection
566  * @param unique_name the unique name
567  * @returns #FALSE if not enough memory
568  */
569 dbus_bool_t
570 dbus_bus_set_unique_name (DBusConnection *connection,
571                           const char     *unique_name)
572 {
573   BusData *bd;
574
575   _dbus_return_val_if_fail (connection != NULL, FALSE);
576   _dbus_return_val_if_fail (unique_name != NULL, FALSE);
577   
578   bd = ensure_bus_data (connection);
579   if (bd == NULL)
580     return FALSE;
581
582   _dbus_assert (bd->unique_name == NULL);
583   
584   bd->unique_name = _dbus_strdup (unique_name);
585   return bd->unique_name != NULL;
586 }
587
588 /**
589  * Gets the unique name of the connection.  Only possible after the
590  * connection has been registered with the message bus.
591  *
592  * The name remains valid for the duration of the connection and
593  * should not be freed by the caller.
594  * 
595  * @param connection the connection
596  * @returns the unique name or NULL on error
597  */
598 const char*
599 dbus_bus_get_unique_name (DBusConnection *connection)
600 {
601   BusData *bd;
602
603   _dbus_return_val_if_fail (connection != NULL, NULL);
604   
605   bd = ensure_bus_data (connection);
606   if (bd == NULL)
607     return NULL;
608   
609   return bd->unique_name;
610 }
611
612 /**
613  * Asks the bus to return the uid of the named
614  * connection.
615  *
616  * Not going to work on Windows, the bus should return
617  * an error then.
618  * 
619  * @param connection the connection
620  * @param name a name owned by the connection
621  * @param error location to store the error
622  * @returns a result code, -1 if error is set
623  */ 
624 unsigned long
625 dbus_bus_get_unix_user (DBusConnection *connection,
626                         const char     *name,
627                         DBusError      *error)
628 {
629   DBusMessage *message, *reply;
630   dbus_uint32_t uid;
631
632   _dbus_return_val_if_fail (connection != NULL, DBUS_UID_UNSET);
633   _dbus_return_val_if_fail (name != NULL, DBUS_UID_UNSET);
634   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), DBUS_UID_UNSET);
635   _dbus_return_val_if_error_is_set (error, DBUS_UID_UNSET);
636   
637   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
638                                           DBUS_PATH_DBUS,
639                                           DBUS_INTERFACE_DBUS,
640                                           "GetConnectionUnixUser");
641
642   if (message == NULL)
643     {
644       _DBUS_SET_OOM (error);
645       return DBUS_UID_UNSET;
646     }
647  
648   if (!dbus_message_append_args (message,
649                                  DBUS_TYPE_STRING, &name,
650                                  DBUS_TYPE_INVALID))
651     {
652       dbus_message_unref (message);
653       _DBUS_SET_OOM (error);
654       return DBUS_UID_UNSET;
655     }
656   
657   reply = dbus_connection_send_with_reply_and_block (connection, message, -1,
658                                                      error);
659   
660   dbus_message_unref (message);
661   
662   if (reply == NULL)
663     {
664       _DBUS_ASSERT_ERROR_IS_SET (error);
665       return DBUS_UID_UNSET;
666     }  
667
668   if (dbus_set_error_from_message (error, reply))
669     {
670       _DBUS_ASSERT_ERROR_IS_SET (error);
671       dbus_message_unref (reply);
672       return DBUS_UID_UNSET;
673     }
674   
675   if (!dbus_message_get_args (reply, error,
676                               DBUS_TYPE_UINT32, &uid,
677                               DBUS_TYPE_INVALID))
678     {
679       _DBUS_ASSERT_ERROR_IS_SET (error);
680       dbus_message_unref (reply);
681       return DBUS_UID_UNSET;
682     }
683
684   dbus_message_unref (reply);
685   
686   return (unsigned long) uid;
687 }
688
689
690 /**
691  * Asks the bus to assign the given name to this connection by invoking
692  * the RequestName method on the bus. This method is fully documented
693  * in the D-Bus specification. For quick reference, the flags and
694  * result codes are discussed here, but the specification is the
695  * canonical version of this information.
696  *
697  * The #DBUS_NAME_FLAG_ALLOW_REPLACEMENT flag indicates that the caller
698  * will allow other services to take over the name from the current owner.
699  *
700  * The #DBUS_NAME_FLAG_REPLACE_EXISTING flag indicates that the caller
701  * would like to take over the name from the current owner.
702  * If the current name owner did not use #DBUS_NAME_FLAG_ALLOW_REPLACEMENT
703  * then this flag indicates that the caller would like to be placed
704  * in the queue to own the name when the current owner lets go.
705  *
706  * If no flags are given, an application will receive the requested
707  * name only if the name is currently unowned; it will NOT give
708  * up the name if another application asks to take it over using
709  * #DBUS_NAME_FLAG_REPLACE_EXISTING.
710  *
711  * This function returns a result code. The possible result codes
712  * are as follows.
713  * 
714  * #DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER means that the name had no
715  * existing owner, and the caller is now the primary owner; or that
716  * the name had an owner, and the caller specified
717  * #DBUS_NAME_FLAG_REPLACE_EXISTING, and the current owner
718  * specified #DBUS_NAME_FLAG_ALLOW_REPLACEMENT.
719  *
720  * #DBUS_REQUEST_NAME_REPLY_IN_QUEUE happens only if the caller does NOT
721  * specify #DBUS_NAME_FLAG_DO_NOT_QUEUE and either the current owner
722  * did NOT specify #DBUS_NAME_FLAG_ALLOW_REPLACEMENT or the caller did NOT
723  * specify #DBUS_NAME_FLAG_REPLACE_EXISTING. In this case the caller ends up 
724  * in a queue to own the name after the current owner gives it up.
725  *
726  * #DBUS_REQUEST_NAME_REPLY_EXISTS happens if the name has an owner
727  * already and the caller specifies #DBUS_NAME_FLAG_DO_NOT_QUEUE
728  * and either the current owner has NOT specified 
729  * #DBUS_NAME_FLAG_ALLOW_REPLACEMENT or the caller did NOT specify 
730  * #DBUS_NAME_FLAG_REPLACE_EXISTING.
731  *
732  * #DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER happens if an application
733  * requests a name it already owns.
734  *
735  * When a service represents an application, say "text editor," then
736  * it should specify #DBUS_NAME_FLAG_ALLOW_REPLACEMENT if it wants
737  * the last editor started to be the user's editor vs. the first one
738  * started.  Then any editor that can be the user's editor should
739  * specify #DBUS_NAME_FLAG_REPLACE_EXISTING to either take over
740  * (last-started-wins) or be queued up (first-started-wins) according
741  * to whether #DBUS_NAME_FLAG_ALLOW_REPLACEMENT was given.
742  * 
743  * @param connection the connection
744  * @param name the name to request
745  * @param flags flags
746  * @param error location to store the error
747  * @returns a result code, -1 if error is set
748  */ 
749 int
750 dbus_bus_request_name (DBusConnection *connection,
751                        const char     *name,
752                        unsigned int    flags,
753                        DBusError      *error)
754 {
755   DBusMessage *message, *reply;
756   dbus_uint32_t result;
757
758   _dbus_return_val_if_fail (connection != NULL, 0);
759   _dbus_return_val_if_fail (name != NULL, 0);
760   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), 0);
761   _dbus_return_val_if_error_is_set (error, 0);
762   
763   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
764                                           DBUS_PATH_DBUS,
765                                           DBUS_INTERFACE_DBUS,
766                                           "RequestName");
767
768   if (message == NULL)
769     {
770       _DBUS_SET_OOM (error);
771       return -1;
772     }
773  
774   if (!dbus_message_append_args (message,
775                                  DBUS_TYPE_STRING, &name,
776                                  DBUS_TYPE_UINT32, &flags,
777                                  DBUS_TYPE_INVALID))
778     {
779       dbus_message_unref (message);
780       _DBUS_SET_OOM (error);
781       return -1;
782     }
783   
784   reply = dbus_connection_send_with_reply_and_block (connection, message, -1,
785                                                      error);
786   
787   dbus_message_unref (message);
788   
789   if (reply == NULL)
790     {
791       _DBUS_ASSERT_ERROR_IS_SET (error);
792       return -1;
793     }  
794
795   if (dbus_set_error_from_message (error, reply))
796     {
797       _DBUS_ASSERT_ERROR_IS_SET (error);
798       dbus_message_unref (reply);
799       return -1;
800     }
801   
802   if (!dbus_message_get_args (reply, error,
803                               DBUS_TYPE_UINT32, &result,
804                               DBUS_TYPE_INVALID))
805     {
806       _DBUS_ASSERT_ERROR_IS_SET (error);
807       dbus_message_unref (reply);
808       return -1;
809     }
810
811   dbus_message_unref (reply);
812   
813   return result;
814 }
815
816
817 /**
818  * Asks the bus to unassign the given name to this connection by invoking
819  * the ReleaseName method on the bus. This method is fully documented
820  * in the D-Bus specification.
821  *
822  * @param connection the connection
823  * @param name the name to remove 
824  * @param error location to store the error
825  * @returns a result code, -1 if error is set
826  */ 
827 int
828 dbus_bus_release_name (DBusConnection *connection,
829                        const char     *name,
830                        DBusError      *error)
831 {
832   DBusMessage *message, *reply;
833   dbus_uint32_t result;
834
835   _dbus_return_val_if_fail (connection != NULL, 0);
836   _dbus_return_val_if_fail (name != NULL, 0);
837   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), 0);
838   _dbus_return_val_if_error_is_set (error, 0);
839
840   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
841                                           DBUS_PATH_DBUS,
842                                           DBUS_INTERFACE_DBUS,
843                                           "ReleaseName");
844
845   if (message == NULL)
846     {
847       _DBUS_SET_OOM (error);
848       return -1;
849     }
850
851   if (!dbus_message_append_args (message,
852                                  DBUS_TYPE_STRING, &name,
853                                  DBUS_TYPE_INVALID))
854     {
855       dbus_message_unref (message);
856       _DBUS_SET_OOM (error);
857       return -1;
858     }
859
860   reply = dbus_connection_send_with_reply_and_block (connection, message, -1,
861                                                      error);
862
863   dbus_message_unref (message);
864
865   if (reply == NULL)
866     {
867       _DBUS_ASSERT_ERROR_IS_SET (error);
868       return -1;
869     }
870
871   if (dbus_set_error_from_message (error, reply))
872     {
873       _DBUS_ASSERT_ERROR_IS_SET (error);
874       dbus_message_unref (reply);
875       return -1;
876     }
877
878   if (!dbus_message_get_args (reply, error,
879                               DBUS_TYPE_UINT32, &result,
880                               DBUS_TYPE_INVALID))
881     {
882       _DBUS_ASSERT_ERROR_IS_SET (error);
883       dbus_message_unref (reply);
884       return -1;
885     }
886
887   dbus_message_unref (reply);
888
889   return result;
890 }
891
892 /**
893  * Checks whether a certain name has an owner.
894  *
895  * @param connection the connection
896  * @param name the name
897  * @param error location to store any errors
898  * @returns #TRUE if the name exists, #FALSE if not or on error
899  */
900 dbus_bool_t
901 dbus_bus_name_has_owner (DBusConnection *connection,
902                          const char     *name,
903                          DBusError      *error)
904 {
905   DBusMessage *message, *reply;
906   dbus_bool_t exists;
907
908   _dbus_return_val_if_fail (connection != NULL, FALSE);
909   _dbus_return_val_if_fail (name != NULL, FALSE);
910   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), FALSE);
911   _dbus_return_val_if_error_is_set (error, FALSE);
912   
913   message = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
914                                           DBUS_PATH_DBUS,
915                                           DBUS_INTERFACE_DBUS,
916                                           "NameHasOwner");
917   if (message == NULL)
918     {
919       _DBUS_SET_OOM (error);
920       return FALSE;
921     }
922   
923   if (!dbus_message_append_args (message,
924                                  DBUS_TYPE_STRING, &name,
925                                  DBUS_TYPE_INVALID))
926     {
927       dbus_message_unref (message);
928       _DBUS_SET_OOM (error);
929       return FALSE;
930     }
931   
932   reply = dbus_connection_send_with_reply_and_block (connection, message, -1, error);
933   dbus_message_unref (message);
934
935   if (reply == NULL)
936     {
937       _DBUS_ASSERT_ERROR_IS_SET (error);
938       return FALSE;
939     }
940
941   if (!dbus_message_get_args (reply, error,
942                               DBUS_TYPE_BOOLEAN, &exists,
943                               DBUS_TYPE_INVALID))
944     {
945       _DBUS_ASSERT_ERROR_IS_SET (error);
946       dbus_message_unref (reply);
947       return FALSE;
948     }
949   
950   dbus_message_unref (reply);
951   return exists;
952 }
953
954 /**
955  * Starts a service that will request ownership of the given name.
956  * The returned result will be one of be one of
957  * #DBUS_START_REPLY_SUCCESS or #DBUS_START_REPLY_ALREADY_RUNNING if
958  * successful.  Pass #NULL if you don't care about the result.
959  * 
960  * The flags parameter is for future expansion, currently you should
961  * specify 0.
962  *
963  * @param connection the connection
964  * @param name the name we want the new service to request
965  * @param flags the flags (should always be 0 for now)
966  * @param result a place to store the result or #NULL
967  * @param error location to store any errors
968  * @returns #TRUE if the activation succeeded, #FALSE if not
969  */
970 dbus_bool_t
971 dbus_bus_start_service_by_name (DBusConnection *connection,
972                                 const char     *name,
973                                 dbus_uint32_t   flags,
974                                 dbus_uint32_t  *result,
975                                 DBusError      *error)
976 {
977   DBusMessage *msg;
978   DBusMessage *reply;
979
980   _dbus_return_val_if_fail (connection != NULL, FALSE);
981   _dbus_return_val_if_fail (_dbus_check_is_valid_bus_name (name), FALSE);
982   
983   msg = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
984                                       DBUS_PATH_DBUS,
985                                       DBUS_INTERFACE_DBUS,
986                                       "StartServiceByName");
987
988   if (!dbus_message_append_args (msg, DBUS_TYPE_STRING, &name,
989                                  DBUS_TYPE_UINT32, &flags, DBUS_TYPE_INVALID))
990     {
991       dbus_message_unref (msg);
992       _DBUS_SET_OOM (error);
993       return FALSE;
994     }
995
996   reply = dbus_connection_send_with_reply_and_block (connection, msg,
997                                                      -1, error);
998   dbus_message_unref (msg);
999
1000   if (reply == NULL)
1001     {
1002       _DBUS_ASSERT_ERROR_IS_SET (error);
1003       return FALSE;
1004     }
1005
1006   if (dbus_set_error_from_message (error, reply))
1007     {
1008       _DBUS_ASSERT_ERROR_IS_SET (error);
1009       dbus_message_unref (reply);
1010       return FALSE;
1011     }
1012
1013   if (result != NULL &&
1014       !dbus_message_get_args (reply, error, DBUS_TYPE_UINT32,
1015                               result, DBUS_TYPE_INVALID))
1016     {
1017       _DBUS_ASSERT_ERROR_IS_SET (error);
1018       dbus_message_unref (reply);
1019       return FALSE;
1020     }
1021   
1022   dbus_message_unref (reply);
1023   return TRUE;
1024 }
1025
1026 static void
1027 send_no_return_values (DBusConnection *connection,
1028                        DBusMessage    *msg,
1029                        DBusError      *error)
1030 {
1031   if (error)
1032     {
1033       /* Block to check success codepath */
1034       DBusMessage *reply;
1035       
1036       reply = dbus_connection_send_with_reply_and_block (connection, msg,
1037                                                          -1, error);
1038       
1039       if (reply == NULL)
1040         _DBUS_ASSERT_ERROR_IS_SET (error);
1041       else
1042         dbus_message_unref (reply);
1043     }
1044   else
1045     {
1046       /* Silently-fail nonblocking codepath */
1047       dbus_message_set_no_reply (msg, TRUE);
1048       dbus_connection_send (connection, msg, NULL);
1049     }
1050 }
1051
1052 /**
1053  * Adds a match rule to match messages going through the message bus.
1054  * The "rule" argument is the string form of a match rule.
1055  *
1056  * If you pass #NULL for the error, this function will not
1057  * block; the match thus won't be added until you flush the
1058  * connection, and if there's an error adding the match
1059  * (only possible error is lack of resources in the bus),
1060  * you won't find out about it.
1061  *
1062  * If you pass non-#NULL for the error this function will
1063  * block until it gets a reply.
1064  *
1065  * Normal API conventions would have the function return
1066  * a boolean value indicating whether the error was set,
1067  * but that would require blocking always to determine
1068  * the return value.
1069  *
1070  * The AddMatch method is fully documented in the D-Bus 
1071  * specification. For quick reference, the format of the 
1072  * match rules is discussed here, but the specification 
1073  * is the canonical version of this information.
1074  *
1075  * Rules are specified as a string of comma separated 
1076  * key/value pairs. An example is 
1077  * "type='signal',sender='org.freedesktop.DBus',
1078  * interface='org.freedesktop.DBus',member='Foo',
1079  * path='/bar/foo',destination=':452345.34'"
1080  *
1081  * Possible keys you can match on are type, sender, 
1082  * interface, member, path, destination and the special
1083  * arg keys.  Excluding a key from the rule indicates 
1084  * a wildcard match.  For instance excluding the
1085  * the member from a match rule but adding a sender would
1086  * let all messages from that sender through.  
1087  *
1088  * Matches are inclusive not exclusive so as long as one 
1089  * rule matches the message will get through.  It is important
1090  * to note this because every time a message is received the 
1091  * application will be paged into memory to process it.  This
1092  * can cause performance problems such as draining batteries
1093  * on embedded platforms.
1094  *
1095  * The special arg keys are used for further restricting the 
1096  * match based on the parameters sent by the signal or method.
1097  * For instance arg1='foo' will check the first argument, 
1098  * arg2='bar' the second and so on.  For performance reasons
1099  * there is a set limit on the highest number parameter that
1100  * can be checked which is set in dbus-protocol.h
1101  *
1102  * @param connection connection to the message bus
1103  * @param rule textual form of match rule
1104  * @param error location to store any errors
1105  */
1106 void
1107 dbus_bus_add_match (DBusConnection *connection,
1108                     const char     *rule,
1109                     DBusError      *error)
1110 {
1111   DBusMessage *msg;
1112
1113   _dbus_return_if_fail (rule != NULL);
1114
1115   msg = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
1116                                       DBUS_PATH_DBUS,
1117                                       DBUS_INTERFACE_DBUS,
1118                                       "AddMatch");
1119
1120   if (msg == NULL)
1121     {
1122       _DBUS_SET_OOM (error);
1123       return;
1124     }
1125
1126   if (!dbus_message_append_args (msg, DBUS_TYPE_STRING, &rule,
1127                                  DBUS_TYPE_INVALID))
1128     {
1129       dbus_message_unref (msg);
1130       _DBUS_SET_OOM (error);
1131       return;
1132     }
1133
1134   send_no_return_values (connection, msg, error);
1135
1136   dbus_message_unref (msg);
1137 }
1138
1139 /**
1140  * Removes a previously-added match rule "by value" (the most
1141  * recently-added identical rule gets removed).  The "rule" argument
1142  * is the string form of a match rule.
1143  *
1144  * If you pass #NULL for the error, this function will not
1145  * block; otherwise it will. See detailed explanation in
1146  * docs for dbus_bus_add_match().
1147  * 
1148  * @param connection connection to the message bus
1149  * @param rule textual form of match rule
1150  * @param error location to store any errors
1151  */
1152 void
1153 dbus_bus_remove_match (DBusConnection *connection,
1154                        const char     *rule,
1155                        DBusError      *error)
1156 {
1157   DBusMessage *msg;
1158
1159   _dbus_return_if_fail (rule != NULL);
1160   
1161   msg = dbus_message_new_method_call (DBUS_SERVICE_DBUS,
1162                                       DBUS_PATH_DBUS,
1163                                       DBUS_INTERFACE_DBUS,
1164                                       "RemoveMatch");
1165
1166   if (!dbus_message_append_args (msg, DBUS_TYPE_STRING, &rule,
1167                                  DBUS_TYPE_INVALID))
1168     {
1169       dbus_message_unref (msg);
1170       _DBUS_SET_OOM (error);
1171       return;
1172     }
1173
1174   send_no_return_values (connection, msg, error);
1175
1176   dbus_message_unref (msg);
1177 }
1178
1179 /** @} */