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