nms-ifcfg-rh-reader.c 177 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"
24

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

34
#include "nm-utils/nm-secret-utils.h"
35 36 37 38 39 40 41 42
#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"
43
#include "nm-setting-ethtool.h"
44 45 46 47 48 49 50
#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"
51
#include "nm-setting-user.h"
52
#include "nm-setting-proxy.h"
53
#include "nm-setting-generic.h"
54
#include "nm-core-internal.h"
55
#include "nm-utils.h"
56
#include "nm-ethtool-utils.h"
57

58
#include "platform/nm-platform.h"
59
#include "NetworkManagerUtils.h"
60

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

65 66 67 68 69 70
/*****************************************************************************/

#define _NMLOG_DOMAIN      LOGD_SETTINGS
#define _NMLOG_PREFIX_NAME "ifcfg-rh"
#define _NMLOG(level, ...) \
    G_STMT_START { \
71
        nm_log ((level), (_NMLOG_DOMAIN), NULL, NULL, \
72 73 74 75 76 77 78 79
                "%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__))

/*****************************************************************************/
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
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;
}

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

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
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);
190
	if (!nm_utils_hexstr2bin_full (password_raw, FALSE, FALSE, ":", 0, secret->bin, secret->len, &len)) {
191 192 193 194 195 196 197 198 199 200 201 202
		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;
}

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

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
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;
}

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

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

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

	if (v) {
298 299 300 301 302 303 304
		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;
		}

305 306 307 308 309 310 311 312 313 314 315
		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.
	 */
}

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

	v = svGetValueStr (ifcfg, "TEAM_MASTER_UUID", &value);
	if (!v)
		v = svGetValueStr (ifcfg, "TEAM_MASTER", &value);
	if (!v)
328 329 330 331 332 333 334 335
		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;
	}
336 337 338 339 340 341 342

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

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

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

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

	/* 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".
	 */
364 365 366 367
	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);
368 369 370 371

	return full_name;
}

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

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

	s_con = NM_SETTING_CONNECTION (nm_setting_connection_new ());
396

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

401
	/* Try for a UUID key before falling back to hashing the file name */
402 403 404 405 406
	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;
	}
407

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

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

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

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

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

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

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

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

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

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

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

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

500 501 502
	check_if_bond_slave (ifcfg, s_con);
	check_if_team_slave (ifcfg, s_con);

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519
	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);
		}
	}

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

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

536
	switch (svGetValueBoolean (ifcfg, "CONNECTION_METERED", -1)) {
537 538 539 540 541 542 543 544
	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;
	}

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

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

555 556 557 558 559 560 561
	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);

562
	return NM_SETTING (s_con);
563 564
}

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

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

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

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

	NM_SET_OUT (out_has_key, TRUE);
	NM_SET_OUT (out_addr, a);
	return TRUE;
597 598
}

599
static gboolean
600
is_any_ip4_address_defined (shvarFile *ifcfg, int *idx)
601
{
602
	int i, ignore, *ret_idx;
603

604
	ret_idx = idx ?: &ignore;
605 606

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

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

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

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

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

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

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

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

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

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

707
	return FALSE;
708
}
709

710
/*****************************************************************************/
711 712

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

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

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;

745 746 747
	/* the type, one of PARSE_LINE_TYPE_* */
	char type;

748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
	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 */
766
	PARSE_LINE_ATTR_ROUTE_TABLE,
767 768 769
	PARSE_LINE_ATTR_ROUTE_SRC,
	PARSE_LINE_ATTR_ROUTE_FROM,
	PARSE_LINE_ATTR_ROUTE_TOS,
770
	PARSE_LINE_ATTR_ROUTE_ONLINK,
771 772 773 774 775 776 777 778 779 780 781
	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,

782
	/* iproute2 parameters that are well known and that we silently ignore. */
783 784 785 786 787 788 789 790 791
	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'
792
#define PARSE_LINE_TYPE_FLAG              'f'
793 794 795 796 797 798 799 800 801

