nms-ifcfg-rh-reader.c 176 KB
Newer Older
1
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
2 3 4 5 6 7 8 9 10 11 12 13
/* 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.
 *
14 15 16
 * 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.
17
 *
18
 * Copyright 2008 - 2017 Red Hat, Inc.
19 20
 */

21
#include "nm-default.h"
22

Thomas Haller's avatar
Thomas Haller committed
23
#include "nms-ifcfg-rh-reader.h"
Thomas Haller's avatar
Thomas Haller committed
24

25 26 27 28 29
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
30
#include <sys/wait.h>
31
#include <sys/inotify.h>
32 33 34
#include <errno.h>
#include <sys/ioctl.h>
#include <unistd.h>
35

36
#include "nm-utils/nm-secret-utils.h"
37 38 39 40 41 42 43 44
#include "nm-connection.h"
#include "nm-dbus-interface.h"
#include "nm-setting-connection.h"
#include "nm-setting-ip4-config.h"
#include "nm-setting-vlan.h"
#include "nm-setting-ip6-config.h"
#include "nm-setting-wired.h"
#include "nm-setting-wireless.h"
45
#include "nm-setting-ethtool.h"
46 47 48 49 50 51 52
#include "nm-setting-8021x.h"
#include "nm-setting-bond.h"
#include "nm-setting-team.h"
#include "nm-setting-team-port.h"
#include "nm-setting-bridge.h"
#include "nm-setting-bridge-port.h"
#include "nm-setting-dcb.h"
53
#include "nm-setting-user.h"
Atul Anand's avatar
Atul Anand committed
54
#include "nm-setting-proxy.h"
55
#include "nm-setting-generic.h"
56
#include "nm-core-internal.h"
57
#include "nm-utils.h"
58
#include "nm-ethtool-utils.h"
59

60
#include "platform/nm-platform.h"
61
#include "NetworkManagerUtils.h"
62

Thomas Haller's avatar
Thomas Haller committed
63 64
#include "nms-ifcfg-rh-common.h"
#include "nms-ifcfg-rh-utils.h"
65
#include "shvar.h"
66

67 68 69 70 71 72
/*****************************************************************************/

#define _NMLOG_DOMAIN      LOGD_SETTINGS
#define _NMLOG_PREFIX_NAME "ifcfg-rh"
#define _NMLOG(level, ...) \
    G_STMT_START { \
73
        nm_log ((level), (_NMLOG_DOMAIN), NULL, NULL, \
74 75 76 77 78 79 80 81
                "%s" _NM_UTILS_MACRO_FIRST(__VA_ARGS__), \
                _NMLOG_PREFIX_NAME": " \
                _NM_UTILS_MACRO_REST(__VA_ARGS__)); \
    } G_STMT_END

#define PARSE_WARNING(...) _LOGW ("%s" _NM_UTILS_MACRO_FIRST(__VA_ARGS__), "    " _NM_UTILS_MACRO_REST(__VA_ARGS__))

/*****************************************************************************/
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
static char *
get_full_file_path (const char *ifcfg_path, const char *file_path)
{
	const char *base = file_path;
	char *p, *ret, *dirname;

	g_return_val_if_fail (ifcfg_path != NULL, NULL);
	g_return_val_if_fail (file_path != NULL, NULL);

	if (file_path[0] == '/')
		return g_strdup (file_path);

	p = strrchr (file_path, '/');
	if (p)
		base = p + 1;

	dirname = g_path_get_dirname (ifcfg_path);
	ret = g_build_path ("/", dirname, base, NULL);
	g_free (dirname);
	return ret;
}

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

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
static NMSettingSecretFlags
_secret_read_ifcfg_flags (shvarFile *ifcfg, const char *flags_key)
{
	NMSettingSecretFlags flags = NM_SETTING_SECRET_FLAG_NONE;
	gs_free char *val_free = NULL;
	const char *val;

	nm_assert (flags_key);
	nm_assert (g_str_has_suffix (flags_key, "_FLAGS"));

	val = svGetValueStr (ifcfg, flags_key, &val_free);
	if (val) {
		if (strstr (val, SECRET_FLAG_AGENT))
			flags |= NM_SETTING_SECRET_FLAG_AGENT_OWNED;
		if (strstr (val, SECRET_FLAG_NOT_SAVED))
			flags |= NM_SETTING_SECRET_FLAG_NOT_SAVED;
		if (strstr (val, SECRET_FLAG_NOT_REQUIRED))
			flags |= NM_SETTING_SECRET_FLAG_NOT_REQUIRED;
	}
	return flags;
}

static void
_secret_read_ifcfg (shvarFile *ifcfg,
                    shvarFile *keys_ifcfg,
                    const char *name,
                    char **value,
                    NMSettingSecretFlags *flags)
{
	char flags_key[250];

	nm_sprintf_buf (flags_key, "%s_FLAGS", name);

	*flags = _secret_read_ifcfg_flags (ifcfg, flags_key);

	if (*flags != NM_SETTING_SECRET_FLAG_NONE)
		*value = NULL;
	else {
		*value = svGetValue_cp (ifcfg, name);
		if (!*value && keys_ifcfg)
			*value = svGetValue_cp (keys_ifcfg, name);
	}
}

