nm-settings-connection.c 81.2 KB
Newer Older
Dan Williams's avatar
Dan Williams committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager system settings service
 *
 * 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.
 *
18 19
 * Copyright 2008 Novell, Inc.
 * Copyright 2008 - 2014 Red Hat, Inc.
Dan Williams's avatar
Dan Williams committed
20
 */
21

22 23
#include "config.h"

24 25
#include <string.h>

26
#include <nm-dbus-interface.h>
27 28
#include <dbus/dbus-glib-lowlevel.h>

29
#include "nm-settings-connection.h"
30
#include "nm-session-monitor.h"
31
#include "nm-dbus-manager.h"
32
#include "nm-dbus-glib-types.h"
Dan Williams's avatar
Dan Williams committed
33
#include "nm-logging.h"
34
#include "nm-auth-utils.h"
35
#include "nm-auth-subject.h"
36
#include "nm-agent-manager.h"
37
#include "NetworkManagerUtils.h"
38
#include "nm-properties-changed-signal.h"
39
#include "nm-core-internal.h"
40
#include "nm-glib-compat.h"
41

42 43
#define SETTINGS_TIMESTAMPS_FILE  NMSTATEDIR "/timestamps"
#define SETTINGS_SEEN_BSSIDS_FILE NMSTATEDIR "/seen-bssids"
44

45 46
static void impl_settings_connection_get_settings (NMSettingsConnection *connection,
                                                   DBusGMethodInvocation *context);
47

48 49 50
static void impl_settings_connection_update (NMSettingsConnection *connection,
                                             GHashTable *new_settings,
                                             DBusGMethodInvocation *context);
51

52 53 54 55
static void impl_settings_connection_update_unsaved (NMSettingsConnection *connection,
                                                     GHashTable *new_settings,
                                                     DBusGMethodInvocation *context);

56 57 58
static void impl_settings_connection_save (NMSettingsConnection *connection,
                                           DBusGMethodInvocation *context);

59 60
static void impl_settings_connection_delete (NMSettingsConnection *connection,
                                             DBusGMethodInvocation *context);
61

62 63 64
static void impl_settings_connection_get_secrets (NMSettingsConnection *connection,
                                                  const gchar *setting_name,
                                                  DBusGMethodInvocation *context);
65

66 67 68
static void impl_settings_connection_clear_secrets (NMSettingsConnection *connection,
                                                    DBusGMethodInvocation *context);

69
#include "nm-settings-connection-glue.h"
70

71 72 73 74 75
static void nm_settings_connection_connection_interface_init (NMConnectionInterface *iface);

G_DEFINE_TYPE_WITH_CODE (NMSettingsConnection, nm_settings_connection, G_TYPE_OBJECT,
                         G_IMPLEMENT_INTERFACE (NM_TYPE_CONNECTION, nm_settings_connection_connection_interface_init)
                         )
76

77 78 79
#define NM_SETTINGS_CONNECTION_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), \
                                               NM_TYPE_SETTINGS_CONNECTION, \
                                               NMSettingsConnectionPrivate))
80

81 82 83
enum {
	PROP_0 = 0,
	PROP_VISIBLE,
84
	PROP_UNSAVED,
85
	PROP_READY,
86
	PROP_FLAGS,
87
	PROP_FILENAME,
88 89
};

90 91 92
enum {
	UPDATED,
	REMOVED,
93
	UPDATED_BY_USER,
94 95 96 97
	LAST_SIGNAL
};
static guint signals[LAST_SIGNAL] = { 0 };

98
typedef struct {
99
	NMAgentManager *agent_mgr;
100
	guint session_changed_id;
101

102
	NMSettingsConnectionFlags flags;
103
	gboolean ready;
104

105 106
	guint updated_idle_id;

107
	GSList *pending_auths; /* List of pending authentication requests */
108
	gboolean visible; /* Is this connection is visible by some session? */
109 110
	GSList *reqs;  /* in-progress secrets requests */

111 112 113 114 115 116 117 118 119 120 121 122 123 124
	/* Caches secrets from on-disk connections; were they not cached any
	 * call to nm_connection_clear_secrets() wipes them out and we'd have
	 * to re-read them from disk which defeats the purpose of having the
	 * connection in-memory at all.
	 */
	NMConnection *system_secrets;

	/* Caches secrets from agents during the activation process; if new system
	 * secrets are returned from an agent, they get written out to disk,
	 * triggering a re-read of the connection, which reads only system
	 * secrets, and would wipe out any agent-owned or not-saved secrets the
	 * agent also returned.
	 */
	NMConnection *agent_secrets;
125

126
	guint64 timestamp;   /* Up-to-date timestamp of connection use */
127
	gboolean timestamp_set;
128
	GHashTable *seen_bssids; /* Up-to-date BSSIDs that's been seen for the connection */
129 130

	int autoconnect_retries;
131
	gint32 autoconnect_retry_time;
132 133
	NMDeviceStateReason autoconnect_blocked_reason;

134 135
	char *filename;

136
} NMSettingsConnectionPrivate;
137

138 139
/**************************************************************/

140 141 142 143 144 145 146 147
/* Return TRUE to continue, FALSE to stop */
typedef gboolean (*ForEachSecretFunc) (GHashTableIter *iter,
                                       NMSettingSecretFlags flags,
                                       gpointer user_data);