/**
 * 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.
802
 * @out_route: (out) (transfer-full) (allow-none): the parsed %NMIPRoute instance.
803 804 805 806 807 808 809 810
 *   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
811
 * The mode is differentiated by having an @options_route argument.
812 813 814 815 816 817 818 819 820 821 822 823
 *
 * 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;
824 825
	gs_free const char **words_free = NULL;
	const char *const*words;
826 827 828 829 830 831
	const char *s;
	gsize i_words;
	guint i;
	char buf1[256];
	char buf2[256];
	ParseLineInfo infos[] = {
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
		[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), },
871 872 873
	};

	nm_assert (line);
874
	nm_assert_addr_family (addr_family);
875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
	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.
	 */
892
	words_free = nm_utils_strsplit_set (line, " \t\n", FALSE);
893

894
	words = words_free ?: NM_PTRARRAY_EMPTY (const char *);
895

896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
	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. */
914
				g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
915 916
				             "Duplicate option \"%s\"", w);
				return -EINVAL;
917 918
			}

919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
			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;
939 940 941
			case PARSE_LINE_TYPE_FLAG:
				i_words++;
				goto next;
942 943
			default:
				nm_assert_not_reached ();
944 945 946
			}
		}

947 948 949 950 951 952 953
		/* "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;
		}
954

955 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
		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) {
1017 1018
				if (!nm_utils_parse_inaddr_bin (addr_family,
				                                s,
1019
				                                NULL,
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044
				                                &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;
1045 1046
				} else if (!nm_utils_parse_inaddr_prefix_bin (addr_family,
				                                              s,
1047
				                                              NULL,
1048 1049
				                                              &info->v.addr.addr,
				                                              &prefix)) {
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
					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;
1060
			}
1061
		}
1062 1063 1064 1065 1066 1067 1068 1069 1070
		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:
		;
1071 1072
	}

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
	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;
1086 1087
		}

1088 1089 1090 1091 1092 1093 1094 1095
		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. */
1096
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
1097 1098
			             "Ignore manual default route");
			return -ERANGE;
1099 1100
		}

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111
		route = nm_ip_route_new_binary (addr_family,
		                                &info_to->v.addr.addr,
		                                prefix,
		                                info_via->has ? &info_via->v.addr.addr : NULL,
		                                info_metric->has ? (gint64) info_metric->v.uint32 : (gint64) -1,
		                                error);
		info_to->has = FALSE;
		info_via->has = FALSE;
		info_metric->has = FALSE;
		if (!route)
			return -EINVAL;
1112 1113
	}

1114 1115
	for (i = 0; i < G_N_ELEMENTS (infos); i++) {
		ParseLineInfo *info = &infos[i];
1116

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
		if (!info->has)
			continue;
		if (info->ignore || info->disabled)
			continue;
		switch (info->type) {
		case PARSE_LINE_TYPE_UINT8:
			nm_ip_route_set_attribute (route,
			                           info->key,
			                           g_variant_new_byte (info->v.uint8));
			break;
1127 1128 1129 1130 1131
		case PARSE_LINE_TYPE_UINT32:
			nm_ip_route_set_attribute (route,
			                           info->key,
			                           g_variant_new_uint32 (info->v.uint32));
			break;
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
		case PARSE_LINE_TYPE_UINT32_WITH_LOCK:
			if (info->v.uint32_with_lock.lock) {
				nm_ip_route_set_attribute (route,
				                           nm_sprintf_buf (buf1, "lock-%s", info->key),
				                           g_variant_new_boolean (TRUE));
			}
			nm_ip_route_set_attribute (route,
			                           info->key,
			                           g_variant_new_uint32 (info->v.uint32_with_lock.uint32));
			break;
		case PARSE_LINE_TYPE_ADDR:
		case PARSE_LINE_TYPE_ADDR_WITH_PREFIX:
			nm_ip_route_set_attribute (route,
			                           info->key,
			                           g_variant_new_printf ("%s%s",
			                                                 inet_ntop (addr_family, &info->v.addr.addr, buf1, sizeof (buf1)),
			                                                 info->v.addr.has_plen
			                                                    ? nm_sprintf_buf (buf2, "/%u", (unsigned) info->v.addr.plen)
			                                                    : ""));
			break;
1152
		case PARSE_LINE_TYPE_FLAG:
luz.paz's avatar
luz.paz committed
1153
			/* NOTE: the flag (for "onlink") only allows to explicitly set "TRUE".
1154 1155 1156 1157 1158 1159 1160
			 * There is no way to express an explicit "FALSE" setting
			 * of this attribute, hence, the file format cannot encode
			 * that configuration. */
			nm_ip_route_set_attribute (route,
			                           info->key,
			                           g_variant_new_boolean (TRUE));
			break;
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
		default:
			nm_assert_not_reached ();
			break;
		}
	}

	nm_assert (_nm_ip_route_attribute_validate_all (route));

	NM_SET_OUT (out_route, g_steal_pointer (&route));
	return 0;