static void
_secret_set_from_ifcfg (gpointer setting,
                        shvarFile *ifcfg,
                        shvarFile *keys_ifcfg,
                        const char *ifcfg_key,
                        const char *property_name)
{
	nm_auto_free_secret char *secret = NULL;
	NMSettingSecretFlags flags;
	char flags_key[250];

	nm_assert (NM_IS_SETTING (setting));

	_secret_read_ifcfg (ifcfg, keys_ifcfg, ifcfg_key, &secret, &flags);

	g_object_set (setting,
	              property_name,
	              secret,
	              nm_sprintf_buf (flags_key, "%s-flags", property_name),
	              flags,
	              NULL);
}

static gboolean
_secret_password_raw_to_bytes (const char *ifcfg_key,
                               const char *password_raw,
                               GBytes **out_bytes,
                               GError **error)
{
	nm_auto_free_secret_buf NMSecretBuf *secret = NULL;
	gsize len;

	if (!password_raw) {
		NM_SET_OUT (out_bytes, NULL);
		return TRUE;
	}

	if (password_raw[0] == '0' && password_raw[1] == 'x')
		password_raw += 2;

	secret = nm_secret_buf_new (strlen (password_raw) / 2 + 3);
	if (!_nm_utils_str2bin_full (password_raw, FALSE, ":", secret->bin, secret->len, &len)) {
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
		             "Invalid hex password in %s",
		             ifcfg_key);
		return FALSE;
	}

	NM_SET_OUT (out_bytes, nm_secret_buf_to_gbytes_take (g_steal_pointer (&secret), len));
	return TRUE;
}

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

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
static GBytes *
_cert_get_cert_bytes (const char *ifcfg_path,
                      const char *value,
                      GError **error)
{
	gs_free char *path = NULL;

	if (g_str_has_prefix (value, "pkcs11:"))
		return _nm_setting_802_1x_cert_value_to_bytes (NM_SETTING_802_1X_CK_SCHEME_PKCS11, (guint8 *) value, -1, error);

	path = get_full_file_path (ifcfg_path, value);
	return _nm_setting_802_1x_cert_value_to_bytes (NM_SETTING_802_1X_CK_SCHEME_PATH, (guint8 *) path, -1, error);
}

static gboolean
_cert_get_cert (shvarFile *ifcfg,
                const char *ifcfg_key,
                GBytes **out_cert,
                NMSetting8021xCKScheme *out_scheme,
                GError **error)
{
	nm_auto_free_secret char *val_free = NULL;
	const char *val;
	gs_unref_bytes GBytes *cert = NULL;
	GError *local = NULL;
	NMSetting8021xCKScheme scheme;

	val = svGetValueStr (ifcfg, ifcfg_key, &val_free);
	if (!val) {
		NM_SET_OUT (out_cert, NULL);
		NM_SET_OUT (out_scheme, NM_SETTING_802_1X_CK_SCHEME_UNKNOWN);
		return TRUE;
	}

	cert = _cert_get_cert_bytes (svFileGetName (ifcfg), val, &local);
	if (!cert)
		goto err;

	scheme = _nm_setting_802_1x_cert_get_scheme (cert, &local);
	if (scheme == NM_SETTING_802_1X_CK_SCHEME_UNKNOWN)
		goto err;

	NM_SET_OUT (out_cert, g_steal_pointer (&cert));
	NM_SET_OUT (out_scheme, scheme);
	return TRUE;

err:
	g_set_error (error,
	             NM_SETTINGS_ERROR,
	             NM_SETTINGS_ERROR_INVALID_CONNECTION,
	             "invalid certificate %s: %s",
	             ifcfg_key,
	             local->message);
	g_error_free (local);
	return FALSE;
}

static gboolean
_cert_set_from_ifcfg (gpointer setting,
                      shvarFile *ifcfg,
                      const char *ifcfg_key,
                      const char *property_name,
                      GBytes **out_cert,
                      GError **error)
{
	gs_unref_bytes GBytes *cert = NULL;

	if (!_cert_get_cert (ifcfg,
	                     ifcfg_key,
	                     &cert,
	                     NULL,
	                     error))
		return FALSE;

	g_object_set (setting, property_name, cert, NULL);

	NM_SET_OUT (out_cert, g_steal_pointer (&cert));
	return TRUE;
}

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

287 288 289 290 291 292
static void
check_if_bond_slave (shvarFile *ifcfg,
                     NMSettingConnection *s_con)
{
	gs_free char *value = NULL;
	const char *v;
293
	const char *master;
294 295 296 297 298 299

	v = svGetValueStr (ifcfg, "MASTER_UUID", &value);
	if (!v)
		v = svGetValueStr (ifcfg, "MASTER", &value);

	if (v) {
300 301 302 303 304 305 306
		master = nm_setting_connection_get_master (s_con);
		if (master) {
			PARSE_WARNING ("Already configured as slave of %s. Ignoring MASTER{_UUID}=\"%s\"",
			               master, v);
			return;
		}

307 308 309 310 311 312 313 314 315 316 317
		g_object_set (s_con,
		              NM_SETTING_CONNECTION_MASTER, v,
		              NM_SETTING_CONNECTION_SLAVE_TYPE, NM_SETTING_BOND_SETTING_NAME,
		              NULL);
	}

	/* We should be checking for SLAVE=yes as well, but NM used to not set that,
	 * so for backward-compatibility, we don't check.
	 */
}

