nm-default-route-manager.c 33.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* NetworkManager -- Network link manager
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Copyright (C) 2014 Red Hat, Inc.
 */


#include "nm-default-route-manager.h"

#include "config.h"

#include "string.h"

#include "nm-logging.h"
#include "nm-device.h"
30
#include "nm-vpn-connection.h"
31
#include "nm-platform.h"
32
#include "nm-manager.h"
33 34
#include "nm-ip4-config.h"
#include "nm-ip6-config.h"
35
#include "nm-activation-request.h"
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76

typedef struct {
	GPtrArray *entries_ip4;
	GPtrArray *entries_ip6;
} NMDefaultRouteManagerPrivate;

#define NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), NM_TYPE_DEFAULT_ROUTE_MANAGER, NMDefaultRouteManagerPrivate))

G_DEFINE_TYPE (NMDefaultRouteManager, nm_default_route_manager, G_TYPE_OBJECT)

static NMDefaultRouteManager *_instance;

#define _LOG(level, addr_family, ...) \
    G_STMT_START { \
        int __addr_family = (addr_family); \
        guint64 __domain = __addr_family == AF_INET ? LOGD_IP4 : LOGD_IP6; \
        \
        if (nm_logging_enabled ((level), (__domain))) { \
            char __ch = __addr_family == AF_INET ? '4' : '6'; \
            char __prefix[30] = "default-route"; \
            \
            if ((self) != _instance) \
                g_snprintf (__prefix, sizeof (__prefix), "default-route%c[%p]", __ch, (self)); \
            else \
                __prefix[STRLEN ("default-route")] = __ch; \
            nm_log ((level), (__domain), \
                    "%s: " _NM_UTILS_MACRO_FIRST(__VA_ARGS__), \
                    __prefix _NM_UTILS_MACRO_REST(__VA_ARGS__)); \
        } \
    } G_STMT_END

#define _LOGD(addr_family, ...)      _LOG (LOGL_DEBUG, addr_family, __VA_ARGS__)
#define _LOGI(addr_family, ...)      _LOG (LOGL_INFO , addr_family, __VA_ARGS__)
#define _LOGW(addr_family, ...)      _LOG (LOGL_WARN , addr_family, __VA_ARGS__)
#define _LOGE(addr_family, ...)      _LOG (LOGL_ERR  , addr_family, __VA_ARGS__)

#define LOG_ENTRY_FMT  "entry[%u/%s:%p:%s]"
#define LOG_ENTRY_ARGS(entry_idx, entry) \
		entry_idx, \
		NM_IS_DEVICE (entry->source.pointer) ? "dev" : "vpn", \
		entry->source.pointer, \
77
		NM_IS_DEVICE (entry->source.pointer) ? nm_device_get_iface (entry->source.device) : nm_vpn_connection_get_connection_id (entry->source.vpn)
78 79 80 81 82 83 84 85

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

typedef struct {
	union {
		void *pointer;
		GObject *object;
		NMDevice *device;
86
		NMVpnConnection *vpn;
87 88 89 90 91 92 93
	} source;
	union {
		NMPlatformIPRoute route;
		NMPlatformIP4Route route4;
		NMPlatformIP6Route route6;
	};
	gboolean synced; /* if true, we synced the entry to platform. We don't sync assumed devices */
94 95 96 97 98 99

	/* it makes sense to order sources based on their priority, without
	 * actually adding a default route. This is useful to decide which
	 * DNS server to prefer. never_default entries are not synced to platform. */
	gboolean never_default;

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
	guint32 effective_metric;
} Entry;

typedef struct {
	int addr_family;
	GPtrArray *(*get_entries) (NMDefaultRouteManagerPrivate *priv);
	const char *(*platform_route_to_string) (const NMPlatformIPRoute *route);
	gboolean (*platform_route_delete_default) (int ifindex, guint32 metric);
	guint32 (*route_metric_normalize) (guint32 metric);
} VTableIP;

static const VTableIP vtable_ip4, vtable_ip6;

#define VTABLE_IS_IP4 (vtable->addr_family == AF_INET)

static void
_entry_free (Entry *entry)
{
	if (entry) {
		g_object_unref (entry->source.object);
		g_slice_free (Entry, entry);
	}
}

static Entry *
_entry_find_by_source (GPtrArray *entries, gpointer source, guint *out_idx)
{
	guint i;

	for (i = 0; i < entries->len; i++) {
		Entry *e = g_ptr_array_index (entries, i);

		if (e->source.pointer == source) {
			if (out_idx)
				*out_idx = i;
			return e;
		}
	}

	if (out_idx)
		*out_idx = G_MAXUINT;
	return NULL;
}

