nm-default-route-manager.c 44.2 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
/* -*- 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 "config.h"

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

26 27 28 29
#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

typedef struct {
	GPtrArray *entries_ip4;
	GPtrArray *entries_ip6;
40 41 42 43 44 45 46
	struct {
		guint guard;
		guint backoff_wait_time_ms;
		guint idle_handle;
		gboolean has_v4_changes;
		gboolean has_v6_changes;
	} resync;
47 48 49 50 51 52 53 54 55 56 57 58 59 60
} 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))) { \
61
            char __ch = __addr_family == AF_INET ? '4' : (__addr_family == AF_INET6 ? '6' : '-'); \
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
            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__)

79
#define LOG_ENTRY_FMT  "entry[%u/%s:%p:%s:%c%c]"
80
#define LOG_ENTRY_ARGS(entry_idx, entry) \
81 82 83 84 85 86
		(entry_idx), \
		NM_IS_DEVICE ((entry)->source.pointer) ? "dev" : "vpn", \
		(entry)->source.pointer, \
		NM_IS_DEVICE ((entry)->source.pointer) ? nm_device_get_iface ((entry)->source.device) : nm_vpn_connection_get_connection_id ((entry)->source.vpn), \
		((entry)->never_default ? 'N' : 'n'), \
		((entry)->synced ? 'S' : 's')
87 88 89

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

90 91 92 93
static void _resync_idle_cancel (NMDefaultRouteManager *self);

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

94 95 96 97 98
typedef struct {
	union {
		void *pointer;
		GObject *object;
		NMDevice *device;
99
		NMVpnConnection *vpn;
100
	} source;
101
	NMPlatformIPXRoute route;
102

103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
	/* Whether the route is synced to platform and has a default route.
	 *
	 * ( synced && !never_default): the interface gets a default route that
	 *     is enforced and managed by NMDefaultRouteManager.
	 *
	 * (!synced && !never_default): the interface has this route, but it is assumed.
	 *     Assumed interfaces are those that have no tracked entry or that only have
	 *     (!synced && !never_default) entries. NMDefaultRouteManager will not touch
	 *     default routes on these interfaces.
	 *     This combination makes only sense for device sources.
	 *     They are tracked so that assumed devices can also be the best device.
	 *
	 * ( synced &&  never_default): entries of this kind are a placeholder
	 *     to indicate that the ifindex is managed but has no default-route.
	 *     Missing entries also indicate that a certain ifindex has no default-route.
	 *     The difference is that missing entries are considered assumed while on
	 *     (synced && never_default) entires the absence of the default route
	 *     is enforced. NMDefaultRouteManager will actively remove any default
	 *     route on such ifindexes.
122 123
	 *     Also, for VPN sources in addition we track them so that a never-default
	 *     VPN connection can be choosen by get_best_config() to receive the DNS configuration.
124
	 *
125
	 * (!synced &&  never_default): this combination makes no sense.
126 127
	 */
	gboolean synced;
128 129
	gboolean never_default;

130 131 132 133 134 135 136
	guint32 effective_metric;
} Entry;

typedef struct {
	int addr_family;
	GPtrArray *(*get_entries) (NMDefaultRouteManagerPrivate *priv);
	const char *(*platform_route_to_string) (const NMPlatformIPRoute *route);
137
	GArray *(*platform_route_get_all) (int ifindex, NMPlatformGetRouteMode mode);
138 139 140 141 142 143 144 145
	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)

146 147 148 149 150 151 152 153 154
static NMPlatformIPRoute *
_vt_route_index (const VTableIP *vtable, GArray *routes, guint index)
{
	if (VTABLE_IS_IP4)
		return (NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP4Route, index);
	else
		return (NMPlatformIPRoute *) &g_array_index (routes, NMPlatformIP6Route, index);
}

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
static gboolean
_vt_routes_has_entry (const VTableIP *vtable, GArray *routes, const Entry *entry)
{
	guint i;
	NMPlatformIPXRoute route = entry->route;

	route.rx.metric = entry->effective_metric;

	if (VTABLE_IS_IP4) {
		for (i = 0; i < routes->len; i++) {
			NMPlatformIP4Route *r = &g_array_index (routes, NMPlatformIP4Route, i);

			route.rx.source = r->source;
			if (nm_platform_ip4_route_cmp (r, &route.r4) == 0)
				return TRUE;
		}
	} else {
		for (i = 0; i < routes->len; i++) {
			NMPlatformIP6Route *r = &g_array_index (routes, NMPlatformIP6Route, i);

			route.rx.source = r->source;
			if (nm_platform_ip6_route_cmp (r, &route.r6) == 0)
				return TRUE;
		}
	}
	return FALSE;
}

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

