summaryrefslogtreecommitdiff
path: root/src/settings/nm-secret-agent.c
blob: f29c44f912c4f8b75b149b20bdc735d8119723b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Copyright (C) 2010 - 2011 Red Hat, Inc.
 */

#include "nm-default.h"

#include <sys/types.h>
#include <pwd.h>

#include "nm-dbus-interface.h"
#include "nm-secret-agent.h"
#include "nm-bus-manager.h"
#include "nm-auth-subject.h"
#include "nm-simple-connection.h"
#include "NetworkManagerUtils.h"

#include "nmdbus-secret-agent.h"

#define _NMLOG_PREFIX_NAME    "secret-agent"
#define _NMLOG_DOMAIN         LOGD_AGENTS
#define _NMLOG(level, ...) \
    G_STMT_START { \
        if (nm_logging_enabled ((level), (_NMLOG_DOMAIN))) { \
            char __prefix[32]; \
            \
            if ((self)) \
                g_snprintf (__prefix, sizeof (__prefix), "%s[%p]", ""_NMLOG_PREFIX_NAME"", (self)); \
            else \
                g_strlcpy (__prefix, _NMLOG_PREFIX_NAME, sizeof (__prefix)); \
            _nm_log ((level), (_NMLOG_DOMAIN), 0, \
                     "%s: " _NM_UTILS_MACRO_FIRST(__VA_ARGS__), \
                     __prefix _NM_UTILS_MACRO_REST(__VA_ARGS__)); \
        } \
    } G_STMT_END

#define LOG_REQ_FMT          "req[%p,%s,%s%s%s%s]"
#define LOG_REQ_ARG(req)     (req), (req)->dbus_command, NM_PRINT_FMT_QUOTE_STRING ((req)->path), ((req)->cancellable ? "" : " (cancelled)")

G_DEFINE_TYPE (NMSecretAgent, nm_secret_agent, G_TYPE_OBJECT)

#define NM_SECRET_AGENT_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \
                                        NM_TYPE_SECRET_AGENT, \
                                        NMSecretAgentPrivate))

typedef struct {
	char *description;
	NMAuthSubject *subject;
	char *identifier;
	char *owner_username;
	char *dbus_owner;
	NMSecretAgentCapabilities capabilities;

	GSList *permissions;

	NMDBusSecretAgent *proxy;
	NMBusManager *bus_mgr;
	GDBusConnection *connection;
	gboolean connection_is_private;
	gulong on_disconnected_id;

	GHashTable *requests;
} NMSecretAgentPrivate;

enum {
	DISCONNECTED,

	LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };

static void cancel_with_reason_done (GObject *proxy, GAsyncResult *result, gpointer user_data);

/*************************************************************/

struct _NMSecretAgentCallId {
	NMSecretAgent *agent;
	GCancellable *cancellable;
	char *path;
	const char *dbus_command;
	char *setting_name;
	gboolean is_get_secrets;
	NMSecretAgentCallback callback;
	gpointer callback_data;
};

typedef struct _NMSecretAgentCallId Request;

static Request *
request_new (NMSecretAgent *self,
             const char *dbus_command, /* this must be a static string. */
             const char *path,
             const char *setting_name,
             NMSecretAgentCallback callback,
             gpointer callback_data)
{
	Request *r;

	r = g_slice_new0 (Request);
	r->agent = self;
	r->path = g_strdup (path);
	r->setting_name = g_strdup (setting_name);
	r->dbus_command = dbus_command,
	r->callback = callback;
	r->callback_data = callback_data;
	r->cancellable = g_cancellable_new ();
	_LOGt ("request "LOG_REQ_FMT": created", LOG_REQ_ARG (r));
	return r;
}
#define request_new(self,dbus_command,path,setting_name,callback,callback_data) request_new(self,""dbus_command"",path,setting_name,callback,callback_data)

static void
request_free (Request *r)
{
	NMSecretAgent *self = r->agent;

	_LOGt ("request "LOG_REQ_FMT": destroyed", LOG_REQ_ARG (r));
	g_free (r->path);
	g_free (r->setting_name);
	if (r->cancellable)
		g_object_unref (r->cancellable);
	g_slice_free (Request, r);
}

