nm-utils.c 174 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */

/*
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301 USA.
 *
19
 * Copyright 2005 - 2017 Red Hat, Inc.
20 21
 */

22
#include "nm-default.h"
23

24 25
#include "nm-utils.h"

26
#include <string.h>
27
#include <errno.h>
28 29
#include <stdlib.h>
#include <netinet/ether.h>
30
#include <arpa/inet.h>
31
#include <uuid/uuid.h>
32
#include <libintl.h>
33
#include <gmodule.h>
34
#include <sys/stat.h>
35
#include <net/if.h>
36
#include <linux/pkt_sched.h>
37

Thomas Haller's avatar
Thomas Haller committed
38
#include "nm-utils/nm-jansson.h"
39
#include "nm-utils/nm-enum-utils.h"
40
#include "nm-common-macros.h"
41 42 43
#include "nm-utils-private.h"
#include "nm-setting-private.h"
#include "crypto.h"
44 45 46 47 48 49 50 51 52
#include "nm-setting-bond.h"
#include "nm-setting-bridge.h"
#include "nm-setting-infiniband.h"
#include "nm-setting-ip6-config.h"
#include "nm-setting-team.h"
#include "nm-setting-vlan.h"
#include "nm-setting-wired.h"
#include "nm-setting-wireless.h"

53 54 55 56 57 58 59 60 61 62
/**
 * SECTION:nm-utils
 * @short_description: Utility functions
 *
 * A collection of utility functions for working with SSIDs, IP addresses, Wi-Fi
 * access points and devices, among other things.
 */

struct IsoLangToEncodings
{
63 64
	const char *lang;
	const char *const *encodings;
65 66
};

67 68
#define LANG_ENCODINGS(l, ...) { .lang = l, .encodings = (const char *[]) { __VA_ARGS__, NULL }}

69 70 71 72
/* 5-letter language codes */
static const struct IsoLangToEncodings isoLangEntries5[] =
{
	/* Simplified Chinese */
73 74
	LANG_ENCODINGS ("zh_cn",   "euc-cn", "gb2312", "gb18030"),         /* PRC */
	LANG_ENCODINGS ("zh_sg",   "euc-cn", "gb2312", "gb18030"),         /* Singapore */
75 76

	/* Traditional Chinese */
77 78 79
	LANG_ENCODINGS ("zh_tw",   "big5", "euc-tw"),                      /* Taiwan */
	LANG_ENCODINGS ("zh_hk",   "big5", "euc-tw", "big5-hkcs"),         /* Hong Kong */
	LANG_ENCODINGS ("zh_mo",   "big5", "euc-tw"),                      /* Macau */
80

81
	LANG_ENCODINGS (NULL, NULL)
82 83 84 85 86 87
};

/* 2-letter language codes; we don't care about the other 3 in this table */
static const struct IsoLangToEncodings isoLangEntries2[] =
{
	/* Japanese */
88
	LANG_ENCODINGS ("ja",      "euc-jp", "shift_jis", "iso-2022-jp"),
89 90

	/* Korean */
91
	LANG_ENCODINGS ("ko",      "euc-kr", "iso-2022-kr", "johab"),
92 93

	/* Thai */
94
	LANG_ENCODINGS ("th",      "iso-8859-11", "windows-874"),
95 96

	/* Central European */
97 98 99 100 101 102 103 104
	LANG_ENCODINGS ("hu",      "iso-8859-2", "windows-1250"),          /* Hungarian */
	LANG_ENCODINGS ("cs",      "iso-8859-2", "windows-1250"),          /* Czech */
	LANG_ENCODINGS ("hr",      "iso-8859-2", "windows-1250"),          /* Croatian */
	LANG_ENCODINGS ("pl",      "iso-8859-2", "windows-1250"),          /* Polish */
	LANG_ENCODINGS ("ro",      "iso-8859-2", "windows-1250"),          /* Romanian */
	LANG_ENCODINGS ("sk",      "iso-8859-2", "windows-1250"),          /* Slovakian */
	LANG_ENCODINGS ("sl",      "iso-8859-2", "windows-1250"),          /* Slovenian */
	LANG_ENCODINGS ("sh",      "iso-8859-2", "windows-1250"),          /* Serbo-Croatian */
105 106

	/* Cyrillic */
107 108 109 110 111 112
	LANG_ENCODINGS ("ru",      "koi8-r", "windows-1251","iso-8859-5"), /* Russian */
	LANG_ENCODINGS ("be",      "koi8-r", "windows-1251","iso-8859-5"), /* Belorussian */
	LANG_ENCODINGS ("bg",      "windows-1251","koi8-r", "iso-8859-5"), /* Bulgarian */
	LANG_ENCODINGS ("mk",      "koi8-r", "windows-1251", "iso-8859-5"),/* Macedonian */
	LANG_ENCODINGS ("sr",      "koi8-r", "windows-1251", "iso-8859-5"),/* Serbian */
	LANG_ENCODINGS ("uk",      "koi8-u", "koi8-r", "windows-1251"),    /* Ukranian */
113 114

	/* Arabic */
115
	LANG_ENCODINGS ("ar",      "iso-8859-6","windows-1256"),
116 117

	/* Baltic */
118 119 120
	LANG_ENCODINGS ("et",      "iso-8859-4", "windows-1257"),          /* Estonian */
	LANG_ENCODINGS ("lt",      "iso-8859-4", "windows-1257"),          /* Lithuanian */
	LANG_ENCODINGS ("lv",      "iso-8859-4", "windows-1257"),          /* Latvian */
121 122

	/* Greek */
123
	LANG_ENCODINGS ("el",      "iso-8859-7","windows-1253"),
124 125

	/* Hebrew */
126 127
	LANG_ENCODINGS ("he",      "iso-8859-8", "windows-1255"),
	LANG_ENCODINGS ("iw",      "iso-8859-8", "windows-1255"),
128 129

	/* Turkish */
130
	LANG_ENCODINGS ("tr",      "iso-8859-9", "windows-1254"),
131 132

	/* Table end */
133
	LANG_ENCODINGS (NULL, NULL)
134 135 136 137 138 139 140 141 142 143 144 145 146 147
};


static GHashTable * langToEncodings5 = NULL;
static GHashTable * langToEncodings2 = NULL;

static void
init_lang_to_encodings_hash (void)
{
	struct IsoLangToEncodings *enc;

	if (G_UNLIKELY (langToEncodings5 == NULL)) {
		/* Five-letter codes */
		enc = (struct IsoLangToEncodings *) &isoLangEntries5[0];
148
		langToEncodings5 = g_hash_table_new (nm_str_hash, g_str_equal);
149 150
		while (enc->lang) {
			g_hash_table_insert (langToEncodings5, (gpointer) enc->lang,
151
			                     (gpointer) enc->encodings);
152 153 154 155 156 157 158
			enc++;
		}
	}

	if (G_UNLIKELY (langToEncodings2 == NULL)) {
		/* Two-letter codes */
		enc = (struct IsoLangToEncodings *) &isoLangEntries2[0];
159
		langToEncodings2 = g_hash_table_new (nm_str_hash, g_str_equal);
160 161
		while (enc->lang) {
			g_hash_table_insert (langToEncodings2, (gpointer) enc->lang,
162
			                     (gpointer) enc->encodings);
163 164 165 166 167 168
			enc++;
		}
	}
}