212
static gboolean
213 214 215 216 217
_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;
218
	Entry *entry_unsynced = NULL;
219 220 221 222 223 224 225 226 227
	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);

228 229 230
		if (e->never_default)
			continue;

231 232 233 234 235
		if (e->effective_metric != metric)
			continue;

		if (e->synced) {
			g_assert (!entry || metric == G_MAXUINT32);
236 237
			if (!entry)
				entry = e;
238
		} else
239
			entry_unsynced = e;
240 241
	}

242 243 244 245 246 247
	/* We don't expect to have an unsynced *and* a synced entry for the same metric.
	 * Unless, (a) their metric is G_MAXUINT32, in which case we could not find an unused effective metric,
	 * or (b) if we have an unsynced and a synced entry for the same ifindex.
	 * The latter case happens for example when activating an openvpn connection (synced) and
	 * assuming the corresponding tun0 interface (unsynced). */
	g_assert (!entry || !entry_unsynced || (entry->route.rx.ifindex == entry_unsynced->route.rx.ifindex) || metric == G_MAXUINT32);
248 249 250

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

	if (VTABLE_IS_IP4) {
254 255
		success = nm_platform_ip4_route_add (entry->route.rx.ifindex,
		                                     entry->route.rx.source,
256 257
		                                     0,
		                                     0,
258
		                                     entry->route.r4.gateway,
259
		                                     entry->effective_metric,
260
		                                     entry->route.rx.mss);
261
	} else {
262 263
		success = nm_platform_ip6_route_add (entry->route.rx.ifindex,
		                                     entry->route.rx.source,
264 265
		                                     in6addr_any,
		                                     0,
266
		                                     entry->route.r6.gateway,
267
		                                     entry->effective_metric,
268 269 270 271 272
		                                     entry->route.rx.mss);
	}
	if (!success) {
		_LOGW (vtable->addr_family, "failed to add default route %s with effective metric %u",
		       vtable->platform_route_to_string (&entry->route.rx), (guint) entry->effective_metric);
273
	}
274
	return TRUE;
275 276
}

277
static gboolean
278
_platform_route_sync_flush (const VTableIP *vtable, NMDefaultRouteManager *self, int ifindex_to_flush)
279 280 281 282
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	GPtrArray *entries = vtable->get_entries (priv);
	GArray *routes;
283
	guint i, j;
284
	gboolean changed = FALSE;
285 286

	/* prune all other default routes from this device. */
287
	routes = vtable->platform_route_get_all (0, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT);
288 289 290 291 292 293

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

294
		route = _vt_route_index (vtable, routes, i);
295 296 297

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

301
			if (   e->route.rx.ifindex == route->ifindex
302 303
			    && e->synced) {
				has_ifindex_synced = TRUE;
304 305
				if (   !e->never_default
				    && e->effective_metric == route->metric)
306 307 308 309 310 311 312 313 314 315 316
					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).
		 */
317 318
		if (   !entry
		    && (has_ifindex_synced || ifindex_to_flush == route->ifindex)) {
319
			vtable->platform_route_delete_default (route->ifindex, route->metric);
320 321
			changed = TRUE;
		}
322 323
	}
	g_array_free (routes, TRUE);
324
	return changed;
325 326 327 328 329 330 331 332 333 334
}

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. */
335 336
	m_a = e_a->route.rx.metric;
	m_b = e_b->route.rx.metric;
337 338 339 340 341 342 343

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

344 345 346 347
	/* 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;

348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
	/* 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;
}

369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
static GHashTable *
_get_assumed_interface_metrics (const VTableIP *vtable, NMDefaultRouteManager *self, GArray *routes)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	GPtrArray *entries;
	guint i, j;
	GHashTable *result;

	/* create a list of all metrics that are currently assigned on an interface
	 * that is *not* already covered by one of our synced entries.
	 * IOW, returns the metrics that are in use by assumed interfaces
	 * that we want to preserve. */

	entries = vtable->get_entries (priv);

	result = g_hash_table_new (NULL, NULL);

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

		route = _vt_route_index (vtable, routes, i);

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