static gboolean
request_check_return (Request *r)
{
	NMSecretAgentPrivate *priv;

	if (!r->cancellable)
		return FALSE;

	g_return_val_if_fail (NM_IS_SECRET_AGENT (r->agent), FALSE);

	priv = NM_SECRET_AGENT_GET_PRIVATE (r->agent);

	if (!g_hash_table_remove (priv->requests, r))
		g_return_val_if_reached (FALSE);

	return TRUE;
}

/*************************************************************/

typedef struct {
	char *path;
	char *setting;
	char *agent;
} CancelInfo;

static CancelInfo *
cancel_info_new (NMSecretAgent *agent, const char *setting, const char *path)
{
	CancelInfo *info;

	info = g_slice_new (CancelInfo);
	info->agent = g_strdup (nm_secret_agent_get_description (agent));
	info->setting = g_strdup (setting);
	info->path = g_strdup (path);

	return info;
}

static void
cancel_info_free (CancelInfo *info)
{
	g_free (info->agent);
	g_free (info->path);
	g_free (info->setting);
	g_slice_free (CancelInfo, info);
}

/*************************************************************/

static char *
_create_description (const char *dbus_owner, const char *identifier, gulong uid)
{
	return g_strdup_printf ("%s/%s/%lu",
	                        dbus_owner,
	                        identifier,
	                        uid);
}

const char *
nm_secret_agent_get_description (NMSecretAgent *agent)
{
	NMSecretAgentPrivate *priv;

	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), NULL);

	priv = NM_SECRET_AGENT_GET_PRIVATE (agent);
	if (!priv->description) {
		priv->description = _create_description (priv->dbus_owner,
		                                         priv->identifier,
		                                         nm_auth_subject_get_unix_process_uid (priv->subject));
	}

	return priv->description;
}

const char *
nm_secret_agent_get_dbus_owner (NMSecretAgent *agent)
{
	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), NULL);

	return NM_SECRET_AGENT_GET_PRIVATE (agent)->dbus_owner;
}

const char *
nm_secret_agent_get_identifier (NMSecretAgent *agent)
{
	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), NULL);

	return NM_SECRET_AGENT_GET_PRIVATE (agent)->identifier;
}

gulong
nm_secret_agent_get_owner_uid  (NMSecretAgent *agent)
{
	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), G_MAXULONG);

	return nm_auth_subject_get_unix_process_uid (NM_SECRET_AGENT_GET_PRIVATE (agent)->subject);
}

const char *
nm_secret_agent_get_owner_username (NMSecretAgent *agent)
{
	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), NULL);

	return NM_SECRET_AGENT_GET_PRIVATE (agent)->owner_username;
}

gulong
nm_secret_agent_get_pid (NMSecretAgent *agent)
{
	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), G_MAXULONG);

	return nm_auth_subject_get_unix_process_pid (NM_SECRET_AGENT_GET_PRIVATE (agent)->subject);
}

NMSecretAgentCapabilities
nm_secret_agent_get_capabilities (NMSecretAgent *agent)
{
	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), NM_SECRET_AGENT_CAPABILITY_NONE);

	return NM_SECRET_AGENT_GET_PRIVATE (agent)->capabilities;
}

NMAuthSubject *
nm_secret_agent_get_subject (NMSecretAgent *agent)
{
	g_return_val_if_fail (NM_IS_SECRET_AGENT (agent), NULL);

	return NM_SECRET_AGENT_GET_PRIVATE (agent)->subject;
}

/**
 * nm_secret_agent_add_permission:
 * @agent: A #NMSecretAgent.
 * @permission: The name of the permission
 *
 * Records whether or not the agent has a given permission.
 */