static void
_platform_route_sync_add (const VTableIP *vtable, NMDefaultRouteManager *self, guint32 metric)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	GPtrArray *entries = vtable->get_entries (priv);
	guint i;
	gboolean has_unsynced_entry = FALSE;
	Entry *entry = NULL;
	gboolean success;

	/* Find the entries for the given metric.
	 * The effective metric for synced entries is choosen in a way that it
	 * is unique (except for G_MAXUINT32, where a clash is not solvable). */
	for (i = 0; i < entries->len; i++) {
		Entry *e = g_ptr_array_index (entries, i);

160 161 162
		if (e->never_default)
			continue;

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
		if (e->effective_metric != metric)
			continue;

		if (e->synced) {
			g_assert (!entry || metric == G_MAXUINT32);
			entry = e;
		} else
			has_unsynced_entry = TRUE;
	}

	/* For synced entries, we expect that the metric is chosen uniquely. */
	g_assert (!entry || !has_unsynced_entry || metric == G_MAXUINT32);

	/* we only add the route, if we have an (to be synced) entry for it. */
	if (!entry)
		return;

	if (VTABLE_IS_IP4) {
		success = nm_platform_ip4_route_add (entry->route.ifindex,
		                                     entry->route.source,
		                                     0,
		                                     0,
		                                     entry->route4.gateway,
		                                     entry->effective_metric,
		                                     entry->route.mss);
	} else {
		success = nm_platform_ip6_route_add (entry->route.ifindex,
		                                     entry->route.source,
		                                     in6addr_any,
		                                     0,
		                                     entry->route6.gateway,
		                                     entry->effective_metric,
		                                     entry->route.mss);
	}
	if (!success)
		_LOGW (vtable->addr_family, "failed to add default route %s with effective metric %u", vtable->platform_route_to_string (&entry->route), (guint) entry->effective_metric);
}

static void
_platform_route_sync_flush (const VTableIP *vtable, NMDefaultRouteManager *self)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	GPtrArray *entries = vtable->get_entries (priv);
	GArray *routes;
	guint i;

	/* prune all other default routes from this device. */
	if (VTABLE_IS_IP4)
		routes = nm_platform_ip4_route_get_all (0, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT);
	else
		routes = nm_platform_ip6_route_get_all (0, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT);

	for (i = 0; i < routes->len; i++) {
		const NMPlatformIPRoute *route;
		gboolean has_ifindex_synced = FALSE;
		Entry *entry = NULL;

		if (VTABLE_IS_IP4)
			route = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, i);
		else
			route = (const NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, i);

		/* look at all entires and see if the route for this ifindex pair is
		 * a known entry. */
		for (i = 0; i < entries->len; i++) {
			Entry *e = g_ptr_array_index (entries, i);

230 231 232
			if (e->never_default)
				continue;

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
			if (   e->route.ifindex == route->ifindex
			    && e->synced) {
				has_ifindex_synced = TRUE;
				if (e->effective_metric == route->metric)
					entry = e;
			}
		}

		/* we only delete the route if we don't have a matching entry,
		 * and there is at least one entry that references this ifindex
		 * (indicating that the ifindex is managed by us -- not assumed).
		 *
		 * Otherwise, don't delete the route because it's configured
		 * externally (and will be assumed -- or already is assumed).
		 */
		if (has_ifindex_synced && !entry)
			vtable->platform_route_delete_default (route->ifindex, route->metric);
	}
	g_array_free (routes, TRUE);
}

static int
_sort_entries_cmp (gconstpointer a, gconstpointer b, gpointer user_data)
{
	guint32 m_a, m_b;
	const Entry *e_a = *((const Entry **) a);
	const Entry *e_b = *((const Entry **) b);

	/* when comparing routes, we consider the (original) metric. */
	m_a = e_a->route.metric;
	m_b = e_b->route.metric;

	/* we normalize route.metric already in _ipx_update_default_route().
	 * so we can just compare the metrics numerically */

	if (m_a != m_b)
		return (m_a < m_b) ? -1 : 1;

271 272 273 274
	/* If the metrics are equal, we prefer the one that is !never_default */
	if (!!e_a->never_default != !!e_b->never_default)
		return e_a->never_default ? 1 : -1;

275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
	/* If the metrics are equal, we prefer the one that is assumed (!synced).
	 * Entries that we sync, can be modified so that only the best
	 * entry has a (deterministically) lowest metric.
	 * With assumed devices we cannot increase/change the metric.
	 * For example: two devices, both metric 0. One is assumed the other is
	 * synced.
	 * If we would choose the synced entry as best, we cannot
	 * increase the metric of the assumed one and we would have non-determinism.
	 * If we instead prefer the assumed device, we can increase the metric
	 * of the synced device and the assumed device is (deterministically)
	 * prefered.
	 * If both devices are assumed, we also have non-determinism, but also
	 * we don't reorder either.
	 */
	if (!!e_a->synced != !!e_b->synced)
		return e_a->synced ? 1 : -1;

	/* otherwise, do not reorder */
	return 0;
}

