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