void
nm_secret_agent_add_permission (NMSecretAgent *agent,
                                const char *permission,
                                gboolean allowed)
{
	NMSecretAgentPrivate *priv;
	GSList *iter;

	g_return_if_fail (agent != NULL);
	g_return_if_fail (permission != NULL);

	priv = NM_SECRET_AGENT_GET_PRIVATE (agent);

	/* Check if the permission is already in the list */
	for (iter = priv->permissions; iter; iter = g_slist_next (iter)) {
		if (g_strcmp0 (permission, iter->data) == 0) {
			/* If the permission is no longer allowed, remove it from the
			 * list.  If it is now allowed, do nothing since it's already
			 * in the list.
			 */
			if (allowed == FALSE) {
				g_free (iter->data);
				priv->permissions = g_slist_delete_link (priv->permissions, iter);
			}
			return;
		}
	}

	/* New permission that's allowed */
	if (allowed)
		priv->permissions = g_slist_prepend (priv->permissions, g_strdup (permission));
}

/**
 * nm_secret_agent_has_permission:
 * @agent: A #NMSecretAgent.
 * @permission: The name of the permission to check for
 *
 * Returns whether or not the agent has the given permission.
 * 
 * Returns: %TRUE if the agent has the given permission, %FALSE if it does not
 * or if the permission was not previous recorded with
 * nm_secret_agent_add_permission().
 */
gboolean
nm_secret_agent_has_permission (NMSecretAgent *agent, const char *permission)
{
	NMSecretAgentPrivate *priv;
	GSList *iter;

	g_return_val_if_fail (agent != NULL, FALSE);
	g_return_val_if_fail (permission != NULL, FALSE);

	priv = NM_SECRET_AGENT_GET_PRIVATE (agent);

	/* Check if the permission is already in the list */
	for (iter = priv->permissions; iter; iter = g_slist_next (iter)) {
		if (g_strcmp0 (permission, iter->data) == 0)
			return TRUE;
	}
	return FALSE;
}

/*************************************************************/

static void
get_callback (GObject *proxy,
              GAsyncResult *result,
              gpointer user_data)
{
	Request *r = user_data;
	CancelInfo *info;

	if (request_check_return (r)) {
		NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (r->agent);
		gs_free_error GError *error = NULL;
		gs_unref_variant GVariant *secrets = NULL;

		nmdbus_secret_agent_call_get_secrets_finish (priv->proxy, &secrets, result, &error);
		if (error) {
			g_dbus_error_strip_remote_error (error);
			if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_TIMED_OUT)) {
				/* Tell the failed agent we're no longer interested */
				info = cancel_info_new (r->agent, r->setting_name, r->path);
				nmdbus_secret_agent_call_cancel_get_secrets_with_reason (priv->proxy,
				                                                         r->path, r->setting_name,
				                                                         NM_SECRET_AGENT_CANCEL_REASON_TIMED_OUT,
				                                                         NULL,
				                                                         cancel_with_reason_done,
				                                                         info);
			}
		}
		r->callback (r->agent, r, secrets, error, r->callback_data);
	}

	request_free (r);
}

NMSecretAgentCallId
nm_secret_agent_get_secrets (NMSecretAgent *self,
                             const char *path,
                             NMConnection *connection,
                             const char *setting_name,
                             const char **hints,
                             NMSecretAgentGetSecretsFlags flags,
                             NMSecretAgentCallback callback,
                             gpointer callback_data)
{
	NMSecretAgentPrivate *priv;
	static const char *no_hints[] = { NULL };
	GVariant *dict;
	Request *r;

	g_return_val_if_fail (NM_IS_SECRET_AGENT (self), NULL);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), NULL);
	g_return_val_if_fail (path && *path, NULL);
	g_return_val_if_fail (setting_name != NULL, NULL);

	priv = NM_SECRET_AGENT_GET_PRIVATE (self);
	g_return_val_if_fail (priv->proxy != NULL, NULL);

	dict = nm_connection_to_dbus (connection, NM_CONNECTION_SERIALIZE_ALL);

	/* Mask off the private flags if present */
	flags &= ~NM_SECRET_AGENT_GET_SECRETS_FLAG_ONLY_SYSTEM;
	flags &= ~NM_SECRET_AGENT_GET_SECRETS_FLAG_NO_ERRORS;

	r = request_new (self, "GetSecrets", path, setting_name, callback, callback_data);
	r->is_get_secrets = TRUE;
	g_hash_table_add (priv->requests, r);

	/* Increase the timeout only for this call */
	g_dbus_proxy_set_default_timeout (G_DBUS_PROXY (priv->proxy), 120000);
	nmdbus_secret_agent_call_get_secrets (priv->proxy,
	                                      dict,
	                                      path,
	                                      setting_name,
	                                      hints ? hints : no_hints,
	                                      flags,
	                                      r->cancellable,
	                                      get_callback, r);
	g_dbus_proxy_set_default_timeout (G_DBUS_PROXY (priv->proxy), -1);

	return r;
}