static void
for_each_secret (NMConnection *connection,
                 GHashTable *secrets,
148
                 gboolean remove_non_secrets,
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171
                 ForEachSecretFunc callback,
                 gpointer callback_data)
{
	GHashTableIter iter;
	const char *setting_name;
	GHashTable *setting_hash;

	/* This function, given a hash of hashes representing new secrets of
	 * an NMConnection, walks through each toplevel hash (which represents a
	 * NMSetting), and for each setting, walks through that setting hash's
	 * properties.  For each property that's a secret, it will check that
	 * secret's flags in the backing NMConnection object, and call a supplied
	 * callback.
	 *
	 * The one complexity is that the VPN setting's 'secrets' property is
	 * *also* a hash table (since the key/value pairs are arbitrary and known
	 * only to the VPN plugin itself).  That means we have three levels of
	 * GHashTables that we potentially have to traverse here.  When we hit the
	 * VPN setting's 'secrets' property, we special-case that and iterate over
	 * each item in that 'secrets' hash table, calling the supplied callback
	 * each time.
	 */

172 173
	g_return_if_fail (callback);

174 175 176 177 178 179 180 181
	/* Walk through the list of setting hashes */
	g_hash_table_iter_init (&iter, secrets);
	while (g_hash_table_iter_next (&iter, (gpointer) &setting_name, (gpointer) &setting_hash)) {
		NMSetting *setting;
		GHashTableIter secret_iter;
		const char *secret_name;
		GValue *val;

182 183 184
		if (g_hash_table_size (setting_hash) == 0)
			continue;

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
		/* Get the actual NMSetting from the connection so we can get secret flags
		 * from the connection data, since flags aren't secrets.  What we're
		 * iterating here is just the secrets, not a whole connection.
		 */
		setting = nm_connection_get_setting_by_name (connection, setting_name);
		if (setting == NULL)
			continue;

		/* Walk through the list of keys in each setting hash */
		g_hash_table_iter_init (&secret_iter, setting_hash);
		while (g_hash_table_iter_next (&secret_iter, (gpointer) &secret_name, (gpointer) &val)) {
			NMSettingSecretFlags secret_flags = NM_SETTING_SECRET_FLAG_NONE;

			/* VPN secrets need slightly different treatment here since the
			 * "secrets" property is actually a hash table of secrets.
			 */
			if (NM_IS_SETTING_VPN (setting) && (g_strcmp0 (secret_name, NM_SETTING_VPN_SECRETS) == 0)) {
				GHashTableIter vpn_secrets_iter;

				/* Iterate through each secret from the VPN hash in the overall secrets hash */
				g_hash_table_iter_init (&vpn_secrets_iter, g_value_get_boxed (val));
				while (g_hash_table_iter_next (&vpn_secrets_iter, (gpointer) &secret_name, NULL)) {
					secret_flags = NM_SETTING_SECRET_FLAG_NONE;
					nm_setting_get_secret_flags (setting, secret_name, &secret_flags, NULL);
					if (callback (&vpn_secrets_iter, secret_flags, callback_data) == FALSE)
						return;
				}
			} else {
213 214 215 216 217
				if (!nm_setting_get_secret_flags (setting, secret_name, &secret_flags, NULL)) {
					if (remove_non_secrets)
						g_hash_table_iter_remove (&secret_iter);
					continue;
				}
218 219 220 221 222 223 224 225 226
				if (callback (&secret_iter, secret_flags, callback_data) == FALSE)
					return;
			}
		}
	}
}

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

227
static void
228
set_visible (NMSettingsConnection *self, gboolean new_visible)
229
{
230
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
231

232 233 234
	if (new_visible == priv->visible)
		return;
	priv->visible = new_visible;
235
	g_object_notify (G_OBJECT (self), NM_SETTINGS_CONNECTION_VISIBLE);
236 237 238
}

gboolean
239
nm_settings_connection_is_visible (NMSettingsConnection *self)
240
{
Dan Williams's avatar
Dan Williams committed
241
	g_return_val_if_fail (NM_IS_SETTINGS_CONNECTION (self), FALSE);
242

243
	return NM_SETTINGS_CONNECTION_GET_PRIVATE (self)->visible;
244 245
}

246
void
247
nm_settings_connection_recheck_visibility (NMSettingsConnection *self)
248
{
249
	NMSettingsConnectionPrivate *priv;
250 251
	NMSettingConnection *s_con;
	guint32 num, i;
252

Dan Williams's avatar
Dan Williams committed
253
	g_return_if_fail (NM_IS_SETTINGS_CONNECTION (self));
254

255
	priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
256

257
	s_con = nm_connection_get_setting_connection (NM_CONNECTION (self));
258
	g_assert (s_con);
259

260 261 262 263 264 265 266
	/* Check every user in the ACL for a session */
	num = nm_setting_connection_get_num_permissions (s_con);
	if (num == 0) {
		/* Visible to all */
		set_visible (self, TRUE);
		return;
	}
267

268
	for (i = 0; i < num; i++) {
269 270
		const char *user;
		uid_t uid;
271

272 273 274 275 276 277 278 279 280
		if (!nm_setting_connection_get_permission (s_con, i, NULL, &user, NULL))
			continue;
		if (!nm_session_monitor_user_to_uid (user, &uid))
			continue;
		if (!nm_session_monitor_session_exists (uid, FALSE))
			continue;

		set_visible (self, TRUE);
		return;
281 282 283
	}

	set_visible (self, FALSE);
284 285
}

