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