/
nm-utils.c
6035 lines (5215 loc) · 168 KB
/
nm-utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
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
717
718
719
720
721
722
723
724
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
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
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
/*
* 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.
*
* Copyright 2005 - 2017 Red Hat, Inc.
*/
#include "nm-default.h"
#include "nm-utils.h"
#include <stdlib.h>
#include <netinet/ether.h>
#include <arpa/inet.h>
#include <uuid/uuid.h>
#include <libintl.h>
#include <gmodule.h>
#include <sys/stat.h>
#include <net/if.h>
#include <linux/pkt_sched.h>
#if WITH_JSON_VALIDATION
#include "nm-json.h"
#endif
#include "nm-glib-aux/nm-enum-utils.h"
#include "nm-glib-aux/nm-secret-utils.h"
#include "systemd/nm-sd-utils-shared.h"
#include "nm-libnm-core-intern/nm-common-macros.h"
#include "nm-utils-private.h"
#include "nm-setting-private.h"
#include "nm-crypto.h"
#include "nm-setting-bond.h"
#include "nm-setting-bridge.h"
#include "nm-setting-bridge-port.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"
/**
* 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 _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;
}
/*****************************************************************************/
struct IsoLangToEncodings
{
const char *lang;
const char *const *encodings;
};
#define LANG_ENCODINGS(l, ...) { .lang = l, .encodings = NM_MAKE_STRV (__VA_ARGS__), }
/* 5-letter language codes */
static const struct IsoLangToEncodings isoLangEntries5[] =
{
/* Simplified Chinese */
LANG_ENCODINGS ("zh_cn", "euc-cn", "gb2312", "gb18030"), /* PRC */
LANG_ENCODINGS ("zh_sg", "euc-cn", "gb2312", "gb18030"), /* Singapore */
/* Traditional Chinese */
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 */
LANG_ENCODINGS (NULL, NULL)
};
/* 2-letter language codes; we don't care about the other 3 in this table */
static const struct IsoLangToEncodings isoLangEntries2[] =
{
/* Japanese */
LANG_ENCODINGS ("ja", "euc-jp", "shift_jis", "iso-2022-jp"),
/* Korean */
LANG_ENCODINGS ("ko", "euc-kr", "iso-2022-kr", "johab"),
/* Thai */
LANG_ENCODINGS ("th", "iso-8859-11", "windows-874"),
/* Central European */
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 */
/* Cyrillic */
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"), /* Ukrainian */
/* Arabic */
LANG_ENCODINGS ("ar", "iso-8859-6","windows-1256"),
/* Baltic */
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 */
/* Greek */
LANG_ENCODINGS ("el", "iso-8859-7","windows-1253"),
/* Hebrew */
LANG_ENCODINGS ("he", "iso-8859-8", "windows-1255"),
LANG_ENCODINGS ("iw", "iso-8859-8", "windows-1255"),
/* Turkish */
LANG_ENCODINGS ("tr", "iso-8859-9", "windows-1254"),
/* Table end */
LANG_ENCODINGS (NULL, NULL)
};
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];
langToEncodings5 = g_hash_table_new (nm_str_hash, g_str_equal);
while (enc->lang) {
g_hash_table_insert (langToEncodings5, (gpointer) enc->lang,
(gpointer) enc->encodings);
enc++;
}
}
if (G_UNLIKELY (langToEncodings2 == NULL)) {
/* Two-letter codes */
enc = (struct IsoLangToEncodings *) &isoLangEntries2[0];
langToEncodings2 = g_hash_table_new (nm_str_hash, g_str_equal);
while (enc->lang) {
g_hash_table_insert (langToEncodings2, (gpointer) enc->lang,
(gpointer) enc->encodings);
enc++;
}
}
}
static gboolean
get_encodings_for_lang (const char *lang, const char *const **encodings)
{
gs_free char *tmp_lang = NULL;
g_return_val_if_fail (lang, FALSE);
g_return_val_if_fail (encodings, FALSE);
init_lang_to_encodings_hash ();
if ((*encodings = g_hash_table_lookup (langToEncodings5, lang)))
return TRUE;
/* Truncate tmp_lang to length of 2 */
if (strlen (lang) > 2) {
tmp_lang = g_strdup (lang);
tmp_lang[2] = '\0';
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];
const char *const *encodings = NULL;
char *lang;
if (cached_encodings)
return cached_encodings;
/* Use environment variables as encoding hint */
lang = getenv ("LC_ALL");
if (!lang)
lang = getenv ("LC_CTYPE");
if (!lang)
lang = getenv ("LANG");
if (lang) {
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;
}
cached_encodings = encodings;
return cached_encodings;
}
/*****************************************************************************/
static void __attribute__((constructor))
_nm_utils_init (void)
{
static int initialized = 0;
if (g_atomic_int_get (&initialized) != 0)
return;
/* 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. */
bindtextdomain (GETTEXT_PACKAGE, NMLOCALEDIR);
bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
_nm_dbus_errors_init ();
g_atomic_int_set (&initialized, 1);
}
/*****************************************************************************/
gboolean _nm_utils_is_manager_process;
/* ssid helpers */
/**
* nm_utils_ssid_to_utf8:
* @ssid: (array length=len): pointer to a buffer containing the SSID data
* @len: length of the SSID data in @ssid
*
* 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 *
nm_utils_ssid_to_utf8 (const guint8 *ssid, gsize len)
{
const char *const *encodings;
const char *const *e;
char *converted = NULL;
g_return_val_if_fail (ssid != NULL, NULL);
if (g_utf8_validate ((const char *) ssid, len, NULL))
return g_strndup ((const char *) ssid, len);
encodings = get_system_encodings ();
for (e = encodings; *e; e++) {
converted = g_convert ((const char *) ssid, len, "UTF-8", *e, NULL, NULL, NULL);
if (converted)
break;
}
if (!converted) {
converted = g_convert_with_fallback ((const char *) ssid, len,
"UTF-8", encodings[0], "?", NULL, NULL, NULL);
}
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 */
char *valid_chars = " !\"#$%&'()*+,-./0123456789:;<=>?@"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`"
"abcdefghijklmnopqrstuvwxyz{|}~";
converted = g_strndup ((const char *) ssid, len);
g_strcanon (converted, valid_chars, '?');
}
return converted;
}
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);
}
/* Shamelessly ripped from the Linux kernel ieee80211 stack */
/**
* nm_utils_is_empty_ssid:
* @ssid: (array length=len): pointer to a buffer containing the SSID data
* @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
nm_utils_is_empty_ssid (const guint8 *ssid, gsize len)
{
/* 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;
}
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);
}
#define ESSID_MAX_SIZE 32
/**
* nm_utils_escape_ssid:
* @ssid: (array length=len): pointer to a buffer containing the SSID data
* @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 *
nm_utils_escape_ssid (const guint8 *ssid, gsize len)
{
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;
}
char *
_nm_utils_ssid_to_string_arr (const guint8 *ssid, gsize len)
{
gs_free char *s_copy = NULL;
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);
}
/**
* nm_utils_same_ssid:
* @ssid1: (array length=len1): the first SSID to compare
* @len1: length of the SSID data in @ssid1
* @ssid2: (array length=len2): the second SSID to compare
* @len2: length of the SSID data in @ssid2
* @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
nm_utils_same_ssid (const guint8 *ssid1, gsize len1,
const guint8 *ssid2, gsize len2,
gboolean ignore_trailing_null)
{
g_return_val_if_fail (ssid1 != NULL || len1 == 0, FALSE);
g_return_val_if_fail (ssid2 != NULL || len2 == 0, FALSE);
if (ssid1 == ssid2 && len1 == len2)
return TRUE;
if (!ssid1 || !ssid2)
return FALSE;
if (ignore_trailing_null) {
if (len1 && ssid1[len1 - 1] == '\0')
len1--;
if (len2 && ssid2[len2 - 1] == '\0')
len2--;
}
if (len1 != len2)
return FALSE;
return memcmp (ssid1, ssid2, len1) == 0 ? TRUE : FALSE;
}
gboolean
_nm_utils_string_slist_validate (GSList *list, const char **valid_values)
{
GSList *iter;
for (iter = list; iter; iter = iter->next) {
if (!g_strv_contains (valid_values, (char *) iter->data))
return FALSE;
}
return TRUE;
}
/**
* _nm_utils_hash_values_to_slist:
* @hash: a #GHashTable
*
* Utility function to iterate over a hash table and return
* its 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;
}
GVariant *
_nm_utils_strdict_to_dbus (const GValue *prop_value)
{
GHashTable *hash;
GHashTableIter iter;
const char *key, *value;
GVariantBuilder builder;
guint i, len;
g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{ss}"));
hash = g_value_get_boxed (prop_value);
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);
nm_utils_named_value_list_sort (idx, len, NULL, NULL);
for (i = 0; i < len; i++)
g_variant_builder_add (&builder, "{ss}", idx[i].name, idx[i].value_str);
}
out:
return g_variant_builder_end (&builder);
}
void
_nm_utils_strdict_from_dbus (GVariant *dbus_value,
GValue *prop_value)
{
GVariantIter iter;
const char *key, *value;
GHashTable *hash;
hash = g_hash_table_new_full (nm_str_hash, g_str_equal, g_free, g_free);
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);
}
GHashTable *
_nm_utils_copy_strdict (GHashTable *strdict)
{
GHashTable *copy;
GHashTableIter iter;
gpointer key, value;
copy = g_hash_table_new_full (nm_str_hash, g_str_equal, g_free, g_free);
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;
}
GPtrArray *
_nm_utils_copy_array (const GPtrArray *array,
NMUtilsCopyFunc copy_func,
GDestroyNotify free_func)
{
GPtrArray *copy;
int i;
if (!array)
return g_ptr_array_new_with_free_func (free_func);
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);
}
gssize
_nm_utils_ptrarray_find_first (gconstpointer *list, gssize len, gconstpointer needle)
{
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;
}
void
_nm_utils_bytes_from_dbus (GVariant *dbus_value,
GValue *prop_value)
{
GBytes *bytes;
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;
g_value_take_boxed (prop_value, bytes);
}
GSList *
_nm_utils_strv_to_slist (char **strv, gboolean deep_copy)
{
int i;
GSList *list = NULL;
if (strv) {
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]);
}
}
return g_slist_reverse (list);
}
char **
_nm_utils_slist_to_strv (GSList *slist, gboolean deep_copy)
{
GSList *iter;
char **strv;
int len, i;
len = g_slist_length (slist);
if (!len)
return NULL;
strv = g_new (char *, len + 1);
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;
}
strv[i] = NULL;
return strv;
}