static gboolean
169
get_encodings_for_lang (const char *lang, const char *const **encodings)
170
{
171
	gs_free char *tmp_lang = NULL;
172

173 174
	g_return_val_if_fail (lang, FALSE);
	g_return_val_if_fail (encodings, FALSE);
175 176 177

	init_lang_to_encodings_hash ();

178 179
	if ((*encodings = g_hash_table_lookup (langToEncodings5, lang)))
		return TRUE;
180 181

	/* Truncate tmp_lang to length of 2 */
182 183
	if (strlen (lang) > 2) {
		tmp_lang = g_strdup (lang);
184
		tmp_lang[2] = '\0';
185 186 187 188 189 190 191 192 193 194 195 196
		if ((*encodings = g_hash_table_lookup (langToEncodings2, tmp_lang)))
			return TRUE;
	}

	return FALSE;
}

static const char *const *
get_system_encodings (void)
{
	static const char *const *cached_encodings;
	static char *default_encodings[4];
197
	const char *const *encodings = NULL;
198 199 200 201 202
	char *lang;

	if (cached_encodings)
		return cached_encodings;

203 204 205 206 207 208 209
	/* Use environment variables as encoding hint */
	lang = getenv ("LC_ALL");
	if (!lang)
		lang = getenv ("LC_CTYPE");
	if (!lang)
		lang = getenv ("LANG");
	if (lang) {
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224
		char *dot;

		lang = g_ascii_strdown (lang, -1);
		if ((dot = strchr (lang, '.')))
			*dot = '\0';

		get_encodings_for_lang (lang, &encodings);
		g_free (lang);
	}
	if (!encodings) {
		g_get_charset ((const char **) &default_encodings[0]);
		default_encodings[1] = "iso-8859-1";
		default_encodings[2] = "windows-1251";
		default_encodings[3] = NULL;
		encodings = (const char *const *) default_encodings;
225 226
	}

227 228
	cached_encodings = encodings;
	return cached_encodings;
229 230
}

Dan Winship's avatar
Dan Winship committed
231
/* init libnm */
232

233 234
static gboolean initialized = FALSE;

235
static void __attribute__((constructor))
236
_nm_utils_init (void)
237 238 239 240
{
	GModule *self;
	gpointer func;

241 242 243 244
	if (initialized)
		return;
	initialized = TRUE;

245 246 247 248 249
	self = g_module_open (NULL, 0);
	if (g_module_symbol (self, "nm_util_get_private", &func))
		g_error ("libnm-util symbols detected; Mixing libnm with libnm-util/libnm-glib is not supported");
	g_module_close (self);

250 251
	bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
252

253
	nm_g_type_init ();
254

255
	_nm_dbus_errors_init ();
256 257
}

258 259
gboolean _nm_utils_is_manager_process;

260 261 262 263
/* ssid helpers */

/**
 * nm_utils_ssid_to_utf8:
264
 * @ssid: (array length=len): pointer to a buffer containing the SSID data
265
 * @len: length of the SSID data in @ssid
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
 *
 * Wi-Fi SSIDs are byte arrays, they are _not_ strings.  Thus, an SSID may
 * contain embedded NULLs and other unprintable characters.  Often it is
 * useful to print the SSID out for debugging purposes, but that should be the
 * _only_ use of this function.  Do not use this function for any persistent
 * storage of the SSID, since the printable SSID returned from this function
 * cannot be converted back into the real SSID of the access point.
 *
 * This function does almost everything humanly possible to convert the input
 * into a printable UTF-8 string, using roughly the following procedure:
 *
 * 1) if the input data is already UTF-8 safe, no conversion is performed
 * 2) attempts to get the current system language from the LANG environment
 *    variable, and depending on the language, uses a table of alternative
 *    encodings to try.  For example, if LANG=hu_HU, the table may first try
 *    the ISO-8859-2 encoding, and if that fails, try the Windows-1250 encoding.
 *    If all fallback encodings fail, replaces non-UTF-8 characters with '?'.
 * 3) If the system language was unable to be determined, falls back to the
 *    ISO-8859-1 encoding, then to the Windows-1251 encoding.
 * 4) If step 3 fails, replaces non-UTF-8 characters with '?'.
 *
 * Again, this function should be used for debugging and display purposes
 * _only_.
 *
 * Returns: (transfer full): an allocated string containing a UTF-8
 * representation of the SSID, which must be freed by the caller using g_free().
 * Returns %NULL on errors.
 **/
char *
295
nm_utils_ssid_to_utf8 (const guint8 *ssid, gsize len)
296
{
297 298
	const char *const *encodings;
	const char *const *e;
299 300 301 302
	char *converted = NULL;

	g_return_val_if_fail (ssid != NULL, NULL);

303 304
	if (g_utf8_validate ((const gchar *) ssid, len, NULL))
		return g_strndup ((const gchar *) ssid, len);
305

306
	encodings = get_system_encodings ();
307

308 309 310 311
	for (e = encodings; *e; e++) {
		converted = g_convert ((const gchar *) ssid, len, "UTF-8", *e, NULL, NULL, NULL);
		if (converted)
			break;
312 313 314
	}

	if (!converted) {
315
		converted = g_convert_with_fallback ((const gchar *) ssid, len,
316
		                                     "UTF-8", encodings[0], "?", NULL, NULL, NULL);
317 318
	}

319 320 321 322 323 324 325 326 327 328 329
	if (!converted) {
		/* If there is still no converted string, the SSID probably
		 * contains characters not valid in the current locale. Convert
		 * the string to ASCII instead.
		 */

		/* Use the printable range of 0x20-0x7E */
		gchar *valid_chars = " !\"#$%&'()*+,-./0123456789:;<=>?@"
		                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"
		                     "abcdefghijklmnopqrstuvwxyz{|}~";

330
		converted = g_strndup ((const char *) ssid, len);
331 332 333
		g_strcanon (converted, valid_chars, '?');
	}

334 335 336 337 338 339
	return converted;
}

/* Shamelessly ripped from the Linux kernel ieee80211 stack */
/**
 * nm_utils_is_empty_ssid:
340
 * @ssid: (array length=len): pointer to a buffer containing the SSID data
341 342 343 344 345 346 347 348 349
 * @len: length of the SSID data in @ssid
 *
 * Different manufacturers use different mechanisms for not broadcasting the
 * AP's SSID.  This function attempts to detect blank/empty SSIDs using a
 * number of known SSID-cloaking methods.
 *
 * Returns: %TRUE if the SSID is "empty", %FALSE if it is not
 **/
gboolean
350
nm_utils_is_empty_ssid (const guint8 *ssid, gsize len)
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367
{
	/* Single white space is for Linksys APs */
	if (len == 1 && ssid[0] == ' ')
		return TRUE;

	/* Otherwise, if the entire ssid is 0, we assume it is hidden */
	while (len--) {
		if (ssid[len] != '\0')
			return FALSE;
	}
	return TRUE;
}

#define ESSID_MAX_SIZE 32

/**
 * nm_utils_escape_ssid:
368
 * @ssid: (array length=len): pointer to a buffer containing the SSID data
369 370 371 372 373 374 375 376 377 378 379
 * @len: length of the SSID data in @ssid
 *
 * This function does a quick printable character conversion of the SSID, simply
 * replacing embedded NULLs and non-printable characters with the hexadecimal
 * representation of that character.  Intended for debugging only, should not
 * be used for display of SSIDs.
 *
 * Returns: pointer to the escaped SSID, which uses an internal static buffer
 * and will be overwritten by subsequent calls to this function
 **/
const char *
380
nm_utils_escape_ssid (const guint8 *ssid, gsize len)
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
{
	static char escaped[ESSID_MAX_SIZE * 2 + 1];
	const guint8 *s = ssid;
	char *d = escaped;

	if (nm_utils_is_empty_ssid (ssid, len)) {
		memcpy (escaped, "<hidden>", sizeof ("<hidden>"));
		return escaped;
	}

	len = MIN (len, (guint32) ESSID_MAX_SIZE);
	while (len--) {
		if (*s == '\0') {
			*d++ = '\\';
			*d++ = '0';
			s++;
		} else {
			*d++ = *s++;
		}
	}
	*d = '\0';
	return escaped;
}

