GDBus: Fix up i18n
[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 "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       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  * Since: 2.26
466  */
467 guint
468 g_bus_own_name_on_connection (GDBusConnection          *connection,
469                               const gchar              *name,
470                               GBusNameOwnerFlags        flags,
471                               GBusNameAcquiredCallback  name_acquired_handler,
472                               GBusNameLostCallback      name_lost_handler,
473                               gpointer                  user_data,
474                               GDestroyNotify            user_data_free_func)
475 {
476   Client *client;
477
478   g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), 0);
479   g_return_val_if_fail (!g_dbus_connection_is_closed (connection), 0);
480   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);
481
482   G_LOCK (lock);
483
484   client = g_new0 (Client, 1);
485   client->ref_count = 1;
486   client->id = next_global_id++; /* TODO: uh oh, handle overflow */
487   client->name = g_strdup (name);
488   client->flags = flags;
489   client->name_acquired_handler = name_acquired_handler;
490   client->name_lost_handler = name_lost_handler;
491   client->user_data = user_data;
492   client->user_data_free_func = user_data_free_func;
493   client->main_context = g_main_context_get_thread_default ();
494   if (client->main_context != NULL)
495     g_main_context_ref (client->main_context);
496
497   client->connection = g_object_ref (connection);
498
499   if (map_id_to_client == NULL)
500     {
501       map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
502     }
503   g_hash_table_insert (map_id_to_client,
504                        GUINT_TO_POINTER (client->id),
505                        client);
506
507   G_UNLOCK (lock);
508
509   has_connection (client);
510
511   return client->id;
512 }
513
514 /**
515  * g_bus_own_name:
516  * @bus_type: The type of bus to own a name on.
517  * @name: The well-known name to own.
518  * @flags: A set of flags from the #GBusNameOwnerFlags enumeration.
519  * @bus_acquired_handler: Handler to invoke when connected to the bus of type @bus_type or %NULL.
520  * @name_acquired_handler: Handler to invoke when @name is acquired or %NULL.
521  * @name_lost_handler: Handler to invoke when @name is lost or %NULL.
522  * @user_data: User data to pass to handlers.
523  * @user_data_free_func: Function for freeing @user_data or %NULL.
524  *
525  * Starts acquiring @name on the bus specified by @bus_type and calls
526  * @name_acquired_handler and @name_lost_handler when the name is
527  * acquired respectively lost. Callbacks will be invoked in the <link
528  * linkend="g-main-context-push-thread-default">thread-default main
529  * loop</link> of the thread you are calling this function from.
530  *
531  * You are guaranteed that one of the @name_acquired_handler and @name_lost_handler
532  * callbacks will be invoked after calling this function - there are three
533  * possible cases:
534  * <itemizedlist>
535  *   <listitem><para>
536  *     @name_lost_handler with a %NULL connection (if a connection to the bus can't be made).
537  *   </para></listitem>
538  *   <listitem><para>
539  *     @bus_acquired_handler then @name_lost_handler (if the name can't be obtained)
540  *   </para></listitem>
541  *   <listitem><para>
542  *     @bus_acquired_handler then @name_acquired_handler (if the name was obtained).
543  *   </para></listitem>
544  * </itemizedlist>
545  * When you are done owning the name, just call g_bus_unown_name()
546  * with the owner id this function returns.
547  *
548  * If the name is acquired or lost (for example another application
549  * could acquire the name if you allow replacement or the application
550  * currently owning the name exits), the handlers are also invoked. If the
551  * #GDBusConnection that is used for attempting to own the name
552  * closes, then @name_lost_handler is invoked since it is no
553  * longer possible for other processes to access the process.
554  *
555  * You cannot use g_bus_own_name() several times (unless interleaved
556  * with calls to g_bus_unown_name()) - only the first call will work.
557  *
558  * Another guarantee is that invocations of @name_acquired_handler
559  * and @name_lost_handler are guaranteed to alternate; that
560  * is, if @name_acquired_handler is invoked then you are
561  * guaranteed that the next time one of the handlers is invoked, it
562  * will be @name_lost_handler. The reverse is also true.
563  *
564  * If you plan on exporting objects (using e.g. g_dbus_connection_register_object()), note
565  * that it is generally too late to export the objects in @name_acquired_handler. Instead,
566  * you can do this in @bus_acquired_handler since you are guaranteed that this will
567  * run before @name is requested from the bus.
568  *
569  * This behavior makes it very simple to write applications that wants
570  * to own names and export objects, see <xref linkend="gdbus-owning-names"/>. Simply
571  * register objects to be exported in @bus_acquired_handler and
572  * unregister the objects (if any) in @name_lost_handler.
573  *
574  * Returns: An identifier (never 0) that an be used with
575  * g_bus_unown_name() to stop owning the name.
576  *
577  * Since: 2.26
578  */
579 guint
580 g_bus_own_name (GBusType                  bus_type,
581                 const gchar              *name,
582                 GBusNameOwnerFlags        flags,
583                 GBusAcquiredCallback      bus_acquired_handler,
584                 GBusNameAcquiredCallback  name_acquired_handler,
585                 GBusNameLostCallback      name_lost_handler,
586                 gpointer                  user_data,
587                 GDestroyNotify            user_data_free_func)
588 {
589   Client *client;
590
591   g_return_val_if_fail (bus_type != G_BUS_TYPE_NONE, 0);
592   g_return_val_if_fail (g_dbus_is_name (name) && !g_dbus_is_unique_name (name), 0);
593
594   G_LOCK (lock);
595
596   client = g_new0 (Client, 1);
597   client->ref_count = 1;
598   client->id = next_global_id++; /* TODO: uh oh, handle overflow */
599   client->name = g_strdup (name);
600   client->flags = flags;
601   client->bus_acquired_handler = bus_acquired_handler;
602   client->name_acquired_handler = name_acquired_handler;
603   client->name_lost_handler = name_lost_handler;
604   client->user_data = user_data;
605   client->user_data_free_func = user_data_free_func;
606   client->main_context = g_main_context_get_thread_default ();
607   if (client->main_context != NULL)
608     g_main_context_ref (client->main_context);
609
610   if (map_id_to_client == NULL)
611     {
612       map_id_to_client = g_hash_table_new (g_direct_hash, g_direct_equal);
613     }
614   g_hash_table_insert (map_id_to_client,
615                        GUINT_TO_POINTER (client->id),
616                        client);
617
618   g_bus_get (bus_type,
619              NULL,
620              connection_get_cb,
621              client_ref (client));
622
623   G_UNLOCK (lock);
624
625   return client->id;
626 }
627
628 /**
629  * g_bus_unown_name:
630  * @owner_id: An identifier obtained from g_bus_own_name()
631  *
632  * Stops owning a name.
633  *
634  * Since: 2.26
635  */
636 void
637 g_bus_unown_name (guint owner_id)
638 {
639   Client *client;
640
641   g_return_if_fail (owner_id > 0);
642
643   client = NULL;
644
645   G_LOCK (lock);
646   if (owner_id == 0 || map_id_to_client == NULL ||
647       (client = g_hash_table_lookup (map_id_to_client, GUINT_TO_POINTER (owner_id))) == NULL)
648     {
649       g_warning ("Invalid id %d passed to g_bus_unown_name()", owner_id);
650       goto out;
651     }
652
653   client->cancelled = TRUE;
654   g_warn_if_fail (g_hash_table_remove (map_id_to_client, GUINT_TO_POINTER (owner_id)));
655
656  out:
657   G_UNLOCK (lock);
658
659   /* do callback without holding lock */
660   if (client != NULL)
661     {
662       /* Release the name if needed */
663       if (client->needs_release && client->connection != NULL)
664         {
665           GVariant *result;
666           GError *error;
667           guint32 release_name_reply;
668
669           /* TODO: it kinda sucks having to do a sync call to release the name - but if
670            * we don't, then a subsequent grab of the name will make the bus daemon return
671            * IN_QUEUE which will trigger name_lost().
672            *
673            * I believe this is a bug in the bus daemon.
674            */
675           error = NULL;
676           result = g_dbus_connection_invoke_method_sync (client->connection,
677                                                          "org.freedesktop.DBus",  /* bus name */
678                                                          "/org/freedesktop/DBus", /* object path */
679                                                          "org.freedesktop.DBus",  /* interface name */
680                                                          "ReleaseName",           /* method name */
681                                                          g_variant_new ("(s)", client->name),
682                                                          G_DBUS_INVOKE_METHOD_FLAGS_NONE,
683                                                          -1,
684                                                          NULL,
685                                                          &error);
686           if (result == NULL)
687             {
688               g_warning ("Error releasing name %s: %s", client->name, error->message);
689               g_error_free (error);
690             }
691           else
692             {
693               g_variant_get (result, "(u)", &release_name_reply);
694               if (release_name_reply != 1 /* DBUS_RELEASE_NAME_REPLY_RELEASED */)
695                 {
696                   g_warning ("Unexpected reply %d when releasing name %s", release_name_reply, client->name);
697                 }
698               g_variant_unref (result);
699             }
700         }
701
702       if (client->disconnected_signal_handler_id > 0)
703         g_signal_handler_disconnect (client->connection, client->disconnected_signal_handler_id);
704       if (client->name_acquired_subscription_id > 0)
705         g_dbus_connection_signal_unsubscribe (client->connection, client->name_acquired_subscription_id);
706       if (client->name_lost_subscription_id > 0)
707         g_dbus_connection_signal_unsubscribe (client->connection, client->name_lost_subscription_id);
708       client->disconnected_signal_handler_id = 0;
709       client->name_acquired_subscription_id = 0;
710       client->name_lost_subscription_id = 0;
711       if (client->connection != NULL)
712         {
713           g_object_unref (client->connection);
714           client->connection = NULL;
715         }
716
717       client_unref (client);
718     }
719 }