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