/**
 * nm_utils_same_ssid:
407
 * @ssid1: (array length=len1): the first SSID to compare
408
 * @len1: length of the SSID data in @ssid1
409
 * @ssid2: (array length=len2): the second SSID to compare
410
 * @len2: length of the SSID data in @ssid2
411 412 413 414 415 416 417 418 419 420 421 422
 * @ignore_trailing_null: %TRUE to ignore one trailing NULL byte
 *
 * Earlier versions of the Linux kernel added a NULL byte to the end of the
 * SSID to enable easy printing of the SSID on the console or in a terminal,
 * but this behavior was problematic (SSIDs are simply byte arrays, not strings)
 * and thus was changed.  This function compensates for that behavior at the
 * cost of some compatibility with odd SSIDs that may legitimately have trailing
 * NULLs, even though that is functionally pointless.
 *
 * Returns: %TRUE if the SSIDs are the same, %FALSE if they are not
 **/
gboolean
423 424
nm_utils_same_ssid (const guint8 *ssid1, gsize len1,
                    const guint8 *ssid2, gsize len2,
425 426
                    gboolean ignore_trailing_null)
{
427 428
	g_return_val_if_fail (ssid1 != NULL || len1 == 0, FALSE);
	g_return_val_if_fail (ssid2 != NULL || len2 == 0, FALSE);
429

430
	if (ssid1 == ssid2 && len1 == len2)
431 432 433 434
		return TRUE;
	if (!ssid1 || !ssid2)
		return FALSE;

435 436 437 438 439
	if (ignore_trailing_null) {
		if (len1 && ssid1[len1 - 1] == '\0')
			len1--;
		if (len2 && ssid2[len2 - 1] == '\0')
			len2--;
440 441
	}

442
	if (len1 != len2)
443 444
		return FALSE;

445
	return memcmp (ssid1, ssid2, len1) == 0 ? TRUE : FALSE;
446 447 448 449 450 451 452 453
}

gboolean
_nm_utils_string_slist_validate (GSList *list, const char **valid_values)
{
	GSList *iter;

	for (iter = list; iter; iter = iter->next) {
454
		if (!g_strv_contains (valid_values, (char *) iter->data))
455 456 457 458 459 460
			return FALSE;
	}

	return TRUE;
}

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
/**
 * _nm_utils_hash_values_to_slist:
 * @hash: a #GHashTable
 *
 * Utility function to iterate over a hash table and return
 * it's values as a #GSList.
 *
 * Returns: (element-type gpointer) (transfer container): a newly allocated #GSList
 * containing the values of the hash table. The caller must free the
 * returned list with g_slist_free(). The hash values are not owned
 * by the returned list.
 **/
GSList *
_nm_utils_hash_values_to_slist (GHashTable *hash)
{
	GSList *list = NULL;
	GHashTableIter iter;
	void *value;

	g_return_val_if_fail (hash, NULL);

	g_hash_table_iter_init (&iter, hash);
	while (g_hash_table_iter_next (&iter, NULL, &value))
		 list = g_slist_prepend (list, value);

	return list;
}

489 490
GVariant *
_nm_utils_strdict_to_dbus (const GValue *prop_value)
491
{
492 493
	GHashTable *hash;
	GHashTableIter iter;
494
	const char *key, *value;
495
	GVariantBuilder builder;
496
	guint i, len;
497 498

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{ss}"));
499

500
	hash = g_value_get_boxed (prop_value);
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
	if (!hash)
		goto out;
	len = g_hash_table_size (hash);
	if (!len)
		goto out;

	g_hash_table_iter_init (&iter, hash);
	if (!g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value))
		nm_assert_not_reached ();

	if (len == 1)
		g_variant_builder_add (&builder, "{ss}", key, value);
	else {
		gs_free NMUtilsNamedValue *idx = NULL;

		idx = g_new (NMUtilsNamedValue, len);
		i = 0;
		do {
			idx[i].name = key;
			idx[i].value_str = value;
			i++;
		} while (g_hash_table_iter_next (&iter, (gpointer *) &key, (gpointer *) &value));
		nm_assert (i == len);

		g_qsort_with_data (idx, len, sizeof (idx[0]),
		                   nm_utils_named_entry_cmp_with_data, NULL);

		for (i = 0; i < len; i++)
			g_variant_builder_add (&builder, "{ss}", idx[i].name, idx[i].value_str);
530 531
	}

532
out:
533
	return g_variant_builder_end (&builder);
534 535 536
}

void
537
_nm_utils_strdict_from_dbus (GVariant *dbus_value,
538 539
                             GValue *prop_value)
{
540 541 542 543
	GVariantIter iter;
	const char *key, *value;
	GHashTable *hash;

544
	hash = g_hash_table_new_full (nm_str_hash, g_str_equal, g_free, g_free);
545 546 547 548 549
	g_variant_iter_init (&iter, dbus_value);
	while (g_variant_iter_next (&iter, "{&s&s}", &key, &value))
		g_hash_table_insert (hash, g_strdup (key), g_strdup (value));

	g_value_take_boxed (prop_value, hash);
550 551 552 553 554 555 556 557 558
}

GHashTable *
_nm_utils_copy_strdict (GHashTable *strdict)
{
	GHashTable *copy;
	GHashTableIter iter;
	gpointer key, value;

559
	copy = g_hash_table_new_full (nm_str_hash, g_str_equal, g_free, g_free);
560 561 562 563 564 565 566 567
	if (strdict) {
		g_hash_table_iter_init (&iter, strdict);
		while (g_hash_table_iter_next (&iter, &key, &value))
			g_hash_table_insert (copy, g_strdup (key), g_strdup (value));
	}
	return copy;
}

568 569 570 571 572 573 574 575 576 577
GPtrArray *
_nm_utils_copy_slist_to_array (const GSList *list,
                               NMUtilsCopyFunc copy_func,
                               GDestroyNotify unref_func)
{
	const GSList *iter;
	GPtrArray *array;

	array = g_ptr_array_new_with_free_func (unref_func);
	for (iter = list; iter; iter = iter->next)
578
		g_ptr_array_add (array, copy_func ? copy_func (iter->data) : iter->data);
579 580 581 582 583 584 585 586 587 588 589
	return array;
}

GSList *
_nm_utils_copy_array_to_slist (const GPtrArray *array,
                               NMUtilsCopyFunc copy_func)
{
	GSList *slist = NULL;
	gpointer item;
	int i;

590 591 592
	if (!array)
		return NULL;

593 594 595 596 597 598 599 600
	for (i = 0; i < array->len; i++) {
		item = array->pdata[i];
		slist = g_slist_prepend (slist, copy_func (item));
	}

	return g_slist_reverse (slist);
}

601 602 603 604 605 606 607 608
GPtrArray *
_nm_utils_copy_array (const GPtrArray *array,
                      NMUtilsCopyFunc copy_func,
                      GDestroyNotify free_func)
{
	GPtrArray *copy;
	int i;

609 610 611
	if (!array)
		return g_ptr_array_new_with_free_func (free_func);

612 613 614 615 616 617 618 619 620 621 622 623
	copy = g_ptr_array_new_full (array->len, free_func);
	for (i = 0; i < array->len; i++)
		g_ptr_array_add (copy, copy_func (array->pdata[i]));
	return copy;
}

GPtrArray *
_nm_utils_copy_object_array (const GPtrArray *array)
{
	return _nm_utils_copy_array (array, g_object_ref, g_object_unref);
}

