• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * wpa_supplicant/hostapd / common helper functions, etc.
3  * Copyright (c) 2002-2019, Jouni Malinen <j@w1.fi>
4  *
5  * This software may be distributed under the terms of the BSD license.
6  * See README for more details.
7  */
8 
9 #include "includes.h"
10 #include <limits.h>
11 #ifdef CONFIG_OPEN_HARMONY_PATCH
12 #include <sys/stat.h>
13 #endif /* CONFIG_OPEN_HARMONY_PATCH */
14 
15 #include "common/ieee802_11_defs.h"
16 #include "common.h"
17 #ifdef CONFIG_EAP_AUTH
18 #include "securec.h"
19 #define GAP_SIZE 2
20 #endif
hex2num(char c)21 int hex2num(char c)
22 {
23 	if (c >= '0' && c <= '9')
24 		return c - '0';
25 	if (c >= 'a' && c <= 'f')
26 		return c - 'a' + 10;
27 	if (c >= 'A' && c <= 'F')
28 		return c - 'A' + 10;
29 	return -1;
30 }
31 
32 
hex2byte(const char * hex)33 int hex2byte(const char *hex)
34 {
35 	int a, b;
36 	a = hex2num(*hex++);
37 	if (a < 0)
38 		return -1;
39 	b = hex2num(*hex++);
40 	if (b < 0)
41 		return -1;
42 	return (a << 4) | b;
43 }
44 
mac_to_str(const u8 * addr)45 const char *mac_to_str(const u8 *addr)
46 {
47 	const int macAddrIndexOne = 0;
48 	const int macAddrIndexTwo = 1;
49 	const int macAddrIndexThree = 2;
50 	const int macAddrIndexFour = 3;
51 	const int macAddrIndexFive = 4;
52 	const int macAddrIndexSix = 5;
53 	static char macToStr[18];
54 	if (disable_anonymized_print()) {
55 		if (os_snprintf(macToStr, sizeof(macToStr), "%02x:%02x:%02x:%02x:%02x:%02x", addr[macAddrIndexOne],
56 			addr[macAddrIndexTwo], addr[macAddrIndexThree], addr[macAddrIndexFour],
57 			addr[macAddrIndexFive], addr[macAddrIndexSix]) < 0) {
58 				return NULL;
59 		}
60 		return macToStr;
61 	} else {
62 		if (os_snprintf(macToStr, sizeof(macToStr), "%02x:%02x:**:**:**:%02x", addr[macAddrIndexOne],
63 			addr[macAddrIndexTwo], addr[macAddrIndexSix]) < 0) {
64 			return NULL;
65 		}
66 		return macToStr;
67 	}
68 }
69 
hwaddr_parse(const char * txt,u8 * addr)70 static const char * hwaddr_parse(const char *txt, u8 *addr)
71 {
72 	size_t i;
73 
74 	for (i = 0; i < ETH_ALEN; i++) {
75 		int a;
76 
77 		a = hex2byte(txt);
78 		if (a < 0)
79 			return NULL;
80 		txt += 2;
81 		addr[i] = a;
82 		if (i < ETH_ALEN - 1 && *txt++ != ':')
83 			return NULL;
84 	}
85 	return txt;
86 }
87 
88 
89 /**
90  * hwaddr_aton - Convert ASCII string to MAC address (colon-delimited format)
91  * @txt: MAC address as a string (e.g., "00:11:22:33:44:55")
92  * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
93  * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
94  */
hwaddr_aton(const char * txt,u8 * addr)95 int hwaddr_aton(const char *txt, u8 *addr)
96 {
97 	return hwaddr_parse(txt, addr) ? 0 : -1;
98 }
99 
100 
101 /**
102  * hwaddr_masked_aton - Convert ASCII string with optional mask to MAC address (colon-delimited format)
103  * @txt: MAC address with optional mask as a string (e.g., "00:11:22:33:44:55/ff:ff:ff:ff:00:00")
104  * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
105  * @mask: Buffer for the MAC address mask (ETH_ALEN = 6 bytes)
106  * @maskable: Flag to indicate whether a mask is allowed
107  * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
108  */
hwaddr_masked_aton(const char * txt,u8 * addr,u8 * mask,u8 maskable)109 int hwaddr_masked_aton(const char *txt, u8 *addr, u8 *mask, u8 maskable)
110 {
111 	const char *r;
112 
113 	/* parse address part */
114 	r = hwaddr_parse(txt, addr);
115 	if (!r)
116 		return -1;
117 
118 	/* check for optional mask */
119 	if (*r == '\0' || isspace((unsigned char) *r)) {
120 		/* no mask specified, assume default */
121 		os_memset(mask, 0xff, ETH_ALEN);
122 	} else if (maskable && *r == '/') {
123 		/* mask specified and allowed */
124 		r = hwaddr_parse(r + 1, mask);
125 		/* parser error? */
126 		if (!r)
127 			return -1;
128 	} else {
129 		/* mask specified but not allowed or trailing garbage */
130 		return -1;
131 	}
132 
133 	return 0;
134 }
135 
136 
137 /**
138  * hwaddr_compact_aton - Convert ASCII string to MAC address (no colon delimitors format)
139  * @txt: MAC address as a string (e.g., "001122334455")
140  * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
141  * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
142  */
hwaddr_compact_aton(const char * txt,u8 * addr)143 int hwaddr_compact_aton(const char *txt, u8 *addr)
144 {
145 	int i;
146 
147 	for (i = 0; i < 6; i++) {
148 		int a, b;
149 
150 		a = hex2num(*txt++);
151 		if (a < 0)
152 			return -1;
153 		b = hex2num(*txt++);
154 		if (b < 0)
155 			return -1;
156 		*addr++ = (a << 4) | b;
157 	}
158 
159 	return 0;
160 }
161 
162 /**
163  * hwaddr_aton2 - Convert ASCII string to MAC address (in any known format)
164  * @txt: MAC address as a string (e.g., 00:11:22:33:44:55 or 0011.2233.4455)
165  * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
166  * Returns: Characters used (> 0) on success, -1 on failure
167  */
hwaddr_aton2(const char * txt,u8 * addr)168 int hwaddr_aton2(const char *txt, u8 *addr)
169 {
170 	int i;
171 	const char *pos = txt;
172 
173 	for (i = 0; i < 6; i++) {
174 		int a, b;
175 
176 		while (*pos == ':' || *pos == '.' || *pos == '-')
177 			pos++;
178 
179 		a = hex2num(*pos++);
180 		if (a < 0)
181 			return -1;
182 		b = hex2num(*pos++);
183 		if (b < 0)
184 			return -1;
185 		*addr++ = (a << 4) | b;
186 	}
187 
188 	return pos - txt;
189 }
190 
191 
192 /**
193  * hexstr2bin - Convert ASCII hex string into binary data
194  * @hex: ASCII hex string (e.g., "01ab")
195  * @buf: Buffer for the binary data
196  * @len: Length of the text to convert in bytes (of buf); hex will be double
197  * this size
198  * Returns: 0 on success, -1 on failure (invalid hex string)
199  */
hexstr2bin(const char * hex,u8 * buf,size_t len)200 int hexstr2bin(const char *hex, u8 *buf, size_t len)
201 {
202 	size_t i;
203 	int a;
204 	const char *ipos = hex;
205 	u8 *opos = buf;
206 
207 	for (i = 0; i < len; i++) {
208 		a = hex2byte(ipos);
209 		if (a < 0)
210 			return -1;
211 		*opos++ = a;
212 		ipos += 2;
213 	}
214 	return 0;
215 }
216 
217 #ifdef CONFIG_EAP_AUTH
bin2hexstr(const unsigned char * bin,size_t bin_len,char * hexstr,size_t hexstr_len)218 void bin2hexstr(const unsigned char* bin, size_t bin_len, char* hexstr, size_t hexstr_len)
219 {
220 	size_t hexstr_index = 0;
221 	for (size_t i = 0; i < bin_len; i++) {
222 		if (os_snprintf(hexstr + hexstr_index, hexstr_len - hexstr_index, "%02x", bin[i]) <= 0) {
223 			printf("bin2hexstr fail\n");
224 		}
225 		hexstr_index += GAP_SIZE;
226 		if (hexstr_index >= hexstr_len) {
227 			break;
228 		}
229 	}
230 }
231 #endif
232 
hwaddr_mask_txt(char * buf,size_t len,const u8 * addr,const u8 * mask)233 int hwaddr_mask_txt(char *buf, size_t len, const u8 *addr, const u8 *mask)
234 {
235 	size_t i;
236 	int print_mask = 0;
237 	int res;
238 
239 	for (i = 0; i < ETH_ALEN; i++) {
240 		if (mask[i] != 0xff) {
241 			print_mask = 1;
242 			break;
243 		}
244 	}
245 
246 	if (print_mask)
247 		res = os_snprintf(buf, len, MACSTR "/" MACSTR,
248 				  MAC2STR(addr), MAC2STR(mask));
249 	else
250 		res = os_snprintf(buf, len, MACSTR, MAC2STR(addr));
251 	if (os_snprintf_error(len, res))
252 		return -1;
253 	return res;
254 }
255 
256 
257 /**
258  * inc_byte_array - Increment arbitrary length byte array by one
259  * @counter: Pointer to byte array
260  * @len: Length of the counter in bytes
261  *
262  * This function increments the last byte of the counter by one and continues
263  * rolling over to more significant bytes if the byte was incremented from
264  * 0xff to 0x00.
265  */
inc_byte_array(u8 * counter,size_t len)266 void inc_byte_array(u8 *counter, size_t len)
267 {
268 	int pos = len - 1;
269 	while (pos >= 0) {
270 		counter[pos]++;
271 		if (counter[pos] != 0)
272 			break;
273 		pos--;
274 	}
275 }
276 
277 
buf_shift_right(u8 * buf,size_t len,size_t bits)278 void buf_shift_right(u8 *buf, size_t len, size_t bits)
279 {
280 	size_t i;
281 
282 	for (i = len - 1; i > 0; i--)
283 		buf[i] = (buf[i - 1] << (8 - bits)) | (buf[i] >> bits);
284 	buf[0] >>= bits;
285 }
286 
287 
wpa_get_ntp_timestamp(u8 * buf)288 void wpa_get_ntp_timestamp(u8 *buf)
289 {
290 	struct os_time now;
291 	u32 sec, usec;
292 	be32 tmp;
293 
294 	/* 64-bit NTP timestamp (time from 1900-01-01 00:00:00) */
295 	os_get_time(&now);
296 	sec = now.sec + 2208988800U; /* Epoch to 1900 */
297 	/* Estimate 2^32/10^6 = 4295 - 1/32 - 1/512 */
298 	usec = now.usec;
299 	usec = 4295 * usec - (usec >> 5) - (usec >> 9);
300 	tmp = host_to_be32(sec);
301 	os_memcpy(buf, (u8 *) &tmp, 4);
302 	tmp = host_to_be32(usec);
303 	os_memcpy(buf + 4, (u8 *) &tmp, 4);
304 }
305 
306 /**
307  * wpa_scnprintf - Simpler-to-use snprintf function
308  * @buf: Output buffer
309  * @size: Buffer size
310  * @fmt: format
311  *
312  * Simpler snprintf version that doesn't require further error checks - the
313  * return value only indicates how many bytes were actually written, excluding
314  * the NULL byte (i.e., 0 on error, size-1 if buffer is not big enough).
315  */
wpa_scnprintf(char * buf,size_t size,const char * fmt,...)316 int wpa_scnprintf(char *buf, size_t size, const char *fmt, ...)
317 {
318 	va_list ap;
319 	int ret;
320 
321 	if (!size)
322 		return 0;
323 
324 	va_start(ap, fmt);
325 	ret = vsnprintf(buf, size, fmt, ap);
326 	va_end(ap);
327 
328 	if (ret < 0)
329 		return 0;
330 	if ((size_t) ret >= size)
331 		return size - 1;
332 
333 	return ret;
334 }
335 
336 
wpa_snprintf_hex_sep(char * buf,size_t buf_size,const u8 * data,size_t len,char sep)337 int wpa_snprintf_hex_sep(char *buf, size_t buf_size, const u8 *data, size_t len,
338 			 char sep)
339 {
340 	size_t i;
341 	char *pos = buf, *end = buf + buf_size;
342 	int ret;
343 
344 	if (buf_size == 0)
345 		return 0;
346 
347 	for (i = 0; i < len; i++) {
348 		ret = os_snprintf(pos, end - pos, "%02x%c",
349 				  data[i], sep);
350 		if (os_snprintf_error(end - pos, ret)) {
351 			end[-1] = '\0';
352 			return pos - buf;
353 		}
354 		pos += ret;
355 	}
356 	pos[-1] = '\0';
357 	return pos - buf;
358 }
359 
360 
_wpa_snprintf_hex(char * buf,size_t buf_size,const u8 * data,size_t len,int uppercase)361 static inline int _wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data,
362 				    size_t len, int uppercase)
363 {
364 	size_t i;
365 	char *pos = buf, *end = buf + buf_size;
366 	int ret;
367 	if (buf_size == 0)
368 		return 0;
369 	for (i = 0; i < len; i++) {
370 		ret = os_snprintf(pos, end - pos, uppercase ? "%02X" : "%02x",
371 				  data[i]);
372 		if (os_snprintf_error(end - pos, ret)) {
373 			end[-1] = '\0';
374 			return pos - buf;
375 		}
376 		pos += ret;
377 	}
378 	end[-1] = '\0';
379 	return pos - buf;
380 }
381 
382 /**
383  * wpa_snprintf_hex - Print data as a hex string into a buffer
384  * @buf: Memory area to use as the output buffer
385  * @buf_size: Maximum buffer size in bytes (should be at least 2 * len + 1)
386  * @data: Data to be printed
387  * @len: Length of data in bytes
388  * Returns: Number of bytes written
389  */
wpa_snprintf_hex(char * buf,size_t buf_size,const u8 * data,size_t len)390 int wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data, size_t len)
391 {
392 	return _wpa_snprintf_hex(buf, buf_size, data, len, 0);
393 }
394 
395 
396 /**
397  * wpa_snprintf_hex_uppercase - Print data as a upper case hex string into buf
398  * @buf: Memory area to use as the output buffer
399  * @buf_size: Maximum buffer size in bytes (should be at least 2 * len + 1)
400  * @data: Data to be printed
401  * @len: Length of data in bytes
402  * Returns: Number of bytes written
403  */
wpa_snprintf_hex_uppercase(char * buf,size_t buf_size,const u8 * data,size_t len)404 int wpa_snprintf_hex_uppercase(char *buf, size_t buf_size, const u8 *data,
405 			       size_t len)
406 {
407 	return _wpa_snprintf_hex(buf, buf_size, data, len, 1);
408 }
409 
410 
411 #ifdef CONFIG_ANSI_C_EXTRA
412 
413 #ifdef _WIN32_WCE
perror(const char * s)414 void perror(const char *s)
415 {
416 	wpa_printf(MSG_ERROR, "%s: GetLastError: %d",
417 		   s, (int) GetLastError());
418 }
419 #endif /* _WIN32_WCE */
420 
421 
422 int optind = 1;
423 int optopt;
424 char *optarg;
425 
getopt(int argc,char * const argv[],const char * optstring)426 int getopt(int argc, char *const argv[], const char *optstring)
427 {
428 	static int optchr = 1;
429 	char *cp;
430 
431 	if (optchr == 1) {
432 		if (optind >= argc) {
433 			/* all arguments processed */
434 			return EOF;
435 		}
436 
437 		if (argv[optind][0] != '-' || argv[optind][1] == '\0') {
438 			/* no option characters */
439 			return EOF;
440 		}
441 	}
442 
443 	if (os_strcmp(argv[optind], "--") == 0) {
444 		/* no more options */
445 		optind++;
446 		return EOF;
447 	}
448 
449 	optopt = argv[optind][optchr];
450 	cp = os_strchr(optstring, optopt);
451 	if (cp == NULL || optopt == ':') {
452 		if (argv[optind][++optchr] == '\0') {
453 			optchr = 1;
454 			optind++;
455 		}
456 		return '?';
457 	}
458 
459 	if (cp[1] == ':') {
460 		/* Argument required */
461 		optchr = 1;
462 		if (argv[optind][optchr + 1]) {
463 			/* No space between option and argument */
464 			optarg = &argv[optind++][optchr + 1];
465 		} else if (++optind >= argc) {
466 			/* option requires an argument */
467 			return '?';
468 		} else {
469 			/* Argument in the next argv */
470 			optarg = argv[optind++];
471 		}
472 	} else {
473 		/* No argument */
474 		if (argv[optind][++optchr] == '\0') {
475 			optchr = 1;
476 			optind++;
477 		}
478 		optarg = NULL;
479 	}
480 	return *cp;
481 }
482 #endif /* CONFIG_ANSI_C_EXTRA */
483 
484 
485 #ifdef CONFIG_NATIVE_WINDOWS
486 /**
487  * wpa_unicode2ascii_inplace - Convert unicode string into ASCII
488  * @str: Pointer to string to convert
489  *
490  * This function converts a unicode string to ASCII using the same
491  * buffer for output. If UNICODE is not set, the buffer is not
492  * modified.
493  */
wpa_unicode2ascii_inplace(TCHAR * str)494 void wpa_unicode2ascii_inplace(TCHAR *str)
495 {
496 #ifdef UNICODE
497 	char *dst = (char *) str;
498 	while (*str)
499 		*dst++ = (char) *str++;
500 	*dst = '\0';
501 #endif /* UNICODE */
502 }
503 
504 
wpa_strdup_tchar(const char * str)505 TCHAR * wpa_strdup_tchar(const char *str)
506 {
507 #ifdef UNICODE
508 	TCHAR *buf;
509 	buf = os_malloc((strlen(str) + 1) * sizeof(TCHAR));
510 	if (buf == NULL)
511 		return NULL;
512 	wsprintf(buf, L"%S", str);
513 	return buf;
514 #else /* UNICODE */
515 	return os_strdup(str);
516 #endif /* UNICODE */
517 }
518 #endif /* CONFIG_NATIVE_WINDOWS */
519 
520 
printf_encode(char * txt,size_t maxlen,const u8 * data,size_t len)521 void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len)
522 {
523 	char *end = txt + maxlen;
524 	size_t i;
525 
526 	for (i = 0; i < len; i++) {
527 		if (txt + 4 >= end)
528 			break;
529 
530 		switch (data[i]) {
531 		case '\"':
532 			*txt++ = '\\';
533 			*txt++ = '\"';
534 			break;
535 		case '\\':
536 			*txt++ = '\\';
537 			*txt++ = '\\';
538 			break;
539 		case '\033':
540 			*txt++ = '\\';
541 			*txt++ = 'e';
542 			break;
543 		case '\n':
544 			*txt++ = '\\';
545 			*txt++ = 'n';
546 			break;
547 		case '\r':
548 			*txt++ = '\\';
549 			*txt++ = 'r';
550 			break;
551 		case '\t':
552 			*txt++ = '\\';
553 			*txt++ = 't';
554 			break;
555 		default:
556 			if (data[i] >= 32 && data[i] <= 126) {
557 				*txt++ = data[i];
558 			} else {
559 				txt += os_snprintf(txt, end - txt, "\\x%02x",
560 						   data[i]);
561 			}
562 			break;
563 		}
564 	}
565 
566 	*txt = '\0';
567 }
568 
569 
printf_decode(u8 * buf,size_t maxlen,const char * str)570 size_t printf_decode(u8 *buf, size_t maxlen, const char *str)
571 {
572 	const char *pos = str;
573 	size_t len = 0;
574 	int val;
575 
576 	while (*pos) {
577 		if (len + 1 >= maxlen)
578 			break;
579 		switch (*pos) {
580 		case '\\':
581 			pos++;
582 			switch (*pos) {
583 			case '\\':
584 				buf[len++] = '\\';
585 				pos++;
586 				break;
587 			case '"':
588 				buf[len++] = '"';
589 				pos++;
590 				break;
591 			case 'n':
592 				buf[len++] = '\n';
593 				pos++;
594 				break;
595 			case 'r':
596 				buf[len++] = '\r';
597 				pos++;
598 				break;
599 			case 't':
600 				buf[len++] = '\t';
601 				pos++;
602 				break;
603 			case 'e':
604 				buf[len++] = '\033';
605 				pos++;
606 				break;
607 			case 'x':
608 				pos++;
609 				val = hex2byte(pos);
610 				if (val < 0) {
611 					val = hex2num(*pos);
612 					if (val < 0)
613 						break;
614 					buf[len++] = val;
615 					pos++;
616 				} else {
617 					buf[len++] = val;
618 					pos += 2;
619 				}
620 				break;
621 			case '0':
622 			case '1':
623 			case '2':
624 			case '3':
625 			case '4':
626 			case '5':
627 			case '6':
628 			case '7':
629 				val = *pos++ - '0';
630 				if (*pos >= '0' && *pos <= '7')
631 					val = val * 8 + (*pos++ - '0');
632 				if (*pos >= '0' && *pos <= '7')
633 					val = val * 8 + (*pos++ - '0');
634 				buf[len++] = val;
635 				break;
636 			default:
637 				break;
638 			}
639 			break;
640 		default:
641 			buf[len++] = *pos++;
642 			break;
643 		}
644 	}
645 	if (maxlen > len)
646 		buf[len] = '\0';
647 
648 	return len;
649 }
650 
651 
652 /**
653  * wpa_ssid_txt - Convert SSID to a printable string
654  * @ssid: SSID (32-octet string)
655  * @ssid_len: Length of ssid in octets
656  * Returns: Pointer to a printable string
657  *
658  * This function can be used to convert SSIDs into printable form. In most
659  * cases, SSIDs do not use unprintable characters, but IEEE 802.11 standard
660  * does not limit the used character set, so anything could be used in an SSID.
661  *
662  * This function uses a static buffer, so only one call can be used at the
663  * time, i.e., this is not re-entrant and the returned buffer must be used
664  * before calling this again.
665  */
wpa_ssid_txt(const u8 * ssid,size_t ssid_len)666 const char * wpa_ssid_txt(const u8 *ssid, size_t ssid_len)
667 {
668 	static char ssid_txt[SSID_MAX_LEN * 4 + 1];
669 
670 	if (ssid == NULL) {
671 		ssid_txt[0] = '\0';
672 		return ssid_txt;
673 	}
674 
675 	printf_encode(ssid_txt, sizeof(ssid_txt), ssid, ssid_len);
676 	return ssid_txt;
677 }
678 
679 
__hide_aliasing_typecast(void * foo)680 void * __hide_aliasing_typecast(void *foo)
681 {
682 	return foo;
683 }
684 
685 
wpa_config_parse_string(const char * value,size_t * len)686 char * wpa_config_parse_string(const char *value, size_t *len)
687 {
688 	if (*value == '"') {
689 		const char *pos;
690 		char *str;
691 		value++;
692 		pos = os_strrchr(value, '"');
693 		if (pos == NULL || pos[1] != '\0')
694 			return NULL;
695 		*len = pos - value;
696 		str = dup_binstr(value, *len);
697 		if (str == NULL)
698 			return NULL;
699 		return str;
700 	} else if (*value == 'P' && value[1] == '"') {
701 		const char *pos;
702 		char *tstr, *str;
703 		size_t tlen;
704 		value += 2;
705 		pos = os_strrchr(value, '"');
706 		if (pos == NULL || pos[1] != '\0')
707 			return NULL;
708 		tlen = pos - value;
709 		tstr = dup_binstr(value, tlen);
710 		if (tstr == NULL)
711 			return NULL;
712 
713 		str = os_malloc(tlen + 1);
714 		if (str == NULL) {
715 			os_free(tstr);
716 			return NULL;
717 		}
718 
719 		*len = printf_decode((u8 *) str, tlen + 1, tstr);
720 		os_free(tstr);
721 
722 		return str;
723 	} else {
724 		u8 *str;
725 		size_t tlen, hlen = os_strlen(value);
726 		if (hlen & 1)
727 			return NULL;
728 		tlen = hlen / 2;
729 		str = os_malloc(tlen + 1);
730 		if (str == NULL)
731 			return NULL;
732 		if (hexstr2bin(value, str, tlen)) {
733 			os_free(str);
734 			return NULL;
735 		}
736 		str[tlen] = '\0';
737 		*len = tlen;
738 		return (char *) str;
739 	}
740 }
741 
742 
is_hex(const u8 * data,size_t len)743 int is_hex(const u8 *data, size_t len)
744 {
745 	size_t i;
746 
747 	for (i = 0; i < len; i++) {
748 		if (data[i] < 32 || data[i] >= 127)
749 			return 1;
750 	}
751 	return 0;
752 }
753 
754 
has_ctrl_char(const u8 * data,size_t len)755 int has_ctrl_char(const u8 *data, size_t len)
756 {
757 	size_t i;
758 
759 	for (i = 0; i < len; i++) {
760 		if (data[i] < 32 || data[i] == 127)
761 			return 1;
762 	}
763 	return 0;
764 }
765 
766 
has_newline(const char * str)767 int has_newline(const char *str)
768 {
769 	while (*str) {
770 		if (*str == '\n' || *str == '\r')
771 			return 1;
772 		str++;
773 	}
774 	return 0;
775 }
776 
777 
merge_byte_arrays(u8 * res,size_t res_len,const u8 * src1,size_t src1_len,const u8 * src2,size_t src2_len)778 size_t merge_byte_arrays(u8 *res, size_t res_len,
779 			 const u8 *src1, size_t src1_len,
780 			 const u8 *src2, size_t src2_len)
781 {
782 	size_t len = 0;
783 
784 	os_memset(res, 0, res_len);
785 
786 	if (src1) {
787 		if (src1_len >= res_len) {
788 			os_memcpy(res, src1, res_len);
789 			return res_len;
790 		}
791 
792 		os_memcpy(res, src1, src1_len);
793 		len += src1_len;
794 	}
795 
796 	if (src2) {
797 		if (len + src2_len >= res_len) {
798 			os_memcpy(res + len, src2, res_len - len);
799 			return res_len;
800 		}
801 
802 		os_memcpy(res + len, src2, src2_len);
803 		len += src2_len;
804 	}
805 
806 	return len;
807 }
808 
809 
dup_binstr(const void * src,size_t len)810 char * dup_binstr(const void *src, size_t len)
811 {
812 	char *res;
813 
814 	if (src == NULL)
815 		return NULL;
816 	res = os_malloc(len + 1);
817 	if (res == NULL)
818 		return NULL;
819 	os_memcpy(res, src, len);
820 	res[len] = '\0';
821 
822 	return res;
823 }
824 
825 
freq_range_list_parse(struct wpa_freq_range_list * res,const char * value)826 int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value)
827 {
828 	struct wpa_freq_range *freq = NULL, *n;
829 	unsigned int count = 0;
830 	const char *pos, *pos2, *pos3;
831 
832 	/*
833 	 * Comma separated list of frequency ranges.
834 	 * For example: 2412-2432,2462,5000-6000
835 	 */
836 	pos = value;
837 	while (pos && pos[0]) {
838 		if (count == UINT_MAX) {
839 			os_free(freq);
840 			return -1;
841 		}
842 		n = os_realloc_array(freq, count + 1,
843 				     sizeof(struct wpa_freq_range));
844 		if (n == NULL) {
845 			os_free(freq);
846 			return -1;
847 		}
848 		freq = n;
849 		freq[count].min = atoi(pos);
850 		pos2 = os_strchr(pos, '-');
851 		pos3 = os_strchr(pos, ',');
852 		if (pos2 && (!pos3 || pos2 < pos3)) {
853 			pos2++;
854 			freq[count].max = atoi(pos2);
855 		} else
856 			freq[count].max = freq[count].min;
857 		pos = pos3;
858 		if (pos)
859 			pos++;
860 		count++;
861 	}
862 
863 	os_free(res->range);
864 	res->range = freq;
865 	res->num = count;
866 
867 	return 0;
868 }
869 
870 
freq_range_list_includes(const struct wpa_freq_range_list * list,unsigned int freq)871 int freq_range_list_includes(const struct wpa_freq_range_list *list,
872 			     unsigned int freq)
873 {
874 	unsigned int i;
875 
876 	if (list == NULL)
877 		return 0;
878 
879 	for (i = 0; i < list->num; i++) {
880 		if (freq >= list->range[i].min && freq <= list->range[i].max)
881 			return 1;
882 	}
883 
884 	return 0;
885 }
886 
887 
freq_range_list_str(const struct wpa_freq_range_list * list)888 char * freq_range_list_str(const struct wpa_freq_range_list *list)
889 {
890 	char *buf, *pos, *end;
891 	size_t maxlen;
892 	unsigned int i;
893 	int res;
894 
895 	if (list->num == 0)
896 		return NULL;
897 
898 	maxlen = list->num * 30;
899 	buf = os_malloc(maxlen);
900 	if (buf == NULL)
901 		return NULL;
902 	pos = buf;
903 	end = buf + maxlen;
904 
905 	for (i = 0; i < list->num; i++) {
906 		struct wpa_freq_range *range = &list->range[i];
907 
908 		if (range->min == range->max)
909 			res = os_snprintf(pos, end - pos, "%s%u",
910 					  i == 0 ? "" : ",", range->min);
911 		else
912 			res = os_snprintf(pos, end - pos, "%s%u-%u",
913 					  i == 0 ? "" : ",",
914 					  range->min, range->max);
915 		if (os_snprintf_error(end - pos, res)) {
916 			os_free(buf);
917 			return NULL;
918 		}
919 		pos += res;
920 	}
921 
922 	return buf;
923 }
924 
925 
int_array_len(const int * a)926 size_t int_array_len(const int *a)
927 {
928 	size_t i;
929 
930 	for (i = 0; a && a[i]; i++)
931 		;
932 	return i;
933 }
934 
935 
int_array_concat(int ** res,const int * a)936 void int_array_concat(int **res, const int *a)
937 {
938 	size_t reslen, alen, i, max_size;
939 	int *n;
940 
941 	reslen = int_array_len(*res);
942 	alen = int_array_len(a);
943 	max_size = (size_t) -1;
944 	if (alen >= max_size - reslen) {
945 		/* This should not really happen, but if it did, something
946 		 * would overflow. Do not try to merge the arrays; instead, make
947 		 * this behave like memory allocation failure to avoid messing
948 		 * up memory. */
949 		os_free(*res);
950 		*res = NULL;
951 		return;
952 	}
953 	n = os_realloc_array(*res, reslen + alen + 1, sizeof(int));
954 	if (n == NULL) {
955 		os_free(*res);
956 		*res = NULL;
957 		return;
958 	}
959 	for (i = 0; i <= alen; i++)
960 		n[reslen + i] = a[i];
961 	*res = n;
962 }
963 
964 
freq_cmp(const void * a,const void * b)965 static int freq_cmp(const void *a, const void *b)
966 {
967 	int _a = *(int *) a;
968 	int _b = *(int *) b;
969 
970 	if (_a == 0)
971 		return 1;
972 	if (_b == 0)
973 		return -1;
974 	return _a - _b;
975 }
976 
977 
int_array_sort_unique(int * a)978 void int_array_sort_unique(int *a)
979 {
980 	size_t alen, i, j;
981 
982 	if (a == NULL)
983 		return;
984 
985 	alen = int_array_len(a);
986 	qsort(a, alen, sizeof(int), freq_cmp);
987 
988 	i = 0;
989 	j = 1;
990 	while (a[i] && a[j]) {
991 		if (a[i] == a[j]) {
992 			j++;
993 			continue;
994 		}
995 		a[++i] = a[j++];
996 	}
997 	if (a[i])
998 		i++;
999 	a[i] = 0;
1000 }
1001 
1002 
int_array_add_unique(int ** res,int a)1003 void int_array_add_unique(int **res, int a)
1004 {
1005 	size_t reslen, max_size;
1006 	int *n;
1007 
1008 	for (reslen = 0; *res && (*res)[reslen]; reslen++) {
1009 		if ((*res)[reslen] == a)
1010 			return; /* already in the list */
1011 	}
1012 
1013 	max_size = (size_t) -1;
1014 	if (reslen > max_size - 2) {
1015 		/* This should not really happen in practice, but if it did,
1016 		 * something would overflow. Do not try to add the new value;
1017 		 * instead, make this behave like memory allocation failure to
1018 		 * avoid messing up memory. */
1019 		os_free(*res);
1020 		*res = NULL;
1021 		return;
1022 	}
1023 	n = os_realloc_array(*res, reslen + 2, sizeof(int));
1024 	if (n == NULL) {
1025 		os_free(*res);
1026 		*res = NULL;
1027 		return;
1028 	}
1029 
1030 	n[reslen] = a;
1031 	n[reslen + 1] = 0;
1032 
1033 	*res = n;
1034 }
1035 
1036 
int_array_includes(int * arr,int val)1037 bool int_array_includes(int *arr, int val)
1038 {
1039 	int i;
1040 
1041 	for (i = 0; arr && arr[i]; i++) {
1042 		if (val == arr[i])
1043 			return true;
1044 	}
1045 
1046 	return false;
1047 }
1048 
1049 
str_clear_free(char * str)1050 void str_clear_free(char *str)
1051 {
1052 	if (str) {
1053 		size_t len = os_strlen(str);
1054 		forced_memzero(str, len);
1055 		os_free(str);
1056 	}
1057 }
1058 
1059 
bin_clear_free(void * bin,size_t len)1060 void bin_clear_free(void *bin, size_t len)
1061 {
1062 	if (bin) {
1063 		forced_memzero(bin, len);
1064 		os_free(bin);
1065 	}
1066 }
1067 
1068 
random_mac_addr(u8 * addr)1069 int random_mac_addr(u8 *addr)
1070 {
1071 	if (os_get_random(addr, ETH_ALEN) < 0)
1072 		return -1;
1073 	addr[0] &= 0xfe; /* unicast */
1074 	addr[0] |= 0x02; /* locally administered */
1075 	return 0;
1076 }
1077 
1078 
random_mac_addr_keep_oui(u8 * addr)1079 int random_mac_addr_keep_oui(u8 *addr)
1080 {
1081 	if (os_get_random(addr + 3, 3) < 0)
1082 		return -1;
1083 	addr[0] &= 0xfe; /* unicast */
1084 	addr[0] |= 0x02; /* locally administered */
1085 	return 0;
1086 }
1087 
1088 
1089 /**
1090  * cstr_token - Get next token from const char string
1091  * @str: a constant string to tokenize
1092  * @delim: a string of delimiters
1093  * @last: a pointer to a character following the returned token
1094  *      It has to be set to NULL for the first call and passed for any
1095  *      further call.
1096  * Returns: a pointer to token position in str or NULL
1097  *
1098  * This function is similar to str_token, but it can be used with both
1099  * char and const char strings. Differences:
1100  * - The str buffer remains unmodified
1101  * - The returned token is not a NULL terminated string, but a token
1102  *   position in str buffer. If a return value is not NULL a size
1103  *   of the returned token could be calculated as (last - token).
1104  */
cstr_token(const char * str,const char * delim,const char ** last)1105 const char * cstr_token(const char *str, const char *delim, const char **last)
1106 {
1107 	const char *end, *token = str;
1108 
1109 	if (!str || !delim || !last)
1110 		return NULL;
1111 
1112 	if (*last)
1113 		token = *last;
1114 
1115 	while (*token && os_strchr(delim, *token))
1116 		token++;
1117 
1118 	if (!*token)
1119 		return NULL;
1120 
1121 	end = token + 1;
1122 
1123 	while (*end && !os_strchr(delim, *end))
1124 		end++;
1125 
1126 	*last = end;
1127 	return token;
1128 }
1129 
1130 
1131 /**
1132  * str_token - Get next token from a string
1133  * @buf: String to tokenize. Note that the string might be modified.
1134  * @delim: String of delimiters
1135  * @context: Pointer to save our context. Should be initialized with
1136  *	NULL on the first call, and passed for any further call.
1137  * Returns: The next token, NULL if there are no more valid tokens.
1138  */
str_token(char * str,const char * delim,char ** context)1139 char * str_token(char *str, const char *delim, char **context)
1140 {
1141 	char *token = (char *) cstr_token(str, delim, (const char **) context);
1142 
1143 	if (token && **context)
1144 		*(*context)++ = '\0';
1145 
1146 	return token;
1147 }
1148 
1149 
utf8_unescape(const char * inp,size_t in_size,char * outp,size_t out_size)1150 size_t utf8_unescape(const char *inp, size_t in_size,
1151 		     char *outp, size_t out_size)
1152 {
1153 	size_t res_size = 0;
1154 
1155 	if (!inp || !outp)
1156 		return 0;
1157 
1158 	if (!in_size)
1159 		in_size = os_strlen(inp);
1160 
1161 	/* Advance past leading single quote */
1162 	if (*inp == '\'' && in_size) {
1163 		inp++;
1164 		in_size--;
1165 	}
1166 
1167 	while (in_size) {
1168 		in_size--;
1169 		if (res_size >= out_size)
1170 			return 0;
1171 
1172 		switch (*inp) {
1173 		case '\'':
1174 			/* Terminate on bare single quote */
1175 			*outp = '\0';
1176 			return res_size;
1177 
1178 		case '\\':
1179 			if (!in_size)
1180 				return 0;
1181 			in_size--;
1182 			inp++;
1183 			__attribute__((fallthrough));
1184 
1185 		default:
1186 			*outp++ = *inp++;
1187 			res_size++;
1188 		}
1189 	}
1190 
1191 	/* NUL terminate if space allows */
1192 	if (res_size < out_size)
1193 		*outp = '\0';
1194 
1195 	return res_size;
1196 }
1197 
1198 
utf8_escape(const char * inp,size_t in_size,char * outp,size_t out_size)1199 size_t utf8_escape(const char *inp, size_t in_size,
1200 		   char *outp, size_t out_size)
1201 {
1202 	size_t res_size = 0;
1203 
1204 	if (!inp || !outp)
1205 		return 0;
1206 
1207 	/* inp may or may not be NUL terminated, but must be if 0 size
1208 	 * is specified */
1209 	if (!in_size)
1210 		in_size = os_strlen(inp);
1211 
1212 	while (in_size) {
1213 		in_size--;
1214 		if (res_size++ >= out_size)
1215 			return 0;
1216 
1217 		switch (*inp) {
1218 		case '\\':
1219 		case '\'':
1220 			if (res_size++ >= out_size)
1221 				return 0;
1222 			*outp++ = '\\';
1223 			__attribute__((fallthrough));
1224 
1225 		default:
1226 			*outp++ = *inp++;
1227 			break;
1228 		}
1229 	}
1230 
1231 	/* NUL terminate if space allows */
1232 	if (res_size < out_size)
1233 		*outp = '\0';
1234 
1235 	return res_size;
1236 }
1237 
1238 
is_ctrl_char(char c)1239 int is_ctrl_char(char c)
1240 {
1241 	return c > 0 && c < 32;
1242 }
1243 
1244 
1245 /**
1246  * ssid_parse - Parse a string that contains SSID in hex or text format
1247  * @buf: Input NULL terminated string that contains the SSID
1248  * @ssid: Output SSID
1249  * Returns: 0 on success, -1 otherwise
1250  *
1251  * The SSID has to be enclosed in double quotes for the text format or space
1252  * or NULL terminated string of hex digits for the hex format. buf can include
1253  * additional arguments after the SSID.
1254  */
ssid_parse(const char * buf,struct wpa_ssid_value * ssid)1255 int ssid_parse(const char *buf, struct wpa_ssid_value *ssid)
1256 {
1257 	char *tmp, *res, *end;
1258 	size_t len;
1259 
1260 	ssid->ssid_len = 0;
1261 
1262 	tmp = os_strdup(buf);
1263 	if (!tmp)
1264 		return -1;
1265 
1266 	if (*tmp != '"') {
1267 		end = os_strchr(tmp, ' ');
1268 		if (end)
1269 			*end = '\0';
1270 	} else {
1271 		end = os_strchr(tmp + 1, '"');
1272 		if (!end) {
1273 			os_free(tmp);
1274 			return -1;
1275 		}
1276 
1277 		end[1] = '\0';
1278 	}
1279 
1280 	res = wpa_config_parse_string(tmp, &len);
1281 	if (res && len <= SSID_MAX_LEN) {
1282 		ssid->ssid_len = len;
1283 		os_memcpy(ssid->ssid, res, len);
1284 	}
1285 
1286 	os_free(tmp);
1287 	os_free(res);
1288 
1289 	return ssid->ssid_len ? 0 : -1;
1290 }
1291 
1292 
str_starts(const char * str,const char * start)1293 int str_starts(const char *str, const char *start)
1294 {
1295 	return os_strncmp(str, start, os_strlen(start)) == 0;
1296 }
1297 
1298 
1299 /**
1300  * rssi_to_rcpi - Convert RSSI to RCPI
1301  * @rssi: RSSI to convert
1302  * Returns: RCPI corresponding to the given RSSI value, or 255 if not available.
1303  *
1304  * It's possible to estimate RCPI based on RSSI in dBm. This calculation will
1305  * not reflect the correct value for high rates, but it's good enough for Action
1306  * frames which are transmitted with up to 24 Mbps rates.
1307  */
rssi_to_rcpi(int rssi)1308 u8 rssi_to_rcpi(int rssi)
1309 {
1310 	if (!rssi)
1311 		return 255; /* not available */
1312 	if (rssi < -110)
1313 		return 0;
1314 	if (rssi > 0)
1315 		return 220;
1316 	return (rssi + 110) * 2;
1317 }
1318 
1319 
get_param(const char * cmd,const char * param)1320 char * get_param(const char *cmd, const char *param)
1321 {
1322 	const char *pos, *end;
1323 	char *val;
1324 	size_t len;
1325 
1326 	pos = os_strstr(cmd, param);
1327 	if (!pos)
1328 		return NULL;
1329 
1330 	pos += os_strlen(param);
1331 	end = os_strchr(pos, ' ');
1332 	if (end)
1333 		len = end - pos;
1334 	else
1335 		len = os_strlen(pos);
1336 	val = os_malloc(len + 1);
1337 	if (!val)
1338 		return NULL;
1339 	os_memcpy(val, pos, len);
1340 	val[len] = '\0';
1341 	return val;
1342 }
1343 
1344 
1345 /* Try to prevent most compilers from optimizing out clearing of memory that
1346  * becomes unaccessible after this function is called. This is mostly the case
1347  * for clearing local stack variables at the end of a function. This is not
1348  * exactly perfect, i.e., someone could come up with a compiler that figures out
1349  * the pointer is pointing to memset and then end up optimizing the call out, so
1350  * try go a bit further by storing the first octet (now zero) to make this even
1351  * a bit more difficult to optimize out. Once memset_s() is available, that
1352  * could be used here instead. */
1353 static void * (* const volatile memset_func)(void *, int, size_t) = memset;
1354 static u8 forced_memzero_val;
1355 
forced_memzero(void * ptr,size_t len)1356 void forced_memzero(void *ptr, size_t len)
1357 {
1358 	memset_func(ptr, 0, len);
1359 	if (len)
1360 		forced_memzero_val = ((u8 *) ptr)[0];
1361 }
1362 
StrtoUint(const char * input)1363 unsigned int StrtoUint(const char *input)
1364 {
1365 	if(input == NULL || input[0] == '\0' || strlen(input) > MAX_UINT32_LENGTH) {
1366 		return 0;
1367 	}
1368 	char *endPtr = NULL;
1369 	unsigned long result = 0;
1370 	result = strtol(input, &endPtr, NUMBER_BASE);
1371 
1372 	if(endPtr == input || *endPtr != '\0') {
1373 		return 0;
1374 	} else if(errno == ERANGE) {
1375 		return 0;
1376 	} else {
1377 		return (unsigned int)result;
1378 	}
1379 }
1380 
StrtoInt(const char * input)1381 int StrtoInt(const char *input)
1382 {
1383 	if(input == NULL || input[0] == '\0' || strlen(input) > MAX_INT32_LENGTH) {
1384 		return 0;
1385 	}
1386 	char *endPtr = NULL;
1387 	long result = 0;
1388 	result = strtol(input, &endPtr, NUMBER_BASE);
1389 
1390 	if(endPtr == input || *endPtr != '\0') {
1391 		return 0;
1392 	} else if(errno == ERANGE) {
1393 		return 0;
1394 	} else {
1395 		return (int)result;
1396 	}
1397 }
1398 
1399 #ifdef CONFIG_OPEN_HARMONY_PATCH
IsUpdaterMode(void)1400 bool IsUpdaterMode(void)
1401 {
1402 	static bool hasRun = false;
1403 	static bool updaterMode = false;
1404 	if (hasRun) {
1405 		return updaterMode;
1406 	}
1407 	struct stat st = {};
1408 	if (stat("/bin/updater", &st) == 0 && S_ISREG(st.st_mode)) {
1409 		updaterMode = true;
1410 	}
1411 	hasRun = true;
1412 	return updaterMode;
1413 }
1414 #endif /* CONFIG_OPEN_HARMONY_PATCH */