286 287 288
static void
session_changed_cb (NMSessionMonitor *self, gpointer user_data)
{
289
	nm_settings_connection_recheck_visibility (NM_SETTINGS_CONNECTION (user_data));
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
/* Return TRUE if any active user in the connection's ACL has the given
 * permission without having to authorize for it via PolicyKit.  Connections
 * visible to everyone automatically pass the check.
 */
gboolean
nm_settings_connection_check_permission (NMSettingsConnection *self,
                                         const char *permission)
{
	NMSettingsConnectionPrivate *priv;
	NMSettingConnection *s_con;
	guint32 num, i;
	const char *puser;

	g_return_val_if_fail (NM_IS_SETTINGS_CONNECTION (self), FALSE);

	priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);

	if (priv->visible == FALSE)
		return FALSE;

	s_con = nm_connection_get_setting_connection (NM_CONNECTION (self));
	g_assert (s_con);

	/* Check every user in the ACL for a session */
	num = nm_setting_connection_get_num_permissions (s_con);
	if (num == 0) {
		/* Visible to all so it's OK to auto-activate */
		return TRUE;
	}

	for (i = 0; i < num; i++) {
		/* For each user get their secret agent and check if that agent has the
		 * required permission.
		 *
		 * FIXME: what if the user isn't running an agent?  PolKit needs a bus
		 * name or a PID but if the user isn't running an agent they won't have
		 * either.
		 */
		if (nm_setting_connection_get_permission (s_con, i, NULL, &puser, NULL)) {
			NMSecretAgent *agent = nm_agent_manager_get_agent_by_user (priv->agent_mgr, puser);

			if (agent && nm_secret_agent_has_permission (agent, permission))
				return TRUE;
		}
	}

	return FALSE;
}

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

345 346 347 348 349
static gboolean
secrets_filter_cb (NMSetting *setting,
                   const char *secret,
                   NMSettingSecretFlags flags,
                   gpointer user_data)
350
{
351
	NMSettingSecretFlags filter_flags = GPOINTER_TO_UINT (user_data);
352

353
	/* Returns TRUE to remove the secret */
354

355 356 357 358 359 360 361
	/* Can't use bitops with SECRET_FLAG_NONE so handle that specifically */
	if (   (flags == NM_SETTING_SECRET_FLAG_NONE)
	    && (filter_flags == NM_SETTING_SECRET_FLAG_NONE))
		return FALSE;

	/* Otherwise if the secret has at least one of the desired flags keep it */
	return (flags & filter_flags) ? FALSE : TRUE;
362 363 364
}

static void
365
update_system_secrets_cache (NMSettingsConnection *self)
366 367 368
{
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);

369 370
	if (priv->system_secrets)
		g_object_unref (priv->system_secrets);
371
	priv->system_secrets = nm_simple_connection_new_clone (NM_CONNECTION (self));
372 373

	/* Clear out non-system-owned and not-saved secrets */
374 375 376
	nm_connection_clear_secrets_with_flags (priv->system_secrets,
	                                        secrets_filter_cb,
	                                        GUINT_TO_POINTER (NM_SETTING_SECRET_FLAG_NONE));
377 378
}

379 380
static void
update_agent_secrets_cache (NMSettingsConnection *self, NMConnection *new)
381
{
382 383 384 385 386
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
	NMSettingSecretFlags filter_flags = NM_SETTING_SECRET_FLAG_NOT_SAVED | NM_SETTING_SECRET_FLAG_AGENT_OWNED;

	if (priv->agent_secrets)
		g_object_unref (priv->agent_secrets);
387
	priv->agent_secrets = nm_simple_connection_new_clone (new ? new : NM_CONNECTION (self));
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405

	/* Clear out non-system-owned secrets */
	nm_connection_clear_secrets_with_flags (priv->agent_secrets,
	                                        secrets_filter_cb,
	                                        GUINT_TO_POINTER (filter_flags));
}

static void
secrets_cleared_cb (NMSettingsConnection *self)
{
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);

	/* Clear agent secrets when connection's secrets are cleared since agent
	 * secrets are transient.
	 */
	if (priv->agent_secrets)
		g_object_unref (priv->agent_secrets);
	priv->agent_secrets = NULL;
406 407
}

408 409 410 411 412 413 414 415 416 417 418
static gboolean
emit_updated (NMSettingsConnection *self)
{
	NM_SETTINGS_CONNECTION_GET_PRIVATE (self)->updated_idle_id = 0;
	g_signal_emit (self, signals[UPDATED], 0);
	return FALSE;
}

static void
set_unsaved (NMSettingsConnection *self, gboolean now_unsaved)
{
419
	NMSettingsConnectionFlags flags = nm_settings_connection_get_flags (self);
420

421 422 423 424 425
	if (NM_FLAGS_HAS (flags, NM_SETTINGS_CONNECTION_FLAGS_UNSAVED) != !!now_unsaved) {
		if (now_unsaved)
			flags |= NM_SETTINGS_CONNECTION_FLAGS_UNSAVED;
		else {
			flags &= ~(NM_SETTINGS_CONNECTION_FLAGS_UNSAVED |
426 427
			           NM_SETTINGS_CONNECTION_FLAGS_NM_GENERATED |
			           NM_SETTINGS_CONNECTION_FLAGS_NM_GENERATED_ASSUMED);
428 429
		}
		nm_settings_connection_set_flags_all (self, flags);
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
	}
}