624
gssize
625
_nm_utils_ptrarray_find_first (gconstpointer *list, gssize len, gconstpointer needle)
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
{
	gssize i;

	if (len == 0)
		return -1;

	if (len > 0) {
		g_return_val_if_fail (list, -1);
		for (i = 0; i < len; i++) {
			if (list[i] == needle)
				return i;
		}
	} else {
		g_return_val_if_fail (needle, -1);
		for (i = 0; list && list[i]; i++) {
			if (list[i] == needle)
				return i;
		}
	}
	return -1;
}

648
gssize
649 650 651 652 653 654 655
_nm_utils_ptrarray_find_binary_search (gconstpointer *list,
                                       gsize len,
                                       gconstpointer needle,
                                       GCompareDataFunc cmpfcn,
                                       gpointer user_data,
                                       gssize *out_idx_first,
                                       gssize *out_idx_last)
656
{
657
	gssize imin, imax, imid, i2min, i2max, i2mid;
658 659 660 661 662 663
	int cmp;

	g_return_val_if_fail (list || !len, ~((gssize) 0));
	g_return_val_if_fail (cmpfcn, ~((gssize) 0));

	imin = 0;
664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716
	if (len > 0) {
		imax = len - 1;

		while (imin <= imax) {
			imid = imin + (imax - imin) / 2;

			cmp = cmpfcn (list[imid], needle, user_data);
			if (cmp == 0) {
				/* we found a matching entry at index imid.
				 *
				 * Does the caller request the first/last index as well (in case that
				 * there are multiple entries which compare equal). */

				if (out_idx_first) {
					i2min = imin;
					i2max = imid + 1;
					while (i2min <= i2max) {
						i2mid = i2min + (i2max - i2min) / 2;

						cmp = cmpfcn (list[i2mid], needle, user_data);
						if (cmp == 0)
							i2max = i2mid -1;
						else {
							nm_assert (cmp < 0);
							i2min = i2mid + 1;
						}
					}
					*out_idx_first = i2min;
				}
				if (out_idx_last) {
					i2min = imid + 1;
					i2max = imax;
					while (i2min <= i2max) {
						i2mid = i2min + (i2max - i2min) / 2;

						cmp = cmpfcn (list[i2mid], needle, user_data);
						if (cmp == 0)
							i2min = i2mid + 1;
						else {
							nm_assert (cmp > 0);
							i2max = i2mid - 1;
						}
					}
					*out_idx_last = i2min - 1;
				}
				return imid;
			}

			if (cmp < 0)
				imin = imid + 1;
			else
				imax = imid - 1;
		}
717 718 719 720
	}

	/* return the inverse of @imin. This is a negative number, but
	 * also is ~imin the position where the value should be inserted. */
721 722 723 724
	imin = ~imin;
	NM_SET_OUT (out_idx_first, imin);
	NM_SET_OUT (out_idx_last, imin);
	return imin;
725 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 751 752 753 754 755 756 757 758 759 760
gssize
_nm_utils_array_find_binary_search (gconstpointer list, gsize elem_size, gsize len, gconstpointer needle, GCompareDataFunc cmpfcn, gpointer user_data)
{
	gssize imin, imax, imid;
	int cmp;

	g_return_val_if_fail (list || !len, ~((gssize) 0));
	g_return_val_if_fail (cmpfcn, ~((gssize) 0));
	g_return_val_if_fail (elem_size > 0, ~((gssize) 0));

	imin = 0;
	if (len == 0)
		return ~imin;

	imax = len - 1;

	while (imin <= imax) {
		imid = imin + (imax - imin) / 2;

		cmp = cmpfcn (&((const char *) list)[elem_size * imid], needle, user_data);
		if (cmp == 0)
			return imid;

		if (cmp < 0)
			imin = imid + 1;
		else
			imax = imid - 1;
	}

	/* return the inverse of @imin. This is a negative number, but
	 * also is ~imin the position where the value should be inserted. */
	return ~imin;
}

761 762
GVariant *
_nm_utils_bytes_to_dbus (const GValue *prop_value)
763 764 765 766
{
	GBytes *bytes = g_value_get_boxed (prop_value);

	if (bytes) {
767 768 769 770 771 772 773 774
		return g_variant_new_fixed_array (G_VARIANT_TYPE_BYTE,
		                                  g_bytes_get_data (bytes, NULL),
		                                  g_bytes_get_size (bytes),
		                                  1);
	} else {
		return g_variant_new_fixed_array (G_VARIANT_TYPE_BYTE,
		                                  NULL, 0,
		                                  1);
775 776 777 778
	}
}

void
779
_nm_utils_bytes_from_dbus (GVariant *dbus_value,
780 781
                           GValue *prop_value)
{
782
	GBytes *bytes;
783

784 785 786 787 788 789 790 791
	if (g_variant_n_children (dbus_value)) {
		gconstpointer data;
		gsize length;

		data = g_variant_get_fixed_array (dbus_value, &length, 1);
		bytes = g_bytes_new (data, length);
	} else
		bytes = NULL;
792 793 794
	g_value_take_boxed (prop_value, bytes);
}

795
GSList *
796
_nm_utils_strv_to_slist (char **strv, gboolean deep_copy)
797 798 799 800
{
	int i;
	GSList *list = NULL;

801
	if (strv) {
802 803 804 805 806 807 808
		if (deep_copy) {
			for (i = 0; strv[i]; i++)
				list = g_slist_prepend (list, g_strdup (strv[i]));
		} else {
			for (i = 0; strv[i]; i++)
				list = g_slist_prepend (list, strv[i]);
		}
809
	}
810 811 812 813 814

	return g_slist_reverse (list);
}

char **
815
_nm_utils_slist_to_strv (GSList *slist, gboolean deep_copy)
816 817 818
{
	GSList *iter;
	char **strv;
819
	int len, i;
820 821

	len = g_slist_length (slist);
822 823
	if (!len)
		return NULL;
824 825
	strv = g_new (char *, len + 1);

826 827 828 829 830 831 832
	if (deep_copy) {
		for (i = 0, iter = slist; iter; iter = iter->next, i++)
			strv[i] = g_strdup (iter->data);
	} else {
		for (i = 0, iter = slist; iter; iter = iter->next, i++)
			strv[i] = iter->data;
	}
833 834 835 836 837
	strv[i] = NULL;

	return strv;
}

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
GPtrArray *
_nm_utils_strv_to_ptrarray (char **strv)
{
	GPtrArray *ptrarray;
	int i;

	ptrarray = g_ptr_array_new_with_free_func (g_free);

	if (strv) {
		for (i = 0; strv[i]; i++)
			g_ptr_array_add (ptrarray, g_strdup (strv[i]));
	}

	return ptrarray;
}

char **
_nm_utils_ptrarray_to_strv (GPtrArray *ptrarray)
{
	char **strv;
	int i;

	if (!ptrarray)
		return g_new0 (char *, 1);

	strv = g_new (char *, ptrarray->len + 1);

	for (i = 0; i < ptrarray->len; i++)
		strv[i] = g_strdup (ptrarray->pdata[i]);
	strv[i] = NULL;

	return strv;
}

872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
/**
 * _nm_utils_strv_equal:
 * @strv1: a string array
 * @strv2: a string array
 *
 * Compare NULL-terminated string arrays for equality.
 *
 * Returns: %TRUE if the arrays are equal, %FALSE otherwise.
 **/
gboolean
_nm_utils_strv_equal (char **strv1, char **strv2)
{
	if (strv1 == strv2)
		return TRUE;

	if (!strv1 || !strv2)
		return FALSE;

	for ( ; *strv1 && *strv2 && !strcmp (*strv1, *strv2); strv1++, strv2++)
		;

	return !*strv1 && !*strv2;
}

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 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 1035 1036 1037
static gboolean
device_supports_ap_ciphers (guint32 dev_caps,
                            guint32 ap_flags,
                            gboolean static_wep)
{
	gboolean have_pair = FALSE;
	gboolean have_group = FALSE;
	/* Device needs to support at least one pairwise and one group cipher */

	/* Pairwise */
	if (static_wep) {
		/* Static WEP only uses group ciphers */
		have_pair = TRUE;
	} else {
		if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_WEP40)
			if (ap_flags & NM_802_11_AP_SEC_PAIR_WEP40)
				have_pair = TRUE;
		if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_WEP104)
			if (ap_flags & NM_802_11_AP_SEC_PAIR_WEP104)
				have_pair = TRUE;
		if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_TKIP)
			if (ap_flags & NM_802_11_AP_SEC_PAIR_TKIP)
				have_pair = TRUE;
		if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_CCMP)
			if (ap_flags & NM_802_11_AP_SEC_PAIR_CCMP)
				have_pair = TRUE;
	}

	/* Group */
	if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_WEP40)
		if (ap_flags & NM_802_11_AP_SEC_GROUP_WEP40)
			have_group = TRUE;
	if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_WEP104)
		if (ap_flags & NM_802_11_AP_SEC_GROUP_WEP104)
			have_group = TRUE;
	if (!static_wep) {
		if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_TKIP)
			if (ap_flags & NM_802_11_AP_SEC_GROUP_TKIP)
				have_group = TRUE;
		if (dev_caps & NM_WIFI_DEVICE_CAP_CIPHER_CCMP)
			if (ap_flags & NM_802_11_AP_SEC_GROUP_CCMP)
				have_group = TRUE;
	}

	return (have_pair && have_group);
}

