nm-utils.c 198 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 27
#include <stdlib.h>
#include <netinet/ether.h>
28
#include <arpa/inet.h>
29
#include <uuid/uuid.h>
30
#include <libintl.h>
31
#include <gmodule.h>
32
#include <sys/stat.h>
33
#include <net/if.h>
34
#include <linux/pkt_sched.h>
35

Lubomir Rintel's avatar
Lubomir Rintel committed
36
#if WITH_JSON_VALIDATION
37
#include "nm-json.h"
Lubomir Rintel's avatar
Lubomir Rintel committed
38 39
#endif

40 41
#include "nm-glib-aux/nm-enum-utils.h"
#include "nm-glib-aux/nm-secret-utils.h"
42
#include "systemd/nm-sd-utils-shared.h"
43
#include "nm-libnm-core-intern/nm-common-macros.h"
44 45
#include "nm-utils-private.h"
#include "nm-setting-private.h"
46
#include "nm-crypto.h"
47 48
#include "nm-setting-bond.h"
#include "nm-setting-bridge.h"
49
#include "nm-setting-bridge-port.h"
50 51 52 53 54 55 56
#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"

57 58 59 60 61 62 63 64
/**
 * 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.
 */

65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
/*****************************************************************************/

struct _NMSockAddrEndpoint {
	const char *host;
	guint16 port;
	guint refcount;
	char endpoint[];
};

static gboolean
NM_IS_SOCK_ADDR_ENDPOINT (const NMSockAddrEndpoint *self)
{
	return self && self->refcount > 0;
}

static const char *
_parse_endpoint (char *str,
                 guint16 *out_port)
{
	char *s;
	const char *s_port;
	gint16 port;

	/* Like
	 * - https://git.zx2c4.com/WireGuard/tree/src/tools/config.c?id=5e99a6d43fe2351adf36c786f5ea2086a8fe7ab8#n192
	 * - https://github.com/systemd/systemd/blob/911649fdd43f3a9158b847947724a772a5a45c34/src/network/netdev/wireguard.c#L614
	 */

	g_strstrip (str);

	if (!str[0])
		return NULL;

	if (str[0] == '[') {
		str++;
		s = strchr (str, ']');
		if (!s)
			return NULL;
		if (s == str)
			return NULL;
		if (s[1] != ':')
			return NULL;
		if (!s[2])
			return NULL;
		*s = '\0';
		s_port = &s[2];
	} else {
		s = strrchr (str, ':');
		if (!s)
			return NULL;
		if (s == str)
			return NULL;
		if (!s[1])
			return NULL;
		*s = '\0';
		s_port = &s[1];
	}

	if (!NM_STRCHAR_ALL (s_port, ch, (ch >= '0' && ch <= '9')))
		return NULL;

	port = _nm_utils_ascii_str_to_int64 (s_port, 10, 1, G_MAXUINT16, 0);
	if (port == 0)
		return NULL;

	*out_port = port;
	return str;
}

/**
 * nm_sock_addr_endpoint_new:
 * @endpoint: the endpoint string.
 *
 * This function cannot fail, even if the @endpoint is invalid.
 * The reason is to allow NMSockAddrEndpoint also to be used
 * for tracking invalid endpoints. Use nm_sock_addr_endpoint_get_host()
 * to determine whether the endpoint is valid.
 *
 * Returns: (transfer full): the new #NMSockAddrEndpoint endpoint.
 */
NMSockAddrEndpoint *
nm_sock_addr_endpoint_new (const char *endpoint)
{
	NMSockAddrEndpoint *ep;
	gsize l_endpoint;
	gsize l_host = 0;
	gsize i;
	gs_free char *host_clone = NULL;
	const char *host;
	guint16 port;

	g_return_val_if_fail (endpoint, NULL);

	l_endpoint = strlen (endpoint) + 1;

	host = _parse_endpoint (nm_strndup_a (200, endpoint, l_endpoint - 1, &host_clone),
	                        &port);

	if (host)
		l_host = strlen (host) + 1;

	ep = g_malloc (sizeof (NMSockAddrEndpoint) + l_endpoint + l_host);
	ep->refcount = 1;
	memcpy (ep->endpoint, endpoint, l_endpoint);
	if (host) {
		i = l_endpoint;
		memcpy (&ep->endpoint[i], host, l_host);
		ep->host = &ep->endpoint[i];
		ep->port = port;
	} else {
		ep->host = NULL;
		ep->port = 0;
	}
	return ep;
}