1171 1172
}

1173 1174
/* Returns TRUE on missing route or valid route */
static gboolean
1175 1176
read_one_ip4_route (shvarFile *ifcfg,
                    guint32 which,
1177
                    NMIPRoute **out_route,
1178 1179
                    GError **error)
{
1180 1181
	char tag[256];
	char netmask_tag[256];
1182 1183 1184 1185
	guint32 dest;
	guint32 next_hop;
	guint32 netmask;
	gboolean has_key;
1186
	const char *v;
1187
	gs_free char *value = NULL;
1188
	gint64 prefix, metric;
1189
	char inet_buf[NM_UTILS_INET_ADDRSTRLEN];
1190

1191
	g_return_val_if_fail (ifcfg != NULL, FALSE);
1192
	g_return_val_if_fail (out_route && !*out_route, FALSE);
1193
	g_return_val_if_fail (!error || !*error, FALSE);
1194 1195

	/* Destination */
1196 1197 1198
	if (!read_ip4_address (ifcfg,
	                       numbered_tag (tag, "ADDRESS", which),
	                       &has_key, &dest, error))
1199
		return FALSE;
1200 1201 1202 1203
	if (!has_key) {
		/* missing route = success */
		*out_route = NULL;
		return TRUE;
1204 1205 1206
	}

	/* Next hop */
1207 1208 1209
	if (!read_ip4_address (ifcfg,
	                       numbered_tag (tag, "GATEWAY", which),
	                       NULL, &next_hop, error))
1210
		return FALSE;
1211
	/* We don't make distinction between missing GATEWAY IP and 0.0.0.0 */
1212 1213

	/* Prefix */
1214 1215 1216
	if (!read_ip4_address (ifcfg,
	                       numbered_tag (netmask_tag, "NETMASK", which),
	                       &has_key, &netmask, error))
1217
		return FALSE;
1218
	if (has_key) {
1219
		prefix = nm_utils_ip4_netmask_to_prefix (netmask);
1220
		if (prefix == 0 || netmask != _nm_utils_ip4_prefix_to_netmask (prefix)) {
1221
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
1222
			             "Invalid IP4 netmask '%s' \"%s\"", netmask_tag, nm_utils_inet4_ntop (netmask, inet_buf));
1223
			return FALSE;
1224 1225
		}
	} else {
1226
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
1227
		             "Missing IP4 route element '%s'", netmask_tag);
1228
		return FALSE;
1229 1230 1231
	}

	/* Metric */
1232
	nm_clear_g_free (&value);
1233 1234 1235
	v = svGetValueStr (ifcfg, numbered_tag (tag, "METRIC", which), &value);
	if (v) {
		metric = _nm_utils_ascii_str_to_int64 (v, 10, 0, G_MAXUINT32, -1);
1236
		if (metric < 0) {
1237
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
1238
			             "Invalid IP4 route metric '%s'", v);
1239
			return FALSE;
1240
		}
1241
	} else
1242
		metric = -1;
1243

1244
	*out_route = nm_ip_route_new_binary (AF_INET, &dest, prefix, &next_hop, metric, error);