static void
_resync_all (const VTableIP *vtable, NMDefaultRouteManager *self, const Entry *changed_entry, const Entry *old_entry, gboolean do_sync)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	Entry *entry;
	guint i;
	gint64 last_metric = -1;
	guint32 expected_metric;
	GPtrArray *entries;
	GHashTableIter iter;
	gpointer ptr;
	GHashTable *changed_metrics = g_hash_table_new (NULL, NULL);

	entries = vtable->get_entries (priv);

	if (old_entry && old_entry->synced) {
		/* The old version obviously changed. */
		g_hash_table_add (changed_metrics, GUINT_TO_POINTER (old_entry->effective_metric));
	}

	/* first iterate over all entries and adjust the effective metrics. */
	for (i = 0; i < entries->len; i++) {
		entry = g_ptr_array_index (entries, i);

		g_assert (entry != old_entry);

322 323 324
		if (entry->never_default)
			continue;

325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
		if (!entry->synced) {
			last_metric = MAX (last_metric, (gint64) entry->effective_metric);
			continue;
		}

		expected_metric = entry->route.metric;
		if ((gint64) expected_metric <= last_metric)
			expected_metric = last_metric == G_MAXUINT32 ? G_MAXUINT32 : last_metric + 1;

		if (changed_entry == entry) {
			/* for the changed entry, the previous metric was either old_entry->effective_metric,
			 * or none. Hence, we only have to remember what is going to change. */
			g_hash_table_add (changed_metrics, GUINT_TO_POINTER (expected_metric));
			if (old_entry)
				_LOGD (vtable->addr_family, LOG_ENTRY_FMT": update %s (%u -> %u)", LOG_ENTRY_ARGS (i, entry), vtable->platform_route_to_string (&entry->route), (guint) old_entry->effective_metric, (guint) expected_metric);
			else
				_LOGD (vtable->addr_family, LOG_ENTRY_FMT": add %s (%u)", LOG_ENTRY_ARGS (i, entry), vtable->platform_route_to_string (&entry->route), (guint) expected_metric);
		} else if (entry->effective_metric != expected_metric) {
			g_hash_table_add (changed_metrics, GUINT_TO_POINTER (entry->effective_metric));
			g_hash_table_add (changed_metrics, GUINT_TO_POINTER (expected_metric));
			_LOGD (vtable->addr_family, LOG_ENTRY_FMT": resync metric %s (%u -> %u)", LOG_ENTRY_ARGS (i, entry), vtable->platform_route_to_string (&entry->route), (guint) entry->effective_metric, (guint) expected_metric);
		}

		entry->effective_metric = expected_metric;
		last_metric = expected_metric;
	}

	if (do_sync) {
		g_hash_table_iter_init (&iter, changed_metrics);
		while (g_hash_table_iter_next (&iter, &ptr, NULL))
			_platform_route_sync_add (vtable, self, GPOINTER_TO_UINT (ptr));
		_platform_route_sync_flush (vtable, self);
	}

	g_hash_table_unref (changed_metrics);
}

static void
_entry_at_idx_update (const VTableIP *vtable, NMDefaultRouteManager *self, guint entry_idx, const Entry *old_entry, gboolean do_sync)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	Entry *entry;
367
	NMDevice *device = NULL;
368 369 370 371 372 373 374
	GPtrArray *entries;

	entries = vtable->get_entries (priv);
	g_assert (entry_idx < entries->len);

	entry = g_ptr_array_index (entries, entry_idx);

375 376
	if (NM_IS_DEVICE (entry->source.pointer))
		device = entry->source.device;