/**
 * nm_sock_addr_endpoint_ref:
 * @self: (allow-none): the #NMSockAddrEndpoint
 */
NMSockAddrEndpoint *
nm_sock_addr_endpoint_ref (NMSockAddrEndpoint *self)
{
	if (!self)
		return NULL;

	g_return_val_if_fail (NM_IS_SOCK_ADDR_ENDPOINT (self), NULL);

	nm_assert (self->refcount < G_MAXUINT);

	self->refcount++;
	return self;
}

/**
 * nm_sock_addr_endpoint_unref:
 * @self: (allow-none): the #NMSockAddrEndpoint
 */
void
nm_sock_addr_endpoint_unref (NMSockAddrEndpoint *self)
{
	if (!self)
		return;

	g_return_if_fail (NM_IS_SOCK_ADDR_ENDPOINT (self));

	if (--self->refcount == 0)
		g_free (self);
}

/**
 * nm_sock_addr_endpoint_get_endpoint:
 * @self: the #NMSockAddrEndpoint
 *
 * Gives the endpoint string. Since #NMSockAddrEndpoint's only
 * information is the endpoint string, this can be used for comparing
 * to instances for equality and order them lexically.
 *
 * Returns: (transfer none): the endpoint.
 */
const char *
nm_sock_addr_endpoint_get_endpoint (NMSockAddrEndpoint *self)
{
	g_return_val_if_fail (NM_IS_SOCK_ADDR_ENDPOINT (self), NULL);

	return self->endpoint;
}

/**
 * nm_sock_addr_endpoint_get_host:
 * @self: the #NMSockAddrEndpoint
 *
 * Returns: (transfer none): the parsed host part of the endpoint.
 *   If the endpoint is invalid, %NULL will be returned.
 */
const char *
nm_sock_addr_endpoint_get_host (NMSockAddrEndpoint *self)
{
	g_return_val_if_fail (NM_IS_SOCK_ADDR_ENDPOINT (self), NULL);

	return self->host;
}

/**
 * nm_sock_addr_endpoint_get_port:
 * @self: the #NMSockAddrEndpoint
 *
 * Returns: the parsed port part of the endpoint (the service).
 *   If the endpoint is invalid, -1 will be returned.
 */
gint32
nm_sock_addr_endpoint_get_port (NMSockAddrEndpoint *self)
{
	g_return_val_if_fail (NM_IS_SOCK_ADDR_ENDPOINT (self), -1);

	return self->host ? (int) self->port : -1;
}

gboolean
nm_sock_addr_endpoint_get_fixed_sockaddr (NMSockAddrEndpoint *self,
                                          gpointer sockaddr)
{
	int addr_family;
	NMIPAddr addrbin;
	const char *s;
	guint scope_id = 0;

	g_return_val_if_fail (NM_IS_SOCK_ADDR_ENDPOINT (self), FALSE);
	g_return_val_if_fail (sockaddr, FALSE);

	if (!self->host)
		return FALSE;

	if (nm_utils_parse_inaddr_bin (AF_UNSPEC, self->host, &addr_family, &addrbin))
		goto good;

	/* See if there is an IPv6 scope-id...
	 *
	 * Note that it does not make sense to persist connection profiles to disk,
	 * that refenrence a scope-id (because the interface's ifindex changes on
	 * reboot). However, we also support runtime only changes like `nmcli device modify`
	 * where nothing is persisted to disk. At least in that case, passing a scope-id
	 * might be reasonable. So, parse that too. */
	s = strchr (self->host, '%');
	if (!s)
		return FALSE;

	if (   s[1] == '\0'
	    || !NM_STRCHAR_ALL (&s[1], ch, (ch >= '0' && ch <= '9')))
		return FALSE;

	scope_id = _nm_utils_ascii_str_to_int64 (&s[1], 10, 0, G_MAXINT32, G_MAXUINT);
	if (scope_id == G_MAXUINT && errno)
		return FALSE;

	{
		gs_free char *tmp_str = NULL;
		const char *host_part;

		host_part = nm_strndup_a (200, self->host, s - self->host, &tmp_str);
		if (nm_utils_parse_inaddr_bin (AF_INET6, host_part, &addr_family, &addrbin))
			goto good;
	}

	return FALSE;

good:
	switch (addr_family) {
	case AF_INET:
		*((struct sockaddr_in *) sockaddr) = (struct sockaddr_in) {
			.sin_family = AF_INET,
			.sin_addr   = addrbin.addr4_struct,
			.sin_port   = htons (self->port),
		};
		return TRUE;
	case AF_INET6:
		*((struct sockaddr_in6 *) sockaddr) = (struct sockaddr_in6) {
			.sin6_family   = AF_INET6,
			.sin6_addr     = addrbin.addr6,
			.sin6_port     = htons (self->port),
			.sin6_scope_id = scope_id,
			.sin6_flowinfo = 0,
		};
		return TRUE;
	}

	return FALSE;
}

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