static void
changed_cb (NMSettingsConnection *self, gpointer user_data)
{
	gboolean update_unsaved = !!user_data;

	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);

	if (update_unsaved)
		set_unsaved (self, TRUE);
	if (priv->updated_idle_id == 0)
		priv->updated_idle_id = g_idle_add ((GSourceFunc) emit_updated, self);
}

446 447
/* Update the settings of this connection to match that of 'new_connection',
 * taking care to make a private copy of secrets.
448
 */
449
gboolean
450
nm_settings_connection_replace_settings (NMSettingsConnection *self,
451
                                         NMConnection *new_connection,
452
                                         gboolean update_unsaved,
453
                                         const char *log_diff_name,
454
                                         GError **error)
455
{
456
	NMSettingsConnectionPrivate *priv;
457 458
	gboolean success = FALSE;

459
	g_return_val_if_fail (NM_IS_SETTINGS_CONNECTION (self), FALSE);
460
	g_return_val_if_fail (NM_IS_CONNECTION (new_connection), FALSE);
461

462
	priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
463

464
	if (!nm_connection_normalize (new_connection, NULL, NULL, error))
465 466
		return FALSE;

467 468 469 470 471 472 473 474 475
	if (   nm_connection_get_path (NM_CONNECTION (self))
	    && g_strcmp0 (nm_connection_get_uuid (NM_CONNECTION (self)), nm_connection_get_uuid (new_connection)) != 0) {
		/* Updating the UUID is not allowed once the path is exported. */
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
		             "connection %s cannot change the UUID from %s to %s", nm_connection_get_id (NM_CONNECTION (self)),
		             nm_connection_get_uuid (NM_CONNECTION (self)), nm_connection_get_uuid (new_connection));
		return FALSE;
	}

476 477 478 479 480 481 482
	/* Do nothing if there's nothing to update */
	if (nm_connection_compare (NM_CONNECTION (self),
	                           new_connection,
	                           NM_SETTING_COMPARE_FLAG_EXACT)) {
		return TRUE;
	}

483 484 485 486 487
	/* Disconnect the changed signal to ensure we don't set Unsaved when
	 * it's not required.
	 */
	g_signal_handlers_block_by_func (self, G_CALLBACK (changed_cb), GUINT_TO_POINTER (TRUE));

488 489
	if (log_diff_name)
		nm_utils_log_connection_diff (new_connection, NM_CONNECTION (self), LOGL_DEBUG, LOGD_CORE, log_diff_name, "++ ");
490

491
	nm_connection_replace_settings_from_connection (NM_CONNECTION (self), new_connection);
492 493 494
	nm_settings_connection_set_flags (self,
	                                  NM_SETTINGS_CONNECTION_FLAGS_NM_GENERATED | NM_SETTINGS_CONNECTION_FLAGS_NM_GENERATED_ASSUMED,
	                                  FALSE);
495

496 497 498 499 500
	/* Cache the just-updated system secrets in case something calls
	 * nm_connection_clear_secrets() and clears them.
	 */
	update_system_secrets_cache (self);
	success = TRUE;
501

502 503 504 505
	/* Add agent and always-ask secrets back; they won't necessarily be
	 * in the replacement connection data if it was eg reread from disk.
	 */
	if (priv->agent_secrets) {
506 507 508 509 510 511
		GVariant *dict;

		dict = nm_connection_to_dbus (priv->agent_secrets, NM_CONNECTION_SERIALIZE_ONLY_SECRETS);
		if (dict) {
			(void) nm_connection_update_secrets (NM_CONNECTION (self), NULL, dict, NULL);
			g_variant_unref (dict);
512
		}
513
	}
514

515
	nm_settings_connection_recheck_visibility (self);
516

517 518 519 520
	/* Manually emit changed signal since we disconnected the handler, but
	 * only update Unsaved if the caller wanted us to.
	 */
	changed_cb (self, GUINT_TO_POINTER (update_unsaved));
521

522
	g_signal_emit (self, signals[UPDATED_BY_USER], 0);
523 524 525

	g_signal_handlers_unblock_by_func (self, G_CALLBACK (changed_cb), GUINT_TO_POINTER (TRUE));

526 527 528
	return success;
}

529
static void
530
ignore_cb (NMSettingsConnection *connection,
531 532 533 534 535
           GError *error,
           gpointer user_data)
{
}

536 537 538 539
/* Replaces the settings in this connection with those in 'new_connection'. If
 * any changes are made, commits them to permanent storage and to any other
 * subsystems watching this connection. Before returning, 'callback' is run
 * with the given 'user_data' along with any errors encountered.
540
 */
541 542 543 544 545
static void
replace_and_commit (NMSettingsConnection *self,
                    NMConnection *new_connection,
                    NMSettingsConnectionCommitFunc callback,
                    gpointer user_data)
546 547 548
{
	GError *error = NULL;

549
	if (nm_settings_connection_replace_settings (self, new_connection, TRUE, "replace-and-commit-disk", &error))
550
		nm_settings_connection_commit_changes (self, callback, user_data);
551
	else {
552
		g_assert (error);
553 554
		if (callback)
			callback (self, error, user_data);
555 556 557 558
		g_clear_error (&error);
	}
}