395
			if (   e->synced
396 397 398 399 400 401 402 403 404 405 406 407 408
			    && e->route.rx.ifindex == route->ifindex) {
				ifindex_has_synced_entry = TRUE;
				break;
			}
		}

		if (!ifindex_has_synced_entry)
			g_hash_table_add (result, GUINT_TO_POINTER (vtable->route_metric_normalize (route->metric)));
	}

	return result;
}

409 410 411 412 413 414 415 416 417 418 419
static int
_sort_metrics_ascending_fcn (gconstpointer a, gconstpointer b)
{
	guint32 m_a = *((guint32 *) a);
	guint32 m_b = *((guint32 *) b);

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

420 421
static gboolean
_resync_all (const VTableIP *vtable, NMDefaultRouteManager *self, const Entry *changed_entry, const Entry *old_entry, gboolean external_change)
422 423 424
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	Entry *entry;
425
	guint i, j;
426 427 428
	gint64 last_metric = -1;
	guint32 expected_metric;
	GPtrArray *entries;
429
	GArray *changed_metrics = g_array_new (FALSE, FALSE, sizeof (guint32));
430 431
	GHashTable *assumed_metrics;
	GArray *routes;
432
	gboolean changed = FALSE;
433
	int ifindex_to_flush = 0;
434 435 436 437 438 439 440 441 442 443 444 445

	g_assert (priv->resync.guard == 0);
	priv->resync.guard++;

	if (!external_change) {
		if (VTABLE_IS_IP4)
			priv->resync.has_v4_changes = FALSE;
		else
			priv->resync.has_v6_changes = FALSE;
		if (!priv->resync.has_v4_changes && !priv->resync.has_v6_changes)
			_resync_idle_cancel (self);
	}
446 447 448

	entries = vtable->get_entries (priv);

449 450 451 452
	routes = vtable->platform_route_get_all (0, NM_PLATFORM_GET_ROUTE_MODE_ONLY_DEFAULT);

	assumed_metrics = _get_assumed_interface_metrics (vtable, self, routes);

453
	if (old_entry && old_entry->synced && !old_entry->never_default) {
454
		/* The old version obviously changed. */
455
		g_array_append_val (changed_metrics, old_entry->effective_metric);
456 457 458 459 460 461 462 463
	}

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

464 465 466
		if (entry->never_default)
			continue;

467
		if (!entry->synced) {
468 469 470 471 472 473 474 475 476
			gboolean has_synced_entry = FALSE;

			/* A non synced entry is completely ignored, if we have
			 * a synced entry for the same if index.
			 * Otherwise the metric of the entry is still remembered as
			 * last_metric to avoid reusing it. */
			for (j = 0; j < entries->len; j++) {
				const Entry *e = g_ptr_array_index (entries, j);

477
				if (   e->synced
478 479 480 481 482 483 484
					&& e->route.rx.ifindex == entry->route.rx.ifindex) {
					has_synced_entry = TRUE;
					break;
				}
			}
			if (!has_synced_entry)
				last_metric = MAX (last_metric, (gint64) entry->effective_metric);
485 486 487
			continue;
		}

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

492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
		while (   expected_metric < G_MAXUINT32
		       && g_hash_table_contains (assumed_metrics, GUINT_TO_POINTER (expected_metric))) {
			gboolean has_metric_for_ifindex = FALSE;

			/* Check if there are assumed devices that have default routes with this metric.
			 * If there are any, we have to pick another effective_metric. */

			/* However, if there is a matching route (ifindex+metric) for our current entry, we are done. */
			for (j = 0; j < routes->len; j++) {
				const NMPlatformIPRoute *r = _vt_route_index (vtable, routes, i);

				if (   r->metric == expected_metric
				    && r->ifindex == entry->route.rx.ifindex) {
					has_metric_for_ifindex = TRUE;
					break;
				}
			}
			if (has_metric_for_ifindex)
				break;
			expected_metric++;
		}

514 515 516
		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. */
517
			g_array_append_val (changed_metrics, expected_metric);
518 519 520 521 522 523 524 525
			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.rx), (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.rx), (guint) expected_metric);
			}