1245 1246
	if (!*out_route)
		return FALSE;
1247

1248 1249
	/* Options */
	nm_clear_g_free (&value);
1250 1251
	v = svGetValueStr (ifcfg, numbered_tag (tag, "OPTIONS", which), &value);
	if (v) {
1252
		if (parse_route_line (v, AF_INET, *out_route, NULL, error) < 0) {
1253 1254 1255 1256 1257 1258
			g_clear_pointer (out_route, nm_ip_route_unref);
			return FALSE;
		}
	}

	return TRUE;
1259 1260 1261
}

static gboolean
1262 1263 1264 1265
read_route_file (int addr_family,
                 const char *filename,
                 NMSettingIPConfig *s_ip,
                 GError **error)
1266
{
1267
	gs_free char *contents = NULL;
1268
	char *contents_rest = NULL;
1269
	const char *line;
1270
	gsize len = 0;
1271
	gsize line_num;
1272

1273 1274 1275
	g_return_val_if_fail (filename, FALSE);
	g_return_val_if_fail (   (addr_family == AF_INET  && NM_IS_SETTING_IP4_CONFIG (s_ip))
	                      || (addr_family == AF_INET6 && NM_IS_SETTING_IP6_CONFIG (s_ip)), FALSE);
1276
	g_return_val_if_fail (!error || !*error, FALSE);
1277

1278 1279
	if (   !g_file_get_contents (filename, &contents, &len, NULL)
	    || !len) {
1280
		return TRUE;  /* missing/empty = success */
1281 1282
	}

1283 1284 1285 1286 1287 1288 1289
	line_num = 0;
	for (line = strtok_r (contents, "\n", &contents_rest);
	     line;
	     line = strtok_r (NULL, "\n", &contents_rest)) {
		nm_auto_ip_route_unref NMIPRoute *route = NULL;
		gs_free_error GError *local = NULL;
		int e;
1290

1291 1292 1293
		line_num++;

		if (parse_route_line_is_comment (line))
1294
			continue;
1295

1296
		e = parse_route_line (line, addr_family, NULL, &route, &local);
1297

1298 1299 1300 1301 1302 1303 1304
		if (e < 0) {
			if (e == -ERANGE)
				PARSE_WARNING ("ignoring manual default route: '%s' (%s)", line, filename);
			else {
				/* we accept all unrecognized lines, because otherwise we would reject the
				 * entire connection. */
				PARSE_WARNING ("ignoring invalid route at \"%s\" (%s:%lu): %s", line, filename, (long unsigned) line_num, local->message);
1305
			}
1306
			continue;
1307 1308
		}

1309 1310
		if (!nm_setting_ip_config_add_route (s_ip, route))
			PARSE_WARNING ("duplicate IPv%c route", addr_family == AF_INET ? '4' : '6');
1311 1312
	}

1313
	return TRUE;
1314 1315
}

1316
static void
1317
parse_dns_options (NMSettingIPConfig *ip_config, const char *value)
1318
{
1319 1320
	gs_free const char **options = NULL;
	const char *const *item;
1321 1322 1323 1324 1325 1326

	g_return_if_fail (ip_config);

	if (!value)
		return;

1327 1328 1329
	if (!nm_setting_ip_config_has_dns_options (ip_config))
		nm_setting_ip_config_clear_dns_options (ip_config, TRUE);

1330
	options = nm_utils_strsplit_set (value, " ", FALSE);
1331 1332
	if (options) {
		for (item = options; *item; item++) {
1333 1334
			if (!nm_setting_ip_config_add_dns_option (ip_config, *item))
				PARSE_WARNING ("can't add DNS option '%s'", *item);
1335 1336 1337 1338
		}
	}
}

1339
static gboolean
1340 1341 1342
parse_full_ip6_address (shvarFile *ifcfg,
                        const char *addr_str,
                        int i,
1343
                        NMIPAddress **out_address,
1344
                        GError **error)