336 337
struct IsoLangToEncodings
{
338 339
	const char *lang;
	const char *const *encodings;
340 341
};

342
#define LANG_ENCODINGS(l, ...) { .lang = l, .encodings = NM_MAKE_STRV (__VA_ARGS__), }
343

344 345 346 347
/* 5-letter language codes */
static const struct IsoLangToEncodings isoLangEntries5[] =
{
	/* Simplified Chinese */
348 349
	LANG_ENCODINGS ("zh_cn",   "euc-cn", "gb2312", "gb18030"),         /* PRC */
	LANG_ENCODINGS ("zh_sg",   "euc-cn", "gb2312", "gb18030"),         /* Singapore */
350 351

	/* Traditional Chinese */
352 353 354
	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 */
355

356
	LANG_ENCODINGS (NULL, NULL)
357 358 359 360 361 362
};

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

	/* Korean */
366
	LANG_ENCODINGS ("ko",      "euc-kr", "iso-2022-kr", "johab"),
367 368

	/* Thai */
369
	LANG_ENCODINGS ("th",      "iso-8859-11", "windows-874"),
370 371

	/* Central European */
372 373 374 375 376 377 378 379
	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 */
380 381

	/* Cyrillic */
382 383 384 385 386
	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 */
luz.paz's avatar
luz.paz committed
387
	LANG_ENCODINGS ("uk",      "koi8-u", "koi8-r", "windows-1251"),    /* Ukrainian */
388 389

	/* Arabic */
390
	LANG_ENCODINGS ("ar",      "iso-8859-6","windows-1256"),
391 392

	/* Baltic */
393 394 395
	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 */
396 397

	/* Greek */
398
	LANG_ENCODINGS ("el",      "iso-8859-7","windows-1253"),
399 400

	/* Hebrew */
401 402
	LANG_ENCODINGS ("he",      "iso-8859-8", "windows-1255"),
	LANG_ENCODINGS ("iw",      "iso-8859-8", "windows-1255"),
403 404

	/* Turkish */
405
	LANG_ENCODINGS ("tr",      "iso-8859-9", "windows-1254"),
406 407

	/* Table end */
408
	LANG_ENCODINGS (NULL, NULL)
409 410 411 412 413 414 415 416 417 418 419 420 421
};

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];
422
		langToEncodings5 = g_hash_table_new (nm_str_hash, g_str_equal);
423 424
		while (enc->lang) {
			g_hash_table_insert (langToEncodings5, (gpointer) enc->lang,
425
			                     (gpointer) enc->encodings);
426 427 428 429 430 431 432
			enc++;
		}
	}

	if (G_UNLIKELY (langToEncodings2 == NULL)) {
		/* Two-letter codes */
		enc = (struct IsoLangToEncodings *) &isoLangEntries2[0];
433
		langToEncodings2 = g_hash_table_new (nm_str_hash, g_str_equal);
434 435
		while (enc->lang) {
			g_hash_table_insert (langToEncodings2, (gpointer) enc->lang,
436
			                     (gpointer) enc->encodings);
437 438 439 440 441 442
			enc++;
		}
	}
}

static gboolean
443
get_encodings_for_lang (const char *lang, const char *const **encodings)
444
{
445
	gs_free char *tmp_lang = NULL;
446

447 448
	g_return_val_if_fail (lang, FALSE);
	g_return_val_if_fail (encodings, FALSE);
449 450 451

	init_lang_to_encodings_hash ();

452 453
	if ((*encodings = g_hash_table_lookup (langToEncodings5, lang)))
		return TRUE;
454 455

	/* Truncate tmp_lang to length of 2 */
456 457
	if (strlen (lang) > 2) {
		tmp_lang = g_strdup (lang);
458
		tmp_lang[2] = '\0';
459 460 461 462 463 464 465 466 467 468 469 470
		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];
471
	const char *const *encodings = NULL;
472 473 474 475 476
	char *lang;

	if (cached_encodings)
		return cached_encodings;

477 478 479 480 481 482 483
	/* Use environment variables as encoding hint */
	lang = getenv ("LC_ALL");
	if (!lang)
		lang = getenv ("LC_CTYPE");
	if (!lang)
		lang = getenv ("LANG");
	if (lang) {
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
		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;
499 500
	}

501 502
	cached_encodings = encodings;
	return cached_encodings;
503 504
}