526
		} else if (entry->effective_metric != expected_metric) {
527 528
			g_array_append_val (changed_metrics, entry->effective_metric);
			g_array_append_val (changed_metrics, expected_metric);
529 530 531
			_LOGD (vtable->addr_family, LOG_ENTRY_FMT": resync metric %s (%u -> %u)", LOG_ENTRY_ARGS (i, entry),
			       vtable->platform_route_to_string (&entry->route.rx), (guint) entry->effective_metric,
			       (guint) expected_metric);
532 533
		} else {
			if (!_vt_routes_has_entry (vtable, routes, entry)) {
534
				g_array_append_val (changed_metrics, entry->effective_metric);
535 536 537 538
				_LOGD (vtable->addr_family, LOG_ENTRY_FMT": readd route %s (%u -> %u)", LOG_ENTRY_ARGS (i, entry),
				       vtable->platform_route_to_string (&entry->route.rx), (guint) entry->effective_metric,
				       (guint) entry->effective_metric);
			}
539 540
		}

541 542 543 544
		if (entry->effective_metric != expected_metric) {
			entry->effective_metric = expected_metric;
			changed = TRUE;
		}
545 546 547
		last_metric = expected_metric;
	}

548 549
	g_array_free (routes, TRUE);

550 551 552 553 554 555 556 557 558 559 560 561 562
	g_array_sort (changed_metrics, _sort_metrics_ascending_fcn);
	last_metric = -1;
	for (j = 0; j < changed_metrics->len; j++) {
		expected_metric = g_array_index (changed_metrics, guint32, j);

		if (last_metric == (gint64) expected_metric) {
			/* skip duplicates. */
			continue;
		}
		changed |= _platform_route_sync_add (vtable, self, expected_metric);
		last_metric = expected_metric;
	}

563 564 565 566 567 568 569 570 571 572 573
	if (   old_entry
	    && !changed_entry
	    && old_entry->synced
	    && !old_entry->never_default) {
		/* If we entriely remove an entry that was synced before, we must make
		 * sure to flush routes for this ifindex too. Otherwise they linger
		 * around as "assumed" routes */
		ifindex_to_flush = old_entry->route.rx.ifindex;
	}

	changed |= _platform_route_sync_flush (vtable, self, ifindex_to_flush);
574

575
	g_array_free (changed_metrics, TRUE);
576
	g_hash_table_unref (assumed_metrics);
577 578 579

	priv->resync.guard--;
	return changed;
580 581 582
}

static void
583
_entry_at_idx_update (const VTableIP *vtable, NMDefaultRouteManager *self, guint entry_idx, const Entry *old_entry)
584 585 586 587 588 589 590 591 592 593 594
{
	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);

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

597
	if (!entry->synced && !entry->never_default)
598
		entry->effective_metric = entry->route.rx.metric;
599 600 601 602 603

	_LOGD (vtable->addr_family, LOG_ENTRY_FMT": %s %s",
	       LOG_ENTRY_ARGS (entry_idx, entry),
	       old_entry ? "update" : "add",
	       vtable->platform_route_to_string (&entry->route.rx));
604 605 606

	g_ptr_array_sort_with_data (entries, _sort_entries_cmp, NULL);

607
	_resync_all (vtable, self, entry, old_entry, FALSE);
608 609 610
}

static void
611
_entry_at_idx_remove (const VTableIP *vtable, NMDefaultRouteManager *self, guint entry_idx)
612 613 614 615 616 617 618 619 620 621 622
{
	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);

623 624
	_LOGD (vtable->addr_family, LOG_ENTRY_FMT": remove %s (%u)", LOG_ENTRY_ARGS (entry_idx, entry),
	       vtable->platform_route_to_string (&entry->route.rx), (guint) entry->effective_metric);
625 626 627 628 629

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

630
	_resync_all (vtable, self, NULL, entry, FALSE);
631 632 633 634 635 636 637 638 639 640 641 642 643

	_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;
644
	NMPlatformIPXRoute rt;
645 646 647
	int ip_ifindex;
	GPtrArray *entries;
	NMDevice *device = NULL;
648 649
	NMVpnConnection *vpn = NULL;
	gboolean never_default = FALSE;
650
	gboolean synced = FALSE;
651 652 653 654

	g_return_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self));
	if (NM_IS_DEVICE (source))
		device = source;
655 656
	else if (NM_IS_VPN_CONNECTION (source))
		vpn = source;