/**
 * nm_utils_ap_mode_security_valid:
 * @type: the security type to check device capabilties against,
 * e.g. #NMU_SEC_STATIC_WEP
 * @wifi_caps: bitfield of the capabilities of the specific Wi-Fi device, e.g.
 * #NM_WIFI_DEVICE_CAP_CIPHER_WEP40
 *
 * Given a set of device capabilities, and a desired security type to check
 * against, determines whether the combination of device capabilities and
 * desired security type are valid for AP/Hotspot connections.
 *
 * Returns: %TRUE if the device capabilities are compatible with the desired
 * @type, %FALSE if they are not.
 **/
gboolean
nm_utils_ap_mode_security_valid (NMUtilsSecurityType type,
                                 NMDeviceWifiCapabilities wifi_caps)
{
	if (!(wifi_caps & NM_WIFI_DEVICE_CAP_AP))
		return FALSE;

	/* Return TRUE for any security that wpa_supplicant's lightweight AP
	 * mode can handle: which is open, WEP, and WPA/WPA2 PSK.
	 */
	switch (type) {
	case NMU_SEC_NONE:
	case NMU_SEC_STATIC_WEP:
	case NMU_SEC_WPA_PSK:
	case NMU_SEC_WPA2_PSK:
		return TRUE;
	default:
		break;
	}
	return FALSE;
}

/**
 * nm_utils_security_valid:
 * @type: the security type to check AP flags and device capabilties against,
 * e.g. #NMU_SEC_STATIC_WEP
 * @wifi_caps: bitfield of the capabilities of the specific Wi-Fi device, e.g.
 * #NM_WIFI_DEVICE_CAP_CIPHER_WEP40
 * @have_ap: whether the @ap_flags, @ap_wpa, and @ap_rsn arguments are valid
 * @adhoc: whether the capabilities being tested are from an Ad-Hoc AP (IBSS)
 * @ap_flags: bitfield of AP capabilities, e.g. #NM_802_11_AP_FLAGS_PRIVACY
 * @ap_wpa: bitfield of AP capabilties derived from the AP's WPA beacon,
 * e.g. (#NM_802_11_AP_SEC_PAIR_TKIP | #NM_802_11_AP_SEC_KEY_MGMT_PSK)
 * @ap_rsn: bitfield of AP capabilties derived from the AP's RSN/WPA2 beacon,
 * e.g. (#NM_802_11_AP_SEC_PAIR_CCMP | #NM_802_11_AP_SEC_PAIR_TKIP)
 *
 * Given a set of device capabilities, and a desired security type to check
 * against, determines whether the combination of device, desired security
 * type, and AP capabilities intersect.
 *
 * NOTE: this function cannot handle checking security for AP/Hotspot mode;
 * use nm_utils_ap_mode_security_valid() instead.
 *
 * Returns: %TRUE if the device capabilities and AP capabilties intersect and are
 * compatible with the desired @type, %FALSE if they are not
 **/
gboolean
nm_utils_security_valid (NMUtilsSecurityType type,
                         NMDeviceWifiCapabilities wifi_caps,
                         gboolean have_ap,
                         gboolean adhoc,
                         NM80211ApFlags ap_flags,
                         NM80211ApSecurityFlags ap_wpa,
                         NM80211ApSecurityFlags ap_rsn)
{
	gboolean good = TRUE;

	if (!have_ap) {
		if (type == NMU_SEC_NONE)
			return TRUE;
		if (   (type == NMU_SEC_STATIC_WEP)
		    || ((type == NMU_SEC_DYNAMIC_WEP) && !adhoc)
		    || ((type == NMU_SEC_LEAP) && !adhoc)) {
			if (wifi_caps & (NM_WIFI_DEVICE_CAP_CIPHER_WEP40 | NM_WIFI_DEVICE_CAP_CIPHER_WEP104))
				return TRUE;
			else
				return FALSE;
		}
	}

	switch (type) {
	case NMU_SEC_NONE:
		g_assert (have_ap);
		if (ap_flags & NM_802_11_AP_FLAGS_PRIVACY)
			return FALSE;
		if (ap_wpa || ap_rsn)
			return FALSE;
		break;
	case NMU_SEC_LEAP: /* require PRIVACY bit for LEAP? */
		if (adhoc)
			return FALSE;
1038
		/* fall through */
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 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 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 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
	case NMU_SEC_STATIC_WEP:
		g_assert (have_ap);
		if (!(ap_flags & NM_802_11_AP_FLAGS_PRIVACY))
			return FALSE;
		if (ap_wpa || ap_rsn) {
			if (!device_supports_ap_ciphers (wifi_caps, ap_wpa, TRUE))
				if (!device_supports_ap_ciphers (wifi_caps, ap_rsn, TRUE))
					return FALSE;
		}
		break;
	case NMU_SEC_DYNAMIC_WEP:
		if (adhoc)
			return FALSE;
		g_assert (have_ap);
		if (ap_rsn || !(ap_flags & NM_802_11_AP_FLAGS_PRIVACY))
			return FALSE;
		/* Some APs broadcast minimal WPA-enabled beacons that must be handled */
		if (ap_wpa) {
			if (!(ap_wpa & NM_802_11_AP_SEC_KEY_MGMT_802_1X))
				return FALSE;
			if (!device_supports_ap_ciphers (wifi_caps, ap_wpa, FALSE))
				return FALSE;
		}
		break;
	case NMU_SEC_WPA_PSK:
		if (adhoc)
			return FALSE;  /* FIXME: Kernel WPA Ad-Hoc support is buggy */
		if (!(wifi_caps & NM_WIFI_DEVICE_CAP_WPA))
			return FALSE;
		if (have_ap) {
			/* Ad-Hoc WPA APs won't necessarily have the PSK flag set, and
			 * they don't have any pairwise ciphers. */
			if (adhoc) {
				/* coverity[dead_error_line] */
				if (   (ap_wpa & NM_802_11_AP_SEC_GROUP_TKIP)
				    && (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_TKIP))
					return TRUE;
				if (   (ap_wpa & NM_802_11_AP_SEC_GROUP_CCMP)
				    && (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_CCMP))
					return TRUE;
			} else {
				if (ap_wpa & NM_802_11_AP_SEC_KEY_MGMT_PSK) {
					if (   (ap_wpa & NM_802_11_AP_SEC_PAIR_TKIP)
					    && (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_TKIP))
						return TRUE;
					if (   (ap_wpa & NM_802_11_AP_SEC_PAIR_CCMP)
					    && (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_CCMP))
						return TRUE;
				}
			}
			return FALSE;
		}
		break;
	case NMU_SEC_WPA2_PSK:
		if (adhoc)
			return FALSE;  /* FIXME: Kernel WPA Ad-Hoc support is buggy */
		if (!(wifi_caps & NM_WIFI_DEVICE_CAP_RSN))
			return FALSE;
		if (have_ap) {
			/* Ad-Hoc WPA APs won't necessarily have the PSK flag set, and
			 * they don't have any pairwise ciphers, nor any RSA flags yet. */
			if (adhoc) {
				/* coverity[dead_error_line] */
				if (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_TKIP)
					return TRUE;
				if (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_CCMP)
					return TRUE;
			} else {
				if (ap_rsn & NM_802_11_AP_SEC_KEY_MGMT_PSK) {
					if (   (ap_rsn & NM_802_11_AP_SEC_PAIR_TKIP)
					    && (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_TKIP))
						return TRUE;
					if (   (ap_rsn & NM_802_11_AP_SEC_PAIR_CCMP)
					    && (wifi_caps & NM_WIFI_DEVICE_CAP_CIPHER_CCMP))
						return TRUE;
				}
			}
			return FALSE;
		}
		break;
	case NMU_SEC_WPA_ENTERPRISE:
		if (adhoc)
			return FALSE;
		if (!(wifi_caps & NM_WIFI_DEVICE_CAP_WPA))
			return FALSE;
		if (have_ap) {
			if (!(ap_wpa & NM_802_11_AP_SEC_KEY_MGMT_802_1X))
				return FALSE;
			/* Ensure at least one WPA cipher is supported */
			if (!device_supports_ap_ciphers (wifi_caps, ap_wpa, FALSE))
				return FALSE;
		}
		break;
	case NMU_SEC_WPA2_ENTERPRISE:
		if (adhoc)
			return FALSE;
		if (!(wifi_caps & NM_WIFI_DEVICE_CAP_RSN))
			return FALSE;
		if (have_ap) {
			if (!(ap_rsn & NM_802_11_AP_SEC_KEY_MGMT_802_1X))
				return FALSE;
			/* Ensure at least one WPA cipher is supported */
			if (!device_supports_ap_ciphers (wifi_caps, ap_rsn, FALSE))
				return FALSE;
		}
		break;
	default:
		good = FALSE;
		break;
	}

	return good;
}

