Initial GDBus code-drop from GDBus-standalone repo
[platform/upstream/glib.git] / gio / gdbusnameowning.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2009 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 <glib/gi18n.h>
28
29 #include "gdbusutils.h"
30 #include "gdbusnameowning.h"
31 #include "gdbuserror.h"
32 #include "gdbusprivate.h"
33 #include "gdbusconnection.h"
34
35 /**
36  * SECTION:gdbusnameowning
37  * @title: Owning Bus Names
38  * @short_description: Simple API for owning bus names
39  * @include: gdbus/gdbus.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       if (client->main_context != NULL)
109         g_main_context_unref (client->main_context);
110       g_free (client->name);
111       if (client->user_data_free_func != NULL)
112         client->user_data_free_func (client->user_data);
113       g_free (client);
114     }
115 }
116
117 /* ---------------------------------------------------------------------------------------------------- */
118
119
120 typedef enum
121 {
122   CALL_TYPE_NAME_ACQUIRED,
123   CALL_TYPE_NAME_LOST
124 } CallType;
125
126 typedef struct
127 {
128   Client *client;
129
130   /* keep this separate because client->connection may
131    * be set to NULL after scheduling the call
132    */
133   GDBusConnection *connection;
134
135   /* set to TRUE to call acquired */
136   CallType call_type;
137 } CallHandlerData;
138
139 static void
140 call_handler_data_free (CallHandlerData *data)
141 {
142   if (data->connection != NULL)
143     g_object_unref (data->connection);
144   client_unref (data->client);
145   g_free (data);
146 }
147
148 static void
149 actually_do_call (Client *client, GDBusConnection *connection, CallType call_type)
150 {
151   switch (call_type)
152     {
153     case CALL_TYPE_NAME_ACQUIRED:
154       if (client->name_acquired_handler != NULL)
155         {
156           client->name_acquired_handler (connection,
157                                          client->name,
158                                          client->user_data);
159         }
160       break;
161
162     case CALL_TYPE_NAME_LOST:
163       if (client->name_lost_handler != NULL)
164         {
165           client->name_lost_handler (connection,
166                                      client->name,
167                                      client->user_data);
168         }
169       break;
170
171     default:
172       g_assert_not_reached ();
173       break;
174     }
175 }
176
177 static gboolean
178 call_in_idle_cb (gpointer _data)
179 {
180   CallHandlerData *data = _data;
181   actually_do_call (data->client, data->connection, data->call_type);
182   return FALSE;
183 }
184
185 static void
186 schedule_call_in_idle (Client *client, CallType  call_type)
187 {
188   CallHandlerData *data;
189   GSource *idle_source;
190
191   data = g_new0 (CallHandlerData, 1);
192   data->client = client_ref (client);
193   data->connection = client->connection != NULL ? g_object_ref (client->connection) : NULL;
194   data->call_type = call_type;
195
196   idle_source = g_idle_source_new ();
197   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
198   g_source_set_callback (idle_source,
199                          call_in_idle_cb,
200                          data,
201                          (GDestroyNotify) call_handler_data_free);
202   g_source_attach (idle_source, client->main_context);
203   g_source_unref (idle_source);
204 }
205
206 static void
207 do_call (Client *client, CallType call_type)
208 {
209   /* only schedule in idle if we're not in the right thread */
210   if (g_main_context_get_thread_default () != client->main_context)
211     schedule_call_in_idle (client, call_type);
212   else
213     actually_do_call (client, client->connection, call_type);
214 }
215
216 static void
217 call_acquired_handler (Client *client)
218 {
219   if (client->previous_call != PREVIOUS_CALL_ACQUIRED)
220     {
221       client->previous_call = PREVIOUS_CALL_ACQUIRED;
222       if (!client->cancelled)
223         {
224           do_call (client, CALL_TYPE_NAME_ACQUIRED);
225         }
226     }
227 }
228
229 static void
230 call_lost_handler (Client  *client)
231 {
232   if (client->previous_call != PREVIOUS_CALL_LOST)
233     {
234       client->previous_call = PREVIOUS_CALL_LOST;
235       if (!client->cancelled)
236         {
237           do_call (client, CALL_TYPE_NAME_LOST);
238         }
239     }
240 }
241
242 /* ---------------------------------------------------------------------------------------------------- */
243
244 static void
245 on_name_lost_or_acquired (GDBusConnection  *connection,
246                           const gchar      *sender_name,
247                           const gchar      *object_path,
248                           const gchar      *interface_name,
249                           const gchar      *signal_name,
250                           GVariant         *parameters,
251                           gpointer          user_data)
252 {
253   Client *client = user_data;
254   const gchar *name;
255
256   if (g_strcmp0 (object_path, "/org/freedesktop/DBus") != 0 ||
257       g_strcmp0 (interface_name, "org.freedesktop.DBus") != 0 ||
258       g_strcmp0 (sender_name, "org.freedesktop.DBus") != 0)
259     goto out;
260
261   if (g_strcmp0 (signal_name, "NameLost") == 0)
262     {
263       g_variant_get (parameters, "(s)", &name);
264       if (g_strcmp0 (name, client->name) == 0)
265         {
266           call_lost_handler (client);
267         }
268     }
269   else if (g_strcmp0 (signal_name, "NameAcquired") == 0)
270     {
271       g_variant_get (parameters, "(s)", &name);
272       if (g_strcmp0 (name, client->name) == 0)
273         {
274           call_acquired_handler (client);
275         }
276     }
277  out:
278   ;
279 }
280
281 /* ---------------------------------------------------------------------------------------------------- */
282
283 static void
284 request_name_cb (GObject      *source_object,
285                  GAsyncResult *res,
286                  gpointer      user_data)
287 {
288   Client *client = user_data;
289   GVariant *result;
290   guint32 request_name_reply;
291   gboolean subscribe;
292
293   request_name_reply = 0;
294   result = NULL;
295
296   result = g_dbus_connection_invoke_method_finish (client->connection,
297                                                    res,
298                                                    NULL);
299   if (result != NULL)
300     {
301       g_variant_get (result, "(u)", &request_name_reply);
302       g_variant_unref (result);
303     }
304
305   subscribe = FALSE;
306
307   switch (request_name_reply)
308     {
309     case 1: /* DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER */
310       /* We got the name - now listen for NameLost and NameAcquired */
311       call_acquired_handler (client);
312       subscribe = TRUE;
313       client->needs_release = TRUE;
314       break;
315
316     case 2: /* DBUS_REQUEST_NAME_REPLY_IN_QUEUE */
317       /* Waiting in line - listen for NameLost and NameAcquired */
318       call_lost_handler (client);
319       subscribe = TRUE;
320       client->needs_release = TRUE;
321       break;
322
323     default:
324       /* assume we couldn't get the name - explicit fallthrough */
325     case 3: /* DBUS_REQUEST_NAME_REPLY_EXISTS */
326     case 4: /* DBUS_REQUEST_NAME_REPLY_ALREADY_OWNER */
327       /* Some other part of the process is already owning the name */
328       call_lost_handler (client);
329       break;
330     }
331
332   if (subscribe)
333     {
334       /* start listening to NameLost and NameAcquired messages */
335       client->name_lost_subscription_id =
336         g_dbus_connection_signal_subscribe (client->connection,
337                                             "org.freedesktop.DBus",
338                                             "org.freedesktop.DBus",
339                                             "NameLost",
340                                             "/org/freedesktop/DBus",
341                                             client->name,
342                                             on_name_lost_or_acquired,
343                                             client,
344                                             NULL);
345       client->name_acquired_subscription_id =
346         g_dbus_connection_signal_subscribe (client->connection,
347                                             "org.freedesktop.DBus",
348                                             "org.freedesktop.DBus",
349                                             "NameAcquired",
350                                             "/org/freedesktop/DBus",
351                                             client->name,
352                                             on_name_lost_or_acquired,
353                                             client,
354                                             NULL);
355     }
356
357   client_unref (client);
358 }
359
360 /* ---------------------------------------------------------------------------------------------------- */
361
362 static void
363 on_connection_disconnected (GDBusConnection *connection,
364                             gboolean         remote_peer_vanished,
365                             GError          *error,
366                             gpointer         user_data)
367 {
368   Client *client = user_data;
369
370   if (client->disconnected_signal_handler_id > 0)
371     g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
372   if (client->name_acquired_subscription_id > 0)
373     g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
374   if (client->name_lost_subscription_id > 0)
375     g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
376   g_object_unref (client->connection);
377   client->disconnected_signal_handler_id = 0;
378   client->name_acquired_subscription_id = 0;
379   client->name_lost_subscription_id = 0;
380   client->connection = NULL;
381
382   call_lost_handler (client);
383 }
384
385 /* ---------------------------------------------------------------------------------------------------- */
386
387 static void
388 has_connection (Client *client)
389 {
390   /* listen for disconnection */
391   client->disconnected_signal_handler_id = g_signal_connect (client->connection,
392                                                              "closed",
393                                                              G_CALLBACK (on_connection_disconnected),
394                                                              client);
395
396   /* attempt to acquire the name */
397   g_dbus_connection_invoke_method (client->connection,
398                                    "org.freedesktop.DBus",  /* bus name */
399                                    "/org/freedesktop/DBus", /* object path */
400                                    "org.freedesktop.DBus",  /* interface name */
401                                    "RequestName",           /* method name */
402                                    g_variant_new ("(su)",
403                                                   client->name,
404                                                   client->flags),
405                                    G_DBUS_INVOKE_METHOD_FLAGS_NONE,
406                                    -1,
407                                    NULL,
408                                    (GAsyncReadyCallback) request_name_cb,
409                                    client_ref (client));
410 }
411
412
413 static void
414 connection_get_cb (GObject      *source_object,
415                    GAsyncResult *res,
416                    gpointer      user_data)
417 {
418   Client *client = user_data;
419
420   client->connection = g_bus_get_finish (res, NULL);
421   if (client->connection == NULL)
422     {
423       call_lost_handler (client);
424       goto out;
425     }
426
427   /* No need to schedule this in idle as we're already in the thread
428    * that the user called g_bus_own_name() from. This is because
429    * g_bus_get() guarantees that.
430    *
431    * Also, we need to ensure that the handler is invoked *before*
432    * we call RequestName(). Otherwise there is a race.
433    */
434   if (client->bus_acquired_handler != NULL)
435     {
436       client->bus_acquired_handler (client->connection,
437                                     client->name,
438                                     client->user_data);
439     }
440
441   has_connection (client);
442
443  out:
444   client_unref (client);
445 }
446
447 /* ---------------------------------------------------------------------------------------------------- */
448
449 /**
450  * g_bus_own_name_on_connection:
451  * @connection: A #GDBusConnection that is not closed.
452  * @name: The well-known name to own.
453  * @flags: A set of flags from the #GBusNameOwnerFlags enumeration.
454  * @name_acquired_handler: Handler to invoke when @name is acquired or %NULL.
455  * @name_lost_handler: Handler to invoke when @name is lost or %NULL.
456  * @user_data: User data to pass to handlers.
457  * @user_data_free_func: Function for freeing @user_data or %NULL.
458  *
459  * Like g_bus_own_name() but takes a #GDBusConnection instead of a
460  * #GBusType.
461  *
462  * Returns: An identifier (never 0) that an be used with
463  * g_bus_unown_name() to stop owning the name.
464  **/
465 guint
466 g_bus_own_name_on_connection (GDBusConnection          *connection,
467                               const gchar              *name,
468                               GBusNameOwnerFlags        flags,
469                               GBusNameAcquiredCallback  name_acquired_handler,
470                               GBusNameLostCallback      name_lost_handler,
471                               gpointer                  user_data,
472                               GDestroyNotify            user_data_free_func)
473 {
474   Client *client;
475
476   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
477   g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
478   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);
479
480   G_LOCK (lock);
481
482   client = g_new0 (Client, 1);
483   client->ref_count = 1;
484   client->id = next_global_id++; /* TODO: uh oh, handle overflow */
485   client->name = g_strdup (name);
486   client->flags = flags;
487   client->name_acquired_handler = name_acquired_handler;
488   client->name_lost_handler = name_lost_handler;
489   client->user_data = user_data;
490   client->user_data_free_func = user_data_free_func;
491   client->main_context = g_main_context_get_thread_default ();
492   if (client->main_context != NULL)
493     g_main_context_ref (client->main_context);
494
495   client->connection = g_object_ref (connection);
496
497   if (map_id_to_client == NULL)
498     {
499       map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
500     }
501   g_hash_table_insert (map_id_to_client,
502                        GUINT_TO_POINTER (client->id),
503                        client);
504
505   G_UNLOCK (lock);
506
507   has_connection (client);
508
509   return client->id;
510 }
511
512 /**
513  * g_bus_own_name:
514  * @bus_type: The type of bus to own a name on.
515  * @name: The well-known name to own.
516  * @flags: A set of flags from the #GBusNameOwnerFlags enumeration.
517  * @bus_acquired_handler: Handler to invoke when connected to the bus of type @bus_type or %NULL.
518  * @name_acquired_handler: Handler to invoke when @name is acquired or %NULL.
519  * @name_lost_handler: Handler to invoke when @name is lost or %NULL.
520  * @user_data: User data to pass to handlers.
521  * @user_data_free_func: Function for freeing @user_data or %NULL.
522  *
523  * Starts acquiring @name on the bus specified by @bus_type and calls
524  * @name_acquired_handler and @name_lost_handler when the name is
525  * acquired respectively lost. Callbacks will be invoked in the <link
526  * linkend="g-main-context-push-thread-default">thread-default main
527  * loop</link> of the thread you are calling this function from.
528  *
529  * You are guaranteed that one of the @name_acquired_handler and @name_lost_handler
530  * callbacks will be invoked after calling this function - there are three
531  * possible cases:
532  * <itemizedlist>
533  *   <listitem><para>
534  *     @name_lost_handler with a %NULL connection (if a connection to the bus can't be made).
535  *   </para></listitem>
536  *   <listitem><para>
537  *     @bus_acquired_handler then @name_lost_handler (if the name can't be obtained)
538  *   </para></listitem>
539  *   <listitem><para>
540  *     @bus_acquired_handler then @name_acquired_handler (if the name was obtained).
541  *   </para></listitem>
542  * </itemizedlist>
543  * When you are done owning the name, just call g_bus_unown_name()
544  * with the owner id this function returns.
545  *
546  * If the name is acquired or lost (for example another application
547  * could acquire the name if you allow replacement or the application
548  * currently owning the name exits), the handlers are also invoked. If the
549  * #GDBusConnection that is used for attempting to own the name
550  * closes, then @name_lost_handler is invoked since it is no
551  * longer possible for other processes to access the process.
552  *
553  * You cannot use g_bus_own_name() several times (unless interleaved
554  * with calls to g_bus_unown_name()) - only the first call will work.
555  *
556  * Another guarantee is that invocations of @name_acquired_handler
557  * and @name_lost_handler are guaranteed to alternate; that
558  * is, if @name_acquired_handler is invoked then you are
559  * guaranteed that the next time one of the handlers is invoked, it
560  * will be @name_lost_handler. The reverse is also true.
561  *
562  * If you plan on exporting objects (using e.g. g_dbus_connection_register_object()), note
563  * that it is generally too late to export the objects in @name_acquired_handler. Instead,
564  * you can do this in @bus_acquired_handler since you are guaranteed that this will
565  * run before @name is requested from the bus.
566  *
567  * This behavior makes it very simple to write applications that wants
568  * to own names and export objects, see <xref linkend="gdbus-owning-names"/>. Simply
569  * register objects to be exported in @bus_acquired_handler and
570  * unregister the objects (if any) in @name_lost_handler.
571  *
572  * Returns: An identifier (never 0) that an be used with
573  * g_bus_unown_name() to stop owning the name.
574  **/
575 guint
576 g_bus_own_name (GBusType                  bus_type,
577                 const gchar              *name,
578                 GBusNameOwnerFlags        flags,
579                 GBusAcquiredCallback      bus_acquired_handler,
580                 GBusNameAcquiredCallback  name_acquired_handler,
581                 GBusNameLostCallback      name_lost_handler,
582                 gpointer                  user_data,
583                 GDestroyNotify            user_data_free_func)
584 {
585   Client *client;
586
587   g_return_val_if_fail (bus_type != G_BUS_TYPE_NONE, 0);
588   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);
589
590   G_LOCK (lock);
591
592   client = g_new0 (Client, 1);
593   client->ref_count = 1;
594   client->id = next_global_id++; /* TODO: uh oh, handle overflow */
595   client->name = g_strdup (name);
596   client->flags = flags;
597   client->bus_acquired_handler = bus_acquired_handler;
598   client->name_acquired_handler = name_acquired_handler;
599   client->name_lost_handler = name_lost_handler;
600   client->user_data = user_data;
601   client->user_data_free_func = user_data_free_func;
602   client->main_context = g_main_context_get_thread_default ();
603   if (client->main_context != NULL)
604     g_main_context_ref (client->main_context);
605
606   if (map_id_to_client == NULL)
607     {
608       map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
609     }
610   g_hash_table_insert (map_id_to_client,
611                        GUINT_TO_POINTER (client->id),
612                        client);
613
614   g_bus_get (bus_type,
615              NULL,
616              connection_get_cb,
617              client_ref (client));
618
619   G_UNLOCK (lock);
620
621   return client->id;
622 }
623
624 /**
625  * g_bus_unown_name:
626  * @owner_id: An identifier obtained from g_bus_own_name()
627  *
628  * Stops owning a name.
629  */
630 void
631 g_bus_unown_name (guint owner_id)
632 {
633   Client *client;
634
635   g_return_if_fail (owner_id > 0);
636
637   client = NULL;
638
639   G_LOCK (lock);
640   if (owner_id == 0 || map_id_to_client == NULL ||
641       (client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (owner_id))) == NULL)
642     {
643       g_warning ("Invalid id %d passed to g_bus_unown_name()", owner_id);
644       goto out;
645     }
646
647   client->cancelled = TRUE;
648   g_warn_if_fail (g_hash_table_remove (map_id_to_client, GUINT_TO_POINTER (owner_id)));
649
650  out:
651   G_UNLOCK (lock);
652
653   /* do callback without holding lock */
654   if (client != NULL)
655     {
656       /* Release the name if needed */
657       if (client->needs_release && client->connection != NULL)
658         {
659           GVariant *result;
660           GError *error;
661           guint32 release_name_reply;
662
663           /* TODO: it kinda sucks having to do a sync call to release the name - but if
664            * we don't, then a subsequent grab of the name will make the bus daemon return
665            * IN_QUEUE which will trigger name_lost().
666            *
667            * I believe this is a bug in the bus daemon.
668            */
669           error = NULL;
670           result = g_dbus_connection_invoke_method_sync (client->connection,
671                                                          "org.freedesktop.DBus",  /* bus name */
672                                                          "/org/freedesktop/DBus", /* object path */
673                                                          "org.freedesktop.DBus",  /* interface name */
674                                                          "ReleaseName",           /* method name */
675                                                          g_variant_new ("(s)", client->name),
676                                                          G_DBUS_INVOKE_METHOD_FLAGS_NONE,
677                                                          -1,
678                                                          NULL,
679                                                          &error);
680           if (result == NULL)
681             {
682               g_warning ("Error releasing name %s: %s", client->name, error->message);
683               g_error_free (error);
684             }
685           else
686             {
687               g_variant_get (result, "(u)", &release_name_reply);
688               if (release_name_reply != 1 /* DBUS_RELEASE_NAME_REPLY_RELEASED */)
689                 {
690                   g_warning ("Unexpected reply %d when releasing name %s", release_name_reply, client->name);
691                 }
692               g_variant_unref (result);
693             }
694         }
695
696       if (client->disconnected_signal_handler_id > 0)
697         g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
698       if (client->name_acquired_subscription_id > 0)
699         g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
700       if (client->name_lost_subscription_id > 0)
701         g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
702       client->disconnected_signal_handler_id = 0;
703       client->name_acquired_subscription_id = 0;
704       client->name_lost_subscription_id = 0;
705       if (client->connection != NULL)
706         {
707           g_object_unref (client->connection);
708           client->connection = NULL;
709         }
710
711       client_unref (client);
712     }
713 }