657 658 659
	else
		g_return_if_reached ();

660 661 662 663 664 665 666 667 668 669 670 671
	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);
		}
	}
672 673 674 675 676 677 678

	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

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

	if (   entry
679
	    && entry->route.rx.ifindex != ip_ifindex) {
680 681 682
		/* 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),
683
		       entry->route.rx.ifindex, ip_ifindex);
684 685

		g_object_freeze_notify (G_OBJECT (self));
686
		_entry_at_idx_remove (vtable, self, entry_idx);
687 688 689 690 691 692 693 694
		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) {
695
		if (device) {
696 697
			gboolean is_assumed;

698
			if (VTABLE_IS_IP4)
699
				default_route = (const NMPlatformIPRoute *) nm_device_get_ip4_default_route (device, &is_assumed);
700
			else
701
				default_route = (const NMPlatformIPRoute *) nm_device_get_ip6_default_route (device, &is_assumed);
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
			if (!default_route && !is_assumed) {
				/* the device has no default route, but it is not assumed. That means, NMDefaultRouteManager
				 * enforces that the device has no default route.
				 *
				 * Hence we have to keep track of this entry, otherwise a missing entry tells us
				 * that the interface is assumed and NM would not remove the default routes on
				 * the device. */
				memset (&rt, 0, sizeof (rt));
				rt.rx.ifindex = ip_ifindex;
				rt.rx.source = NM_IP_CONFIG_SOURCE_UNKNOWN;
				rt.rx.metric = G_MAXUINT32;
				default_route = &rt.rx;

				never_default = TRUE;
				synced = TRUE;
			} else
				synced = default_route && !is_assumed;
719 720 721 722 723 724
		} else {
			NMConnection *connection = nm_active_connection_get_connection ((NMActiveConnection *) vpn);

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

725
				memset (&rt, 0, sizeof (rt));
726 727 728 729 730 731
				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);
732 733 734 735 736 737
						rt.r4.ifindex = ip_ifindex;
						rt.r4.source = NM_IP_CONFIG_SOURCE_VPN;
						rt.r4.gateway = nm_vpn_connection_get_ip4_internal_gateway (vpn);
						rt.r4.metric = nm_vpn_connection_get_ip4_route_metric (vpn);
						rt.r4.mss = nm_ip4_config_get_mss (vpn_config);
						default_route = &rt.rx;
738 739 740 741 742 743 744 745 746
					}
				} 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);
747 748 749 750 751 752
						rt.r6.ifindex = ip_ifindex;
						rt.r6.source = NM_IP_CONFIG_SOURCE_VPN;
						rt.r6.gateway = int_gw ? *int_gw : in6addr_any;
						rt.r6.metric = nm_vpn_connection_get_ip6_route_metric (vpn);
						rt.r6.mss = nm_ip6_config_get_mss (vpn_config);
						default_route = &rt.rx;
753 754 755
					}
				}
			}
756
			synced = TRUE;
757
		}
758 759 760 761 762 763 764 765 766 767 768
	}
	g_assert (!default_route || default_route->plen == 0);

	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)
769
			entry->route.r4 = *((const NMPlatformIP4Route *) default_route);
770
		else
771
			entry->route.r6 = *((const NMPlatformIP6Route *) default_route);
772 773

		/* only use normalized metrics */
774 775
		entry->route.rx.metric = vtable->route_metric_normalize (entry->route.rx.metric);
		entry->route.rx.ifindex = ip_ifindex;
776
		entry->never_default = never_default;
777
		entry->effective_metric = entry->route.rx.metric;
778 779 780
		entry->synced = synced;

		g_ptr_array_add (entries, entry);
781
		_entry_at_idx_update (vtable, self, entries->len - 1, NULL);
782 783 784 785 786 787
	} else if (default_route) {
		/* update */
		Entry old_entry, new_entry;

		new_entry = *entry;
		if (VTABLE_IS_IP4)
788
			new_entry.route.r4 = *((const NMPlatformIP4Route *) default_route);
789
		else
790
			new_entry.route.r6 = *((const NMPlatformIP6Route *) default_route);
791
		/* only use normalized metrics */
792 793
		new_entry.route.rx.metric = vtable->route_metric_normalize (new_entry.route.rx.metric);
		new_entry.route.rx.ifindex = ip_ifindex;
794
		new_entry.never_default = never_default;
795 796 797 798 799 800 801
		new_entry.synced = synced;

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

		old_entry = *entry;
		*entry = new_entry;
802
		_entry_at_idx_update (vtable, self, entry_idx, &old_entry);
803 804
	} else {
		/* delete */
805
		_entry_at_idx_remove (vtable, self, entry_idx);
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
	}
}

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

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