559 560 561 562 563 564 565 566 567 568 569 570
void
nm_settings_connection_replace_and_commit (NMSettingsConnection *self,
                                           NMConnection *new_connection,
                                           NMSettingsConnectionCommitFunc callback,
                                           gpointer user_data)
{
	g_return_if_fail (NM_IS_SETTINGS_CONNECTION (self));
	g_return_if_fail (NM_IS_CONNECTION (new_connection));

	NM_SETTINGS_CONNECTION_GET_CLASS (self)->replace_and_commit (self, new_connection, callback, user_data);
}

571 572 573 574 575 576 577 578 579 580 581 582 583 584 585
static void
commit_changes (NMSettingsConnection *self,
                NMSettingsConnectionCommitFunc callback,
                gpointer user_data)
{
	/* Subclasses only call this function if the save was successful, so at
	 * this point the connection is synced to disk and no longer unsaved.
	 */
	set_unsaved (self, FALSE);

	g_object_ref (self);
	callback (self, NULL, user_data);
	g_object_unref (self);
}

586
void
587 588 589
nm_settings_connection_commit_changes (NMSettingsConnection *connection,
                                       NMSettingsConnectionCommitFunc callback,
                                       gpointer user_data)
590
{
591
	g_return_if_fail (NM_IS_SETTINGS_CONNECTION (connection));
592

593 594
	if (NM_SETTINGS_CONNECTION_GET_CLASS (connection)->commit_changes) {
		NM_SETTINGS_CONNECTION_GET_CLASS (connection)->commit_changes (connection,
595
		                                                               callback ? callback : ignore_cb,
596
		                                                               user_data);
597
	} else {
598
		GError *error = g_error_new (NM_SETTINGS_ERROR,
599
		                             NM_SETTINGS_ERROR_FAILED,
600
		                             "%s: %s:%d commit_changes() unimplemented", __func__, __FILE__, __LINE__);
601 602
		if (callback)
			callback (connection, error, user_data);
603 604 605 606 607
		g_error_free (error);
	}
}

void
608 609 610
nm_settings_connection_delete (NMSettingsConnection *connection,
                               NMSettingsConnectionDeleteFunc callback,
                               gpointer user_data)
611
{
612
	g_return_if_fail (NM_IS_SETTINGS_CONNECTION (connection));
613

614 615
	if (NM_SETTINGS_CONNECTION_GET_CLASS (connection)->delete) {
		NM_SETTINGS_CONNECTION_GET_CLASS (connection)->delete (connection,
616
		                                                       callback ? callback : ignore_cb,
617
		                                                       user_data);
618
	} else {
619
		GError *error = g_error_new (NM_SETTINGS_ERROR,
620
		                             NM_SETTINGS_ERROR_FAILED,
621
		                             "%s: %s:%d delete() unimplemented", __func__, __FILE__, __LINE__);
622 623
		if (callback)
			callback (connection, error, user_data);
624 625 626 627
		g_error_free (error);
	}
}

628
static void
629
remove_entry_from_db (NMSettingsConnection *connection, const char* db_name)
630
{
631 632
	GKeyFile *key_file;
	const char *db_file;
633

634 635 636 637 638 639 640 641 642
	if (strcmp (db_name, "timestamps") == 0)
		db_file = SETTINGS_TIMESTAMPS_FILE;
	else if (strcmp (db_name, "seen-bssids") == 0)
		db_file = SETTINGS_SEEN_BSSIDS_FILE;
	else
		return;

	key_file = g_key_file_new ();
	if (g_key_file_load_from_file (key_file, db_file, G_KEY_FILE_KEEP_COMMENTS, NULL)) {
643 644 645 646 647 648 649
		const char *connection_uuid;
		char *data;
		gsize len;
		GError *error = NULL;

		connection_uuid = nm_connection_get_uuid (NM_CONNECTION (connection));

650 651
		g_key_file_remove_key (key_file, db_name, connection_uuid, NULL);
		data = g_key_file_to_data (key_file, &len, &error);
652
		if (data) {
653
			g_file_set_contents (db_file, data, len, &error);
654 655 656
			g_free (data);
		}
		if (error) {
657
			nm_log_warn (LOGD_SETTINGS, "error writing %s file '%s': %s", db_name, db_file, error->message);
658 659 660
			g_error_free (error);
		}
	}
661
	g_key_file_free (key_file);
662 663
}

664
static void
665 666 667
do_delete (NMSettingsConnection *connection,
           NMSettingsConnectionDeleteFunc callback,
           gpointer user_data)
668
{
669 670 671
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (connection);
	NMConnection *for_agents;

672
	g_object_ref (connection);
673
	set_visible (connection, FALSE);
674 675

	/* Tell agents to remove secrets for this connection */
676
	for_agents = nm_simple_connection_new_clone (NM_CONNECTION (connection));
677
	nm_connection_clear_secrets (for_agents);
678
	nm_agent_manager_delete_secrets (priv->agent_mgr, for_agents);
679
	g_object_unref (for_agents);
680

681
	/* Remove timestamp from timestamps database file */
682 683 684 685
	remove_entry_from_db (connection, "timestamps");

	/* Remove connection from seen-bssids database file */
	remove_entry_from_db (connection, "seen-bssids");
686

687 688
	nm_settings_connection_signal_remove (connection);

689
	callback (connection, NULL, user_data);
690

691 692 693
	g_object_unref (connection);
}

694 695 696
/**************************************************************/