318
static void
319 320 321 322 323
check_if_team_slave (shvarFile *ifcfg,
                     NMSettingConnection *s_con)
{
	gs_free char *value = NULL;
	const char *v;
324
	const char *master;
325 326 327 328 329

	v = svGetValueStr (ifcfg, "TEAM_MASTER_UUID", &value);
	if (!v)
		v = svGetValueStr (ifcfg, "TEAM_MASTER", &value);
	if (!v)
330 331 332 333 334 335 336 337
		return;

	master = nm_setting_connection_get_master (s_con);
	if (master) {
		PARSE_WARNING ("Already configured as slave of %s. Ignoring TEAM_MASTER{_UUID}=\"%s\"",
		               master, v);
		return;
	}
338 339 340 341 342 343 344

	g_object_set (s_con,
	              NM_SETTING_CONNECTION_MASTER, v,
	              NM_SETTING_CONNECTION_SLAVE_TYPE, NM_SETTING_TEAM_SETTING_NAME,
	              NULL);
}

345
static char *
346 347 348 349
make_connection_name (shvarFile *ifcfg,
                      const char *ifcfg_name,
                      const char *suggested,
                      const char *prefix)
350
{
351
	char *full_name = NULL, *name;
352 353

	/* If the ifcfg file already has a NAME, always use that */
354
	name = svGetValueStr_cp (ifcfg, "NAME");
355
	if (name)
356 357 358 359
		return name;

	/* Otherwise construct a new NAME */
	if (!prefix)
360
		prefix = "System";
361 362 363 364 365

	/* For cosmetic reasons, if the suggested name is the same as
	 * the ifcfg files name, don't use it.  Mainly for wifi so that
	 * the SSID is shown in the connection ID instead of just "wlan0".
	 */
366 367 368 369
	if (suggested && strcmp (ifcfg_name, suggested))
		full_name = g_strdup_printf ("%s %s (%s)", prefix, suggested, ifcfg_name);
	else
		full_name = g_strdup_printf ("%s %s", prefix, ifcfg_name);
370 371 372 373

	return full_name;
}

374 375 376 377
static NMSetting *
make_connection_setting (const char *file,
                         shvarFile *ifcfg,
                         const char *type,
378 379
                         const char *suggested,
                         const char *prefix)