870
static NMDevice *
871
_ipx_get_best_device (const VTableIP *vtable, NMDefaultRouteManager *self, const GSList *devices)
872 873 874 875 876 877 878
{
	NMDefaultRouteManagerPrivate *priv;
	GPtrArray *entries;
	guint i;

	g_return_val_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self), NULL);

879 880 881
	if (!devices)
		return NULL;

882 883 884 885 886 887 888 889 890
	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	entries = vtable->get_entries (priv);

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

		if (!NM_IS_DEVICE (entry->source.pointer))
			continue;

891 892
		if (entry->never_default)
			continue;
893 894 895

		if (g_slist_find ((GSList *) devices, entry->source.device))
			return entry->source.pointer;
896 897 898 899 900
	}
	return NULL;
}

/** _ipx_get_best_activating_device:
901 902 903 904 905 906 907 908 909 910
 * @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 *
911
_ipx_get_best_activating_device (const VTableIP *vtable, NMDefaultRouteManager *self, const GSList *devices, NMDevice *preferred_device)
912
{
913
	NMDefaultRouteManagerPrivate *priv;
914 915 916
	const GSList *iter;
	NMDevice *best_device = NULL;
	guint32 best_prio = G_MAXUINT32;
917
	NMDevice *best_activated_device;
918 919 920

	g_return_val_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self), NULL);

921 922
	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

923
	best_activated_device = _ipx_get_best_device (vtable, self, devices);
924

925 926 927
	for (iter = devices; iter; iter = g_slist_next (iter)) {
		NMDevice *device = NM_DEVICE (iter->data);
		guint32 prio;
928
		Entry *entry;
929

930
		entry = _entry_find_by_source (vtable->get_entries (priv), device, NULL);
931

932 933 934 935 936 937 938 939
		if (entry) {
			/* of all the device that have an entry, we already know that best_activated_device
			 * is the best. entry cannot be better. */
			if (entry->source.device != best_activated_device)
				continue;
			prio = entry->effective_metric;
		} else {
			NMDeviceState state = nm_device_get_state (device);
940

941 942 943
			if (   state <= NM_DEVICE_STATE_DISCONNECTED
			    || state >= NM_DEVICE_STATE_DEACTIVATING)
				continue;
944

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

948
			prio = nm_device_get_ip4_route_metric (device);
949
		}
950 951
		prio = vtable->route_metric_normalize (prio);

952 953 954 955 956
		if (   !best_device
		    || prio < best_prio
			|| (prio == best_prio && preferred_device == device)) {
			best_device = device;
			best_prio = prio;
957 958 959
		}
	}

960 961 962 963 964 965
	/* There's only a best activating device if the best device
	 * among all activating and already-activated devices is a
	 * still-activating one.
	 */
	if (best_device && nm_device_get_state (best_device) >= NM_DEVICE_STATE_SECONDARIES)
		return NULL;
966 967 968 969 970 971
	return best_device;
}

NMDevice *
nm_default_route_manager_ip4_get_best_device (NMDefaultRouteManager *self, const GSList *devices, gboolean fully_activated, NMDevice *preferred_device)
{
972
	if (fully_activated)
973
		return _ipx_get_best_device (&vtable_ip4, self, devices);
974 975
	else
		return _ipx_get_best_activating_device (&vtable_ip4, self, devices, preferred_device);
976 977 978 979 980
}

NMDevice *
nm_default_route_manager_ip6_get_best_device (NMDefaultRouteManager *self, const GSList *devices, gboolean fully_activated, NMDevice *preferred_device)
{
981
	if (fully_activated)
982
		return _ipx_get_best_device (&vtable_ip6, self, devices);
983 984
	else
		return _ipx_get_best_activating_device (&vtable_ip6, self, devices, preferred_device);
985 986 987 988
}

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