377 378 379 380 381 382 383 384 385 386

	g_assert (   !old_entry
	          || (entry->source.pointer == old_entry->source.pointer && entry->route.ifindex == old_entry->route.ifindex));

	if (!entry->synced) {
		entry->effective_metric = entry->route.metric;
		_LOGD (vtable->addr_family, LOG_ENTRY_FMT": %s %s%s",
		       LOG_ENTRY_ARGS (entry_idx, entry),
		       old_entry ? "update" : "add",
		       vtable->platform_route_to_string (&entry->route),
387
		       entry->never_default ? " (never-default)" : (entry->synced ? "" : " (not synced)"));
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
	}

	g_ptr_array_sort_with_data (entries, _sort_entries_cmp, NULL);

	_resync_all (vtable, self, entry, old_entry, do_sync);
}

static void
_entry_at_idx_remove (const VTableIP *vtable, NMDefaultRouteManager *self, guint entry_idx, gboolean do_sync)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	Entry *entry;
	GPtrArray *entries;

	entries = vtable->get_entries (priv);

	g_assert (entry_idx < entries->len);

	entry = g_ptr_array_index (entries, entry_idx);

	_LOGD (vtable->addr_family, LOG_ENTRY_FMT": remove %s (%u%s)", LOG_ENTRY_ARGS (entry_idx, entry), vtable->platform_route_to_string (&entry->route), (guint) entry->effective_metric, entry->synced ? "" : ", not synced");

	/* Remove the entry from the list (but don't free it yet) */
	g_ptr_array_index (entries, entry_idx) = NULL;
	g_ptr_array_remove_index (entries, entry_idx);

	_resync_all (vtable, self, NULL, entry, do_sync);

	_entry_free (entry);
}

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

static void
_ipx_update_default_route (const VTableIP *vtable, NMDefaultRouteManager *self, gpointer source)
{
	NMDefaultRouteManagerPrivate *priv;
	Entry *entry;
	guint entry_idx;
	const NMPlatformIPRoute *default_route = NULL;
428 429 430 431 432
	union {
		NMPlatformIPRoute vx;
		NMPlatformIP4Route v4;
		NMPlatformIP6Route v6;
	} rt;
433 434 435
	int ip_ifindex;
	GPtrArray *entries;
	NMDevice *device = NULL;
436 437
	NMVpnConnection *vpn = NULL;
	gboolean never_default = FALSE;
438 439 440 441 442
	gboolean synced;

	g_return_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self));
	if (NM_IS_DEVICE (source))
		device = source;
443 444
	else if (NM_IS_VPN_CONNECTION (source))
		vpn = source;
445 446 447
	else
		g_return_if_reached ();

448 449 450 451 452 453 454 455 456 457 458 459
	if (device)
		ip_ifindex = nm_device_get_ip_ifindex (device);
	else {
		ip_ifindex = nm_vpn_connection_get_ip_ifindex (vpn);

		if (ip_ifindex <= 0) {
			NMDevice *parent = nm_active_connection_get_device (NM_ACTIVE_CONNECTION (vpn));

			if (parent)
				ip_ifindex = nm_device_get_ip_ifindex (parent);
		}
	}
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

	entries = vtable->get_entries (priv);
	entry = _entry_find_by_source (entries, source, &entry_idx);

	if (   entry
	    && entry->route.ifindex != ip_ifindex) {
		/* Strange... the ifindex changed... Remove the device and start again. */
		_LOGD (vtable->addr_family, "ifindex of "LOG_ENTRY_FMT" changed: %d -> %d",
		       LOG_ENTRY_ARGS (entry_idx, entry),
		       entry->route.ifindex, ip_ifindex);

		g_object_freeze_notify (G_OBJECT (self));
		_entry_at_idx_remove (vtable, self, entry_idx, FALSE);
		g_assert (!_entry_find_by_source (entries, source, NULL));
		_ipx_update_default_route (vtable, self, source);
		g_object_thaw_notify (G_OBJECT (self));
		return;
	}

	/* get the @default_route from the device. */
	if (ip_ifindex > 0) {
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
		if (device) {
			if (VTABLE_IS_IP4)
				default_route = (const NMPlatformIPRoute *) nm_device_get_ip4_default_route (device);
			else
				default_route = (const NMPlatformIPRoute *) nm_device_get_ip6_default_route (device);
		} else {
			NMConnection *connection = nm_active_connection_get_connection ((NMActiveConnection *) vpn);

			if (   connection
			    && nm_vpn_connection_get_vpn_state (vpn) == NM_VPN_CONNECTION_STATE_ACTIVATED) {

				if (VTABLE_IS_IP4) {
					NMIP4Config *vpn_config;

					vpn_config = nm_vpn_connection_get_ip4_config (vpn);
					if (vpn_config) {
						never_default = nm_ip4_config_get_never_default (vpn_config);
						memset (&rt.v4, 0, sizeof (rt.v4));
						rt.v4.ifindex = ip_ifindex;
						rt.v4.source = NM_IP_CONFIG_SOURCE_VPN;
						rt.v4.gateway = nm_vpn_connection_get_ip4_internal_gateway (vpn);
						rt.v4.metric = nm_vpn_connection_get_ip4_route_metric (vpn);
						rt.v4.mss = nm_ip4_config_get_mss (vpn_config);
						default_route = &rt.vx;
					}
				} else {
					NMIP6Config *vpn_config;

					vpn_config = nm_vpn_connection_get_ip6_config (vpn);
					if (vpn_config) {
						const struct in6_addr *int_gw = nm_vpn_connection_get_ip6_internal_gateway (vpn);

						never_default = nm_ip6_config_get_never_default (vpn_config);
						memset (&rt.v6, 0, sizeof (rt.v6));
						rt.v6.ifindex = ip_ifindex;
						rt.v6.source = NM_IP_CONFIG_SOURCE_VPN;
						rt.v6.gateway = int_gw ? *int_gw : in6addr_any;
						rt.v6.metric = nm_vpn_connection_get_ip6_route_metric (vpn);
						rt.v6.mss = nm_ip6_config_get_mss (vpn_config);
						default_route = &rt.vx;
					}
				}
			}

			/* FIXME: for now, only track the default route for VPN.
			 * Enable actual configuration of the route later. */
			never_default = TRUE;
		}
531 532 533
	}
	g_assert (!default_route || default_route->plen == 0);