380 381
{
	NMSettingConnection *s_con;
382
	NMSettingConnectionLldp lldp;
383
	const char *ifcfg_name = NULL;
384 385 386 387 388
	char *new_id;
	const char *uuid;
	gs_free char *uuid_free = NULL;
	gs_free char *value = NULL;
	const char *v;
389
	gs_free char *stable_id = NULL;
390
	const char *const *iter;
391
	int vint64, i_val;
392

393
	ifcfg_name = utils_get_ifcfg_name (file, TRUE);
394 395 396 397
	if (!ifcfg_name)
		return NULL;

	s_con = NM_SETTING_CONNECTION (nm_setting_connection_new ());
398

399 400
	new_id = make_connection_name (ifcfg, ifcfg_name, suggested, prefix);
	g_object_set (s_con, NM_SETTING_CONNECTION_ID, new_id, NULL);
401
	g_free (new_id);
402

403
	/* Try for a UUID key before falling back to hashing the file name */
404 405 406 407 408
	uuid = svGetValueStr (ifcfg, "UUID", &uuid_free);
	if (!uuid) {
		uuid_free = nm_utils_uuid_generate_from_string (svFileGetName (ifcfg), -1, NM_UTILS_UUID_TYPE_LEGACY, NULL);
		uuid = uuid_free;
	}
409

410 411 412
	g_object_set (s_con,
	              NM_SETTING_CONNECTION_TYPE, type,
	              NM_SETTING_CONNECTION_UUID, uuid,
413
	              NM_SETTING_CONNECTION_STABLE_ID, svGetValue (ifcfg, "STABLE_ID", &stable_id),
414
	              NULL);
415

416 417
	v = svGetValueStr (ifcfg, "DEVICE", &value);
	if (v) {
418 419
		GError *error = NULL;

420
		if (nm_utils_is_valid_iface_name (v, &error)) {
421
			g_object_set (s_con,
422
			              NM_SETTING_CONNECTION_INTERFACE_NAME, v,
423
			              NULL);
424
		} else {
425
			PARSE_WARNING ("invalid DEVICE name '%s': %s", v, error->message);
426 427
			g_error_free (error);
		}
428 429
	}

430 431 432
	nm_clear_g_free (&value);
	v = svGetValueStr (ifcfg, "LLDP", &value);
	if (nm_streq0 (v, "rx"))
433 434
		lldp = NM_SETTING_CONNECTION_LLDP_ENABLE_RX;
	else
435
		lldp = svParseBoolean (v, NM_SETTING_CONNECTION_LLDP_DEFAULT);
436

437
	/* Missing ONBOOT is treated as "ONBOOT=true" by the old network service */
438 439
	g_object_set (s_con,
	              NM_SETTING_CONNECTION_AUTOCONNECT,
440
	              svGetValueBoolean (ifcfg, "ONBOOT", TRUE),
441
	              NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY,
442
	              (int) svGetValueInt64 (ifcfg, "AUTOCONNECT_PRIORITY", 10,
443 444 445
	                                      NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY_MIN,
	                                      NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY_MAX,
	                                      NM_SETTING_CONNECTION_AUTOCONNECT_PRIORITY_DEFAULT),
446
	              NM_SETTING_CONNECTION_AUTOCONNECT_RETRIES,
447
	              (int) svGetValueInt64 (ifcfg, "AUTOCONNECT_RETRIES", 10,
448
	                                      -1, G_MAXINT32, -1),
449 450 451
	              NM_SETTING_CONNECTION_MULTI_CONNECT,
	              (gint) svGetValueInt64 (ifcfg, "MULTI_CONNECT", 10,
	                                      G_MININT32, G_MAXINT32, NM_CONNECTION_MULTI_CONNECT_DEFAULT),
452
	              NM_SETTING_CONNECTION_AUTOCONNECT_SLAVES,
453
	              svGetValueBoolean (ifcfg, "AUTOCONNECT_SLAVES", NM_SETTING_CONNECTION_AUTOCONNECT_SLAVES_DEFAULT),
454
	              NM_SETTING_CONNECTION_LLDP, lldp,
Dan Williams's avatar
Dan Williams committed
455
	              NULL);
456

457 458 459 460
	nm_clear_g_free (&value);
	v = svGetValueStr (ifcfg, "USERS", &value);
	if (v) {
		gs_free const char **items = NULL;
461

462
		items = nm_utils_strsplit_set (v, " ", FALSE);
463
		for (iter = items; iter && *iter; iter++) {
464 465
			if (!nm_setting_connection_add_permission (s_con, "user", *iter, NULL))
				PARSE_WARNING ("invalid USERS item '%s'", *iter);
466 467 468
		}
	}

469 470 471
	nm_clear_g_free (&value);
	v = svGetValueStr (ifcfg, "ZONE", &value);
	g_object_set (s_con, NM_SETTING_CONNECTION_ZONE, v, NULL);
472

473 474 475 476
	nm_clear_g_free (&value);
	v = svGetValueStr (ifcfg, "SECONDARY_UUIDS", &value);
	if (v) {
		gs_free const char **items = NULL;
477

478
		items = nm_utils_strsplit_set (v, " \t", FALSE);
479
		for (iter = items; iter && *iter; iter++) {
480 481
			if (!nm_setting_connection_add_secondary (s_con, *iter))
				PARSE_WARNING ("secondary connection UUID '%s' already added", *iter);
482 483 484
		}
	}

485 486 487 488 489
	nm_clear_g_free (&value);
	v = svGetValueStr (ifcfg, "BRIDGE_UUID", &value);
	if (!v)
		v = svGetValueStr (ifcfg, "BRIDGE", &value);
	if (v) {
490
		const char *old_value;
491

492
		if ((old_value = nm_setting_connection_get_master (s_con))) {
493
			PARSE_WARNING ("Already configured as slave of %s. Ignoring BRIDGE=\"%s\"",
494
			               old_value, v);
495
		} else {
496
			g_object_set (s_con, NM_SETTING_CONNECTION_MASTER, v, NULL);
497 498
			g_object_set (s_con, NM_SETTING_CONNECTION_SLAVE_TYPE,
			              NM_SETTING_BRIDGE_SETTING_NAME, NULL);
499 500 501
		}
	}

502 503 504
	check_if_bond_slave (ifcfg, s_con);
	check_if_team_slave (ifcfg, s_con);

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521
	nm_clear_g_free (&value);
	v = svGetValueStr (ifcfg, "OVS_PORT_UUID", &value);
	if (!v)
		v = svGetValueStr (ifcfg, "OVS_PORT", &value);
	if (v) {
		const char *old_value;

		if ((old_value = nm_setting_connection_get_master (s_con))) {
			PARSE_WARNING ("Already configured as slave of %s. Ignoring OVS_PORT=\"%s\"",
			               old_value, v);
		} else {
			g_object_set (s_con, NM_SETTING_CONNECTION_MASTER, v, NULL);
			g_object_set (s_con, NM_SETTING_CONNECTION_SLAVE_TYPE,
			              NM_SETTING_OVS_PORT_SETTING_NAME, NULL);
		}
	}

522 523 524
	nm_clear_g_free (&value);
	v = svGetValueStr (ifcfg, "GATEWAY_PING_TIMEOUT", &value);
	if (v) {
525
		gint64 tmp;
526

527
		tmp = _nm_utils_ascii_str_to_int64 (v, 10, 0, G_MAXINT32 - 1, -1);
528 529 530 531 532
		if (tmp >= 0) {
			if (tmp > 600) {
				tmp = 600;
				PARSE_WARNING ("invalid GATEWAY_PING_TIMEOUT time");
			}
533
			g_object_set (s_con, NM_SETTING_CONNECTION_GATEWAY_PING_TIMEOUT, (guint) tmp, NULL);
534
		} else
535
			PARSE_WARNING ("invalid GATEWAY_PING_TIMEOUT time");
536 537
	}

538
	switch (svGetValueBoolean (ifcfg, "CONNECTION_METERED", -1)) {
539 540 541 542 543 544 545 546
	case TRUE:
		g_object_set (s_con, NM_SETTING_CONNECTION_METERED, NM_METERED_YES, NULL);
		break;
	case FALSE:
		g_object_set (s_con, NM_SETTING_CONNECTION_METERED, NM_METERED_NO, NULL);
		break;
	}

547
	vint64 = svGetValueInt64 (ifcfg, "AUTH_RETRIES", 10, -1, G_MAXINT32, -1);
548
	g_object_set (s_con, NM_SETTING_CONNECTION_AUTH_RETRIES, (int) vint64, NULL);
549

550
	i_val = NM_SETTING_CONNECTION_MDNS_DEFAULT;
551 552
	if (!svGetValueEnum (ifcfg, "MDNS",
	                     nm_setting_connection_mdns_get_type (),
553 554
	                     &i_val, NULL))
		PARSE_WARNING ("invalid MDNS setting");
555 556
	g_object_set (s_con, NM_SETTING_CONNECTION_MDNS, i_val, NULL);

557 558 559 560 561 562 563
	i_val = NM_SETTING_CONNECTION_LLMNR_DEFAULT;
	if (!svGetValueEnum (ifcfg, "LLMNR",
	                     nm_setting_connection_llmnr_get_type (),
	                     &i_val, NULL))
		PARSE_WARNING ("invalid LLMNR setting");
	g_object_set (s_con, NM_SETTING_CONNECTION_LLMNR, i_val, NULL);

564
	return NM_SETTING (s_con);
565 566
}