/*************************************************************/

static void
cancel_done (GObject *proxy, GAsyncResult *result, gpointer user_data)
{
	CancelInfo *info = user_data;
	gs_free_error GError *error = NULL;
	gboolean r;

	r = nmdbus_secret_agent_call_cancel_get_secrets_finish (NMDBUS_SECRET_AGENT (proxy),
	                                                        result,
	                                                        &error);

	if (!r) {
		nm_log_dbg (LOGD_AGENTS, "%s%s%s: agent failed to cancel secrets: %s",
		            NM_PRINT_FMT_QUOTED (info->agent, "(", info->agent, ")", "???"),
		            error->message);
	}

	cancel_info_free (info);
}

static void
cancel_with_reason_done (GObject *proxy, GAsyncResult *result, gpointer user_data)
{
	CancelInfo *info = user_data;
	gs_free_error GError *error = NULL;
	gboolean r;

	r = nmdbus_secret_agent_call_cancel_get_secrets_with_reason_finish (NMDBUS_SECRET_AGENT (proxy),
	                                                                    result,
	                                                                    &error);
	if (!r) {
		nm_log_dbg (LOGD_AGENTS, "%s%s%s: agent failed to cancel secrets with reason: %s",
		            NM_PRINT_FMT_QUOTED (info->agent, "(", info->agent, ")", "???"),
		            error->message);

		if (g_error_matches (error, G_DBUS_ERROR, G_DBUS_ERROR_UNKNOWN_METHOD)) {
			nmdbus_secret_agent_call_cancel_get_secrets (NMDBUS_SECRET_AGENT (proxy),
			                                             info->path, info->setting,
			                                             NULL,
			                                             cancel_done,
			                                             info);
			return;
		}
	}

	cancel_info_free (info);
}

static void
do_cancel_secrets (NMSecretAgent *self, Request *r, gboolean disposing)
{
	NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (self);
	GCancellable *cancellable;
	NMSecretAgentCallback callback;
	gpointer callback_data;
	CancelInfo *info;

	g_return_if_fail (r->agent == self);
	g_return_if_fail (r->cancellable);

	if (   r->is_get_secrets
	    && priv->proxy) {
		/* for GetSecrets call, we must cancel the request. */
		info = cancel_info_new (r->agent, r->setting_name, r->path);
		nmdbus_secret_agent_call_cancel_get_secrets_with_reason (priv->proxy,
		                                                         r->path, r->setting_name,
		                                                         NM_SECRET_AGENT_CANCEL_REASON_CANCELED,
		                                                         NULL,
		                                                         cancel_with_reason_done,
		                                                         info);
	}

	cancellable = r->cancellable;
	callback = r->callback;
	callback_data = r->callback_data;

	/* During g_cancellable_cancel() the d-bus method might return synchronously.
	 * Clear r->cancellable first, so that it doesn't actually do anything.
	 * After that, @r might be already freed. */
	r->cancellable = NULL;
	g_cancellable_cancel (cancellable);
	g_object_unref (cancellable);

	/* Don't free the request @r. It will be freed when the d-bus call returns.
	 * Only clear r->cancellable to indicate that the request was cancelled. */

	if (callback) {
		gs_free_error GError *error = NULL;

		nm_utils_error_set_cancelled (&error, disposing, "NMSecretAgent");
		/* @r might be a dangling pointer at this point. However, that is no problem
		 * to pass it as (opaque) call_id. */
		callback (self, r, NULL, error, callback_data);
	}
}

