Properly refer to the fact that multiple passwords may be removed.
[platform/upstream/libsecret.git] / libsecret / secret-prompt.c
1 /* libsecret - GLib wrapper for Secret Prompt
2  *
3  * Copyright 2011 Collabora Ltd.
4  *
5  * This program is free software: you can redistribute it and/or modify
6  * it under the terms of the GNU Lesser General Public License as published
7  * by the Free Software Foundation; either version 2.1 of the licence or (at
8  * your option) any later version.
9  *
10  * See the included COPYING file for more information.
11  *
12  * Author: Stef Walter <stefw@gnome.org>
13  */
14
15 #include "config.h"
16
17 #include "secret-dbus-generated.h"
18 #include "secret-private.h"
19 #include "secret-prompt.h"
20
21 #include <glib.h>
22 #include <glib/gi18n-lib.h>
23
24 /**
25  * SECTION:secret-prompt
26  * @title: SecretPrompt
27  * @short_description: a prompt in the Service
28  *
29  * A #SecretPrompt represents a prompt in the Secret Service.
30  *
31  * Certain actions on the Secret Service require user prompting to complete,
32  * such as creating a collection, or unlocking a collection. When such a prompt
33  * is necessary, then a #SecretPrompt object is created by this library, and
34  * passed to the secret_service_prompt() method. In this way it is handled
35  * automatically.
36  *
37  * In order to customize prompt handling, override the
38  * SecretServiceClass::prompt_async and SecretServiceClass::prompt_finish
39  * virtual methods of the #SecretService class.
40  *
41  * These functions have an unstable API and may change across versions. Use
42  * <literal>libsecret-unstable</literal> package to access them.
43  *
44  * Stability: Unstable
45  */
46
47 /**
48  * SecretPrompt:
49  *
50  * A proxy object representing a prompt that the Secret Service will display
51  * to the user.
52  */
53
54 /**
55  * SecretPromptClass:
56  * @parent_class: the parent class
57  *
58  * The class for #SecretPrompt.
59  */
60
61 struct _SecretPromptPrivate {
62         gint prompted;
63 };
64
65 G_DEFINE_TYPE (SecretPrompt, secret_prompt, G_TYPE_DBUS_PROXY);
66
67 static void
68 secret_prompt_init (SecretPrompt *self)
69 {
70         self->pv = G_TYPE_INSTANCE_GET_PRIVATE (self, SECRET_TYPE_PROMPT,
71                                                 SecretPromptPrivate);
72 }
73
74 static void
75 secret_prompt_class_init (SecretPromptClass *klass)
76 {
77         g_type_class_add_private (klass, sizeof (SecretPromptPrivate));
78 }
79
80 typedef struct {
81         GMainLoop *loop;
82         GAsyncResult *result;
83 } RunClosure;
84
85 static void
86 on_prompt_run_complete (GObject *source,
87                         GAsyncResult *result,
88                         gpointer user_data)
89 {
90         RunClosure *closure = user_data;
91         closure->result = g_object_ref (result);
92         g_main_loop_quit (closure->loop);
93 }
94
95 SecretPrompt *
96 _secret_prompt_instance (SecretService *service,
97                          const gchar *prompt_path)
98 {
99         GDBusProxy *proxy;
100         SecretPrompt *prompt;
101         GError *error = NULL;
102
103         g_return_val_if_fail (SECRET_IS_SERVICE (service), NULL);
104         g_return_val_if_fail (prompt_path != NULL, NULL);
105
106         proxy = G_DBUS_PROXY (service);
107         prompt = g_initable_new (SECRET_TYPE_PROMPT, NULL, &error,
108                                  "g-flags", G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES,
109                                  "g-interface-info", _secret_gen_prompt_interface_info (),
110                                  "g-name", g_dbus_proxy_get_name (proxy),
111                                  "g-connection", g_dbus_proxy_get_connection (proxy),
112                                  "g-object-path", prompt_path,
113                                  "g-interface-name", SECRET_PROMPT_INTERFACE,
114                                  NULL);
115
116         if (error != NULL) {
117                 g_warning ("couldn't create SecretPrompt object: %s", error->message);
118                 g_clear_error (&error);
119                 return NULL;
120         }
121
122         return prompt;
123 }
124
125 /**
126  * secret_prompt_run:
127  * @self: a prompt
128  * @window_id: XWindow id for parent window to be transient for
129  * @cancellable: optional cancellation object
130  * @return_type: the variant type of the prompt result
131  * @error: location to place an error on failure
132  *
133  * Runs a prompt and performs the prompting. Returns a variant result if the
134  * prompt was completed and not dismissed. The type of result depends on the
135  * action the prompt is completing, and is defined in the Secret Service DBus
136  * API specification.
137  *
138  * If @window_id is non-zero then it is used as an XWindow id. The Secret
139  * Service can make its prompt transient for the window with this id. In some
140  * Secret Service implementations this is not possible, so the behavior
141  * depending on this should degrade gracefully.
142  *
143  * This runs the dialog in a recursive mainloop. When run from a user interface
144  * thread, this means the user interface will remain responsive. Care should be
145  * taken that appropriate user interface actions are disabled while running the
146  * prompt.
147  *
148  * Returns: (transfer full): %NULL if the prompt was dismissed or an error occurred
149  */
150 GVariant *
151 secret_prompt_run (SecretPrompt *self,
152                    gulong window_id,
153                    GCancellable *cancellable,
154                    const GVariantType *return_type,
155                    GError **error)
156 {
157         GMainContext *context;
158         RunClosure *closure;
159         GVariant *retval;
160
161         g_return_val_if_fail (SECRET_IS_PROMPT (self), NULL);
162         g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
163         g_return_val_if_fail (error == NULL || *error == NULL, NULL);
164
165         context = g_main_context_get_thread_default ();
166
167         closure = g_new0 (RunClosure, 1);
168         closure->loop = g_main_loop_new (context, FALSE);
169
170         secret_prompt_perform (self, window_id, cancellable,
171                                on_prompt_run_complete, closure);
172
173         g_main_loop_run (closure->loop);
174
175         retval = secret_prompt_perform_finish (self, closure->result, return_type, error);
176
177         g_main_loop_unref (closure->loop);
178         g_object_unref (closure->result);
179         g_free (closure);
180
181         return retval;
182 }
183
184 /**
185  * secret_prompt_perform_sync:
186  * @self: a prompt
187  * @window_id: XWindow id for parent window to be transient for
188  * @cancellable: optional cancellation object
189  * @return_type: the variant type of the prompt result
190  * @error: location to place an error on failure
191  *
192  * Runs a prompt and performs the prompting. Returns a variant result if the
193  * prompt was completed and not dismissed. The type of result depends on the
194  * action the prompt is completing, and is defined in the Secret Service DBus
195  * API specification.
196  *
197  * If @window_id is non-zero then it is used as an XWindow id. The Secret
198  * Service can make its prompt transient for the window with this id. In some
199  * Secret Service implementations this is not possible, so the behavior
200  * depending on this should degrade gracefully.
201  *
202  * This method may block indefinitely and should not be used in user interface
203  * threads.
204  *
205  * Returns: (transfer full): %NULL if the prompt was dismissed or an error occurred
206  */
207 GVariant *
208 secret_prompt_perform_sync (SecretPrompt *self,
209                             gulong window_id,
210                             GCancellable *cancellable,
211                             const GVariantType *return_type,
212                             GError **error)
213 {
214         GMainContext *context;
215         GVariant *retval;
216
217         g_return_val_if_fail (SECRET_IS_PROMPT (self), NULL);
218         g_return_val_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable), NULL);
219         g_return_val_if_fail (error == NULL || *error == NULL, NULL);
220
221         context = g_main_context_new ();
222         g_main_context_push_thread_default (context);
223
224         retval = secret_prompt_run (self, window_id, cancellable, return_type, error);
225
226         /* Needed to prevent memory leaks */
227         while (g_main_context_iteration (context, FALSE));
228
229         g_main_context_pop_thread_default (context);
230         g_main_context_unref (context);
231
232         return retval;
233 }
234
235 typedef struct {
236         GDBusConnection *connection;
237         GCancellable *call_cancellable;
238         GCancellable *async_cancellable;
239         gulong cancelled_sig;
240         gboolean prompting;
241         gboolean dismissed;
242         gboolean vanished;
243         gboolean completed;
244         GVariant *result;
245         guint signal;
246         guint watch;
247 } PerformClosure;
248
249 static void
250 perform_closure_free (gpointer data)
251 {
252         PerformClosure *closure = data;
253         g_object_unref (closure->call_cancellable);
254         g_clear_object (&closure->async_cancellable);
255         g_object_unref (closure->connection);
256         if (closure->result)
257                 g_variant_unref (closure->result);
258         g_assert (closure->signal == 0);
259         g_assert (closure->watch == 0);
260         g_slice_free (PerformClosure, closure);
261 }
262
263 static void
264 perform_prompt_complete (GSimpleAsyncResult *res,
265                          gboolean dismissed)
266 {
267         PerformClosure *closure = g_simple_async_result_get_op_res_gpointer (res);
268
269         closure->dismissed = dismissed;
270         if (closure->completed)
271                 return;
272         closure->completed = TRUE;
273
274         if (closure->signal)
275                 g_dbus_connection_signal_unsubscribe (closure->connection, closure->signal);
276         closure->signal = 0;
277
278         if (closure->watch)
279                 g_bus_unwatch_name (closure->watch);
280         closure->watch = 0;
281
282         if (closure->cancelled_sig)
283                 g_signal_handler_disconnect (closure->async_cancellable, closure->cancelled_sig);
284         closure->cancelled_sig = 0;
285
286         g_simple_async_result_complete (res);
287 }
288
289 static void
290 on_prompt_completed (GDBusConnection *connection,
291                      const gchar *sender_name,
292                      const gchar *object_path,
293                      const gchar *interface_name,
294                      const gchar *signal_name,
295                      GVariant *parameters,
296                      gpointer user_data)
297 {
298         GSimpleAsyncResult *res = G_SIMPLE_ASYNC_RESULT (user_data);
299         SecretPrompt *self = SECRET_PROMPT (g_async_result_get_source_object (user_data));
300         PerformClosure *closure = g_simple_async_result_get_op_res_gpointer (res);
301         gboolean dismissed;
302
303         closure->prompting = FALSE;
304
305         if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(bv)"))) {
306                 g_warning ("SecretPrompt received invalid %s signal of type %s",
307                            signal_name, g_variant_get_type_string (parameters));
308                 perform_prompt_complete (res, TRUE);
309
310         } else {
311                 g_variant_get (parameters, "(bv)", &dismissed, &closure->result);
312                 perform_prompt_complete (res, dismissed);
313         }
314
315         g_object_unref (self);
316 }
317
318 static void
319 on_prompt_prompted (GObject *source,
320                     GAsyncResult *result,
321                     gpointer user_data)
322 {
323         GSimpleAsyncResult *res = G_SIMPLE_ASYNC_RESULT (user_data);
324         PerformClosure *closure = g_simple_async_result_get_op_res_gpointer (res);
325         SecretPrompt *self = SECRET_PROMPT (source);
326         GError *error = NULL;
327         GVariant *retval;
328
329         retval = g_dbus_proxy_call_finish (G_DBUS_PROXY (self), result, &error);
330
331         if (retval)
332                 g_variant_unref (retval);
333         if (closure->vanished)
334                 g_clear_error (&error);
335
336         if (error != NULL) {
337                 _secret_util_strip_remote_error (&error);
338                 g_simple_async_result_take_error (res, error);
339                 perform_prompt_complete (res, TRUE);
340
341         } else {
342                 closure->prompting = TRUE;
343                 g_atomic_int_set (&self->pv->prompted, 1);
344
345                 /* And now we wait for the signal */
346         }
347
348         g_object_unref (res);
349 }
350
351 static void
352 on_prompt_vanished (GDBusConnection *connection,
353                     const gchar *name,
354                     gpointer user_data)
355 {
356         GSimpleAsyncResult *res = G_SIMPLE_ASYNC_RESULT (user_data);
357         PerformClosure *closure = g_simple_async_result_get_op_res_gpointer (res);
358         closure->vanished = TRUE;
359         g_cancellable_cancel (closure->call_cancellable);
360         perform_prompt_complete (res, TRUE);
361 }
362
363 static void
364 on_prompt_dismissed (GObject *source,
365                      GAsyncResult *result,
366                      gpointer user_data)
367 {
368         GSimpleAsyncResult *res = G_SIMPLE_ASYNC_RESULT (user_data);
369         PerformClosure *closure = g_simple_async_result_get_op_res_gpointer (res);
370         SecretPrompt *self = SECRET_PROMPT (source);
371         GError *error = NULL;
372         GVariant *retval;
373
374         retval = g_dbus_proxy_call_finish (G_DBUS_PROXY (self), result, &error);
375
376         if (retval)
377                 g_variant_unref (retval);
378         if (closure->vanished)
379                 g_clear_error (&error);
380         if (g_error_matches (error, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD))
381                 g_clear_error (&error);
382
383         if (error != NULL) {
384                 _secret_util_strip_remote_error (&error);
385                 g_simple_async_result_take_error (res, error);
386                 perform_prompt_complete (res, TRUE);
387         }
388
389         g_object_unref (res);
390 }
391
392 static void
393 on_prompt_cancelled (GCancellable *cancellable,
394                      gpointer user_data)
395 {
396         GSimpleAsyncResult *res = G_SIMPLE_ASYNC_RESULT (user_data);
397         PerformClosure *closure = g_simple_async_result_get_op_res_gpointer (res);
398         SecretPrompt *self = SECRET_PROMPT (g_async_result_get_source_object (user_data));
399
400         /* Instead of cancelling our dbus calls, we cancel the prompt itself via this dbus call */
401
402         g_dbus_proxy_call (G_DBUS_PROXY (self), "Dismiss", g_variant_new ("()"),
403                            G_DBUS_CALL_FLAGS_NO_AUTO_START, -1,
404                            closure->call_cancellable,
405                            on_prompt_dismissed, g_object_ref (res));
406
407         g_object_unref (self);
408 }
409
410 /**
411  * secret_prompt_perform:
412  * @self: a prompt
413  * @window_id: XWindow id for parent window to be transient for
414  * @cancellable: optional cancellation object
415  * @callback: called when the operation completes
416  * @user_data: data to be passed to the callback
417  *
418  * Runs a prompt and performs the prompting. Returns %TRUE if the prompt
419  * was completed and not dismissed.
420  *
421  * If @window_id is non-zero then it is used as an XWindow id. The Secret
422  * Service can make its prompt transient for the window with this id. In some
423  * Secret Service implementations this is not possible, so the behavior
424  * depending on this should degrade gracefully.
425  *
426  * This method will return immediately and complete asynchronously.
427  */
428 void
429 secret_prompt_perform (SecretPrompt *self,
430                        gulong window_id,
431                        GCancellable *cancellable,
432                        GAsyncReadyCallback callback,
433                        gpointer user_data)
434 {
435         GSimpleAsyncResult *res;
436         PerformClosure *closure;
437         const gchar *owner_name;
438         const gchar *object_path;
439         gboolean prompted;
440         GDBusProxy *proxy;
441         gchar *window;
442
443         g_return_if_fail (SECRET_IS_PROMPT (self));
444         g_return_if_fail (cancellable == NULL || G_IS_CANCELLABLE (cancellable));
445
446         prompted = g_atomic_int_get (&self->pv->prompted);
447         if (prompted) {
448                 g_warning ("The prompt object has already had its prompt called.");
449                 return;
450         }
451
452         proxy = G_DBUS_PROXY (self);
453
454         res = g_simple_async_result_new (G_OBJECT (self), callback, user_data,
455                                          secret_prompt_perform);
456         closure = g_slice_new0 (PerformClosure);
457         closure->connection = g_object_ref (g_dbus_proxy_get_connection (proxy));
458         closure->call_cancellable = g_cancellable_new ();
459         closure->async_cancellable = cancellable ? g_object_ref (cancellable) : NULL;
460         g_simple_async_result_set_op_res_gpointer (res, closure, perform_closure_free);
461
462         if (window_id == 0)
463                 window = g_strdup ("");
464         else
465                 window = g_strdup_printf ("%lu", window_id);
466
467         owner_name = g_dbus_proxy_get_name_owner (proxy);
468         object_path = g_dbus_proxy_get_object_path (proxy);
469
470         closure->signal = g_dbus_connection_signal_subscribe (closure->connection, owner_name,
471                                                               SECRET_PROMPT_INTERFACE,
472                                                               SECRET_PROMPT_SIGNAL_COMPLETED,
473                                                               object_path, NULL,
474                                                               G_DBUS_SIGNAL_FLAGS_NONE,
475                                                               on_prompt_completed,
476                                                               g_object_ref (res),
477                                                               g_object_unref);
478
479         closure->watch = g_bus_watch_name_on_connection (closure->connection, owner_name,
480                                                          G_BUS_NAME_WATCHER_FLAGS_NONE, NULL,
481                                                          on_prompt_vanished,
482                                                          g_object_ref (res),
483                                                          g_object_unref);
484
485         if (closure->async_cancellable) {
486                 closure->cancelled_sig = g_cancellable_connect (closure->async_cancellable,
487                                                                 G_CALLBACK (on_prompt_cancelled),
488                                                                 res, NULL);
489         }
490
491         g_dbus_proxy_call (proxy, "Prompt", g_variant_new ("(s)", window),
492                            G_DBUS_CALL_FLAGS_NO_AUTO_START, -1,
493                            closure->call_cancellable, on_prompt_prompted, g_object_ref (res));
494
495         g_free (window);
496         g_object_unref (res);
497 }
498
499 /**
500  * secret_prompt_perform_finish:
501  * @self: a prompt
502  * @result: the asynchronous result passed to the callback
503  * @return_type: the variant type of the prompt result
504  * @error: location to place an error on failure
505  *
506  * Complete asynchronous operation to run a prompt and perform the prompting.
507  *
508  * Returns a variant result if the prompt was completed and not dismissed. The
509  * type of result depends on the action the prompt is completing, and is
510  * defined in the Secret Service DBus API specification.
511  *
512  * Returns: (transfer full): %NULL if the prompt was dismissed or an error occurred,
513  *          a variant result if the prompt was successful
514  */
515 GVariant *
516 secret_prompt_perform_finish (SecretPrompt *self,
517                               GAsyncResult *result,
518                               const GVariantType *return_type,
519                               GError **error)
520 {
521         PerformClosure *closure;
522         GSimpleAsyncResult *res;
523         gchar *string;
524
525         g_return_val_if_fail (SECRET_IS_PROMPT (self), NULL);
526         g_return_val_if_fail (error == NULL || *error == NULL, NULL);
527         g_return_val_if_fail (g_simple_async_result_is_valid (result, G_OBJECT (self),
528                                                               secret_prompt_perform), NULL);
529
530         res = G_SIMPLE_ASYNC_RESULT (result);
531
532         if (g_simple_async_result_propagate_error (res, error))
533                 return NULL;
534
535         closure = g_simple_async_result_get_op_res_gpointer (res);
536         if (closure->result == NULL)
537                 return NULL;
538         if (return_type != NULL && !g_variant_is_of_type (closure->result, return_type)) {
539                 string = g_variant_type_dup_string (return_type);
540                 g_warning ("received unexpected result type %s from Completed signal instead of expected %s",
541                            g_variant_get_type_string (closure->result), string);
542                 g_free (string);
543                 return NULL;
544         }
545         return g_variant_ref (closure->result);
546 }