/**
 * nm_utils_wep_key_valid:
 * @key: a string that might be a WEP key
 * @wep_type: the #NMWepKeyType type of the WEP key
 *
 * Checks if @key is a valid WEP key
 *
 * Returns: %TRUE if @key is a WEP key, %FALSE if not
 */
gboolean
nm_utils_wep_key_valid (const char *key, NMWepKeyType wep_type)
{
	int keylen, i;

	if (!key)
		return FALSE;

1170 1171 1172 1173 1174
	if (wep_type == NM_WEP_KEY_TYPE_UNKNOWN) {
		return nm_utils_wep_key_valid (key, NM_WEP_KEY_TYPE_KEY) ||
		       nm_utils_wep_key_valid (key, NM_WEP_KEY_TYPE_PASSPHRASE);
	}

1175
	keylen = strlen (key);
1176
	if (wep_type == NM_WEP_KEY_TYPE_KEY) {
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
		if (keylen == 10 || keylen == 26) {
			/* Hex key */
			for (i = 0; i < keylen; i++) {
				if (!g_ascii_isxdigit (key[i]))
					return FALSE;
			}
		} else if (keylen == 5 || keylen == 13) {
			/* ASCII key */
			for (i = 0; i < keylen; i++) {
				if (!g_ascii_isprint (key[i]))
					return FALSE;
			}
		} else
			return FALSE;
	} else if (wep_type == NM_WEP_KEY_TYPE_PASSPHRASE) {
		if (!keylen || keylen > 64)
			return FALSE;
	}

	return TRUE;
}

/**
 * nm_utils_wpa_psk_valid:
 * @psk: a string that might be a WPA PSK
 *
 * Checks if @psk is a valid WPA PSK
 *
 * Returns: %TRUE if @psk is a WPA PSK, %FALSE if not
 */
gboolean
nm_utils_wpa_psk_valid (const char *psk)
{
	int psklen, i;

	if (!psk)
		return FALSE;

	psklen = strlen (psk);
	if (psklen < 8 || psklen > 64)
		return FALSE;

	if (psklen == 64) {
		/* Hex PSK */
		for (i = 0; i < psklen; i++) {
			if (!g_ascii_isxdigit (psk[i]))
				return FALSE;
		}
	}

	return TRUE;
}

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
/**
 * nm_utils_ip4_dns_to_variant:
 * @dns: (type utf8): an array of IP address strings
 *
 * Utility function to convert an array of IP address strings int a #GVariant of
 * type 'au' representing an array of IPv4 addresses.
 *
 * Returns: (transfer none): a new floating #GVariant representing @dns.
 **/
GVariant *
nm_utils_ip4_dns_to_variant (char **dns)
{
	GVariantBuilder builder;
	int i;

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("au"));

	if (dns) {
		for (i = 0; dns[i]; i++) {
			guint32 ip = 0;

			inet_pton (AF_INET, dns[i], &ip);
			g_variant_builder_add (&builder, "u", ip);
		}
	}

	return g_variant_builder_end (&builder);
}

/**
 * nm_utils_ip4_dns_from_variant:
 * @value: a #GVariant of type 'au'
 *
 * Utility function to convert a #GVariant of type 'au' representing a list of
 * IPv4 addresses into an array of IP address strings.
 *
 * Returns: (transfer full) (type utf8): a %NULL-terminated array of IP address strings.
 **/
char **
nm_utils_ip4_dns_from_variant (GVariant *value)
{
	const guint32 *array;
	gsize length;
	char **dns;
	int i;

	g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("au")), NULL);

	array = g_variant_get_fixed_array (value, &length, sizeof (guint32));
	dns = g_new (char *, length + 1);

	for (i = 0; i < length; i++)
		dns[i] = g_strdup (nm_utils_inet4_ntop (array[i], NULL));
	dns[i] = NULL;

	return dns;
}

/**
 * nm_utils_ip4_addresses_to_variant:
1290
 * @addresses: (element-type NMIPAddress): an array of #NMIPAddress objects
1291
 * @gateway: (allow-none): the gateway IP address
1292
 *
1293 1294 1295
 * Utility function to convert a #GPtrArray of #NMIPAddress objects representing
 * IPv4 addresses into a #GVariant of type 'aau' representing an array of
 * NetworkManager IPv4 addresses (which are tuples of address, prefix, and
1296 1297
 * gateway). The "gateway" field of the first address will get the value of
 * @gateway (if non-%NULL). In all of the other addresses, that field will be 0.
1298 1299 1300 1301
 *
 * Returns: (transfer none): a new floating #GVariant representing @addresses.
 **/
GVariant *
1302
nm_utils_ip4_addresses_to_variant (GPtrArray *addresses, const char *gateway)
1303 1304 1305 1306 1307 1308 1309 1310
{
	GVariantBuilder builder;
	int i;

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("aau"));

	if (addresses) {
		for (i = 0; i < addresses->len; i++) {
1311
			NMIPAddress *addr = addresses->pdata[i];
1312 1313
			guint32 array[3];

1314 1315 1316 1317 1318
			if (nm_ip_address_get_family (addr) != AF_INET)
				continue;

			nm_ip_address_get_address_binary (addr, &array[0]);
			array[1] = nm_ip_address_get_prefix (addr);
1319 1320
			if (i == 0 && gateway)
				inet_pton (AF_INET, gateway, &array[2]);
1321 1322
			else
				array[2] = 0;
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335

			g_variant_builder_add (&builder, "@au",
			                       g_variant_new_fixed_array (G_VARIANT_TYPE_UINT32,
			                                                  array, 3, sizeof (guint32)));
		}
	}

	return g_variant_builder_end (&builder);
}