534 535 536
	/* if the source is never_default or the device uses an assumed connection,
	 * we don't sync the route. */
	synced = !never_default && (!device || !nm_device_uses_assumed_connection (device));
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552

	if (!entry && !default_route)
		/* nothing to do */;
	else if (!entry) {
		/* add */
		entry = g_slice_new0 (Entry);
		entry->source.object = g_object_ref (source);

		if (VTABLE_IS_IP4)
			entry->route4 = *((const NMPlatformIP4Route *) default_route);
		else
			entry->route6 = *((const NMPlatformIP6Route *) default_route);

		/* only use normalized metrics */
		entry->route.metric = vtable->route_metric_normalize (entry->route.metric);
		entry->route.ifindex = ip_ifindex;
553
		entry->never_default = never_default;
554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
		entry->effective_metric = entry->route.metric;
		entry->synced = synced;

		g_ptr_array_add (entries, entry);
		_entry_at_idx_update (vtable, self, entries->len - 1, NULL, TRUE);
	} else if (default_route) {
		/* update */
		Entry old_entry, new_entry;

		new_entry = *entry;
		if (VTABLE_IS_IP4)
			new_entry.route4 = *((const NMPlatformIP4Route *) default_route);
		else
			new_entry.route6 = *((const NMPlatformIP6Route *) default_route);
		/* only use normalized metrics */
		new_entry.route.metric = vtable->route_metric_normalize (new_entry.route.metric);
		new_entry.route.ifindex = ip_ifindex;
571
		new_entry.never_default = never_default;
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606
		new_entry.synced = synced;

		if (memcmp (entry, &new_entry, sizeof (new_entry)) == 0)
			return;

		old_entry = *entry;
		*entry = new_entry;
		_entry_at_idx_update (vtable, self, entry_idx, &old_entry, TRUE);
	} else {
		/* delete */
		_entry_at_idx_remove (vtable, self, entry_idx, TRUE);
	}
}

void
nm_default_route_manager_ip4_update_default_route (NMDefaultRouteManager *self, gpointer source)
{
	_ipx_update_default_route (&vtable_ip4, self, source);
}

void
nm_default_route_manager_ip6_update_default_route (NMDefaultRouteManager *self, gpointer source)
{
	_ipx_update_default_route (&vtable_ip6, self, source);
}

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

static void
_ipx_remove_default_route (const VTableIP *vtable, NMDefaultRouteManager *self, gpointer source)
{
	NMDefaultRouteManagerPrivate *priv;
	guint entry_idx;

	g_return_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self));
607
	g_return_if_fail (NM_IS_DEVICE (source) || NM_IS_VPN_CONNECTION (source));
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675

	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

	if (_entry_find_by_source (vtable->get_entries (priv), source, &entry_idx))
		_entry_at_idx_remove (vtable, self, entry_idx, TRUE);
}

void
nm_default_route_manager_ip4_remove_default_route (NMDefaultRouteManager *self, gpointer source)
{
	_ipx_remove_default_route (&vtable_ip4, self, source);
}