505
/*****************************************************************************/
506

507
static void __attribute__((constructor))
508
_nm_utils_init (void)
509
{
510
	static int initialized = 0;
511

512
	if (g_atomic_int_get (&initialized) != 0)
513
		return;
514 515 516 517 518 519 520

	/* we don't expect this code to run multiple times, nor on multiple threads.
	 *
	 * In practice, it would not be a problem if two threads concurrently try to
	 * run the initialization code below, all code below itself is thread-safe,
	 * Hence, a poor-man guard "initialized" above is more than sufficient,
	 * although it does not guarantee that the code is not run concurrently. */
521

522
	bindtextdomain (GETTEXT_PACKAGE, NMLOCALEDIR);
523
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
524

525
	_nm_dbus_errors_init ();
526 527

	g_atomic_int_set (&initialized, 1);
528 529
}

530 531
/*****************************************************************************/

532 533
gboolean _nm_utils_is_manager_process;

534 535 536 537
/* ssid helpers */

/**
 * nm_utils_ssid_to_utf8:
538
 * @ssid: (array length=len): pointer to a buffer containing the SSID data
539
 * @len: length of the SSID data in @ssid
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
 *
 * 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 *
569
nm_utils_ssid_to_utf8 (const guint8 *ssid, gsize len)
570
{
571 572
	const char *const *encodings;
	const char *const *e;
573 574 575 576
	char *converted = NULL;

	g_return_val_if_fail (ssid != NULL, NULL);

577 578
	if (g_utf8_validate ((const char *) ssid, len, NULL))
		return g_strndup ((const char *) ssid, len);
579

580
	encodings = get_system_encodings ();
581

582
	for (e = encodings; *e; e++) {
583
		converted = g_convert ((const char *) ssid, len, "UTF-8", *e, NULL, NULL, NULL);
584 585
		if (converted)
			break;
586 587 588
	}

	if (!converted) {
589
		converted = g_convert_with_fallback ((const char *) ssid, len,
590
		                                     "UTF-8", encodings[0], "?", NULL, NULL, NULL);
591 592
	}

593 594 595 596 597 598 599
	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 */
600
		char *valid_chars = " !\"#$%&'()*+,-./0123456789:;<=>?@"
601 602 603
		                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"
		                     "abcdefghijklmnopqrstuvwxyz{|}~";

604
		converted = g_strndup ((const char *) ssid, len);
605 606 607
		g_strcanon (converted, valid_chars, '?');
	}

608 609 610
	return converted;
}

611 612 613 614 615 616 617 618 619 620 621 622
char *
_nm_utils_ssid_to_utf8 (GBytes *ssid)
{
	const guint8 *p;
	gsize l;

	g_return_val_if_fail (ssid, NULL);

	p = g_bytes_get_data (ssid, &l);
	return nm_utils_ssid_to_utf8 (p, l);
}