989 990 991 992 993 994 995 996 997 998
static gpointer
_ipx_get_best_config (const VTableIP *vtable,
                      NMDefaultRouteManager *self,
                      gboolean ignore_never_default,
                      const char **out_ip_iface,
                      NMActiveConnection **out_ac,
                      NMDevice **out_device,
                      NMVpnConnection **out_vpn)
{
	NMDefaultRouteManagerPrivate *priv;
999 1000
	GPtrArray *entries;
	guint i;
1001 1002 1003 1004
	gpointer config_result = NULL;

	g_return_val_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self), NULL);

1005 1006 1007 1008 1009 1010 1011 1012 1013
	if (out_ip_iface)
		*out_ip_iface = NULL;
	if (out_ac)
		*out_ac = NULL;
	if (out_device)
		*out_device = NULL;
	if (out_vpn)
		*out_vpn = NULL;

1014 1015
	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

1016
	g_return_val_if_fail (NM_IS_DEFAULT_ROUTE_MANAGER (self), NULL);
1017

1018 1019
	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
	entries = vtable->get_entries (priv);
1020

1021 1022
	for (i = 0; i < entries->len; i++) {
		Entry *entry = g_ptr_array_index (entries, i);
1023

1024 1025
		if (!NM_IS_DEVICE (entry->source.pointer)) {
			NMVpnConnection *vpn = NM_VPN_CONNECTION (entry->source.vpn);
1026

1027
			if (entry->never_default && !ignore_never_default)
1028 1029
				continue;

1030 1031 1032 1033 1034
			if (VTABLE_IS_IP4)
				config_result = nm_vpn_connection_get_ip4_config (vpn);
			else
				config_result = nm_vpn_connection_get_ip6_config (vpn);
			g_assert (config_result);
1035

1036 1037 1038 1039 1040 1041
			if (out_vpn)
				*out_vpn = vpn;
			if (out_ac)
				*out_ac = NM_ACTIVE_CONNECTION (vpn);
			if (out_ip_iface)
				*out_ip_iface = nm_vpn_connection_get_ip_iface (vpn);
1042
		} else {
1043 1044
			NMDevice *device = entry->source.device;
			NMActRequest *req;
1045

1046 1047 1048
			if (entry->never_default)
				continue;

1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
			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);
		}
1064
		break;
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
	}

	return config_result;
}

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

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

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

1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139
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,
1140
	.platform_route_get_all         = nm_platform_ip4_route_get_all,
1141 1142 1143 1144 1145 1146 1147 1148
	.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,
1149
	.platform_route_get_all         = nm_platform_ip6_route_get_all,
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
	.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;
}

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

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
static gboolean
_resync_idle_now (NMDefaultRouteManager *self)
{
	gboolean has_v4_changes, has_v6_changes;
	gboolean changed = FALSE;

	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

	has_v4_changes = priv->resync.has_v4_changes;
	has_v6_changes = priv->resync.has_v6_changes;

	_LOGD (0, "resync: sync now (%u) (IPv4 changes: %s, IPv6 changes: %s)", priv->resync.idle_handle,
	       has_v4_changes ? "yes" : "no", has_v6_changes ? "yes" : "no");

	priv->resync.has_v4_changes = FALSE;
	priv->resync.has_v6_changes = FALSE;
	priv->resync.idle_handle = 0;
	priv->resync.backoff_wait_time_ms =
	    priv->resync.backoff_wait_time_ms == 0
	    ? 100
	    : priv->resync.backoff_wait_time_ms * 2;

	if (has_v4_changes)
		changed |= _resync_all (&vtable_ip4, self, NULL, NULL, TRUE);

	if (has_v6_changes)
		changed |= _resync_all (&vtable_ip6, self, NULL, NULL, TRUE);

	if (!changed) {
		/* Nothing changed: reset the backoff wait time */
		_resync_idle_cancel (self);
	}

	return G_SOURCE_REMOVE;
}

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

	if (priv->resync.idle_handle) {
		_LOGD (0, "resync: cancelled (%u)", priv->resync.idle_handle);
		g_source_remove (priv->resync.idle_handle);
		priv->resync.idle_handle = 0;
	}
	priv->resync.backoff_wait_time_ms = 0;
	priv->resync.has_v4_changes = FALSE;
	priv->resync.has_v6_changes = FALSE;
}

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

	/* since we react on external changes and readd/remove default routes for
	 * the interfaces we manage, there could be the erronous situation where two applications
	 * fight over a certain default route.
	 * Avoid this, by increasingly wait longer to touch the system (backoff wait time). */

	if (priv->resync.backoff_wait_time_ms == 0) {
		/* for scheduling idle, always reschedule (to process all other events first) */
		if (priv->resync.idle_handle)
			g_source_remove (priv->resync.idle_handle);
		else
			_LOGD (0, "resync: schedule on idle");
		priv->resync.idle_handle = g_idle_add ((GSourceFunc) _resync_idle_now, self);
	} else if (!priv->resync.idle_handle) {
		priv->resync.idle_handle =  g_timeout_add (priv->resync.backoff_wait_time_ms, (GSourceFunc) _resync_idle_now, self);
		_LOGD (0, "resync: schedule in %u.%03u seconds (%u)", priv->resync.backoff_wait_time_ms/1000,
		       priv->resync.backoff_wait_time_ms%1000, priv->resync.idle_handle);
	}
}