1345 1346
{
	char **list;
1347
	char *ip_val, *prefix_val;
1348
	int prefix;
1349 1350
	gboolean success = FALSE;

1351 1352 1353
	g_return_val_if_fail (addr_str != NULL, FALSE);
	g_return_val_if_fail (out_address != NULL, FALSE);
	g_return_val_if_fail (*out_address == NULL, FALSE);
1354
	g_return_val_if_fail (!error || !*error, FALSE);
1355

1356
	/* Split the address and prefix */
1357 1358
	list = g_strsplit_set (addr_str, "/", 2);
	if (g_strv_length (list) < 1) {
1359
		g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
1360 1361 1362 1363
		             "Invalid IP6 address '%s'", addr_str);
		goto error;
	}

1364
	ip_val = list[0];
1365

1366
	prefix_val = list[1];
1367
	if (prefix_val) {
1368 1369
		prefix = _nm_utils_ascii_str_to_int64 (prefix_val, 10, 0, 128, -1);
		if (prefix < 0) {
1370
			g_set_error (error, NM_SETTINGS_ERROR, NM_SETTINGS_ERROR_INVALID_CONNECTION,
1371
			             "Invalid IP6 prefix '%s'", prefix_val);
1372 1373 1374 1375
			goto error;
		}
	} else {
		/* Missing prefix is treated as prefix of 64 */
1376
		prefix = 64;
1377 1378
	}

1379
	*out_address = nm_ip_address_new (AF_INET6, ip_val, prefix, error);
1380 1381
	if (*out_address)
		success = TRUE;
1382

1383
error:
1384
	g_strfreev (list);
1385
	return success;
1386 1387
}

1388
static NMSetting *
1389
make_user_setting (shvarFile *ifcfg)
1390 1391 1392 1393 1394 1395 1396 1397
{
	gboolean has_user_data = FALSE;
	gs_unref_object NMSettingUser *s_user = NULL;
	gs_unref_hashtable GHashTable *keys = NULL;
	GHashTableIter iter;
	const char *key;
	nm_auto_free_gstring GString *str = NULL;

1398
	keys = svGetKeys (ifcfg, SV_KEY_TYPE_USER);
1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
	if (!keys)
		return NULL;

	g_hash_table_iter_init (&iter, keys);
	while (g_hash_table_iter_next (&iter, (gpointer *) &key, NULL)) {
		const char *value;
		gs_free char *value_to_free = NULL;

		value = svGetValue (ifcfg, key, &value_to_free);

		if (!value)
			continue;

		if (!str)
			str = g_string_sized_new (100);
		else
			g_string_set_size (str, 0);

		if (!nms_ifcfg_rh_utils_user_key_decode (key + NM_STRLEN ("NM_USER_"), str))
			continue;

		if (!s_user)
			s_user = NM_SETTING_USER (nm_setting_user_new ());

		if (nm_setting_user_set_data (s_user, str->str,
		                              value, NULL))
			has_user_data = TRUE;
	}

1428 1429
	return   has_user_data
	       ? NM_SETTING (g_steal_pointer (&s_user))
1430 1431 1432
	       : NULL;
}

1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
static NMSetting *
make_match_setting (shvarFile *ifcfg)
{
	NMSettingMatch *s_match = NULL;
	gs_free const char **strv = NULL;
	gs_free char *value = NULL;
	const char *v;
	gsize i;

	v = svGetValueStr (ifcfg, "MATCH_INTERFACE_NAME", &value);
	if (!v)
		return NULL;

	strv = nm_utils_strsplit_set (v, " \t", TRUE);
	if (strv) {
		for (i = 0; strv[i]; i++) {
			if (!s_match)
				s_match = (NMSettingMatch *) nm_setting_match_new ();
			nm_setting_match_add_interface_name (s_match,
			                                     _nm_utils_unescape_spaces ((char *) strv[i]));
		}
	}

	return (NMSetting *) s_match;
}

1459
static NMSetting *
1460
make_proxy_setting (shvarFile *ifcfg)
1461 1462
{
	NMSettingProxy *s_proxy = NULL;
1463 1464
	gs_free char *value = NULL;
	const char