623 624 625
/* Shamelessly ripped from the Linux kernel ieee80211 stack */
/**
 * nm_utils_is_empty_ssid:
626
 * @ssid: (array length=len): pointer to a buffer containing the SSID data
627 628 629 630 631 632 633 634 635
 * @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
636
nm_utils_is_empty_ssid (const guint8 *ssid, gsize len)
637 638 639 640 641 642 643 644 645 646 647 648 649
{
	/* 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;
}

650 651 652 653 654 655 656 657 658 659 660 661
gboolean
_nm_utils_is_empty_ssid (GBytes *ssid)
{
	const guint8 *p;
	gsize l;

	g_return_val_if_fail (ssid, FALSE);

	p = g_bytes_get_data (ssid, &l);
	return nm_utils_is_empty_ssid (p, l);
}

662 663 664 665
#define ESSID_MAX_SIZE 32

/**
 * nm_utils_escape_ssid:
666
 * @ssid: (array length=len): pointer to a buffer containing the SSID data
667 668 669 670 671 672 673 674 675 676 677
 * @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 *
678
nm_utils_escape_ssid (const guint8 *ssid, gsize len)
679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
{
	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;
}

703 704 705
char *
_nm_utils_ssid_to_string_arr (const guint8 *ssid, gsize len)
{
706
	gs_free char *s_copy = NULL;
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
	const char *s_cnst;

	if (len == 0)
		return g_strdup ("(empty)");

	s_cnst = nm_utils_buf_utf8safe_escape (ssid, len, NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL, &s_copy);
	nm_assert (s_cnst);

	if (nm_utils_is_empty_ssid (ssid, len))
		return g_strdup_printf ("\"%s\" (hidden)", s_cnst);

	return g_strdup_printf ("\"%s\"", s_cnst);
}

char *
_nm_utils_ssid_to_string (GBytes *ssid)
{
	gconstpointer p;
	gsize l;

	if (!ssid)
		return g_strdup ("(none)");

	p = g_bytes_get_data (ssid, &l);
	return _nm_utils_ssid_to_string_arr (p, l);
}

734 735
/**
 * nm_utils_same_ssid:
736
 * @ssid1: (array length=len1): the first SSID to compare
737
 * @len1: length of the SSID data in @ssid1
738
 * @ssid2: (array length=len2): the second SSID to compare
739
 * @len2: length of the SSID data in @ssid2
740 741 742 743 744 745 746 747 748 749 750 751
 * @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
752 753
nm_utils_same_ssid (const guint8 *ssid1, gsize len1,
                    const guint8 *ssid2, gsize len2,
754 755
                    gboolean ignore_trailing_null)
{
756 757
	g_return_val_if_fail (ssid1 != NULL || len1 == 0, FALSE);
	g_return_val_if_fail (ssid2 != NULL || len2 == 0, FALSE);
758

759
	if (ssid1 == ssid2 && len1 == len2)
760 761 762 763
		return TRUE;
	if (!ssid1 || !ssid2)
		return FALSE;

764 765 766 767 768
	if (ignore_trailing_null) {
		if (len1 && ssid1[len1 - 1] == '\0')
			len1--;
		if (len2 && ssid2[len2 - 1] == '\0')
			len2--;
769 770
	}

771
	if (len1 != len2)
772 773
		return FALSE;

774
	return memcmp (ssid1, ssid2, len1) == 0 ? TRUE : FALSE;
775 776 777 778 779 780 781 782
}

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

	for (iter = list; iter; iter = iter->next) {
783
		if (!g_strv_contains (valid_values, (char *) iter->data))
784 785 786 787 788 789
			return FALSE;
	}

	return TRUE;
}

790 791 792 793 794
/**
 * _nm_utils_hash_values_to_slist:
 * @hash: a #GHashTable
 *
 * Utility function to iterate over a hash table and return
795
 * its values as a #GSList.
796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
 *
 * 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;
}

818 819
GVariant *
_nm_utils_strdict_to_dbus (const GValue *prop_value)
820
{
821 822
	GHashTable *hash;
	GHashTableIter iter;
823
	const char *key, *value;
824
	GVariantBuilder builder;
825
	guint i, len;
826 827

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

829
	hash = g_value_get_boxed (prop_value);
830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853
	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);

854
		nm_utils_named_value_list_sort (idx, len, NULL, NULL);
855 856 857

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

860
out:
861
	return g_variant_builder_end (&builder);
862 863 864
}

void
865
_nm_utils_strdict_from_dbus (GVariant *dbus_value,
866 867
                             GValue *prop_value)
{
868 869 870 871
	GVariantIter iter;
	const char *key, *value;
	GHashTable *hash;

872
	hash = g_hash_table_new_full (nm_str_hash, g_str_equal, g_free, g_free);
873 874 875 876 877
	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);
878 879 880 881 882 883 884 885 886
}

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

887
	copy = g_hash_table_new_full (nm_str_hash, g_str_equal, g_free, g_free);
888 889 890 891 892 893 894 895
	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;
}

896 897 898 899 900 901 902 903
GPtrArray *
_nm_utils_copy_array (const GPtrArray *array,
                      NMUtilsCopyFunc copy_func,
                      GDestroyNotify free_func)
{
	GPtrArray *copy;
	int i;

904 905 906
	if (!array)
		return g_ptr_array_new_with_free_func (free_func);

907 908 909 910 911 912 913 914 915 916 917 918
	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);
}

919
gssize
920
_nm_utils_ptrarray_find_first (gconstpointer *list, gssize len, gconstpointer needle)
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
{
	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;
}

943
void
944
_nm_utils_bytes_from_dbus (GVariant *dbus_value,
945 946
                           GValue *prop_value)
{
947
	GBytes *bytes;
948

949 950 951 952 953 954 955 956
	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;
957 958 959
	g_value_take_boxed (prop_value, bytes);
}

960
GSList *
961
_nm_utils_strv_to_slist (char **strv, gboolean deep_copy)
962 963 964 965
{
	int i;
	GSList *list = NULL;

966
	if (strv) {
967 968 969 970 971 972 973
		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]);
		}
974
	}
975 976 977 978 979

	return g_slist_reverse (list);
}

char **
980
_nm_utils_slist_to_strv (GSList *slist, gboolean deep_copy)
981 982 983
{
	GSList *iter;
	char **strv;
984
	int len, i;
985 986

	len = g_slist_length (slist);
987 988
	if (!len)
		return NULL;
989 990
	strv = g_new (char *, len + 1);

991 992 993 994 995 996 997
	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;
	}
998 999 1000 1001 1002
	strv[i] = NULL;

	return strv;
}

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

1037 1038 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
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:
luz.paz's avatar
luz.paz committed
1086
 * @type: the security type to check device capabilities against,
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
 * 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:
luz.paz's avatar
luz.paz committed
1122
 * @type: the security type to check AP flags and device capabilities against,
1123 1124 1125 1126 1127 1128
 * 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
luz.paz's avatar
luz.paz committed
1129
 * @ap_wpa: bitfield of AP capabilities derived from the AP's WPA beacon,
1130
 * e.g. (#NM_802_11_AP_SEC_PAIR_TKIP | #NM_802_11_AP_SEC_KEY_MGMT_PSK)
luz.paz's avatar
luz.paz committed
1131
 * @ap_rsn: bitfield of AP capabilities derived from the AP's RSN/WPA2 beacon,
1132 1133 1134 1135 1136 1137 1138 1139 1140
 * 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.
 *
luz.paz's avatar
luz.paz committed
1141
 * Returns: %TRUE if the device capabilities and AP capabilities intersect and are
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 1170 1171 1172 1173 1174 1175 1176 1177 1178
 * 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;
1179
		/* fall through */
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
	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;