static void
_platform_ipx_route_changed_cb (const VTableIP *vtable,
                                NMDefaultRouteManager *self,
                                const NMPlatformIPRoute *route)
{
	NMDefaultRouteManagerPrivate *priv;

	if (route && !NM_PLATFORM_IP_ROUTE_IS_DEFAULT (route)) {
		/* we only care about address changes or changes of default route. */
		return;
	}

	priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);

	if (priv->resync.guard) {
		/* callbacks while executing _resync_all() are ignored. */
		return;
	}

	if (VTABLE_IS_IP4)
		priv->resync.has_v4_changes = TRUE;
	else
		priv->resync.has_v6_changes = TRUE;

	_resync_idle_reschedule (self);
}

static void
_platform_ip4_address_changed_cb (NMPlatform *platform,
                                  int ifindex,
                                  gpointer platform_object,
                                  NMPlatformSignalChangeType change_type,
                                  NMPlatformReason reason,
                                  NMDefaultRouteManager *self)
{
	_platform_ipx_route_changed_cb (&vtable_ip4, self, NULL);
}

static void
_platform_ip6_address_changed_cb (NMPlatform *platform,
                                  int ifindex,
                                  gpointer platform_object,
                                  NMPlatformSignalChangeType change_type,
                                  NMPlatformReason reason,
                                  NMDefaultRouteManager *self)
{
	_platform_ipx_route_changed_cb (&vtable_ip6, self, NULL);
}

static void
_platform_ip4_route_changed_cb (NMPlatform *platform,
                                int ifindex,
                                gpointer platform_object,
                                NMPlatformSignalChangeType change_type,
                                NMPlatformReason reason,
                                NMDefaultRouteManager *self)
{
	_platform_ipx_route_changed_cb (&vtable_ip4, self, platform_object);
}

static void
_platform_ip6_route_changed_cb (NMPlatform *platform,
                                int ifindex,
                                gpointer platform_object,
                                NMPlatformSignalChangeType change_type,
                                NMPlatformReason reason,
                                NMDefaultRouteManager *self)
{
	_platform_ipx_route_changed_cb (&vtable_ip6, self, platform_object);
}

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

1316 1317 1318 1319
static void
nm_default_route_manager_init (NMDefaultRouteManager *self)
{
	NMDefaultRouteManagerPrivate *priv = NM_DEFAULT_ROUTE_MANAGER_GET_PRIVATE (self);
1320
	NMPlatform *platform;
1321 1322 1323

	priv->entries_ip4 = g_ptr_array_new_full (0, (GDestroyNotify) _entry_free);
	priv->entries_ip6 = g_ptr_array_new_full (0, (GDestroyNotify) _entry_free);
1324 1325 1326 1327 1328 1329

	platform = nm_platform_get ();
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP4_ADDRESS_CHANGED, G_CALLBACK (_platform_ip4_address_changed_cb), self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP6_ADDRESS_CHANGED, G_CALLBACK (_platform_ip6_address_changed_cb), self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP4_ROUTE_CHANGED, G_CALLBACK (_platform_ip4_route_changed_cb), self);
	g_signal_connect (platform, NM_PLATFORM_SIGNAL_IP6_ROUTE_CHANGED, G_CALLBACK (_platform_ip6_route_changed_cb), self);
1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
}

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

1347 1348 1349 1350
	_resync_idle_cancel (self);

	g_signal_handlers_disconnect_by_data (nm_platform_get (), self);

1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361