static gboolean
697
supports_secrets (NMSettingsConnection *connection, const char *setting_name)
698 699 700 701 702
{
	/* All secrets supported */
	return TRUE;
}

703
static gboolean
704 705 706
clear_nonagent_secrets (GHashTableIter *iter,
                        NMSettingSecretFlags flags,
                        gpointer user_data)
707
{
708
	if (flags != NM_SETTING_SECRET_FLAG_AGENT_OWNED)
709 710 711 712
		g_hash_table_iter_remove (iter);
	return TRUE;
}

713 714 715 716 717 718 719 720 721 722
static gboolean
clear_unsaved_secrets (GHashTableIter *iter,
                       NMSettingSecretFlags flags,
                       gpointer user_data)
{
	if (flags & (NM_SETTING_SECRET_FLAG_NOT_SAVED | NM_SETTING_SECRET_FLAG_NOT_REQUIRED))
		g_hash_table_iter_remove (iter);
	return TRUE;
}

723 724 725 726 727 728 729
static gboolean
has_system_owned_secrets (GHashTableIter *iter,
                          NMSettingSecretFlags flags,
                          gpointer user_data)
{
	gboolean *has_system_owned = user_data;

730
	if (flags == NM_SETTING_SECRET_FLAG_NONE) {
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747
		*has_system_owned = TRUE;
		return FALSE;
	}
	return TRUE;
}

static void
new_secrets_commit_cb (NMSettingsConnection *connection,
                       GError *error,
                       gpointer user_data)
{
	if (error) {
		nm_log_warn (LOGD_SETTINGS, "Error saving new secrets to backing storage: (%d) %s",
		             error->code, error->message ? error->message : "(unknown)");
	}
}

748 749 750
static void
agent_secrets_done_cb (NMAgentManager *manager,
                       guint32 call_id,
751
                       const char *agent_dbus_owner,
752
                       const char *agent_username,
753
                       gboolean agent_has_modify,
754
                       const char *setting_name,
755
                       NMSecretAgentGetSecretsFlags flags,
756 757 758 759 760 761 762 763 764 765 766
                       GHashTable *secrets,
                       GError *error,
                       gpointer user_data,
                       gpointer other_data2,
                       gpointer other_data3)
{
	NMSettingsConnection *self = NM_SETTINGS_CONNECTION (user_data);
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
	NMSettingsConnectionSecretsFunc callback = other_data2;
	gpointer callback_data = other_data3;
	GError *local = NULL;
767
	GVariant *dict;
768
	gboolean agent_had_system = FALSE;
769

770
	if (error) {
771
		nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) secrets request error: (%d) %s",
772
		            nm_connection_get_uuid (NM_CONNECTION (self)),
773 774 775 776
		            setting_name,
		            call_id,
		            error->code,
		            error->message ? error->message : "(unknown)");
777

778
		callback (self, call_id, NULL, setting_name, error, callback_data);
779 780 781
		return;
	}

782
	if (!nm_connection_get_setting_by_name (NM_CONNECTION (self), setting_name)) {
783
		local = g_error_new (NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_SETTING_NOT_FOUND,
784 785
		                     "%s.%d - Connection didn't have requested setting '%s'.",
		                     __FILE__, __LINE__, setting_name);
786
		callback (self, call_id, NULL, setting_name, local, callback_data);
787 788 789
		g_clear_error (&local);
		return;
	}
790

791 792 793
	g_assert (secrets);
	if (agent_dbus_owner) {
		nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) secrets returned from agent %s",
794
		            nm_connection_get_uuid (NM_CONNECTION (self)),
795 796 797
		            setting_name,
		            call_id,
		            agent_dbus_owner);
798 799 800 801 802 803 804

		/* If the agent returned any system-owned secrets (initial connect and no
		 * secrets given when the connection was created, or something like that)
		 * make sure the agent's UID has the 'modify' permission before we use or
		 * save those system-owned secrets.  If not, discard them and use the
		 * existing secrets, or fail the connection.
		 */
805
		for_each_secret (NM_CONNECTION (self), secrets, TRUE, has_system_owned_secrets, &agent_had_system);
806
		if (agent_had_system) {
807
			if (flags == NM_SECRET_AGENT_GET_SECRETS_FLAG_NONE) {
808 809 810 811
				/* No user interaction was allowed when requesting secrets; the
				 * agent is being bad.  Remove system-owned secrets.
				 */
				nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) interaction forbidden but agent %s returned system secrets",
812
				            nm_connection_get_uuid (NM_CONNECTION (self)),
813 814 815 816
				            setting_name,
				            call_id,
				            agent_dbus_owner);

817
				for_each_secret (NM_CONNECTION (self), secrets, FALSE, clear_nonagent_secrets, NULL);
818 819 820
			} else if (agent_has_modify == FALSE) {
				/* Agent didn't successfully authenticate; clear system-owned secrets
				 * from the secrets the agent returned.
821
				 */
822
				nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) agent failed to authenticate but provided system secrets",
823
				            nm_connection_get_uuid (NM_CONNECTION (self)),
824 825 826
				            setting_name,
				            call_id);

827
				for_each_secret (NM_CONNECTION (self), secrets, FALSE, clear_nonagent_secrets, NULL);
828 829 830 831
			}
		}
	} else {
		nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) existing secrets returned",
832
		            nm_connection_get_uuid (NM_CONNECTION (self)),
833 834
		            setting_name,
		            call_id);
