GDBus: Use call() instead of invoke_method()
[platform/upstream/glib.git] / gio / gdbusnamewatching.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 #include <string.h>
27
28 #include "gdbusutils.h"
29 #include "gdbusnamewatching.h"
30 #include "gdbuserror.h"
31 #include "gdbusprivate.h"
32 #include "gdbusconnection.h"
33
34 #include "glibintl.h"
35 #include "gioalias.h"
36
37 /**
38  * SECTION:gdbusnamewatching
39  * @title: Watching Bus Names
40  * @short_description: Simple API for watching bus names
41  * @include: gio/gio.h
42  *
43  * Convenience API for watching bus names.
44  *
45  * <example id="gdbus-watching-names"><title>Simple application watching a name</title><programlisting><xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gdbus-example-watch-name.c"><xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback></xi:include></programlisting></example>
46  */
47
48 G_LOCK_DEFINE_STATIC (lock);
49
50 /* ---------------------------------------------------------------------------------------------------- */
51
52 typedef enum
53 {
54   PREVIOUS_CALL_NONE = 0,
55   PREVIOUS_CALL_APPEARED,
56   PREVIOUS_CALL_VANISHED,
57 } PreviousCall;
58
59 typedef struct
60 {
61   volatile gint             ref_count;
62   guint                     id;
63   gchar                    *name;
64   GBusNameWatcherFlags      flags;
65   gchar                    *name_owner;
66   GBusNameAppearedCallback  name_appeared_handler;
67   GBusNameVanishedCallback  name_vanished_handler;
68   gpointer                  user_data;
69   GDestroyNotify            user_data_free_func;
70   GMainContext             *main_context;
71
72   GDBusConnection          *connection;
73   gulong                    disconnected_signal_handler_id;
74   guint                     name_owner_changed_subscription_id;
75
76   PreviousCall              previous_call;
77
78   gboolean                  cancelled;
79   gboolean                  initialized;
80 } Client;
81
82 static guint next_global_id = 1;
83 static GHashTable *map_id_to_client = NULL;
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->name_owner_changed_subscription_id > 0)
100             g_dbus_connection_signal_unsubscribe (client->connection, client->name_owner_changed_subscription_id);
101           if (client->disconnected_signal_handler_id > 0)
102             g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
103           g_object_unref (client->connection);
104         }
105       g_free (client->name);
106       g_free (client->name_owner);
107       if (client->main_context != NULL)
108         g_main_context_unref (client->main_context);
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 typedef enum
118 {
119   CALL_TYPE_NAME_APPEARED,
120   CALL_TYPE_NAME_VANISHED
121 } CallType;
122
123 typedef struct
124 {
125   Client *client;
126
127   /* keep this separate because client->connection may
128    * be set to NULL after scheduling the call
129    */
130   GDBusConnection *connection;
131
132   /* ditto */
133   gchar *name_owner;
134
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   g_free (data->name_owner);
144   client_unref (data->client);
145   g_free (data);
146 }
147
148 static void
149 actually_do_call (Client *client, GDBusConnection *connection, const gchar *name_owner, CallType call_type)
150 {
151   switch (call_type)
152     {
153     case CALL_TYPE_NAME_APPEARED:
154       if (client->name_appeared_handler != NULL)
155         {
156           client->name_appeared_handler (connection,
157                                          client->name,
158                                          name_owner,
159                                          client->user_data);
160         }
161       break;
162
163     case CALL_TYPE_NAME_VANISHED:
164       if (client->name_vanished_handler != NULL)
165         {
166           client->name_vanished_handler (connection,
167                                          client->name,
168                                          client->user_data);
169         }
170       break;
171
172     default:
173       g_assert_not_reached ();
174       break;
175     }
176 }
177
178 static gboolean
179 call_in_idle_cb (gpointer _data)
180 {
181   CallHandlerData *data = _data;
182   actually_do_call (data->client, data->connection, data->name_owner, data->call_type);
183   return FALSE;
184 }
185
186 static void
187 schedule_call_in_idle (Client *client, CallType call_type)
188 {
189   CallHandlerData *data;
190   GSource *idle_source;
191
192   data = g_new0 (CallHandlerData, 1);
193   data->client = client_ref (client);
194   data->connection = client->connection != NULL ? g_object_ref (client->connection) : NULL;
195   data->name_owner = g_strdup (client->name_owner);
196   data->call_type = call_type;
197
198   idle_source = g_idle_source_new ();
199   g_source_set_priority (idle_source, G_PRIORITY_HIGH);
200   g_source_set_callback (idle_source,
201                          call_in_idle_cb,
202                          data,
203                          (GDestroyNotify) call_handler_data_free);
204   g_source_attach (idle_source, client->main_context);
205   g_source_unref (idle_source);
206 }
207
208 static void
209 do_call (Client *client, CallType call_type)
210 {
211   /* only schedule in idle if we're not in the right thread */
212   if (g_main_context_get_thread_default () != client->main_context)
213     schedule_call_in_idle (client, call_type);
214   else
215     actually_do_call (client, client->connection, client->name_owner, call_type);
216 }
217
218 static void
219 call_appeared_handler (Client *client)
220 {
221   if (client->previous_call != PREVIOUS_CALL_APPEARED)
222     {
223       client->previous_call = PREVIOUS_CALL_APPEARED;
224       if (!client->cancelled && client->name_appeared_handler != NULL)
225         {
226           do_call (client, CALL_TYPE_NAME_APPEARED);
227         }
228     }
229 }
230
231 static void
232 call_vanished_handler (Client  *client,
233                        gboolean ignore_cancelled)
234 {
235   if (client->previous_call != PREVIOUS_CALL_VANISHED)
236     {
237       client->previous_call = PREVIOUS_CALL_VANISHED;
238       if (((!client->cancelled) || ignore_cancelled) && client->name_vanished_handler != NULL)
239         {
240           do_call (client, CALL_TYPE_NAME_VANISHED);
241         }
242     }
243 }
244
245 /* ---------------------------------------------------------------------------------------------------- */
246
247 static void
248 on_connection_disconnected (GDBusConnection *connection,
249                             gboolean         remote_peer_vanished,
250                             GError          *error,
251                             gpointer         user_data)
252 {
253   Client *client = user_data;
254
255   if (client->name_owner_changed_subscription_id > 0)
256     g_dbus_connection_signal_unsubscribe (client->connection, client->name_owner_changed_subscription_id);
257   if (client->disconnected_signal_handler_id > 0)
258     g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
259   g_object_unref (client->connection);
260   client->disconnected_signal_handler_id = 0;
261   client->name_owner_changed_subscription_id = 0;
262   client->connection = NULL;
263
264   call_vanished_handler (client, FALSE);
265 }
266
267 /* ---------------------------------------------------------------------------------------------------- */
268
269 static void
270 on_name_owner_changed (GDBusConnection *connection,
271                        const gchar      *sender_name,
272                        const gchar      *object_path,
273                        const gchar      *interface_name,
274                        const gchar      *signal_name,
275                        GVariant         *parameters,
276                        gpointer          user_data)
277 {
278   Client *client = user_data;
279   const gchar *name;
280   const gchar *old_owner;
281   const gchar *new_owner;
282
283   if (!client->initialized)
284     goto out;
285
286   if (g_strcmp0 (object_path, "/org/freedesktop/DBus") != 0 ||
287       g_strcmp0 (interface_name, "org.freedesktop.DBus") != 0 ||
288       g_strcmp0 (sender_name, "org.freedesktop.DBus") != 0)
289     goto out;
290
291   g_variant_get (parameters,
292                  "(sss)",
293                  &name,
294                  &old_owner,
295                  &new_owner);
296
297   /* we only care about a specific name */
298   if (g_strcmp0 (name, client->name) != 0)
299     goto out;
300
301   if ((old_owner != NULL && strlen (old_owner) > 0) && client->name_owner != NULL)
302     {
303       g_free (client->name_owner);
304       client->name_owner = NULL;
305       call_vanished_handler (client, FALSE);
306     }
307
308   if (new_owner != NULL && strlen (new_owner) > 0)
309     {
310       g_warn_if_fail (client->name_owner == NULL);
311       g_free (client->name_owner);
312       client->name_owner = g_strdup (new_owner);
313       call_appeared_handler (client);
314     }
315
316  out:
317   ;
318 }
319
320 /* ---------------------------------------------------------------------------------------------------- */
321
322 static void
323 get_name_owner_cb (GObject      *source_object,
324                    GAsyncResult *res,
325                    gpointer      user_data)
326 {
327   Client *client = user_data;
328   GVariant *result;
329   const char *name_owner;
330
331   name_owner = NULL;
332   result = NULL;
333
334   result = g_dbus_connection_call_finish (client->connection,
335                                           res,
336                                           NULL);
337   if (result != NULL)
338     {
339       g_variant_get (result, "(s)", &name_owner);
340     }
341
342   if (name_owner != NULL)
343     {
344       g_warn_if_fail (client->name_owner == NULL);
345       client->name_owner = g_strdup (name_owner);
346       call_appeared_handler (client);
347     }
348   else
349     {
350       call_vanished_handler (client, FALSE);
351     }
352
353   client->initialized = TRUE;
354
355   if (result != NULL)
356     g_variant_unref (result);
357   client_unref (client);
358 }
359
360 /* ---------------------------------------------------------------------------------------------------- */
361
362 static void
363 invoke_get_name_owner (Client *client)
364 {
365   g_dbus_connection_call (client->connection,
366                           "org.freedesktop.DBus",  /* bus name */
367                           "/org/freedesktop/DBus", /* object path */
368                           "org.freedesktop.DBus",  /* interface name */
369                           "GetNameOwner",          /* method name */
370                           g_variant_new ("(s)", client->name),
371                           G_DBUS_CALL_FLAGS_NONE,
372                           -1,
373                           NULL,
374                           (GAsyncReadyCallback) get_name_owner_cb,
375                           client_ref (client));
376 }
377
378 /* ---------------------------------------------------------------------------------------------------- */
379
380 static void
381 start_service_by_name_cb (GObject      *source_object,
382                           GAsyncResult *res,
383                           gpointer      user_data)
384 {
385   Client *client = user_data;
386   GVariant *result;
387
388   result = NULL;
389
390   result = g_dbus_connection_call_finish (client->connection,
391                                           res,
392                                           NULL);
393   if (result != NULL)
394     {
395       guint32 start_service_result;
396       g_variant_get (result, "(u)", &start_service_result);
397
398       if (start_service_result == 1) /* DBUS_START_REPLY_SUCCESS */
399         {
400           invoke_get_name_owner (client);
401         }
402       else if (start_service_result == 2) /* DBUS_START_REPLY_ALREADY_RUNNING */
403         {
404           invoke_get_name_owner (client);
405         }
406       else
407         {
408           g_warning ("Unexpected reply %d from StartServiceByName() method", start_service_result);
409           call_vanished_handler (client, FALSE);
410           client->initialized = TRUE;
411         }
412     }
413   else
414     {
415       /* Errors are not unexpected; the bus will reply e.g.
416        *
417        *   org.freedesktop.DBus.Error.ServiceUnknown: The name org.gnome.Epiphany2
418        *   was not provided by any .service files
419        *
420        * so just report vanished.
421        */
422       call_vanished_handler (client, FALSE);
423       client->initialized = TRUE;
424     }
425
426   if (result != NULL)
427     g_variant_unref (result);
428   client_unref (client);
429 }
430
431 /* ---------------------------------------------------------------------------------------------------- */
432
433 static void
434 has_connection (Client *client)
435 {
436   /* listen for disconnection */
437   client->disconnected_signal_handler_id = g_signal_connect (client->connection,
438                                                              "closed",
439                                                              G_CALLBACK (on_connection_disconnected),
440                                                              client);
441
442   /* start listening to NameOwnerChanged messages immediately */
443   client->name_owner_changed_subscription_id = g_dbus_connection_signal_subscribe (client->connection,
444                                                                                    "org.freedesktop.DBus",  /* name */
445                                                                                    "org.freedesktop.DBus",  /* if */
446                                                                                    "NameOwnerChanged",      /* signal */
447                                                                                    "/org/freedesktop/DBus", /* path */
448                                                                                    client->name,
449                                                                                    on_name_owner_changed,
450                                                                                    client,
451                                                                                    NULL);
452
453   if (client->flags & G_BUS_NAME_WATCHER_FLAGS_AUTO_START)
454     {
455       g_dbus_connection_call (client->connection,
456                               "org.freedesktop.DBus",  /* bus name */
457                               "/org/freedesktop/DBus", /* object path */
458                               "org.freedesktop.DBus",  /* interface name */
459                               "StartServiceByName",    /* method name */
460                               g_variant_new ("(su)", client->name, 0),
461                               G_DBUS_CALL_FLAGS_NONE,
462                               -1,
463                               NULL,
464                               (GAsyncReadyCallback) start_service_by_name_cb,
465                               client_ref (client));
466     }
467   else
468     {
469       /* check owner */
470       invoke_get_name_owner (client);
471     }
472 }
473
474
475 static void
476 connection_get_cb (GObject      *source_object,
477                    GAsyncResult *res,
478                    gpointer      user_data)
479 {
480   Client *client = user_data;
481
482   client->connection = g_bus_get_finish (res, NULL);
483   if (client->connection == NULL)
484     {
485       call_vanished_handler (client, FALSE);
486       goto out;
487     }
488
489   has_connection (client);
490
491  out:
492   client_unref (client);
493 }
494
495 /* ---------------------------------------------------------------------------------------------------- */
496
497 /**
498  * g_bus_watch_name:
499  * @bus_type: The type of bus to watch a name on.
500  * @name: The name (well-known or unique) to watch.
501  * @flags: Flags from the #GBusNameWatcherFlags enumeration.
502  * @name_appeared_handler: Handler to invoke when @name is known to exist or %NULL.
503  * @name_vanished_handler: Handler to invoke when @name is known to not exist or %NULL.
504  * @user_data: User data to pass to handlers.
505  * @user_data_free_func: Function for freeing @user_data or %NULL.
506  *
507  * Starts watching @name on the bus specified by @bus_type and calls
508  * @name_appeared_handler and @name_vanished_handler when the name is
509  * known to have a owner respectively known to lose its
510  * owner. Callbacks will be invoked in the <link
511  * linkend="g-main-context-push-thread-default">thread-default main
512  * loop</link> of the thread you are calling this function from.
513  *
514  * You are guaranteed that one of the handlers will be invoked after
515  * calling this function. When you are done watching the name, just
516  * call g_bus_unwatch_name() with the watcher id this function
517  * returns.
518  *
519  * If the name vanishes or appears (for example the application owning
520  * the name could restart), the handlers are also invoked. If the
521  * #GDBusConnection that is used for watching the name disconnects, then
522  * @name_vanished_handler is invoked since it is no longer
523  * possible to access the name.
524  *
525  * Another guarantee is that invocations of @name_appeared_handler
526  * and @name_vanished_handler are guaranteed to alternate; that
527  * is, if @name_appeared_handler is invoked then you are
528  * guaranteed that the next time one of the handlers is invoked, it
529  * will be @name_vanished_handler. The reverse is also true.
530  *
531  * This behavior makes it very simple to write applications that wants
532  * to take action when a certain name exists, see <xref
533  * linkend="gdbus-watching-names"/>. Basically, the application
534  * should create object proxies in @name_appeared_handler and destroy
535  * them again (if any) in @name_vanished_handler.
536  *
537  * Returns: An identifier (never 0) that an be used with
538  * g_bus_unwatch_name() to stop watching the name.
539  *
540  * Since: 2.26
541  */
542 guint
543 g_bus_watch_name (GBusType                  bus_type,
544                   const gchar              *name,
545                   GBusNameWatcherFlags      flags,
546                   GBusNameAppearedCallback  name_appeared_handler,
547                   GBusNameVanishedCallback  name_vanished_handler,
548                   gpointer                  user_data,
549                   GDestroyNotify            user_data_free_func)
550 {
551   Client *client;
552
553   g_return_val_if_fail (bus_type != G_BUS_TYPE_NONE, 0);
554   g_return_val_if_fail (g_dbus_is_name (name), 0);
555
556   G_LOCK (lock);
557
558   client = g_new0 (Client, 1);
559   client->ref_count = 1;
560   client->id = next_global_id++; /* TODO: uh oh, handle overflow */
561   client->name = g_strdup (name);
562   client->flags = flags;
563   client->name_appeared_handler = name_appeared_handler;
564   client->name_vanished_handler = name_vanished_handler;
565   client->user_data = user_data;
566   client->user_data_free_func = user_data_free_func;
567   client->main_context = g_main_context_get_thread_default ();
568   if (client->main_context != NULL)
569     g_main_context_ref (client->main_context);
570
571   if (map_id_to_client == NULL)
572     {
573       map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
574     }
575   g_hash_table_insert (map_id_to_client,
576                        GUINT_TO_POINTER (client->id),
577                        client);
578
579   g_bus_get (bus_type,
580              NULL,
581              connection_get_cb,
582              client_ref (client));
583
584   G_UNLOCK (lock);
585
586   return client->id;
587 }
588
589 /**
590  * g_bus_unwatch_name:
591  * @watcher_id: An identifier obtained from g_bus_watch_name()
592  *
593  * Stops watching a name.
594  *
595  * Since: 2.26
596  */
597 void
598 g_bus_unwatch_name (guint watcher_id)
599 {
600   Client *client;
601
602   g_return_if_fail (watcher_id > 0);
603
604   client = NULL;
605
606   G_LOCK (lock);
607   if (watcher_id == 0 ||
608       map_id_to_client == NULL ||
609       (client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (watcher_id))) == NULL)
610     {
611       g_warning ("Invalid id %d passed to g_bus_unwatch_name()", watcher_id);
612       goto out;
613     }
614
615   client->cancelled = TRUE;
616   g_warn_if_fail (g_hash_table_remove (map_id_to_client, GUINT_TO_POINTER (watcher_id)));
617
618  out:
619   G_UNLOCK (lock);
620
621   /* do callback without holding lock */
622   if (client != NULL)
623     {
624       client_unref (client);
625     }
626 }
627
628 #define __G_DBUS_NAME_WATCHING_C__
629 #include "gioaliasdef.c"