void
nm_default_route_manager_ip6_remove_default_route (NMDefaultRouteManager *self, gpointer source)
{
	_ipx_remove_default_route (&vtable_ip6, self, source);
}

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

static gboolean
_ipx_connection_has_default_route (const VTableIP *vtable, NMDefaultRouteManager *self, NMConnection *connection)
{
	const char *method;
	NMSettingIPConfig *s_ip;

	g_return_val_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self), FALSE);
	g_return_val_if_fail (NM_IS_CONNECTION (connection), FALSE);

	if (VTABLE_IS_IP4)
		s_ip = nm_connection_get_setting_ip4_config (connection);
	else
		s_ip = nm_connection_get_setting_ip6_config (connection);
	if (!s_ip || nm_setting_ip_config_get_never_default (s_ip))
		return FALSE;

	if (VTABLE_IS_IP4) {
		method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP4_CONFIG);
		if (   !method
		    || !strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_DISABLED)
		    || !strcmp (method, NM_SETTING_IP4_CONFIG_METHOD_LINK_LOCAL))
			return FALSE;
	} else {
		method = nm_utils_get_ip_config_method (connection, NM_TYPE_SETTING_IP6_CONFIG);
		if (   !method
		    || !strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_IGNORE)
		    || !strcmp (method, NM_SETTING_IP6_CONFIG_METHOD_LINK_LOCAL))
			return FALSE;
	}

	return TRUE;
}

gboolean
nm_default_route_manager_ip4_connection_has_default_route (NMDefaultRouteManager *self, NMConnection *connection)
{
	return _ipx_connection_has_default_route (&vtable_ip4, self, connection);
}

gboolean
nm_default_route_manager_ip6_connection_has_default_route (NMDefaultRouteManager *self, NMConnection *connection)
{
	return _ipx_connection_has_default_route (&vtable_ip6, self, connection);
}

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

676 677 678 679 680 681 682 683 684 685 686 687 688
/** _ipx_get_best_device:
 * @vtable: the virtual table
 * @self: #NMDefaultRouteManager
 * @devices: list of devices to be searched. Only devices from this list will be considered
 * @fully_activated: if #TRUE, only search for devices that are fully activated. Otherwise,
 *   search if there is a best device going to be activated. In the latter case, this will
 *   return NULL if the best device is already activated.
 * @preferred_device: if not-NULL, this device is preferred if there are more devices with
 *   the same priority.
 **/
static NMDevice *
_ipx_get_best_device (const VTableIP *vtable, NMDefaultRouteManager *self, const GSList *devices, gboolean fully_activated, NMDevice *preferred_device)
{
689
	NMDefaultRouteManagerPrivate *priv;
690 691 692
	const GSList *iter;
	NMDevice *best_device = NULL;
	guint32 best_prio = G_MAXUINT32;
693
	guint best_idx = G_MAXUINT;
694 695 696

	g_return_val_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self), NULL);

697 698
	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

699 700 701 702
	for (iter = devices; iter; iter = g_slist_next (iter)) {
		NMDevice *device = NM_DEVICE (iter->data);
		NMDeviceState state = nm_device_get_state (device);
		guint32 prio;
703 704
		guint idx;
		Entry *entry;
705 706 707 708 709 710 711 712 713 714 715

		if (   state <= NM_DEVICE_STATE_DISCONNECTED
		    || state >= NM_DEVICE_STATE_DEACTIVATING)
			continue;

		if (fully_activated && state < NM_DEVICE_STATE_SECONDARIES)
			continue;

		if (!_ipx_connection_has_default_route (vtable, self, nm_device_get_connection (device)))
			continue;

716 717 718
		entry = _entry_find_by_source (vtable->get_entries (priv), device, &idx);
		if (fully_activated && !entry)
			continue;
719

720 721 722 723
		if (entry)
			prio = entry->effective_metric;
		else
			prio = nm_device_get_ip4_route_metric (device);
724 725
		prio = vtable->route_metric_normalize (prio);

726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
		if (!best_device || prio < best_prio)
			goto NEW_BEST_DEVICE;

		if (prio == best_prio) {
			/* the devices have the same priority... which one to prefer? */

			if (fully_activated) {
				/* for @fully_activated, respect the order as from the sorted entries. */
				if (idx < best_idx)
					goto NEW_BEST_DEVICE;
			} else {
				/* for !fully_activated, prefer @preferred_device. */
				if (preferred_device == device)
					goto NEW_BEST_DEVICE;
				if (preferred_device != best_device) {
					/* if both devices are not @preferred_device, prefer
					 * the one with an entry (or the one with lower index,
					 * if both have an entry).
					 *
					 * The following is correct because if @best_device has no entry, @best_idx
					 * is G_MAXUINT. Also, if the currenty device has no entry, @idx is G_MAXUINT. */
					if (idx < best_idx)
						goto NEW_BEST_DEVICE;
				}
			}
751 752
		}

753 754 755 756 757 758
		continue;
NEW_BEST_DEVICE:
		best_device = device;
		best_prio = prio;
		best_idx = idx;
	}