1311 1312 1313 1314 1315
	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);
	}

1316
	keylen = strlen (key);
1317
	if (wep_type == NM_WEP_KEY_TYPE_KEY) {
1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
		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;
}

1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422
/**
 * 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++)
1423
		dns[i] = nm_utils_inet4_ntop_dup (array[i]);
1424 1425 1426 1427 1428 1429 1430
	dns[i] = NULL;

	return dns;
}

/**
 * nm_utils_ip4_addresses_to_variant:
1431
 * @addresses: (element-type NMIPAddress): an array of #NMIPAddress objects
1432
 * @gateway: (allow-none): the gateway IP address
1433
 *
1434 1435 1436
 * 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
1437 1438
 * 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.
1439 1440 1441 1442
 *
 * Returns: (transfer none): a new floating #GVariant representing @addresses.
 **/
GVariant *
1443
nm_utils_ip4_addresses_to_variant (GPtrArray *addresses, const char *gateway)
1444 1445 1446 1447 1448 1449 1450 1451
{
	GVariantBuilder builder;
	int i;

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

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

1455 1456 1457 1458 1459
			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);
1460 1461
			if (i == 0 && gateway)
				inet_pton (AF_INET, gateway, &array[2]);
1462 1463
			else
				array[2] = 0;
1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476

			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'
1477
 * @out_gateway: (out) (allow-none) (transfer full): on return, will contain the IP gateway
1478 1479 1480
 *
 * Utility function to convert a #GVariant of type 'aau' representing a list of
 * NetworkManager IPv4 addresses (which are tuples of address, prefix, and
1481 1482 1483
 * 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.
1484
 *
1485 1486
 * Returns: (transfer full) (element-type NMIPAddress): a newly allocated
 *   #GPtrArray of #NMIPAddress objects
1487 1488
 **/
GPtrArray *
1489
nm_utils_ip4_addresses_from_variant (GVariant *value, char **out_gateway)
1490 1491 1492 1493 1494 1495 1496
{
	GPtrArray *addresses;
	GVariantIter iter;
	GVariant *addr_var;

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

1497 1498 1499
	if (out_gateway)
		*out_gateway = NULL;

1500
	g_variant_iter_init (&iter, value);
1501
	addresses = g_ptr_array_new_with_free_func ((GDestroyNotify) nm_ip_address_unref);
1502 1503 1504 1505

	while (g_variant_iter_next (&iter, "@au", &addr_var)) {
		const guint32 *addr_array;
		gsize length;
1506 1507
		NMIPAddress *addr;
		GError *error = NULL;