/**
 * nm_secret_agent_cancel_secrets:
 * @self: #NMSecretAgent instance
 * @call_id: the call id to cancel
 *
 * It is an error to pass an invalid @call_id or a @call_id for an operation
 * that already completed. NMSecretAgent will always invoke the callback,
 * also for cancel() and dispose().
 * In case of nm_secret_agent_cancel_secrets() this will synchronously invoke the
 * callback before nm_secret_agent_cancel_secrets() returns.
 */
void
nm_secret_agent_cancel_secrets (NMSecretAgent *self, NMSecretAgentCallId call_id)
{
	NMSecretAgentPrivate *priv;
	Request *r = call_id;

	g_return_if_fail (NM_IS_SECRET_AGENT (self));
	g_return_if_fail (r);

	priv = NM_SECRET_AGENT_GET_PRIVATE (self);
	if (!g_hash_table_remove (priv->requests, r))
		g_return_if_reached ();

	do_cancel_secrets (self, r, FALSE);
}

/*************************************************************/

static void
agent_save_cb (GObject *proxy,
               GAsyncResult *result,
               gpointer user_data)
{
	Request *r = user_data;

	if (request_check_return (r)) {
		NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (r->agent);
		gs_free_error GError *error = NULL;

		nmdbus_secret_agent_call_save_secrets_finish (priv->proxy, result, &error);
		if (error)
			g_dbus_error_strip_remote_error (error);
		r->callback (r->agent, r, NULL, error, r->callback_data);
	}

	request_free (r);
}

NMSecretAgentCallId
nm_secret_agent_save_secrets (NMSecretAgent *self,
                              const char *path,
                              NMConnection *connection,
                              NMSecretAgentCallback callback,
                              gpointer callback_data)
{
	NMSecretAgentPrivate *priv;
	GVariant *dict;
	Request *r;

	g_return_val_if_fail (NM_IS_SECRET_AGENT (self), NULL);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), NULL);
	g_return_val_if_fail (path && *path, NULL);

	priv = NM_SECRET_AGENT_GET_PRIVATE (self);

	/* Caller should have ensured that only agent-owned secrets exist in 'connection' */
	dict = nm_connection_to_dbus (connection, NM_CONNECTION_SERIALIZE_ALL);

	r = request_new (self, "SaveSecrets", path, NULL, callback, callback_data);
	g_hash_table_add (priv->requests, r);
	nmdbus_secret_agent_call_save_secrets (priv->proxy,
	                                       dict,
	                                       path,
	                                       NULL, /* cancelling the request does *not* cancel the D-Bus call. */
	                                       agent_save_cb, r);

	return r;
}

/*************************************************************/

static void
agent_delete_cb (GObject *proxy,
                 GAsyncResult *result,
                 gpointer user_data)
{
	Request *r = user_data;

	if (request_check_return (r)) {
		NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (r->agent);
		gs_free_error GError *error = NULL;

		nmdbus_secret_agent_call_delete_secrets_finish (priv->proxy, result, &error);
		if (error)
			g_dbus_error_strip_remote_error (error);
		r->callback (r->agent, r, NULL, error, r->callback_data);
	}

	request_free (r);
}

NMSecretAgentCallId
nm_secret_agent_delete_secrets (NMSecretAgent *self,
                                const char *path,
                                NMConnection *connection,
                                NMSecretAgentCallback callback,
                                gpointer callback_data)
{
	NMSecretAgentPrivate *priv;
	GVariant *dict;
	Request *r;

	g_return_val_if_fail (NM_IS_SECRET_AGENT (self), NULL);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), NULL);
	g_return_val_if_fail (path && *path, NULL);

	priv = NM_SECRET_AGENT_GET_PRIVATE (self);

	/* No secrets sent; agents must be smart enough to track secrets using the UUID or something */
	dict = nm_connection_to_dbus (connection, NM_CONNECTION_SERIALIZE_NO_SECRETS);

	r = request_new (self, "DeleteSecrets", path, NULL, callback, callback_data);
	g_hash_table_add (priv->requests, r);
	nmdbus_secret_agent_call_delete_secrets (priv->proxy,
	                                         dict,
	                                         path,
	                                         NULL, /* cancelling the request does *not* cancel the D-Bus call. */
	                                         agent_delete_cb, r);

	return r;
}