567
/* Returns TRUE on missing address or valid address */
568 569
static gboolean
read_ip4_address (shvarFile *ifcfg,
570
                  const char *tag,
571 572
                  gboolean *out_has_key,
                  guint32 *out_addr,
573
                  GError **error)
574
{
575 576 577 578 579 580 581 582
	gs_free char *value_to_free = NULL;
	const char *value;
	guint32 a;

	nm_assert (ifcfg);
	nm_assert (tag);
	nm_assert (!error || !*error);

583 584
	value = svGetValueStr (ifcfg, tag, &value_to_free);
	if (!value) {
585 586
		NM_SET_OUT (out_has_key, FALSE);
		NM_SET_OUT (out_addr, 0);
587
		return TRUE;
588
	}
589

590
	if (inet_pton (AF_INET, value, &a) != 1) {
591
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
592
		             "Invalid %s IP4 address '%s'", tag, value);
593
		return FALSE;
594
	}
595 596 597 598

	NM_SET_OUT (out_has_key, TRUE);
	NM_SET_OUT (out_addr, a);
	return TRUE;
599 600
}

601
static gboolean
602
is_any_ip4_address_defined (shvarFile *ifcfg, int *idx)
603
{
Beniamino Galvani's avatar
Beniamino Galvani committed
604
	int i, ignore, *ret_idx;
605

606
	ret_idx = idx ?: &ignore;
607 608

	for (i = -1; i <= 2; i++) {
609
		gs_free char *value = NULL;
610
		char tag[256];
611

612
		if (svGetValueStr (ifcfg, numbered_tag (tag, "IPADDR", i), &value)) {
613
			*ret_idx = i;
614 615 616
			return TRUE;
		}

617
		if (svGetValueStr (ifcfg, numbered_tag (tag, "PREFIX", i), &value)) {
618
			*ret_idx = i;
619 620 621
			return TRUE;
		}

622
		if (svGetValueStr (ifcfg, numbered_tag (tag, "NETMASK", i), &value)) {
623
			*ret_idx = i;
624 625 626 627 628 629
			return TRUE;
		}
	}
	return FALSE;
}

630 631
/* Returns TRUE on missing address or valid address */
static gboolean
632
read_full_ip4_address (shvarFile *ifcfg,
633
                       gint32 which,
634 635
                       NMIPAddress *base_addr,
                       NMIPAddress **out_address,
636
                       char **out_gateway,
637 638
                       GError **error)
{
639 640
	char tag[256];
	char prefix_tag[256];
641
	guint32 ipaddr;
642
	gs_free char *value = NULL;
643
	const char *v;
644
	int prefix = 0;
645 646 647
	gboolean has_key;
	guint32 a;
	char inet_buf[NM_UTILS_INET_ADDRSTRLEN];
648

649 650
	g_return_val_if_fail (which >= -1, FALSE);
	g_return_val_if_fail (ifcfg != NULL, FALSE);
651 652
	g_return_val_if_fail (out_address != NULL, FALSE);
	g_return_val_if_fail (*out_address == NULL, FALSE);
653
	g_return_val_if_fail (!error || !*error, FALSE);
654 655

	/* IP address */
656 657 658
	if (!read_ip4_address (ifcfg,
	                       numbered_tag (tag, "IPADDR", which),
	                       &has_key, &ipaddr, error))
659
		return FALSE;
660 661
	if (!has_key) {
		if (!base_addr)
662
			return TRUE;
663
		nm_ip_address_get_address_binary (base_addr, &ipaddr);
664
	}
665 666

	/* Gateway */
667
	if (out_gateway && !*out_gateway) {
668 669 670
		if (!read_ip4_address (ifcfg,
		                       numbered_tag (tag, "GATEWAY", which),
		                       &has_key, &a, error))
671
			return FALSE;
672 673
		if (has_key)
			*out_gateway = g_strdup (nm_utils_inet4_ntop (a, inet_buf));
674 675 676
	}

	/* Prefix */
677
	numbered_tag (prefix_tag, "PREFIX", which);
678 679 680
	v = svGetValueStr (ifcfg, prefix_tag, &value);
	if (v) {
		prefix = _nm_utils_ascii_str_to_int64 (v, 10, 0, 32, -1);
681
		if (prefix < 0) {
682
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
683
			             "Invalid IP4 prefix '%s'", v);
684
			return FALSE;
685
		}
686 687
	} else {
		/* Fall back to NETMASK if no PREFIX was specified */
688 689 690
		if (!read_ip4_address (ifcfg,
		                       numbered_tag (tag, "NETMASK", which),
		                       &has_key, &a, error))
691
			return FALSE;
692 693 694
		if (has_key)
			prefix = nm_utils_ip4_netmask_to_prefix (a);
		else {
695 696 697 698
			if (base_addr)
				prefix = nm_ip_address_get_prefix (base_addr);
			else {
				/* Try to autodetermine the prefix for the address' class */
699
				prefix = _nm_utils_ip4_get_default_prefix (ipaddr);
700
				PARSE_WARNING ("missing %s, assuming %s/%d", prefix_tag, nm_utils_inet4_ntop (ipaddr, inet_buf), prefix);
701
			}
702
		}
703 704
	}

