now come the big changes...
[platform/upstream/glib.git] / gio / gdbusnameowning.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
17  *
18  * Author: David Zeuthen <davidz@redhat.com>
19  */
20
21 #include "config.h"
22
23 #include <stdlib.h>
24
25 #include "gdbusutils.h"
26 #include "gdbusnameowning.h"
27 #include "gdbuserror.h"
28 #include "gdbusprivate.h"
29 #include "gdbusconnection.h"
30
31 #include "glibintl.h"
32
33 /**
34  * SECTION:gdbusnameowning
35  * @title: Owning Bus Names
36  * @short_description: Simple API for owning bus names
37  * @include: gio/gio.h
38  *
39  * Convenience API for owning bus names.
40  *
41  * A simple example for owning a name can be found in
42  * [gdbus-example-own-name.c](https://git.gnome.org/browse/glib/tree/gio/tests/gdbus-example-own-name.c) 
43  */
44
45 G_LOCK_DEFINE_STATIC (lock);
46
47 /* ---------------------------------------------------------------------------------------------------- */
48
49 typedef enum
50 {
51   PREVIOUS_CALL_NONE = 0,
52   PREVIOUS_CALL_ACQUIRED,
53   PREVIOUS_CALL_LOST,
54 } PreviousCall;
55
56 typedef struct
57 {
58   volatile gint             ref_count;
59   guint                     id;
60   GBusNameOwnerFlags        flags;
61   gchar                    *name;
62   GBusAcquiredCallback      bus_acquired_handler;
63   GBusNameAcquiredCallback  name_acquired_handler;
64   GBusNameLostCallback      name_lost_handler;
65   gpointer                  user_data;
66   GDestroyNotify            user_data_free_func;
67   GMainContext             *main_context;
68
69   PreviousCall              previous_call;
70
71   GDBusConnection          *connection;
72   gulong                    disconnected_signal_handler_id;
73   guint                     name_acquired_subscription_id;
74   guint                     name_lost_subscription_id;
75
76   volatile gboolean         cancelled; /* must hold lock when reading or modifying */
77
78   gboolean                  needs_release;
79 } Client;
80
81 static guint next_global_id = 1;
82 static GHashTable *map_id_to_client = NULL;
83
84
85 static Client *
86 client_ref (Client *client)
87 {
88   g_atomic_int_inc (&client->ref_count);
89   return client;
90 }
91
92 static void
93 client_unref (Client *client)
94 {
95   if (g_atomic_int_dec_and_test (&client->ref_count))
96     {
97       if (client->connection != NULL)
98         {
99           if (client->disconnected_signal_handler_id > 0)
100             g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
101           if (client->name_acquired_subscription_id > 0)
102             g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
103           if (client->name_lost_subscription_id > 0)
104             g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
105           g_object_unref (client->connection);
106         }
107       g_main_context_unref (client->main_context);
108       g_free (client->name);
109       if (client->user_data_free_func != NULL)
110         client->user_data_free_func (client->user_data);
111       g_free (client);
112     }
113 }
114
115 /* ---------------------------------------------------------------------------------------------------- */
116
117
118 typedef enum
119 {
120   CALL_TYPE_NAME_ACQUIRED,
121   CALL_TYPE_NAME_LOST
122 } CallType;
123
124 typedef struct
125 {
126   Client *client;
127
128   /* keep this separate because client->connection may
129    * be set to NULL after scheduling the call
130    */
131   GDBusConnection *connection;
132
133   /* set to TRUE to call acquired */
134   CallType call_type;
135 } CallHandlerData;
136
137 static void
138 call_handler_data_free (CallHandlerData *data)
139 {
140   if (data->connection != NULL)
141     g_object_unref (data->connection);
142   client_unref (data->client);
143   g_free (data);
144 }
145
146 static void
147 actually_do_call (Client *client, GDBusConnection *connection, CallType call_type)
148 {
149   switch (call_type)
150     {
151     case CALL_TYPE_NAME_ACQUIRED:
152       if (client->name_acquired_handler != NULL)
153         {
154           client->name_acquired_handler (connection,
155                                          client->name,
156                                          client->user_data);
157         }
158       break;
159
160     case CALL_TYPE_NAME_LOST:
161       if (client->name_lost_handler != NULL)
162         {
163           client->name_lost_handler (connection,
164                                      client->name,
165                                      client->user_data);
166         }
167       break;
168
169     default:
170       g_assert_not_reached ();
171       break;
172     }
173 }
174
175 static gboolean
176 call_in_idle_cb (gpointer _data)
177 {
178   CallHandlerData *data = _data;
179   actually_do_call (data->client, data->connection, data->call_type);
180   return FALSE;
181 }
182
183 static void
184 schedule_call_in_idle (Client *client, CallType  call_type)
185 {
186   CallHandlerData *data;
187   GSource *idle_source;
188
189   data = g_new0 (CallHandlerData, 1);
190   data->client = client_ref (client);
191   data->connection = client->connection != NULL ? g_object_ref (client->connection) : NULL;
192   data->call_type = call_type;
193
194   idle_source = g_idle_source_new ();
195   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
196   g_source_set_callback (idle_source,
197                          call_in_idle_cb,
198                          data,
199                          (GDestroyNotify) call_handler_data_free);
200   g_source_set_name (idle_source, "[gio] call_in_idle_cb");
201   g_source_attach (idle_source, client->main_context);
202   g_source_unref (idle_source);
203 }
204
205 static void
206 do_call (Client *client, CallType call_type)
207 {
208   GMainContext *current_context;
209
210   /* only schedule in idle if we're not in the right thread */
211   current_context = g_main_context_ref_thread_default ();
212   if (current_context != client->main_context)
213     schedule_call_in_idle (client, call_type);
214   else
215     actually_do_call (client, client->connection, call_type);
216   g_main_context_unref (current_context);
217 }
218
219 static void
220 call_acquired_handler (Client *client)
221 {
222   G_LOCK (lock);
223   if (client->previous_call != PREVIOUS_CALL_ACQUIRED)
224     {
225       client->previous_call = PREVIOUS_CALL_ACQUIRED;
226       if (!client->cancelled)
227         {
228           G_UNLOCK (lock);
229           do_call (client, CALL_TYPE_NAME_ACQUIRED);
230           goto out;
231         }
232     }
233   G_UNLOCK (lock);
234  out:
235   ;
236 }
237
238 static void
239 call_lost_handler (Client  *client)
240 {
241   G_LOCK (lock);
242   if (client->previous_call != PREVIOUS_CALL_LOST)
243     {
244       client->previous_call = PREVIOUS_CALL_LOST;
245       if (!client->cancelled)
246         {
247           G_UNLOCK (lock);
248           do_call (client, CALL_TYPE_NAME_LOST);
249           goto out;
250         }
251     }
252   G_UNLOCK (lock);
253  out:
254   ;
255 }
256
257 /* ---------------------------------------------------------------------------------------------------- */
258
259 static void
260 on_name_lost_or_acquired (GDBusConnection  *connection,
261                           const gchar      *sender_name,
262                           const gchar      *object_path,
263                           const gchar      *interface_name,
264                           const gchar      *signal_name,
265                           GVariant         *parameters,
266                           gpointer          user_data)
267 {
268   Client *client = user_data;
269   const gchar *name;
270
271   if (g_strcmp0 (object_path, "/org/freedesktop/DBus") != 0 ||
272       g_strcmp0 (interface_name, "org.freedesktop.DBus") != 0 ||
273       g_strcmp0 (sender_name, "org.freedesktop.DBus") != 0)
274     goto out;
275
276   if (g_strcmp0 (signal_name, "NameLost") == 0)
277     {
278       g_variant_get (parameters, "(&s)", &name);
279       if (g_strcmp0 (name, client->name) == 0)
280         {
281           call_lost_handler (client);
282         }
283     }
284   else if (g_strcmp0 (signal_name, "NameAcquired") == 0)
285     {
286       g_variant_get (parameters, "(&s)", &name);
287       if (g_strcmp0 (name, client->name) == 0)
288         {
289           call_acquired_handler (client);
290         }
291     }
292  out:
293   ;
294 }
295
296 /* ---------------------------------------------------------------------------------------------------- */
297
298 static void
299 process_request_name_reply (Client  *client,
300                             guint32  request_name_reply)
301 {
302   gboolean subscribe;
303
304   subscribe = FALSE;
305
306   switch (request_name_reply)
307     {
308     case 1: /* DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER */
309       /* We got the name - now listen for NameLost and NameAcquired */
310       call_acquired_handler (client);
311       subscribe = TRUE;
312       client->needs_release = TRUE;
313       break;
314
315     case 2: /* DBUS_REQUEST_NAME_REPLY_IN_QUEUE */
316       /* Waiting in line - listen for NameLost and NameAcquired */
317       call_lost_handler (client);
318       subscribe = TRUE;
319       client->needs_release = TRUE;
320       break;
321
322     default:
323       /* assume we couldn't get the name - explicit fallthrough */
324     case 3: /* DBUS_REQUEST_NAME_REPLY_EXISTS */
325     case 4: /* DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER */
326       /* Some other part of the process is already owning the name */
327       call_lost_handler (client);
328       break;
329     }
330
331
332   if (subscribe)
333     {
334       GDBusConnection *connection = NULL;
335
336       /* if cancelled, there is no point in subscribing to signals - if not, make sure
337        * we use a known good Connection object since it may be set to NULL at any point
338        * after being cancelled
339        */
340       G_LOCK (lock);
341       if (!client->cancelled)
342         connection = g_object_ref (client->connection);
343       G_UNLOCK (lock);
344
345       /* start listening to NameLost and NameAcquired messages */
346       if (connection != NULL)
347         {
348           client->name_lost_subscription_id =
349             g_dbus_connection_signal_subscribe (connection,
350                                                 "org.freedesktop.DBus",
351                                                 "org.freedesktop.DBus",
352                                                 "NameLost",
353                                                 "/org/freedesktop/DBus",
354                                                 client->name,
355                                                 G_DBUS_SIGNAL_FLAGS_NONE,
356                                                 on_name_lost_or_acquired,
357                                                 client,
358                                                 NULL);
359           client->name_acquired_subscription_id =
360             g_dbus_connection_signal_subscribe (connection,
361                                                 "org.freedesktop.DBus",
362                                                 "org.freedesktop.DBus",
363                                                 "NameAcquired",
364                                                 "/org/freedesktop/DBus",
365                                                 client->name,
366                                                 G_DBUS_SIGNAL_FLAGS_NONE,
367                                                 on_name_lost_or_acquired,
368                                                 client,
369                                                 NULL);
370           g_object_unref (connection);
371         }
372     }
373 }
374
375 /* ---------------------------------------------------------------------------------------------------- */
376
377 static void
378 request_name_cb (GObject      *source_object,
379                  GAsyncResult *res,
380                  gpointer      user_data)
381 {
382   Client *client = user_data;
383   GVariant *result;
384   guint32 request_name_reply;
385
386   request_name_reply = 0;
387   result = NULL;
388
389   /* don't use client->connection - it may be NULL already */
390   result = g_dbus_connection_call_finish (G_DBUS_CONNECTION (source_object),
391                                           res,
392                                           NULL);
393   if (result != NULL)
394     {
395       g_variant_get (result, "(u)", &request_name_reply);
396       g_variant_unref (result);
397     }
398
399   process_request_name_reply (client, request_name_reply);
400
401   client_unref (client);
402 }
403
404 /* ---------------------------------------------------------------------------------------------------- */
405
406 static void
407 on_connection_disconnected (GDBusConnection *connection,
408                             gboolean         remote_peer_vanished,
409                             GError          *error,
410                             gpointer         user_data)
411 {
412   Client *client = user_data;
413
414   if (client->disconnected_signal_handler_id > 0)
415     g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
416   if (client->name_acquired_subscription_id > 0)
417     g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
418   if (client->name_lost_subscription_id > 0)
419     g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
420   g_object_unref (client->connection);
421   client->disconnected_signal_handler_id = 0;
422   client->name_acquired_subscription_id = 0;
423   client->name_lost_subscription_id = 0;
424   client->connection = NULL;
425
426   call_lost_handler (client);
427 }
428
429 /* ---------------------------------------------------------------------------------------------------- */
430
431 static void
432 has_connection (Client *client)
433 {
434   /* listen for disconnection */
435   client->disconnected_signal_handler_id = g_signal_connect (client->connection,
436                                                              "closed",
437                                                              G_CALLBACK (on_connection_disconnected),
438                                                              client);
439 #if 0
440   /* attempt to acquire the name */
441   if (G_IS_KDBUS_CONNECTION (g_dbus_connection_get_stream (client->connection)))
442     {
443       GVariant *result;
444       guint32 request_name_reply;
445
446       request_name_reply = 0;
447       result = NULL;
448
449       result = _g_kdbus_RequestName (client->connection, client->name, client->flags, NULL);
450
451       if (result != NULL)
452         {
453           g_variant_get (result, "(u)", &request_name_reply);
454           g_variant_unref (result);
455         }
456
457       process_request_name_reply (client, request_name_reply);
458     }
459   else
460 #endif
461     {
462       g_dbus_connection_call (client->connection,
463                               "org.freedesktop.DBus",  /* bus name */
464                               "/org/freedesktop/DBus", /* object path */
465                               "org.freedesktop.DBus",  /* interface name */
466                               "RequestName",           /* method name */
467                               g_variant_new ("(su)",
468                                              client->name,
469                                              client->flags),
470                               G_VARIANT_TYPE ("(u)"),
471                               G_DBUS_CALL_FLAGS_NONE,
472                               -1,
473                               NULL,
474                               (GAsyncReadyCallback) request_name_cb,
475                               client_ref (client));
476     }
477 }
478
479
480 static void
481 connection_get_cb (GObject      *source_object,
482                    GAsyncResult *res,
483                    gpointer      user_data)
484 {
485   Client *client = user_data;
486
487   /* must not do anything if already cancelled */
488   G_LOCK (lock);
489   if (client->cancelled)
490     {
491       G_UNLOCK (lock);
492       goto out;
493     }
494   G_UNLOCK (lock);
495
496   client->connection = g_bus_get_finish (res, NULL);
497   if (client->connection == NULL)
498     {
499       call_lost_handler (client);
500       goto out;
501     }
502
503   /* No need to schedule this in idle as we're already in the thread
504    * that the user called g_bus_own_name() from. This is because
505    * g_bus_get() guarantees that.
506    *
507    * Also, we need to ensure that the handler is invoked *before*
508    * we call RequestName(). Otherwise there is a race.
509    */
510   if (client->bus_acquired_handler != NULL)
511     {
512       client->bus_acquired_handler (client->connection,
513                                     client->name,
514                                     client->user_data);
515     }
516
517   has_connection (client);
518
519  out:
520   client_unref (client);
521 }
522
523 /* ---------------------------------------------------------------------------------------------------- */
524
525 /**
526  * g_bus_own_name_on_connection:
527  * @connection: a #GDBusConnection
528  * @name: the well-known name to own
529  * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
530  * @name_acquired_handler: (allow-none): handler to invoke when @name is acquired or %NULL
531  * @name_lost_handler: (allow-none): handler to invoke when @name is lost or %NULL
532  * @user_data: user data to pass to handlers
533  * @user_data_free_func: (allow-none): function for freeing @user_data or %NULL
534  *
535  * Like g_bus_own_name() but takes a #GDBusConnection instead of a
536  * #GBusType.
537  *
538  * Returns: an identifier (never 0) that an be used with
539  *     g_bus_unown_name() to stop owning the name
540  *
541  * Since: 2.26
542  */
543 guint
544 g_bus_own_name_on_connection (GDBusConnection          *connection,
545                               const gchar              *name,
546                               GBusNameOwnerFlags        flags,
547                               GBusNameAcquiredCallback  name_acquired_handler,
548                               GBusNameLostCallback      name_lost_handler,
549                               gpointer                  user_data,
550                               GDestroyNotify            user_data_free_func)
551 {
552   Client *client;
553
554   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
555   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);
556
557   G_LOCK (lock);
558
559   client = g_new0 (Client, 1);
560   client->ref_count = 1;
561   client->id = next_global_id++; /* TODO: uh oh, handle overflow */
562   client->name = g_strdup (name);
563   client->flags = flags;
564   client->name_acquired_handler = name_acquired_handler;
565   client->name_lost_handler = name_lost_handler;
566   client->user_data = user_data;
567   client->user_data_free_func = user_data_free_func;
568   client->main_context = g_main_context_ref_thread_default ();
569
570   client->connection = g_object_ref (connection);
571
572   if (map_id_to_client == NULL)
573     {
574       map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
575     }
576   g_hash_table_insert (map_id_to_client,
577                        GUINT_TO_POINTER (client->id),
578                        client);
579
580   G_UNLOCK (lock);
581
582   has_connection (client);
583
584   return client->id;
585 }
586
587 /**
588  * g_bus_own_name:
589  * @bus_type: the type of bus to own a name on
590  * @name: the well-known name to own
591  * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
592  * @bus_acquired_handler: (allow-none): handler to invoke when connected to the bus of type @bus_type or %NULL
593  * @name_acquired_handler: (allow-none): handler to invoke when @name is acquired or %NULL
594  * @name_lost_handler: (allow-none): handler to invoke when @name is lost or %NULL
595  * @user_data: user data to pass to handlers
596  * @user_data_free_func: (allow-none): function for freeing @user_data or %NULL
597  *
598  * Starts acquiring @name on the bus specified by @bus_type and calls
599  * @name_acquired_handler and @name_lost_handler when the name is
600  * acquired respectively lost. Callbacks will be invoked in the 
601  * [thread-default main context][g-main-context-push-thread-default]
602  * of the thread you are calling this function from.
603  *
604  * You are guaranteed that one of the @name_acquired_handler and @name_lost_handler
605  * callbacks will be invoked after calling this function - there are three
606  * possible cases:
607  * 
608  * - @name_lost_handler with a %NULL connection (if a connection to the bus
609  *   can't be made).
610  *
611  * - @bus_acquired_handler then @name_lost_handler (if the name can't be
612  *   obtained)
613  *
614  * - @bus_acquired_handler then @name_acquired_handler (if the name was
615  *   obtained).
616  *
617  * When you are done owning the name, just call g_bus_unown_name()
618  * with the owner id this function returns.
619  *
620  * If the name is acquired or lost (for example another application
621  * could acquire the name if you allow replacement or the application
622  * currently owning the name exits), the handlers are also invoked.
623  * If the #GDBusConnection that is used for attempting to own the name
624  * closes, then @name_lost_handler is invoked since it is no longer
625  * possible for other processes to access the process.
626  *
627  * You cannot use g_bus_own_name() several times for the same name (unless
628  * interleaved with calls to g_bus_unown_name()) - only the first call
629  * will work.
630  *
631  * Another guarantee is that invocations of @name_acquired_handler
632  * and @name_lost_handler are guaranteed to alternate; that
633  * is, if @name_acquired_handler is invoked then you are
634  * guaranteed that the next time one of the handlers is invoked, it
635  * will be @name_lost_handler. The reverse is also true.
636  *
637  * If you plan on exporting objects (using e.g.
638  * g_dbus_connection_register_object()), note that it is generally too late
639  * to export the objects in @name_acquired_handler. Instead, you can do this
640  * in @bus_acquired_handler since you are guaranteed that this will run
641  * before @name is requested from the bus.
642  *
643  * This behavior makes it very simple to write applications that wants
644  * to [own names][gdbus-owning-names] and export objects.
645  * Simply register objects to be exported in @bus_acquired_handler and
646  * unregister the objects (if any) in @name_lost_handler.
647  *
648  * Returns: an identifier (never 0) that an be used with
649  *     g_bus_unown_name() to stop owning the name.
650  *
651  * Since: 2.26
652  */
653 guint
654 g_bus_own_name (GBusType                  bus_type,
655                 const gchar              *name,
656                 GBusNameOwnerFlags        flags,
657                 GBusAcquiredCallback      bus_acquired_handler,
658                 GBusNameAcquiredCallback  name_acquired_handler,
659                 GBusNameLostCallback      name_lost_handler,
660                 gpointer                  user_data,
661                 GDestroyNotify            user_data_free_func)
662 {
663   Client *client;
664
665   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);
666
667   G_LOCK (lock);
668
669   client = g_new0 (Client, 1);
670   client->ref_count = 1;
671   client->id = next_global_id++; /* TODO: uh oh, handle overflow */
672   client->name = g_strdup (name);
673   client->flags = flags;
674   client->bus_acquired_handler = bus_acquired_handler;
675   client->name_acquired_handler = name_acquired_handler;
676   client->name_lost_handler = name_lost_handler;
677   client->user_data = user_data;
678   client->user_data_free_func = user_data_free_func;
679   client->main_context = g_main_context_ref_thread_default ();
680
681   if (map_id_to_client == NULL)
682     {
683       map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
684     }
685   g_hash_table_insert (map_id_to_client,
686                        GUINT_TO_POINTER (client->id),
687                        client);
688
689   g_bus_get (bus_type,
690              NULL,
691              connection_get_cb,
692              client_ref (client));
693
694   G_UNLOCK (lock);
695
696   return client->id;
697 }
698
699 typedef struct {
700   GClosure *bus_acquired_closure;
701   GClosure *name_acquired_closure;
702   GClosure *name_lost_closure;
703 } OwnNameData;
704
705 static OwnNameData *
706 own_name_data_new (GClosure *bus_acquired_closure,
707                    GClosure *name_acquired_closure,
708                    GClosure *name_lost_closure)
709 {
710   OwnNameData *data;
711
712   data = g_new0 (OwnNameData, 1);
713
714   if (bus_acquired_closure != NULL)
715     {
716       data->bus_acquired_closure = g_closure_ref (bus_acquired_closure);
717       g_closure_sink (bus_acquired_closure);
718       if (G_CLOSURE_NEEDS_MARSHAL (bus_acquired_closure))
719         g_closure_set_marshal (bus_acquired_closure, g_cclosure_marshal_generic);
720     }
721
722   if (name_acquired_closure != NULL)
723     {
724       data->name_acquired_closure = g_closure_ref (name_acquired_closure);
725       g_closure_sink (name_acquired_closure);
726       if (G_CLOSURE_NEEDS_MARSHAL (name_acquired_closure))
727         g_closure_set_marshal (name_acquired_closure, g_cclosure_marshal_generic);
728     }
729
730   if (name_lost_closure != NULL)
731     {
732       data->name_lost_closure = g_closure_ref (name_lost_closure);
733       g_closure_sink (name_lost_closure);
734       if (G_CLOSURE_NEEDS_MARSHAL (name_lost_closure))
735         g_closure_set_marshal (name_lost_closure, g_cclosure_marshal_generic);
736     }
737
738   return data;
739 }
740
741 static void
742 own_with_closures_on_bus_acquired (GDBusConnection *connection,
743                                    const gchar     *name,
744                                    gpointer         user_data)
745 {
746   OwnNameData *data = user_data;
747   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
748
749   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
750   g_value_set_object (&params[0], connection);
751
752   g_value_init (&params[1], G_TYPE_STRING);
753   g_value_set_string (&params[1], name);
754
755   g_closure_invoke (data->bus_acquired_closure, NULL, 2, params, NULL);
756
757   g_value_unset (params + 0);
758   g_value_unset (params + 1);
759 }
760
761 static void
762 own_with_closures_on_name_acquired (GDBusConnection *connection,
763                                     const gchar     *name,
764                                     gpointer         user_data)
765 {
766   OwnNameData *data = user_data;
767   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
768
769   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
770   g_value_set_object (&params[0], connection);
771
772   g_value_init (&params[1], G_TYPE_STRING);
773   g_value_set_string (&params[1], name);
774
775   g_closure_invoke (data->name_acquired_closure, NULL, 2, params, NULL);
776
777   g_value_unset (params + 0);
778   g_value_unset (params + 1);
779 }
780
781 static void
782 own_with_closures_on_name_lost (GDBusConnection *connection,
783                                 const gchar     *name,
784                                 gpointer         user_data)
785 {
786   OwnNameData *data = user_data;
787   GValue params[2] = { G_VALUE_INIT, G_VALUE_INIT };
788
789   g_value_init (&params[0], G_TYPE_DBUS_CONNECTION);
790   g_value_set_object (&params[0], connection);
791
792   g_value_init (&params[1], G_TYPE_STRING);
793   g_value_set_string (&params[1], name);
794
795   g_closure_invoke (data->name_lost_closure, NULL, 2, params, NULL);
796
797   g_value_unset (params + 0);
798   g_value_unset (params + 1);
799 }
800
801 static void
802 bus_own_name_free_func (gpointer user_data)
803 {
804   OwnNameData *data = user_data;
805
806   if (data->bus_acquired_closure != NULL)
807     g_closure_unref (data->bus_acquired_closure);
808
809   if (data->name_acquired_closure != NULL)
810     g_closure_unref (data->name_acquired_closure);
811
812   if (data->name_lost_closure != NULL)
813     g_closure_unref (data->name_lost_closure);
814
815   g_free (data);
816 }
817
818 /**
819  * g_bus_own_name_with_closures:
820  * @bus_type: the type of bus to own a name on
821  * @name: the well-known name to own
822  * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
823  * @bus_acquired_closure: (allow-none): #GClosure to invoke when connected to
824  *     the bus of type @bus_type or %NULL
825  * @name_acquired_closure: (allow-none): #GClosure to invoke when @name is
826  *     acquired or %NULL
827  * @name_lost_closure: (allow-none): #GClosure to invoke when @name is lost or
828  *     %NULL
829  *
830  * Version of g_bus_own_name() using closures instead of callbacks for
831  * easier binding in other languages.
832  *
833  * Returns: an identifier (never 0) that an be used with
834  *     g_bus_unown_name() to stop owning the name.
835  *
836  * Rename to: g_bus_own_name
837  *
838  * Since: 2.26
839  */
840 guint
841 g_bus_own_name_with_closures (GBusType            bus_type,
842                               const gchar        *name,
843                               GBusNameOwnerFlags  flags,
844                               GClosure           *bus_acquired_closure,
845                               GClosure           *name_acquired_closure,
846                               GClosure           *name_lost_closure)
847 {
848   return g_bus_own_name (bus_type,
849           name,
850           flags,
851           bus_acquired_closure != NULL ? own_with_closures_on_bus_acquired : NULL,
852           name_acquired_closure != NULL ? own_with_closures_on_name_acquired : NULL,
853           name_lost_closure != NULL ? own_with_closures_on_name_lost : NULL,
854           own_name_data_new (bus_acquired_closure,
855                              name_acquired_closure,
856                              name_lost_closure),
857           bus_own_name_free_func);
858 }
859
860 /**
861  * g_bus_own_name_on_connection_with_closures:
862  * @connection: a #GDBusConnection
863  * @name: the well-known name to own
864  * @flags: a set of flags from the #GBusNameOwnerFlags enumeration
865  * @name_acquired_closure: (allow-none): #GClosure to invoke when @name is
866  *     acquired or %NULL
867  * @name_lost_closure: (allow-none): #GClosure to invoke when @name is lost
868  *     or %NULL
869  *
870  * Version of g_bus_own_name_on_connection() using closures instead of
871  * callbacks for easier binding in other languages.
872  *
873  * Returns: an identifier (never 0) that an be used with
874  *     g_bus_unown_name() to stop owning the name.
875  *
876  * Rename to: g_bus_own_name_on_connection
877  *
878  * Since: 2.26
879  */
880 guint
881 g_bus_own_name_on_connection_with_closures (GDBusConnection    *connection,
882                                             const gchar        *name,
883                                             GBusNameOwnerFlags  flags,
884                                             GClosure           *name_acquired_closure,
885                                             GClosure           *name_lost_closure)
886 {
887   return g_bus_own_name_on_connection (connection,
888           name,
889           flags,
890           name_acquired_closure != NULL ? own_with_closures_on_name_acquired : NULL,
891           name_lost_closure != NULL ? own_with_closures_on_name_lost : NULL,
892           own_name_data_new (NULL,
893                              name_acquired_closure,
894                              name_lost_closure),
895           bus_own_name_free_func);
896 }
897
898 /**
899  * g_bus_unown_name:
900  * @owner_id: an identifier obtained from g_bus_own_name()
901  *
902  * Stops owning a name.
903  *
904  * Since: 2.26
905  */
906 void
907 g_bus_unown_name (guint owner_id)
908 {
909   Client *client;
910
911   g_return_if_fail (owner_id > 0);
912
913   client = NULL;
914
915   G_LOCK (lock);
916   if (owner_id == 0 || map_id_to_client == NULL ||
917       (client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (owner_id))) == NULL)
918     {
919       g_warning ("Invalid id %d passed to g_bus_unown_name()", owner_id);
920       goto out;
921     }
922
923   client->cancelled = TRUE;
924   g_warn_if_fail (g_hash_table_remove (map_id_to_client, GUINT_TO_POINTER (owner_id)));
925
926  out:
927   G_UNLOCK (lock);
928
929   /* do callback without holding lock */
930   if (client != NULL)
931     {
932       /* Release the name if needed */
933       if (client->needs_release &&
934           client->connection != NULL &&
935           !g_dbus_connection_is_closed (client->connection))
936         {
937           GVariant *result;
938           GError *error;
939           guint32 release_name_reply;
940
941           /* TODO: it kinda sucks having to do a sync call to release the name - but if
942            * we don't, then a subsequent grab of the name will make the bus daemon return
943            * IN_QUEUE which will trigger name_lost().
944            *
945            * I believe this is a bug in the bus daemon.
946            */
947           error = NULL;
948 #if 0
949           if (G_IS_KDBUS_CONNECTION (g_dbus_connection_get_stream (client->connection)))
950             result = _g_kdbus_ReleaseName (client->connection, client->name, &error);
951           else
952 #endif
953             result = g_dbus_connection_call_sync (client->connection,
954                                                   "org.freedesktop.DBus",  /* bus name */
955                                                   "/org/freedesktop/DBus", /* object path */
956                                                   "org.freedesktop.DBus",  /* interface name */
957                                                   "ReleaseName",           /* method name */
958                                                   g_variant_new ("(s)", client->name),
959                                                   G_VARIANT_TYPE ("(u)"),
960                                                   G_DBUS_CALL_FLAGS_NONE,
961                                                   -1,
962                                                   NULL,
963                                                   &error);
964           if (result == NULL)
965             {
966               g_warning ("Error releasing name %s: %s", client->name, error->message);
967               g_error_free (error);
968             }
969           else
970             {
971               g_variant_get (result, "(u)", &release_name_reply);
972               if (release_name_reply != 1 /* DBUS_RELEASE_NAME_REPLY_RELEASED */)
973                 {
974                   g_warning ("Unexpected reply %d when releasing name %s", release_name_reply, client->name);
975                 }
976               g_variant_unref (result);
977             }
978         }
979
980       if (client->disconnected_signal_handler_id > 0)
981         g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
982       if (client->name_acquired_subscription_id > 0)
983         g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
984       if (client->name_lost_subscription_id > 0)
985         g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
986       client->disconnected_signal_handler_id = 0;
987       client->name_acquired_subscription_id = 0;
988       client->name_lost_subscription_id = 0;
989       if (client->connection != NULL)
990         {
991           g_object_unref (client->connection);
992           client->connection = NULL;
993         }
994
995       client_unref (client);
996     }
997 }