/**
 * nm_utils_ip4_addresses_from_variant:
 * @value: a #GVariant of type 'aau'
1336
 * @out_gateway: (out) (allow-none) (transfer full): on return, will contain the IP gateway
1337 1338 1339
 *
 * Utility function to convert a #GVariant of type 'aau' representing a list of
 * NetworkManager IPv4 addresses (which are tuples of address, prefix, and
1340 1341 1342
 * gateway) into a #GPtrArray of #NMIPAddress objects. The "gateway" field of
 * the first address (if set) will be returned in @out_gateway; the "gateway" fields
 * of the other addresses are ignored.
1343
 *
1344 1345
 * Returns: (transfer full) (element-type NMIPAddress): a newly allocated
 *   #GPtrArray of #NMIPAddress objects
1346 1347
 **/
GPtrArray *
1348
nm_utils_ip4_addresses_from_variant (GVariant *value, char **out_gateway)
1349 1350 1351 1352 1353 1354 1355
{
	GPtrArray *addresses;
	GVariantIter iter;
	GVariant *addr_var;

	g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("aau")), NULL);

1356 1357 1358
	if (out_gateway)
		*out_gateway = NULL;

1359
	g_variant_iter_init (&iter, value);
1360
	addresses = g_ptr_array_new_with_free_func ((GDestroyNotify) nm_ip_address_unref);
1361 1362 1363 1364

	while (g_variant_iter_next (&iter, "@au", &addr_var)) {
		const guint32 *addr_array;
		gsize length;
1365 1366
		NMIPAddress *addr;
		GError *error = NULL;
1367 1368 1369 1370 1371 1372 1373 1374

		addr_array = g_variant_get_fixed_array (addr_var, &length, sizeof (guint32));
		if (length < 3) {
			g_warning ("Ignoring invalid IP4 address");
			g_variant_unref (addr_var);
			continue;
		}

1375
		addr = nm_ip_address_new_binary (AF_INET, &addr_array[0], addr_array[1], &error);
1376
		if (addr) {
1377
			g_ptr_array_add (addresses, addr);
1378 1379 1380 1381

			if (addr_array[2] && out_gateway && !*out_gateway)
				*out_gateway = g_strdup (nm_utils_inet4_ntop (addr_array[2], NULL));
		} else {
1382 1383 1384
			g_warning ("Ignoring invalid IP4 address: %s", error->message);
			g_clear_error (&error);
		}
1385

1386 1387 1388 1389 1390 1391 1392 1393
		g_variant_unref (addr_var);
	}

	return addresses;
}

/**
 * nm_utils_ip4_routes_to_variant:
1394
 * @routes: (element-type NMIPRoute): an array of #NMIP4Route objects
1395
 *
1396 1397 1398 1399
 * Utility function to convert a #GPtrArray of #NMIPRoute objects representing
 * IPv4 routes into a #GVariant of type 'aau' representing an array of
 * NetworkManager IPv4 routes (which are tuples of route, prefix, next hop, and
 * metric).
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412
 *
 * Returns: (transfer none): a new floating #GVariant representing @routes.
 **/
GVariant *
nm_utils_ip4_routes_to_variant (GPtrArray *routes)
{
	GVariantBuilder builder;
	int i;

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("aau"));

	if (routes) {
		for (i = 0; i < routes->len; i++) {
1413
			NMIPRoute *route = routes->pdata[i];
1414 1415
			guint32 array[4];

1416 1417 1418 1419 1420 1421
			if (nm_ip_route_get_family (route) != AF_INET)
				continue;

			nm_ip_route_get_dest_binary (route, &array[0]);
			array[1] = nm_ip_route_get_prefix (route);
			nm_ip_route_get_next_hop_binary (route, &array[2]);
1422 1423
			/* The old routes format uses "0" for default, not "-1" */
			array[3] = MAX (0, nm_ip_route_get_metric (route));
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

			g_variant_builder_add (&builder, "@au",
			                       g_variant_new_fixed_array (G_VARIANT_TYPE_UINT32,
			                                                  array, 4, sizeof (guint32)));
		}
	}

	return g_variant_builder_end (&builder);
}

/**
 * nm_utils_ip4_routes_from_variant:
 * @value: #GVariant of type 'aau'
 *
 * Utility function to convert a #GVariant of type 'aau' representing an array
 * of NetworkManager IPv4 routes (which are tuples of route, prefix, next hop,
1440
 * and metric) into a #GPtrArray of #NMIPRoute objects.
1441
 *
1442 1443
 * Returns: (transfer full) (element-type NMIPRoute): a newly allocated
 *   #GPtrArray of #NMIPRoute objects
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454
 **/
GPtrArray *
nm_utils_ip4_routes_from_variant (GVariant *value)
{
	GVariantIter iter;
	GVariant *route_var;
	GPtrArray *routes;

	g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("aau")), NULL);

	g_variant_iter_init (&iter, value);
1455
	routes = g_ptr_array_new_with_free_func ((GDestroyNotify) nm_ip_route_unref);
1456 1457 1458 1459

	while (g_variant_iter_next (&iter, "@au", &route_var)) {
		const guint32 *route_array;
		gsize length;
1460 1461
		NMIPRoute *route;
		GError *error = NULL;
1462 1463 1464 1465 1466 1467 1468 1469

		route_array = g_variant_get_fixed_array (route_var, &length, sizeof (guint32));
		if (length < 4) {
			g_warning ("Ignoring invalid IP4 route");
			g_variant_unref (route_var);
			continue;
		}

1470
		route = nm_ip_route_new_binary (AF_INET,
1471 1472 1473 1474 1475
		                                &route_array[0],
		                                route_array[1],
		                                &route_array[2],
		                                /* The old routes format uses "0" for default, not "-1" */
		                                route_array[3] ? (gint64) route_array[3] : -1,
1476 1477 1478 1479 1480 1481 1482
		                                &error);
		if (route)
			g_ptr_array_add (routes, route);
		else {
			g_warning ("Ignoring invalid IP4 route: %s", error->message);
			g_clear_error (&error);
		}
1483 1484 1485 1486 1487 1488
		g_variant_unref (route_var);
	}

	return routes;
}

1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532
/**
 * nm_utils_ip4_netmask_to_prefix:
 * @netmask: an IPv4 netmask in network byte order
 *
 * Returns: the CIDR prefix represented by the netmask
 **/
guint32
nm_utils_ip4_netmask_to_prefix (guint32 netmask)
{
	guint32 prefix;
	guint8 v;
	const guint8 *p = (guint8 *) &netmask;

	if (p[3]) {
		prefix = 24;
		v = p[3];
	} else if (p[2]) {
		prefix = 16;
		v = p[2];
	} else if (p[1]) {
		prefix = 8;
		v = p[1];
	} else {
		prefix = 0;
		v = p[0];
	}

	while (v) {
		prefix++;
		v <<= 1;
	}

	return prefix;
}

/**
 * nm_utils_ip4_prefix_to_netmask:
 * @prefix: a CIDR prefix
 *
 * Returns: the netmask represented by the prefix, in network byte order
 **/
guint32
nm_utils_ip4_prefix_to_netmask (guint32 prefix)
{
1533
	return _nm_utils_ip4_prefix_to_netmask (prefix);
1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550
}