/*************************************************************/

static void
_on_disconnected_cleanup (NMSecretAgentPrivate *priv)
{
	if (priv->on_disconnected_id) {
		if (priv->connection_is_private) {
			g_signal_handler_disconnect (priv->bus_mgr,
			                             priv->on_disconnected_id);
		} else {
			g_dbus_connection_signal_unsubscribe (priv->connection,
			                                      priv->on_disconnected_id);
		}
		priv->on_disconnected_id = 0;
	}

	g_clear_object (&priv->connection);
	g_clear_object (&priv->proxy);
	g_clear_object (&priv->bus_mgr);
}

static void
_on_disconnected_private_connection (NMBusManager *mgr,
                                     GDBusConnection *connection,
                                     NMSecretAgent *self)
{
	NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (self);

	if (priv->connection != connection)
		return;

	_LOGt ("private connection disconnected");

	_on_disconnected_cleanup (priv);
	g_signal_emit (self, signals[DISCONNECTED], 0);
}

static void
_on_disconnected_name_owner_changed (GDBusConnection *connection,
                                     const gchar      *sender_name,
                                     const gchar      *object_path,
                                     const gchar      *interface_name,
                                     const gchar      *signal_name,
                                     GVariant         *parameters,
                                     gpointer          user_data)
{
	NMSecretAgent *self = NM_SECRET_AGENT (user_data);
	NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (self);
	const char *old_owner, *new_owner;

	g_variant_get (parameters,
	               "(&s&s&s)",
	               NULL,
	               &old_owner,
	               &new_owner);

	_LOGt ("name-owner-changed: %s%s%s => %s%s%s",
	       NM_PRINT_FMT_QUOTE_STRING (old_owner),
	       NM_PRINT_FMT_QUOTE_STRING (new_owner));

	if (!*new_owner) {
		_on_disconnected_cleanup (priv);
		g_signal_emit (self, signals[DISCONNECTED], 0);
	}
}

/*************************************************************/

NMSecretAgent *
nm_secret_agent_new (GDBusMethodInvocation *context,
                     NMAuthSubject *subject,
                     const char *identifier,
                     NMSecretAgentCapabilities capabilities)
{
	NMSecretAgent *self;
	NMSecretAgentPrivate *priv;
	const char *dbus_owner;
	struct passwd *pw;
	GDBusProxy *proxy;
	char *owner_username = NULL;
	char *description = NULL;
	char buf_subject[64];
	gulong uid;
	GDBusConnection *connection;

	g_return_val_if_fail (context != NULL, NULL);
	g_return_val_if_fail (NM_IS_AUTH_SUBJECT (subject), NULL);
	g_return_val_if_fail (nm_auth_subject_is_unix_process (subject), NULL);
	g_return_val_if_fail (identifier != NULL, NULL);

	connection = g_dbus_method_invocation_get_connection (context);

	g_return_val_if_fail (G_IS_DBUS_CONNECTION (connection), NULL);

	uid = nm_auth_subject_get_unix_process_uid (subject);

	pw = getpwuid (uid);
	if (pw && pw->pw_name && pw->pw_name[0])
		owner_username = g_strdup (pw->pw_name);

	dbus_owner = nm_auth_subject_get_unix_process_dbus_sender (subject);

	self = (NMSecretAgent *) g_object_new (NM_TYPE_SECRET_AGENT, NULL);

	priv = NM_SECRET_AGENT_GET_PRIVATE (self);

	priv->bus_mgr = g_object_ref (nm_bus_manager_get ());
	priv->connection = g_object_ref (connection);
	priv->connection_is_private = !!nm_bus_manager_connection_get_private_name (priv->bus_mgr, connection);

	_LOGt ("constructed: %s, owner=%s%s%s (%s), private-connection=%d, unique-name=%s%s%s",
	       (description = _create_description (dbus_owner, identifier, uid)),
	       NM_PRINT_FMT_QUOTE_STRING (owner_username),
	       nm_auth_subject_to_string (subject, buf_subject, sizeof (buf_subject)),
	       priv->connection_is_private,
	       NM_PRINT_FMT_QUOTE_STRING (g_dbus_connection_get_unique_name (priv->connection)));

	priv->identifier = g_strdup (identifier);
	priv->owner_username = owner_username;
	priv->dbus_owner = g_strdup (dbus_owner);
	priv->description = description;
	priv->capabilities = capabilities;
	priv->subject = g_object_ref (subject);

	proxy = nm_bus_manager_new_proxy (priv->bus_mgr,
	                                  priv->connection,
	                                  NMDBUS_TYPE_SECRET_AGENT_PROXY,
	                                  priv->dbus_owner,
	                                  NM_DBUS_PATH_SECRET_AGENT,
	                                  NM_DBUS_INTERFACE_SECRET_AGENT);
	g_assert (proxy);
	priv->proxy = NMDBUS_SECRET_AGENT (proxy);

	/* we cannot subscribe to notify::g-name-owner because that doesn't work
	 * for unique names and it doesn't work for private connections. */
	if (priv->connection_is_private) {
		priv->on_disconnected_id = g_signal_connect (priv->bus_mgr,
		                                             NM_BUS_MANAGER_PRIVATE_CONNECTION_DISCONNECTED,
		                                             G_CALLBACK (_on_disconnected_private_connection),
		                                             self);
	} else {
		priv->on_disconnected_id = g_dbus_connection_signal_subscribe (priv->connection,
		                                                               "org.freedesktop.DBus",  /* name */
		                                                               "org.freedesktop.DBus",  /* interface */
		                                                               "NameOwnerChanged",      /* signal name */
		                                                               "/org/freedesktop/DBus", /* path */
		                                                               priv->dbus_owner,        /* arg0 */
		                                                               G_DBUS_SIGNAL_FLAGS_NONE,
		                                                               _on_disconnected_name_owner_changed,
		                                                               self,
		                                                               NULL);
	}

	return self;
}