759

760
	if (best_device && !fully_activated) {
761 762 763 764
		/* There's only a best activating device if the best device
		 * among all activating and already-activated devices is a
		 * still-activating one.
		 */
765
		if (nm_device_get_state (best_device) >= NM_DEVICE_STATE_SECONDARIES)
766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
			return NULL;
	}

	return best_device;
}

NMDevice *
nm_default_route_manager_ip4_get_best_device (NMDefaultRouteManager *self, const GSList *devices, gboolean fully_activated, NMDevice *preferred_device)
{
	return _ipx_get_best_device (&vtable_ip4, self, devices, fully_activated, preferred_device);
}

NMDevice *
nm_default_route_manager_ip6_get_best_device (NMDefaultRouteManager *self, const GSList *devices, gboolean fully_activated, NMDevice *preferred_device)
{
	return _ipx_get_best_device (&vtable_ip6, self, devices, fully_activated, preferred_device);
}

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

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936
static gpointer
_ipx_get_best_config (const VTableIP *vtable,
                      NMDefaultRouteManager *self,
                      NMManager *manager,
                      gboolean ignore_never_default,
                      NMDevice *preferred_device,
                      const char **out_ip_iface,
                      int *out_ip_ifindex,
                      NMActiveConnection **out_ac,
                      NMDevice **out_device,
                      NMVpnConnection **out_vpn)
{
	NMDefaultRouteManagerPrivate *priv;
	const GSList *connections, *iter;
	NMDevice *device;
	NMActRequest *req = NULL;
	gpointer config_result = NULL;

	g_return_val_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self), NULL);

	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

	/* If a VPN connection is active, it is preferred */
	connections = nm_manager_get_active_connections (manager);
	for (iter = connections; iter; iter = g_slist_next (iter)) {
		NMActiveConnection *active = NM_ACTIVE_CONNECTION (iter->data);
		NMVpnConnection *candidate;
		NMConnection *tmp;
		NMVpnConnectionState vpn_state;

		if (!NM_IS_VPN_CONNECTION (active))
			continue;

		candidate = NM_VPN_CONNECTION (active);

		tmp = nm_active_connection_get_connection (active);
		g_assert (tmp);

		vpn_state = nm_vpn_connection_get_vpn_state (candidate);
		if (vpn_state != NM_VPN_CONNECTION_STATE_ACTIVATED)
			continue;

		if (VTABLE_IS_IP4) {
			NMIP4Config *vpn_ip4;

			vpn_ip4 = nm_vpn_connection_get_ip4_config (candidate);
			if (!vpn_ip4)
				continue;

			if (!ignore_never_default && nm_ip4_config_get_never_default (vpn_ip4))
				continue;

			config_result = vpn_ip4;
		} else {
			NMIP6Config *vpn_ip6;

			vpn_ip6 = nm_vpn_connection_get_ip6_config (candidate);
			if (!vpn_ip6)
				continue;

			if (!ignore_never_default && nm_ip6_config_get_never_default (vpn_ip6))
				continue;

			config_result = vpn_ip6;
		}

		if (out_vpn)
			*out_vpn = candidate;
		if (out_ac)
			*out_ac = active;
		if (out_ip_iface)
			*out_ip_iface = nm_vpn_connection_get_ip_iface (candidate);
		 if (out_ip_ifindex)
			*out_ip_ifindex = nm_vpn_connection_get_ip_ifindex (candidate);
		break;
	}

	/* If no VPN connections, we use the best device instead */
	if (!config_result) {
		device = _ipx_get_best_device (vtable, self, nm_manager_get_devices (manager), TRUE, preferred_device);
		if (device) {
			if (VTABLE_IS_IP4)
				config_result = nm_device_get_ip4_config (device);
			else
				config_result = nm_device_get_ip6_config (device);
			g_assert (config_result);
			req = nm_device_get_act_request (device);
			g_assert (req);

			if (out_device)
				*out_device = device;
			if (out_ac)
				*out_ac = NM_ACTIVE_CONNECTION (req);
			if (out_ip_iface)
				*out_ip_iface = nm_device_get_ip_iface (device);
			if (out_ip_ifindex)
				*out_ip_ifindex = nm_device_get_ip_ifindex (device);
		}
	}

	return config_result;
}