835 836
	}

837
	nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) secrets request completed",
838
	            nm_connection_get_uuid (NM_CONNECTION (self)),
839 840 841
	            setting_name,
	            call_id);

842 843 844
	/* If no user interaction was allowed, make sure that no "unsaved" secrets
	 * came back.  Unsaved secrets by definition require user interaction.
	 */
845
	if (flags == NM_SECRET_AGENT_GET_SECRETS_FLAG_NONE)
846
		for_each_secret (NM_CONNECTION (self), secrets, TRUE, clear_unsaved_secrets, NULL);
847

848 849
	/* Update the connection with our existing secrets from backing storage */
	nm_connection_clear_secrets (NM_CONNECTION (self));
850 851 852 853
	dict = nm_connection_to_dbus (priv->system_secrets, NM_CONNECTION_SERIALIZE_ONLY_SECRETS);
	if (!dict || nm_connection_update_secrets (NM_CONNECTION (self), setting_name, dict, &local)) {
		GVariant *secrets_dict;

854 855 856 857 858
		/* Update the connection with the agent's secrets; by this point if any
		 * system-owned secrets exist in 'secrets' the agent that provided them
		 * will have been authenticated, so those secrets can replace the existing
		 * system secrets.
		 */
Dan Winship's avatar
Dan Winship committed
859
		secrets_dict = nm_utils_connection_hash_to_dict (secrets);
860
		if (nm_connection_update_secrets (NM_CONNECTION (self), setting_name, secrets_dict, &local)) {
861 862 863
			/* Now that all secrets are updated, copy and cache new secrets, 
			 * then save them to backing storage.
			 */
864 865
			update_system_secrets_cache (self);
			update_agent_secrets_cache (self, NULL);
866

867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
			/* Only save secrets to backing storage if the agent returned any
			 * new system secrets.  If it didn't, then the secrets are agent-
			 * owned and there's no point to writing out the connection when
			 * nothing has changed, since agent-owned secrets don't get saved here.
			 */
			if (agent_had_system) {
				nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) saving new secrets to backing storage",
						    nm_connection_get_uuid (NM_CONNECTION (self)),
						    setting_name,
						    call_id);

				nm_settings_connection_commit_changes (self, new_secrets_commit_cb, NULL);
			} else {
				nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) new agent secrets processed",
						    nm_connection_get_uuid (NM_CONNECTION (self)),
						    setting_name,
						    call_id);
			}
885 886
		} else {
			nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) failed to update with agent secrets: (%d) %s",
887
			            nm_connection_get_uuid (NM_CONNECTION (self)),
888 889
			            setting_name,
			            call_id,
890 891
			            local ? local->code : -1,
			            (local && local->message) ? local->message : "(unknown)");
892
		}
893
		g_variant_unref (secrets_dict);
894 895
	} else {
		nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) failed to update with existing secrets: (%d) %s",
896
		            nm_connection_get_uuid (NM_CONNECTION (self)),
897 898
		            setting_name,
		            call_id,
899 900
		            local ? local->code : -1,
		            (local && local->message) ? local->message : "(unknown)");
901 902
	}

903
	callback (self, call_id, agent_username, setting_name, local, callback_data);
904
	g_clear_error (&local);
905 906
	if (dict)
		g_variant_unref (dict);
907 908
}

909
/**
910 911
 * nm_settings_connection_get_secrets:
 * @connection: the #NMSettingsConnection
912
 * @subject: the #NMAuthSubject originating the request
913
 * @setting_name: the setting to return secrets for
914
 * @flags: flags to modify the secrets request
915 916
 * @hints: key names in @setting_name for which secrets may be required, or some
 *   other information about the request
917 918
 * @callback: the function to call with returned secrets
 * @callback_data: user data to pass to @callback
919
 *
920 921
 * Retrieves secrets from persistent storage and queries any secret agents for
 * additional secrets.
922
 *
923
 * Returns: a call ID which may be used to cancel the ongoing secrets request
924
 **/
925 926
guint32 
nm_settings_connection_get_secrets (NMSettingsConnection *self,
927
                                    NMAuthSubject *subject,
928
                                    const char *setting_name,
929
                                    NMSecretAgentGetSecretsFlags flags,
930
                                    const char **hints,
931 932
                                    NMSettingsConnectionSecretsFunc callback,
                                    gpointer callback_data,
933
                                    GError **error)
934
{
935
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
936 937
	GVariant *existing_secrets;
	GHashTable *existing_secrets_hash;
938
	guint32 call_id = 0;
939
	char *joined_hints = NULL;
940

941
	/* Use priv->secrets to work around the fact that nm_connection_clear_secrets()
942
	 * will clear secrets on this object's settings.
943
	 */
944
	if (!priv->system_secrets) {
945
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_FAILED,
946 947
		             "%s.%d - Internal error; secrets cache invalid.",
		             __FILE__, __LINE__);
948
		return 0;
949 950
	}

951 952
	/* Make sure the request actually requests something we can return */
	if (!nm_connection_get_setting_by_name (NM_CONNECTION (self), setting_name)) {
953
		g_set_error (error, NM_CONNECTION_ERROR, NM_CONNECTION_ERROR_SETTING_NOT_FOUND,
954 955
		             "%s.%d - Connection didn't have requested setting '%s'.",
		             __FILE__, __LINE__, setting_name);
956
		return 0;
957 958
	}