static void
nm_secret_agent_init (NMSecretAgent *self)
{
	NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (self);

	priv->requests = g_hash_table_new (g_direct_hash, g_direct_equal);
}

static void
dispose (GObject *object)
{
	NMSecretAgent *self = NM_SECRET_AGENT (object);
	NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (self);
	GHashTableIter iter;
	Request *r;

	g_hash_table_iter_init (&iter, priv->requests);
	while (g_hash_table_iter_next (&iter, (gpointer *) &r, NULL)) {
		g_hash_table_iter_remove (&iter);
		do_cancel_secrets (self, r, TRUE);
	}

	_on_disconnected_cleanup (priv);

	g_clear_object (&priv->subject);

	G_OBJECT_CLASS (nm_secret_agent_parent_class)->dispose (object);
}

static void
finalize (GObject *object)
{
	NMSecretAgent *self = NM_SECRET_AGENT (object);
	NMSecretAgentPrivate *priv = NM_SECRET_AGENT_GET_PRIVATE (self);

	g_free (priv->description);
	g_free (priv->identifier);
	g_free (priv->owner_username);
	g_free (priv->dbus_owner);

	g_slist_free_full (priv->permissions, g_free);
	g_hash_table_destroy (priv->requests);

	G_OBJECT_CLASS (nm_secret_agent_parent_class)->finalize (object);

	_LOGt ("finalized");
}

static void
nm_secret_agent_class_init (NMSecretAgentClass *config_class)
{
	GObjectClass *object_class = G_OBJECT_CLASS (config_class);

	g_type_class_add_private (config_class, sizeof (NMSecretAgentPrivate));

	/* virtual methods */
	object_class->dispose = dispose;
	object_class->finalize = finalize;

	/* signals */
	signals[DISCONNECTED] =
		g_signal_new (NM_SECRET_AGENT_DISCONNECTED,
		              G_OBJECT_CLASS_TYPE (object_class),
		              G_SIGNAL_RUN_FIRST,
		              G_STRUCT_OFFSET (NMSecretAgentClass, disconnected),
		              NULL, NULL,
		              g_cclosure_marshal_VOID__VOID,
		              G_TYPE_NONE, 0);
}