/**
 * nm_utils_ip4_get_default_prefix:
 * @ip: an IPv4 address (in network byte order)
 *
 * When the Internet was originally set up, various ranges of IP addresses were
 * segmented into three network classes: A, B, and C.  This function will return
 * a prefix that is associated with the IP address specified defining where it
 * falls in the predefined classes.
 *
 * Returns: the default class prefix for the given IP
 **/
/* The function is originally from ipcalc.c of Red Hat's initscripts. */
guint32
nm_utils_ip4_get_default_prefix (guint32 ip)
{
1551
	return _nm_utils_ip4_get_default_prefix (ip);
1552 1553
}

1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628
/**
 * nm_utils_ip6_dns_to_variant:
 * @dns: (type utf8): an array of IP address strings
 *
 * Utility function to convert an array of IP address strings int a #GVariant of
 * type 'aay' representing an array of IPv6 addresses.
 *
 * Returns: (transfer none): a new floating #GVariant representing @dns.
 **/
GVariant *
nm_utils_ip6_dns_to_variant (char **dns)
{
	GVariantBuilder builder;
	int i;

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("aay"));

	if (dns) {
		for (i = 0; dns[i]; i++) {
			struct in6_addr ip;

			inet_pton (AF_INET6, dns[i], &ip);
			g_variant_builder_add (&builder, "@ay",
			                       g_variant_new_fixed_array (G_VARIANT_TYPE_BYTE,
			                                                  &ip, sizeof (ip), 1));
		}
	}

	return g_variant_builder_end (&builder);
}

/**
 * nm_utils_ip6_dns_from_variant:
 * @value: a #GVariant of type 'aay'
 *
 * Utility function to convert a #GVariant of type 'aay' representing a list of
 * IPv6 addresses into an array of IP address strings.
 *
 * Returns: (transfer full) (type utf8): a %NULL-terminated array of IP address strings.
 **/
char **
nm_utils_ip6_dns_from_variant (GVariant *value)
{
	GVariantIter iter;
	GVariant *ip_var;
	char **dns;
	int i;

	g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("aay")), NULL);

	dns = g_new (char *, g_variant_n_children (value) + 1);

	g_variant_iter_init (&iter, value);
	i = 0;
	while (g_variant_iter_next (&iter, "@ay", &ip_var)) {
		gsize length;
		const struct in6_addr *ip = g_variant_get_fixed_array (ip_var, &length, 1);

		if (length != sizeof (struct in6_addr)) {
			g_warning ("%s: ignoring invalid IP6 address of length %d",
			           __func__, (int) length);
			g_variant_unref (ip_var);
			continue;
		}

		dns[i++] = g_strdup (nm_utils_inet6_ntop (ip, NULL));
		g_variant_unref (ip_var);
	}
	dns[i] = NULL;

	return dns;
}

/**
 * nm_utils_ip6_addresses_to_variant:
1629
 * @addresses: (element-type NMIPAddress): an array of #NMIPAddress objects
1630
 * @gateway: (allow-none): the gateway IP address
1631
 *
1632 1633 1634
 * Utility function to convert a #GPtrArray of #NMIPAddress objects representing
 * IPv6 addresses into a #GVariant of type 'a(ayuay)' representing an array of
 * NetworkManager IPv6 addresses (which are tuples of address, prefix, and
1635 1636 1637
 * gateway).  The "gateway" field of the first address will get the value of
 * @gateway (if non-%NULL). In all of the other addresses, that field will be
 * all 0s.
1638 1639 1640 1641
 *
 * Returns: (transfer none): a new floating #GVariant representing @addresses.
 **/
GVariant *
1642
nm_utils_ip6_addresses_to_variant (GPtrArray *addresses, const char *gateway)
1643 1644 1645 1646 1647 1648 1649 1650
{
	GVariantBuilder builder;
	int i;

	g_variant_builder_init (&builder, G_VARIANT_TYPE ("a(ayuay)"));

	if (addresses) {
		for (i = 0; i < addresses->len; i++) {
1651 1652
			NMIPAddress *addr = addresses->pdata[i];
			struct in6_addr ip_bytes, gateway_bytes;
1653
			GVariant *ip_var, *gateway_var;
1654 1655
			guint32 prefix;

1656 1657 1658 1659
			if (nm_ip_address_get_family (addr) != AF_INET6)
				continue;

			nm_ip_address_get_address_binary (addr, &ip_bytes);
1660
			ip_var = g_variant_new_fixed_array (G_VARIANT_TYPE_BYTE, &ip_bytes, 16, 1);
1661 1662

			prefix = nm_ip_address_get_prefix (addr);
1663 1664 1665

			if (i == 0 && gateway)
				inet_pton (AF_INET6, gateway, &gateway_bytes);
1666 1667
			else
				memset (&gateway_bytes, 0, sizeof (gateway_bytes));
1668
			gateway_var = g_variant_new_fixed_array (G_VARIANT_TYPE_BYTE, &gateway_bytes, 16, 1);
1669

1670
			g_variant_builder_add (&builder, "(@ayu@ay)", ip_var, prefix, gateway_var);
1671 1672 1673 1674 1675 1676 1677 1678 1679
		}
	}

	return g_variant_builder_end (&builder);
}

/**
 * nm_utils_ip6_addresses_from_variant:
 * @value: a #GVariant of type 'a(ayuay)'
1680
 * @out_gateway: (out) (allow-none) (transfer full): on return, will contain the IP gateway
1681 1682 1683
 *
 * Utility function to convert a #GVariant of type 'a(ayuay)' representing a
 * list of NetworkManager IPv6 addresses (which are tuples of address, prefix,
1684 1685 1686
 * and gateway) into a #GPtrArray of #NMIPAddress objects. The "gateway" field
 * of the first address (if set) will be returned in @out_gateway; the "gateway"
 * fields of the other addresses are ignored.
1687
 *
1688 1689
 * Returns: (transfer full) (element-type NMIPAddress): a newly allocated
 *   #GPtrArray of #NMIPAddress objects
1690 1691
 **/
GPtrArray *
1692
nm_utils_ip6_addresses_from_variant (GVariant *value, char **out_gateway)
1693 1694 1695 1696 1697 1698 1699 1700
{
	GVariantIter iter;
	GVariant *addr_var, *gateway_var;
	guint32 prefix;
	GPtrArray *addresses;

	g_return_val_if_fail (g_variant_is_of_type (value, G_VARIANT_TYPE ("a(ayuay)")), NULL);

1701 1702 1703
	if (out_gateway)
		*out_gateway = NULL;

1704
	g_variant_iter_init (&iter, value);
1705
	addresses = g_ptr_array_new_with_free_func ((GDestroyNotify) nm_ip_address_unref);
1706 1707

	while (g_variant_iter_next (&iter, "(@ayu@ay)", &addr_var, &prefix, &gateway_var)) {
1708
		NMIPAddress *addr;
1709 1710
		const struct in6_addr *addr_bytes, *gateway_bytes;
		gsize addr_len, gateway_len;
1711
		GError *error = NULL;
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724

		if (   !g_variant_is_of_type (addr_var, G_VARIANT_TYPE_BYTESTRING)
		    || !g_variant_is_of_type (gateway_var, G_VARIANT_TYPE_BYTESTRING)) {
			g_warning ("%s: ignoring invalid IP6 address structure", __func__);
			goto next;
		}

		addr_bytes = g_variant_get_fixed_array (addr_var, &addr_len, 1);
		if (addr_len != 16) {
			g_warning ("%s: ignoring invalid IP6 address of length %d",
			           __func__, (int) addr_len);
			goto next;
		}
1725 1726

		addr = nm_ip_address_new_binary (AF_INET6, addr_bytes, prefix, &error);
1727
		if (addr) {
1728
			g_ptr_array_add (addresses, addr);
1729 1730 1731 1732 1733 1734 1735 1736 1737