705
	*out_address = nm_ip_address_new_binary (AF_INET, &ipaddr, prefix, error);
706
	if (*out_address)
707
		return TRUE;
708

709
	return FALSE;
710
}
711

712
/*****************************************************************************/
713 714

static gboolean
715
parse_route_line_is_comment (const char *line)
716
{
717 718 719 720 721
	/* we obtained the line from a legacy route file. Here we skip
	 * empty lines and comments.
	 *
	 * initscripts compares: "$line" =~ '^[[:space:]]*(\#.*)?$'
	 */
722
	while (nm_utils_is_separator (line[0]))
723 724 725 726 727
		line++;
	if (NM_IN_SET (line[0], '\0', '#'))
		return TRUE;
	return FALSE;
}
728

729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746
/*****************************************************************************/

typedef struct {
	const char *key;

	/* the element is not available in this case. */
	bool disabled:1;

	/* whether the element is to be ignored. Ignord is different from
	 * "disabled", because we still parse the option, but don't use it. */
	bool ignore:1;

	bool int_base_16:1;

	/* whether the command line option was found, and @v is
	 * initialized. */
	bool has:1;

747 748 749
	/* the type, one of PARSE_LINE_TYPE_* */
	char type;

750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767
	union {
		guint8 uint8;
		guint32 uint32;
		struct {
			guint32 uint32;
			bool lock:1;
		} uint32_with_lock;
		struct {
			NMIPAddr addr;
			guint8 plen;
			bool has_plen:1;
		} addr;
	} v;

} ParseLineInfo;

enum {
	/* route attributes */
768
	PARSE_LINE_ATTR_ROUTE_TABLE,
769 770 771
	PARSE_LINE_ATTR_ROUTE_SRC,
	PARSE_LINE_ATTR_ROUTE_FROM,
	PARSE_LINE_ATTR_ROUTE_TOS,
772
	PARSE_LINE_ATTR_ROUTE_ONLINK,
773 774 775 776 777 778 779 780 781 782 783
	PARSE_LINE_ATTR_ROUTE_WINDOW,
	PARSE_LINE_ATTR_ROUTE_CWND,
	PARSE_LINE_ATTR_ROUTE_INITCWND,
	PARSE_LINE_ATTR_ROUTE_INITRWND,
	PARSE_LINE_ATTR_ROUTE_MTU,

	/* iproute2 arguments that only matter when parsing the file. */
	PARSE_LINE_ATTR_ROUTE_TO,
	PARSE_LINE_ATTR_ROUTE_VIA,
	PARSE_LINE_ATTR_ROUTE_METRIC,

784
	/* iproute2 parameters that are well known and that we silently ignore. */
785 786 787 788 789 790 791 792 793
	PARSE_LINE_ATTR_ROUTE_DEV,
};

#define PARSE_LINE_TYPE_UINT8             '8'
#define PARSE_LINE_TYPE_UINT32            'u'
#define PARSE_LINE_TYPE_UINT32_WITH_LOCK  'l'
#define PARSE_LINE_TYPE_ADDR              'a'
#define PARSE_LINE_TYPE_ADDR_WITH_PREFIX  'p'
#define PARSE_LINE_TYPE_IFNAME            'i'
794
#define PARSE_LINE_TYPE_FLAG              'f'
795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812

/**
 * parse_route_line:
 * @line: the line to parse. This is either a line from the route-* or route6-* file,
 *   or the numbered OPTIONS setting.
 * @addr_family: the address family.
 * @options_route: (in-out): when line is from the OPTIONS setting, this is a pre-created
 *   route object that is completed with the settings from options. Otherwise,
 *   it shall point to %NULL and a new route is created and returned.
 * @out_route: (out): (transfer-full): (allow-none): the parsed %NMIPRoute instance.
 *   In case a @options_route is passed in, it returns the input route that was modified
 *   in-place. But the caller must unref the returned route in either case.
 * @error: the failure description.
 *
 * Parsing the route options line has two modes: one for the numbered OPTIONS
 * setting, and one for initscript's handle_ip_file(), which takes the lines
 * and passes them to `ip route add`. The modes are similar, but certain properties
 * are not allowed for OPTIONS.
luz.paz's avatar
luz.paz committed
813
 * The mode is differentiated by having an @options_route argument.
814 815 816 817 818 819 820 821 822 823 824 825
 *
 * Returns: returns a negative errno on failure. On success, it returns 0
 *   and @out_route.
 */