959
	existing_secrets = nm_connection_to_dbus (priv->system_secrets, NM_CONNECTION_SERIALIZE_ONLY_SECRETS);
Dan Winship's avatar
Dan Winship committed
960
	existing_secrets_hash = nm_utils_connection_dict_to_hash (existing_secrets);
961 962
	call_id = nm_agent_manager_get_secrets (priv->agent_mgr,
	                                        NM_CONNECTION (self),
963
	                                        subject,
964
	                                        existing_secrets_hash,
965 966
	                                        setting_name,
	                                        flags,
967
	                                        hints,
968 969 970 971
	                                        agent_secrets_done_cb,
	                                        self,
	                                        callback,
	                                        callback_data);
972 973
	if (existing_secrets_hash)
		g_hash_table_unref (existing_secrets_hash);
974
	if (existing_secrets)
975
		g_variant_unref (existing_secrets);
976

977
	if (nm_logging_enabled (LOGL_DEBUG, LOGD_SETTINGS)) {
978 979 980 981 982 983 984 985 986 987
		if (hints)
			joined_hints = g_strjoinv (",", (char **) hints);
		nm_log_dbg (LOGD_SETTINGS, "(%s/%s:%u) secrets requested flags 0x%X hints '%s'",
		            nm_connection_get_uuid (NM_CONNECTION (self)),
		            setting_name,
		            call_id,
		            flags,
		            joined_hints ? joined_hints : "(none)");
		g_free (joined_hints);
	}
988

989 990 991 992 993 994 995 996
	return call_id;
}

void
nm_settings_connection_cancel_secrets (NMSettingsConnection *self,
                                       guint32 call_id)
{
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
997 998

	nm_log_dbg (LOGD_SETTINGS, "(%s:%u) secrets canceled",
999
	            nm_connection_get_uuid (NM_CONNECTION (self)),
1000
	            call_id);
1001 1002 1003

	priv->reqs = g_slist_remove (priv->reqs, GUINT_TO_POINTER (call_id));
	nm_agent_manager_cancel_secrets (priv->agent_mgr, call_id);
1004 1005
}

1006
/**** User authorization **************************************/
1007

1008 1009
typedef void (*AuthCallback) (NMSettingsConnection *connection, 
                              DBusGMethodInvocation *context,
1010
                              NMAuthSubject *subject,
1011 1012
                              GError *error,
                              gpointer data);
1013 1014

static void
1015 1016 1017 1018
pk_auth_cb (NMAuthChain *chain,
            GError *chain_error,
            DBusGMethodInvocation *context,
            gpointer user_data)
1019
{
1020 1021
	NMSettingsConnection *self = NM_SETTINGS_CONNECTION (user_data);
	NMSettingsConnectionPrivate *priv = NM_SETTINGS_CONNECTION_GET_PRIVATE (self);
1022
	GError *error = NULL;
1023
	NMAuthCallResult result;
1024 1025 1026
	const char *perm;
	AuthCallback callback;
	gpointer callback_data;
1027
	NMAuthSubject *subject;
1028

1029
	priv->pending_auths = g_slist_remove (priv->pending_auths, chain);
1030

1031 1032 1033 1034
	perm = nm_auth_chain_get_data (chain, "perm");
	g_assert (perm);
	result = nm_auth_chain_get_result (chain, perm);

1035
	/* If our NMSettingsConnection is already gone, do nothing */
1036 1037
	if (chain_error) {
		error = g_error_new (NM_SETTINGS_ERROR,
1038
		                     NM_SETTINGS_ERROR_FAILED,
1039 1040
		                     "Error checking authorization: %s",
		                     chain_error->message ? chain_error->message : "(unknown)");
1041 1042 1043 1044
	} else if (result != NM_AUTH_CALL_RESULT_YES) {
		error = g_error_new_literal (NM_SETTINGS_ERROR,
		                             NM_SETTINGS_ERROR_PERMISSION_DENIED,
		                             "Insufficient privileges.");
1045 1046
	}

1047 1048
	callback = nm_auth_chain_get_data (chain, "callback");
	callback_data = nm_auth_chain_get_data (chain, "callback-data");
1049 1050
	subject = nm_auth_chain_get_data (chain, "subject");
	callback (self, context, subject, error, callback_data);
1051

1052 1053
	g_clear_error (&error);
	nm_auth_chain_unref (chain);
1054 1055
}

1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
/**
 * _new_auth_subject:
 * @context: the D-Bus method invocation context
 * @error: on failure, a #GError
 *
 * Creates an NMAuthSubject for the caller.
 *
 * Returns: the #NMAuthSubject on success, or %NULL on failure and sets @error
 */
static NMAuthSubject *
_new_auth_subject (DBusGMethodInvocation *context, GError **error)
1067
{
1068
	NMAuthSubject *subject;
1069

1070
	subject = nm_auth_subject_new_unix_process_from_context (context);
1071
	if (!subject) {
1072 1073 1074
		g_set_error_literal (error,
		                     NM_SETTINGS_ERROR,
		                     NM_SETTINGS_ERROR_PERMISSION_DENIED,
1075
		                     "Unable to determine UID of request.");
1076 1077
	}

1078
	return subject;
1079
}
1080

1081 1082 1083
static void
auth_start (NMSettingsConnection *self,
            DBusGMethodInvocation *context,
1084
            NMAuthSubject *subject,
1085 1086 1087 1088 1089