2 * wpa_supplicant/hostapd / common helper functions, etc.
3 * Copyright (c) 2002-2019, Jouni Malinen <j@w1.fi>
5 * This software may be distributed under the terms of the BSD license.
6 * See README for more details.
11 #include "common/ieee802_11_defs.h"
15 static int hex2num(char c)
17 if (c >= '0' && c <= '9')
19 if (c >= 'a' && c <= 'f')
21 if (c >= 'A' && c <= 'F')
27 int hex2byte(const char *hex)
40 static const char * hwaddr_parse(const char *txt, u8 *addr)
44 for (i = 0; i < ETH_ALEN; i++) {
52 if (i < ETH_ALEN - 1 && *txt++ != ':')
60 * hwaddr_aton - Convert ASCII string to MAC address (colon-delimited format)
61 * @txt: MAC address as a string (e.g., "00:11:22:33:44:55")
62 * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
63 * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
65 int hwaddr_aton(const char *txt, u8 *addr)
67 return hwaddr_parse(txt, addr) ? 0 : -1;
72 * hwaddr_masked_aton - Convert ASCII string with optional mask to MAC address (colon-delimited format)
73 * @txt: MAC address with optional mask as a string (e.g., "00:11:22:33:44:55/ff:ff:ff:ff:00:00")
74 * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
75 * @mask: Buffer for the MAC address mask (ETH_ALEN = 6 bytes)
76 * @maskable: Flag to indicate whether a mask is allowed
77 * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
79 int hwaddr_masked_aton(const char *txt, u8 *addr, u8 *mask, u8 maskable)
83 /* parse address part */
84 r = hwaddr_parse(txt, addr);
88 /* check for optional mask */
89 if (*r == '\0' || isspace((unsigned char) *r)) {
90 /* no mask specified, assume default */
91 os_memset(mask, 0xff, ETH_ALEN);
92 } else if (maskable && *r == '/') {
93 /* mask specified and allowed */
94 r = hwaddr_parse(r + 1, mask);
99 /* mask specified but not allowed or trailing garbage */
108 * hwaddr_compact_aton - Convert ASCII string to MAC address (no colon delimitors format)
109 * @txt: MAC address as a string (e.g., "001122334455")
110 * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
111 * Returns: 0 on success, -1 on failure (e.g., string not a MAC address)
113 int hwaddr_compact_aton(const char *txt, u8 *addr)
117 for (i = 0; i < 6; i++) {
126 *addr++ = (a << 4) | b;
133 * hwaddr_aton2 - Convert ASCII string to MAC address (in any known format)
134 * @txt: MAC address as a string (e.g., 00:11:22:33:44:55 or 0011.2233.4455)
135 * @addr: Buffer for the MAC address (ETH_ALEN = 6 bytes)
136 * Returns: Characters used (> 0) on success, -1 on failure
138 int hwaddr_aton2(const char *txt, u8 *addr)
141 const char *pos = txt;
143 for (i = 0; i < 6; i++) {
146 while (*pos == ':' || *pos == '.' || *pos == '-')
155 *addr++ = (a << 4) | b;
163 * hexstr2bin - Convert ASCII hex string into binary data
164 * @hex: ASCII hex string (e.g., "01ab")
165 * @buf: Buffer for the binary data
166 * @len: Length of the text to convert in bytes (of buf); hex will be double
168 * Returns: 0 on success, -1 on failure (invalid hex string)
170 int hexstr2bin(const char *hex, u8 *buf, size_t len)
174 const char *ipos = hex;
177 for (i = 0; i < len; i++) {
188 int hwaddr_mask_txt(char *buf, size_t len, const u8 *addr, const u8 *mask)
194 for (i = 0; i < ETH_ALEN; i++) {
195 if (mask[i] != 0xff) {
202 res = os_snprintf(buf, len, MACSTR "/" MACSTR,
203 MAC2STR(addr), MAC2STR(mask));
205 res = os_snprintf(buf, len, MACSTR, MAC2STR(addr));
206 if (os_snprintf_error(len, res))
213 * inc_byte_array - Increment arbitrary length byte array by one
214 * @counter: Pointer to byte array
215 * @len: Length of the counter in bytes
217 * This function increments the last byte of the counter by one and continues
218 * rolling over to more significant bytes if the byte was incremented from
221 void inc_byte_array(u8 *counter, size_t len)
226 if (counter[pos] != 0)
233 void buf_shift_right(u8 *buf, size_t len, size_t bits)
237 for (i = len - 1; i > 0; i--)
238 buf[i] = (buf[i - 1] << (8 - bits)) | (buf[i] >> bits);
243 void wpa_get_ntp_timestamp(u8 *buf)
249 /* 64-bit NTP timestamp (time from 1900-01-01 00:00:00) */
251 sec = now.sec + 2208988800U; /* Epoch to 1900 */
252 /* Estimate 2^32/10^6 = 4295 - 1/32 - 1/512 */
254 usec = 4295 * usec - (usec >> 5) - (usec >> 9);
255 tmp = host_to_be32(sec);
256 os_memcpy(buf, (u8 *) &tmp, 4);
257 tmp = host_to_be32(usec);
258 os_memcpy(buf + 4, (u8 *) &tmp, 4);
262 * wpa_scnprintf - Simpler-to-use snprintf function
263 * @buf: Output buffer
267 * Simpler snprintf version that doesn't require further error checks - the
268 * return value only indicates how many bytes were actually written, excluding
269 * the NULL byte (i.e., 0 on error, size-1 if buffer is not big enough).
271 int wpa_scnprintf(char *buf, size_t size, const char *fmt, ...)
280 ret = vsnprintf(buf, size, fmt, ap);
285 if ((size_t) ret >= size)
292 int wpa_snprintf_hex_sep(char *buf, size_t buf_size, const u8 *data, size_t len,
296 char *pos = buf, *end = buf + buf_size;
302 for (i = 0; i < len; i++) {
303 ret = os_snprintf(pos, end - pos, "%02x%c",
305 if (os_snprintf_error(end - pos, ret)) {
316 static inline int _wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data,
317 size_t len, int uppercase)
320 char *pos = buf, *end = buf + buf_size;
324 for (i = 0; i < len; i++) {
325 ret = os_snprintf(pos, end - pos, uppercase ? "%02X" : "%02x",
327 if (os_snprintf_error(end - pos, ret)) {
338 * wpa_snprintf_hex - Print data as a hex string into a buffer
339 * @buf: Memory area to use as the output buffer
340 * @buf_size: Maximum buffer size in bytes (should be at least 2 * len + 1)
341 * @data: Data to be printed
342 * @len: Length of data in bytes
343 * Returns: Number of bytes written
345 int wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data, size_t len)
347 return _wpa_snprintf_hex(buf, buf_size, data, len, 0);
352 * wpa_snprintf_hex_uppercase - Print data as a upper case hex string into buf
353 * @buf: Memory area to use as the output buffer
354 * @buf_size: Maximum buffer size in bytes (should be at least 2 * len + 1)
355 * @data: Data to be printed
356 * @len: Length of data in bytes
357 * Returns: Number of bytes written
359 int wpa_snprintf_hex_uppercase(char *buf, size_t buf_size, const u8 *data,
362 return _wpa_snprintf_hex(buf, buf_size, data, len, 1);
366 #ifdef CONFIG_ANSI_C_EXTRA
369 void perror(const char *s)
371 wpa_printf(MSG_ERROR, "%s: GetLastError: %d",
372 s, (int) GetLastError());
374 #endif /* _WIN32_WCE */
381 int getopt(int argc, char *const argv[], const char *optstring)
383 static int optchr = 1;
387 if (optind >= argc) {
388 /* all arguments processed */
392 if (argv[optind][0] != '-' || argv[optind][1] == '\0') {
393 /* no option characters */
398 if (os_strcmp(argv[optind], "--") == 0) {
399 /* no more options */
404 optopt = argv[optind][optchr];
405 cp = os_strchr(optstring, optopt);
406 if (cp == NULL || optopt == ':') {
407 if (argv[optind][++optchr] == '\0') {
415 /* Argument required */
417 if (argv[optind][optchr + 1]) {
418 /* No space between option and argument */
419 optarg = &argv[optind++][optchr + 1];
420 } else if (++optind >= argc) {
421 /* option requires an argument */
424 /* Argument in the next argv */
425 optarg = argv[optind++];
429 if (argv[optind][++optchr] == '\0') {
437 #endif /* CONFIG_ANSI_C_EXTRA */
440 #ifdef CONFIG_NATIVE_WINDOWS
442 * wpa_unicode2ascii_inplace - Convert unicode string into ASCII
443 * @str: Pointer to string to convert
445 * This function converts a unicode string to ASCII using the same
446 * buffer for output. If UNICODE is not set, the buffer is not
449 void wpa_unicode2ascii_inplace(TCHAR *str)
452 char *dst = (char *) str;
454 *dst++ = (char) *str++;
460 TCHAR * wpa_strdup_tchar(const char *str)
464 buf = os_malloc((strlen(str) + 1) * sizeof(TCHAR));
467 wsprintf(buf, L"%S", str);
470 return os_strdup(str);
473 #endif /* CONFIG_NATIVE_WINDOWS */
476 void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len)
478 char *end = txt + maxlen;
481 for (i = 0; i < len; i++) {
511 if (data[i] >= 32 && data[i] <= 126) {
514 txt += os_snprintf(txt, end - txt, "\\x%02x",
525 size_t printf_decode(u8 *buf, size_t maxlen, const char *str)
527 const char *pos = str;
532 if (len + 1 >= maxlen)
585 if (*pos >= '0' && *pos <= '7')
586 val = val * 8 + (*pos++ - '0');
587 if (*pos >= '0' && *pos <= '7')
588 val = val * 8 + (*pos++ - '0');
608 * wpa_ssid_txt - Convert SSID to a printable string
609 * @ssid: SSID (32-octet string)
610 * @ssid_len: Length of ssid in octets
611 * Returns: Pointer to a printable string
613 * This function can be used to convert SSIDs into printable form. In most
614 * cases, SSIDs do not use unprintable characters, but IEEE 802.11 standard
615 * does not limit the used character set, so anything could be used in an SSID.
617 * This function uses a static buffer, so only one call can be used at the
618 * time, i.e., this is not re-entrant and the returned buffer must be used
619 * before calling this again.
621 const char * wpa_ssid_txt(const u8 *ssid, size_t ssid_len)
623 static char ssid_txt[SSID_MAX_LEN * 4 + 1];
630 printf_encode(ssid_txt, sizeof(ssid_txt), ssid, ssid_len);
635 void * __hide_aliasing_typecast(void *foo)
641 char * wpa_config_parse_string(const char *value, size_t *len)
647 pos = os_strrchr(value, '"');
648 if (pos == NULL || pos[1] != '\0')
651 str = dup_binstr(value, *len);
655 } else if (*value == 'P' && value[1] == '"') {
660 pos = os_strrchr(value, '"');
661 if (pos == NULL || pos[1] != '\0')
664 tstr = dup_binstr(value, tlen);
668 str = os_malloc(tlen + 1);
674 *len = printf_decode((u8 *) str, tlen + 1, tstr);
680 size_t tlen, hlen = os_strlen(value);
684 str = os_malloc(tlen + 1);
687 if (hexstr2bin(value, str, tlen)) {
698 int is_hex(const u8 *data, size_t len)
702 for (i = 0; i < len; i++) {
703 if (data[i] < 32 || data[i] >= 127)
710 int has_ctrl_char(const u8 *data, size_t len)
714 for (i = 0; i < len; i++) {
715 if (data[i] < 32 || data[i] == 127)
722 int has_newline(const char *str)
725 if (*str == '\n' || *str == '\r')
733 size_t merge_byte_arrays(u8 *res, size_t res_len,
734 const u8 *src1, size_t src1_len,
735 const u8 *src2, size_t src2_len)
739 os_memset(res, 0, res_len);
742 if (src1_len >= res_len) {
743 os_memcpy(res, src1, res_len);
747 os_memcpy(res, src1, src1_len);
752 if (len + src2_len >= res_len) {
753 os_memcpy(res + len, src2, res_len - len);
757 os_memcpy(res + len, src2, src2_len);
765 char * dup_binstr(const void *src, size_t len)
771 res = os_malloc(len + 1);
774 os_memcpy(res, src, len);
781 int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value)
783 struct wpa_freq_range *freq = NULL, *n;
784 unsigned int count = 0;
785 const char *pos, *pos2, *pos3;
788 * Comma separated list of frequency ranges.
789 * For example: 2412-2432,2462,5000-6000
792 while (pos && pos[0]) {
793 n = os_realloc_array(freq, count + 1,
794 sizeof(struct wpa_freq_range));
800 freq[count].min = atoi(pos);
801 pos2 = os_strchr(pos, '-');
802 pos3 = os_strchr(pos, ',');
803 if (pos2 && (!pos3 || pos2 < pos3)) {
805 freq[count].max = atoi(pos2);
807 freq[count].max = freq[count].min;
822 int freq_range_list_includes(const struct wpa_freq_range_list *list,
830 for (i = 0; i < list->num; i++) {
831 if (freq >= list->range[i].min && freq <= list->range[i].max)
839 char * freq_range_list_str(const struct wpa_freq_range_list *list)
841 char *buf, *pos, *end;
849 maxlen = list->num * 30;
850 buf = os_malloc(maxlen);
856 for (i = 0; i < list->num; i++) {
857 struct wpa_freq_range *range = &list->range[i];
859 if (range->min == range->max)
860 res = os_snprintf(pos, end - pos, "%s%u",
861 i == 0 ? "" : ",", range->min);
863 res = os_snprintf(pos, end - pos, "%s%u-%u",
865 range->min, range->max);
866 if (os_snprintf_error(end - pos, res)) {
877 int int_array_len(const int *a)
880 for (i = 0; a && a[i]; i++)
886 void int_array_concat(int **res, const int *a)
891 reslen = int_array_len(*res);
892 alen = int_array_len(a);
894 n = os_realloc_array(*res, reslen + alen + 1, sizeof(int));
900 for (i = 0; i <= alen; i++)
901 n[reslen + i] = a[i];
906 static int freq_cmp(const void *a, const void *b)
919 void int_array_sort_unique(int *a)
927 alen = int_array_len(a);
928 qsort(a, alen, sizeof(int), freq_cmp);
932 while (a[i] && a[j]) {
945 void int_array_add_unique(int **res, int a)
950 for (reslen = 0; *res && (*res)[reslen]; reslen++) {
951 if ((*res)[reslen] == a)
952 return; /* already in the list */
955 n = os_realloc_array(*res, reslen + 2, sizeof(int));
969 void str_clear_free(char *str)
972 size_t len = os_strlen(str);
973 forced_memzero(str, len);
979 void bin_clear_free(void *bin, size_t len)
982 forced_memzero(bin, len);
988 int random_mac_addr(u8 *addr)
990 if (os_get_random(addr, ETH_ALEN) < 0)
992 addr[0] &= 0xfe; /* unicast */
993 addr[0] |= 0x02; /* locally administered */
998 int random_mac_addr_keep_oui(u8 *addr)
1000 if (os_get_random(addr + 3, 3) < 0)
1002 addr[0] &= 0xfe; /* unicast */
1003 addr[0] |= 0x02; /* locally administered */
1009 * cstr_token - Get next token from const char string
1010 * @str: a constant string to tokenize
1011 * @delim: a string of delimiters
1012 * @last: a pointer to a character following the returned token
1013 * It has to be set to NULL for the first call and passed for any
1015 * Returns: a pointer to token position in str or NULL
1017 * This function is similar to str_token, but it can be used with both
1018 * char and const char strings. Differences:
1019 * - The str buffer remains unmodified
1020 * - The returned token is not a NULL terminated string, but a token
1021 * position in str buffer. If a return value is not NULL a size
1022 * of the returned token could be calculated as (last - token).
1024 const char * cstr_token(const char *str, const char *delim, const char **last)
1026 const char *end, *token = str;
1028 if (!str || !delim || !last)
1034 while (*token && os_strchr(delim, *token))
1042 while (*end && !os_strchr(delim, *end))
1051 * str_token - Get next token from a string
1052 * @buf: String to tokenize. Note that the string might be modified.
1053 * @delim: String of delimiters
1054 * @context: Pointer to save our context. Should be initialized with
1055 * NULL on the first call, and passed for any further call.
1056 * Returns: The next token, NULL if there are no more valid tokens.
1058 char * str_token(char *str, const char *delim, char **context)
1060 char *token = (char *) cstr_token(str, delim, (const char **) context);
1062 if (token && **context)
1063 *(*context)++ = '\0';
1069 size_t utf8_unescape(const char *inp, size_t in_size,
1070 char *outp, size_t out_size)
1072 size_t res_size = 0;
1078 in_size = os_strlen(inp);
1080 /* Advance past leading single quote */
1081 if (*inp == '\'' && in_size) {
1088 if (res_size >= out_size)
1093 /* Terminate on bare single quote */
1110 /* NUL terminate if space allows */
1111 if (res_size < out_size)
1118 size_t utf8_escape(const char *inp, size_t in_size,
1119 char *outp, size_t out_size)
1121 size_t res_size = 0;
1126 /* inp may or may not be NUL terminated, but must be if 0 size
1129 in_size = os_strlen(inp);
1133 if (res_size++ >= out_size)
1139 if (res_size++ >= out_size)
1150 /* NUL terminate if space allows */
1151 if (res_size < out_size)
1158 int is_ctrl_char(char c)
1160 return c > 0 && c < 32;
1165 * ssid_parse - Parse a string that contains SSID in hex or text format
1166 * @buf: Input NULL terminated string that contains the SSID
1167 * @ssid: Output SSID
1168 * Returns: 0 on success, -1 otherwise
1170 * The SSID has to be enclosed in double quotes for the text format or space
1171 * or NULL terminated string of hex digits for the hex format. buf can include
1172 * additional arguments after the SSID.
1174 int ssid_parse(const char *buf, struct wpa_ssid_value *ssid)
1176 char *tmp, *res, *end;
1181 tmp = os_strdup(buf);
1186 end = os_strchr(tmp, ' ');
1190 end = os_strchr(tmp + 1, '"');
1199 res = wpa_config_parse_string(tmp, &len);
1200 if (res && len <= SSID_MAX_LEN) {
1201 ssid->ssid_len = len;
1202 os_memcpy(ssid->ssid, res, len);
1208 return ssid->ssid_len ? 0 : -1;
1212 int str_starts(const char *str, const char *start)
1214 return os_strncmp(str, start, os_strlen(start)) == 0;
1219 * rssi_to_rcpi - Convert RSSI to RCPI
1220 * @rssi: RSSI to convert
1221 * Returns: RCPI corresponding to the given RSSI value, or 255 if not available.
1223 * It's possible to estimate RCPI based on RSSI in dBm. This calculation will
1224 * not reflect the correct value for high rates, but it's good enough for Action
1225 * frames which are transmitted with up to 24 Mbps rates.
1227 u8 rssi_to_rcpi(int rssi)
1230 return 255; /* not available */
1235 return (rssi + 110) * 2;
1239 char * get_param(const char *cmd, const char *param)
1241 const char *pos, *end;
1245 pos = os_strstr(cmd, param);
1249 pos += os_strlen(param);
1250 end = os_strchr(pos, ' ');
1254 len = os_strlen(pos);
1255 val = os_malloc(len + 1);
1258 os_memcpy(val, pos, len);
1264 /* Try to prevent most compilers from optimizing out clearing of memory that
1265 * becomes unaccessible after this function is called. This is mostly the case
1266 * for clearing local stack variables at the end of a function. This is not
1267 * exactly perfect, i.e., someone could come up with a compiler that figures out
1268 * the pointer is pointing to memset and then end up optimizing the call out, so
1269 * try go a bit further by storing the first octet (now zero) to make this even
1270 * a bit more difficult to optimize out. Once memset_s() is available, that
1271 * could be used here instead. */
1272 static void * (* const volatile memset_func)(void *, int, size_t) = memset;
1273 static u8 forced_memzero_val;
1275 void forced_memzero(void *ptr, size_t len)
1277 memset_func(ptr, 0, len);
1279 forced_memzero_val = ((u8 *) ptr)[0];