static int
parse_route_line (const char *line,
                  int addr_family,
                  NMIPRoute *options_route,
                  NMIPRoute **out_route,
                  GError **error)
{
	nm_auto_ip_route_unref NMIPRoute *route = NULL;
826 827
	gs_free const char **words_free = NULL;
	const char *const*words;
828 829 830 831 832 833
	const char *s;
	gsize i_words;
	guint i;
	char buf1[256];
	char buf2[256];
	ParseLineInfo infos[] = {
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
		[PARSE_LINE_ATTR_ROUTE_TABLE]     = { .key = NM_IP_ROUTE_ATTRIBUTE_TABLE,
		                                      .type = PARSE_LINE_TYPE_UINT32, },
		[PARSE_LINE_ATTR_ROUTE_SRC]       = { .key = NM_IP_ROUTE_ATTRIBUTE_SRC,
		                                      .type = PARSE_LINE_TYPE_ADDR, },
		[PARSE_LINE_ATTR_ROUTE_FROM]      = { .key = NM_IP_ROUTE_ATTRIBUTE_FROM,
		                                      .type = PARSE_LINE_TYPE_ADDR_WITH_PREFIX,
		                                      .disabled = (addr_family != AF_INET6), },
		[PARSE_LINE_ATTR_ROUTE_TOS]       = { .key = NM_IP_ROUTE_ATTRIBUTE_TOS,
		                                      .type = PARSE_LINE_TYPE_UINT8,
		                                      .int_base_16 = TRUE,
		                                      .ignore = (addr_family != AF_INET), },
		[PARSE_LINE_ATTR_ROUTE_ONLINK]    = { .key = NM_IP_ROUTE_ATTRIBUTE_ONLINK,
		                                      .type = PARSE_LINE_TYPE_FLAG,
		                                      .ignore = (addr_family != AF_INET), },
		[PARSE_LINE_ATTR_ROUTE_WINDOW]    = { .key = NM_IP_ROUTE_ATTRIBUTE_WINDOW,
		                                      .type = PARSE_LINE_TYPE_UINT32_WITH_LOCK, },
		[PARSE_LINE_ATTR_ROUTE_CWND]      = { .key = NM_IP_ROUTE_ATTRIBUTE_CWND,
		                                      .type = PARSE_LINE_TYPE_UINT32_WITH_LOCK, },
		[PARSE_LINE_ATTR_ROUTE_INITCWND]  = { .key = NM_IP_ROUTE_ATTRIBUTE_INITCWND,
		                                      .type = PARSE_LINE_TYPE_UINT32_WITH_LOCK, },
		[PARSE_LINE_ATTR_ROUTE_INITRWND]  = { .key = NM_IP_ROUTE_ATTRIBUTE_INITRWND,
		                                      .type = PARSE_LINE_TYPE_UINT32_WITH_LOCK, },
		[PARSE_LINE_ATTR_ROUTE_MTU]       = { .key = NM_IP_ROUTE_ATTRIBUTE_MTU,
		                                      .type = PARSE_LINE_TYPE_UINT32_WITH_LOCK, },

		[PARSE_LINE_ATTR_ROUTE_TO]        = { .key = "to",
		                                      .type = PARSE_LINE_TYPE_ADDR_WITH_PREFIX,
		                                      .disabled = (options_route != NULL), },
		[PARSE_LINE_ATTR_ROUTE_VIA]       = { .key = "via",
		                                      .type = PARSE_LINE_TYPE_ADDR,
		                                      .disabled = (options_route != NULL), },
		[PARSE_LINE_ATTR_ROUTE_METRIC]    = { .key = "metric",
		                                      .type = PARSE_LINE_TYPE_UINT32,
		                                      .disabled = (options_route != NULL), },

		[PARSE_LINE_ATTR_ROUTE_DEV]       = { .key = "dev",
		                                      .type = PARSE_LINE_TYPE_IFNAME,
		                                      .ignore = TRUE,
		                                      .disabled = (options_route != NULL), },
873 874 875
	};

	nm_assert (line);
876
	nm_assert_addr_family (addr_family);
877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
	nm_assert (!options_route || nm_ip_route_get_family (options_route) == addr_family);

	/* initscripts read the legacy route file line-by-line and
	 * use it as `ip route add $line`, thus doing split+glob.
	 * Splitting on IFS (which we consider '<space><tab><newline>')
	 * and globbing (which we obviously don't do).
	 *
	 * I think it's a mess, because it doesn't support escaping or
	 * quoting. In fact, it can only encode benign values.
	 *
	 * We also use the same form for the numbered OPTIONS
	 * variable. I think it's bad not to support any form of
	 * escaping. But do that for now.
	 *
	 * Maybe later we want to support some form of quotation here.
	 * Which of course, would be incompatible with initscripts.
	 */
894
	words_free = nm_utils_strsplit_set (line, " \t\n", FALSE);
895

896
	words = words_free ?: NM_PTRARRAY_EMPTY (const char *);
897

898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915
	for (i_words = 0; words[i_words]; ) {
		const gsize i_words0 = i_words;
		const char *const w = words[i_words0];
		ParseLineInfo *info;
		gboolean unqualified_addr = FALSE;

		for (i = 0; i < G_N_ELEMENTS (infos); i++) {
			info = &infos[i];

			if (info->disabled)
				continue;

			if (!nm_streq (w, info->key))
				continue;

			if (info->has) {
				/* iproute2 for most arguments allows specifying them multiple times.
				 * Let's not do that. */
916
				g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
917 918
				             "Duplicate option \"%s\"", w);
				return -EINVAL;
919 920
			}

921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
			info->has = TRUE;
			switch (info->type) {
			case PARSE_LINE_TYPE_UINT8:
				i_words++;
				goto parse_line_type_uint8;
			case PARSE_LINE_TYPE_UINT32:
				i_words++;
				goto parse_line_type_uint32;
			case PARSE_LINE_TYPE_UINT32_WITH_LOCK:
				i_words++;
				goto parse_line_type_uint32_with_lock;
			case PARSE_LINE_TYPE_ADDR:
				i_words++;
				goto parse_line_type_addr;
			case PARSE_LINE_TYPE_ADDR_WITH_PREFIX:
				i_words++;
				goto parse_line_type_addr_with_prefix;
			case PARSE_LINE_TYPE_IFNAME:
				i_words++;
				goto parse_line_type_ifname;
941 942 943
			case PARSE_LINE_TYPE_FLAG:
				i_words++;
				goto next;
944 945
			default:
				nm_assert_not_reached ();
946 947 948
			}
		}

949 950 951 952 953 954 955
		/* "to" is also accepted unqualified... (once) */
		info = &infos[PARSE_LINE_ATTR_ROUTE_TO];
		if (!info->has && !info->disabled) {
			unqualified_addr = TRUE;
			info->has = TRUE;
			goto parse_line_type_addr;
		}
956

957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
		             "Unrecognized argument (\"to\" is duplicate or \"%s\" is garbage)", w);
		return -EINVAL;