NMIP4Config *
nm_default_route_manager_ip4_get_best_config (NMDefaultRouteManager *self,
                                              NMManager *manager,
                                              gboolean ignore_never_default,
                                              NMDevice *preferred_device,
                                              const char **out_ip_iface,
                                              int *out_ip_ifindex,
                                              NMActiveConnection **out_ac,
                                              NMDevice **out_device,
                                              NMVpnConnection **out_vpn)
{
	return _ipx_get_best_config (&vtable_ip4,
	                             self,
	                             manager,
	                             ignore_never_default,
	                             preferred_device,
	                             out_ip_iface,
	                             out_ip_ifindex,
	                             out_ac,
	                             out_device,
	                             out_vpn);
}

NMIP6Config *
nm_default_route_manager_ip6_get_best_config (NMDefaultRouteManager *self,
                                              NMManager *manager,
                                              gboolean ignore_never_default,
                                              NMDevice *preferred_device,
                                              const char **out_ip_iface,
                                              int *out_ip_ifindex,
                                              NMActiveConnection **out_ac,
                                              NMDevice **out_device,
                                              NMVpnConnection **out_vpn)
{
	return _ipx_get_best_config (&vtable_ip6,
	                             self,
	                             manager,
	                             ignore_never_default,
	                             preferred_device,
	                             out_ip_iface,
	                             out_ip_ifindex,
	                             out_ac,
	                             out_device,
	                             out_vpn);
}

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

937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 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 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
static GPtrArray *
_v4_get_entries (NMDefaultRouteManagerPrivate *priv)
{
	return priv->entries_ip4;
}

static GPtrArray *
_v6_get_entries (NMDefaultRouteManagerPrivate *priv)
{
	return priv->entries_ip6;
}

static gboolean
_v4_platform_route_delete_default (int ifindex, guint32 metric)
{
	return nm_platform_ip4_route_delete (ifindex, 0, 0, metric);
}

static gboolean
_v6_platform_route_delete_default (int ifindex, guint32 metric)
{
	return nm_platform_ip6_route_delete (ifindex, in6addr_any, 0, metric);
}

static guint32
_v4_route_metric_normalize (guint32 metric)
{
	return metric;
}

static const VTableIP vtable_ip4 = {
	.addr_family                    = AF_INET,
	.get_entries                    = _v4_get_entries,
	.platform_route_to_string       = (const char *(*)(const NMPlatformIPRoute *)) nm_platform_ip4_route_to_string,
	.platform_route_delete_default  = _v4_platform_route_delete_default,
	.route_metric_normalize         = _v4_route_metric_normalize,
};

static const VTableIP vtable_ip6 = {
	.addr_family                    = AF_INET6,
	.get_entries                    = _v6_get_entries,
	.platform_route_to_string       = (const char *(*)(const NMPlatformIPRoute *)) nm_platform_ip6_route_to_string,
	.platform_route_delete_default  = _v6_platform_route_delete_default,
	.route_metric_normalize         = nm_utils_ip6_route_metric_normalize,
};

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

NMDefaultRouteManager *
nm_default_route_manager_get ()
{
	if (G_UNLIKELY (!_instance)) {
		_instance = NM_DEFAULT_ROUTE_MANAGER (g_object_new (NM_TYPE_DEFAULT_ROUTE_MANAGER, NULL));
		g_object_add_weak_pointer (G_OBJECT (_instance), (gpointer *) &_instance);
	}
	return _instance;
}

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

static void
nm_default_route_manager_init (NMDefaultRouteManager *self)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

	priv->entries_ip4 = g_ptr_array_new_full (0, (GDestroyNotify) _entry_free);
	priv->entries_ip6 = g_ptr_array_new_full (0, (GDestroyNotify) _entry_free);
}

static void
dispose (GObject *object)
{
	NMDefaultRouteManager *self = NM_DEFAULT_ROUTE_MANAGER (object);
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

	if (priv->entries_ip4) {
		g_ptr_array_free (priv->entries_ip4, TRUE);
		priv->entries_ip4 = NULL;
	}
	if (priv->entries_ip6) {
		g_ptr_array_free (priv->entries_ip6, TRUE);
		priv->entries_ip6 = NULL;
	}

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

static void
nm_default_route_manager_class_init (NMDefaultRouteManagerClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);

	g_type_class_add_private (klass, sizeof (NMDefaultRouteManagerPrivate));

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