parse_line_type_uint8:
		s = words[i_words];
		if (!s)
			goto err_word_missing_argument;
		info->v.uint8 = _nm_utils_ascii_str_to_int64 (s,
		                                              info->int_base_16 ? 16 : 10,
		                                              0,
		                                              G_MAXUINT8,
		                                              0);;
		if (errno) {
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
			             "Argument for \"%s\" is not a valid number", w);
			return -EINVAL;
		}
		i_words++;
		goto next;

parse_line_type_uint32:
parse_line_type_uint32_with_lock:
		s = words[i_words];
		if (!s)
			goto err_word_missing_argument;
		if (info->type == PARSE_LINE_TYPE_UINT32_WITH_LOCK) {
			if (nm_streq (s, "lock")) {
				s = words[++i_words];
				if (!s)
					goto err_word_missing_argument;
				info->v.uint32_with_lock.lock = TRUE;
			} else
				info->v.uint32_with_lock.lock = FALSE;
			info->v.uint32_with_lock.uint32 = _nm_utils_ascii_str_to_int64 (s, 10, 0, G_MAXUINT32, 0);;
		} else {
			info->v.uint32 = _nm_utils_ascii_str_to_int64 (s, 10, 0, G_MAXUINT32, 0);
		}
		if (errno) {
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
			             "Argument for \"%s\" is not a valid number", w);
			return -EINVAL;
		}
		i_words++;
		goto next;

parse_line_type_ifname:
		s = words[i_words];
		if (!s)
			goto err_word_missing_argument;
		i_words++;
		goto next;

parse_line_type_addr:
parse_line_type_addr_with_prefix:
		s = words[i_words];
		if (!s)
			goto err_word_missing_argument;
		{
			int prefix = -1;

			if (info->type == PARSE_LINE_TYPE_ADDR) {
1019 1020
				if (!nm_utils_parse_inaddr_bin (addr_family,
				                                s,
1021
				                                NULL,
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046
				                                &info->v.addr.addr)) {
					if (   info == &infos[PARSE_LINE_ATTR_ROUTE_VIA]
					    && nm_streq (s, "(null)")) {
						/* Due to a bug, would older versions of NM write "via (null)"
						 * (rh#1452648). Workaround that, and accept it.*/
						memset (&info->v.addr.addr, 0, sizeof (info->v.addr.addr));
					} else {
						if (unqualified_addr) {
							g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
							             "Unrecognized argument (inet prefix is expected rather then \"%s\")", w);
							return -EINVAL;
						} else {
							g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
							             "Argument for \"%s\" is not a valid IPv%c address", w,
							             addr_family == AF_INET ? '4' : '6');
						}
						return -EINVAL;
					}
				}
			} else {
				nm_assert (info->type == PARSE_LINE_TYPE_ADDR_WITH_PREFIX);
				if (   info == &infos[PARSE_LINE_ATTR_ROUTE_TO]
				    && nm_streq (s, "default")) {
					memset (&info->v.addr.addr, 0, sizeof (info->v.addr.addr));
					prefix = 0;
1047 1048
				} else if (!nm_utils_parse_inaddr_prefix_bin (addr_family,
				                                              s,
1049
				                                              NULL,
1050 1051
				                                              &info->v.addr.addr,
				                                              &prefix)) {
1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
					g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
					             "Argument for \"%s\" is not ADDR/PREFIX format", w);
					return -EINVAL;
				}
			}
			if (prefix == -1)
				info->v.addr.has_plen = FALSE;
			else {
				info->v.addr.has_plen = TRUE;
				info->v.addr.plen = prefix;
1062
			}
1063
		}
1064 1065 1066 1067 1068 1069 1070 1071 1072
		i_words++;
		goto next;

err_word_missing_argument:
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
		             "Missing argument for \"%s\"", w);
		return -EINVAL;
next:
		;
1073 1074
	}

1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
	if (options_route) {
		route = options_route;
		nm_ip_route_ref (route);
	} else {
		ParseLineInfo *info_to = &infos[PARSE_LINE_ATTR_ROUTE_TO];
		ParseLineInfo *info_via = &infos[PARSE_LINE_ATTR_ROUTE_VIA];
		ParseLineInfo *info_metric = &infos[PARSE_LINE_ATTR_ROUTE_METRIC];
		guint prefix;

		if (!info_to->has) {
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
			             "Missing destination prefix");
			return -EINVAL;
1088 1089
		}

1090 1091 1092 1093 1094 1095 1096 1097
		prefix =   info_to->v.addr.has_plen
		         ? info_to->v.addr.plen
		         : (addr_family == AF_INET ? 32 : 128);

		if (   (   (addr_family == AF_INET  && !info_to->v.addr.addr.addr4)
		        || (addr_family == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED (&info_to->v.addr.addr.addr6)))
		    && prefix == 0) {
			/* we ignore default routes by returning -ERANGE. */
1098
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
1099