2 * wpa_supplicant/hostapd / common helper functions, etc.
3 * Copyright (c) 2002-2007, 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 wpa_get_ntp_timestamp(u8 *buf)
239 /* 64-bit NTP timestamp (time from 1900-01-01 00:00:00) */
241 sec = now.sec + 2208988800U; /* Epoch to 1900 */
242 /* Estimate 2^32/10^6 = 4295 - 1/32 - 1/512 */
244 usec = 4295 * usec - (usec >> 5) - (usec >> 9);
245 tmp = host_to_be32(sec);
246 os_memcpy(buf, (u8 *) &tmp, 4);
247 tmp = host_to_be32(usec);
248 os_memcpy(buf + 4, (u8 *) &tmp, 4);
252 * wpa_scnprintf - Simpler-to-use snprintf function
253 * @buf: Output buffer
257 * Simpler snprintf version that doesn't require further error checks - the
258 * return value only indicates how many bytes were actually written, excluding
259 * the NULL byte (i.e., 0 on error, size-1 if buffer is not big enough).
261 int wpa_scnprintf(char *buf, size_t size, const char *fmt, ...)
270 ret = vsnprintf(buf, size, fmt, ap);
275 if ((size_t) ret >= size)
282 int wpa_snprintf_hex_sep(char *buf, size_t buf_size, const u8 *data, size_t len,
286 char *pos = buf, *end = buf + buf_size;
292 for (i = 0; i < len; i++) {
293 ret = os_snprintf(pos, end - pos, "%02x%c",
295 if (os_snprintf_error(end - pos, ret)) {
306 static inline int _wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data,
307 size_t len, int uppercase)
310 char *pos = buf, *end = buf + buf_size;
314 for (i = 0; i < len; i++) {
315 ret = os_snprintf(pos, end - pos, uppercase ? "%02X" : "%02x",
317 if (os_snprintf_error(end - pos, ret)) {
328 * wpa_snprintf_hex - Print data as a hex string into a buffer
329 * @buf: Memory area to use as the output buffer
330 * @buf_size: Maximum buffer size in bytes (should be at least 2 * len + 1)
331 * @data: Data to be printed
332 * @len: Length of data in bytes
333 * Returns: Number of bytes written
335 int wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data, size_t len)
337 return _wpa_snprintf_hex(buf, buf_size, data, len, 0);
342 * wpa_snprintf_hex_uppercase - Print data as a upper case hex string into buf
343 * @buf: Memory area to use as the output buffer
344 * @buf_size: Maximum buffer size in bytes (should be at least 2 * len + 1)
345 * @data: Data to be printed
346 * @len: Length of data in bytes
347 * Returns: Number of bytes written
349 int wpa_snprintf_hex_uppercase(char *buf, size_t buf_size, const u8 *data,
352 return _wpa_snprintf_hex(buf, buf_size, data, len, 1);
356 #ifdef CONFIG_ANSI_C_EXTRA
359 void perror(const char *s)
361 wpa_printf(MSG_ERROR, "%s: GetLastError: %d",
362 s, (int) GetLastError());
364 #endif /* _WIN32_WCE */
371 int getopt(int argc, char *const argv[], const char *optstring)
373 static int optchr = 1;
377 if (optind >= argc) {
378 /* all arguments processed */
382 if (argv[optind][0] != '-' || argv[optind][1] == '\0') {
383 /* no option characters */
388 if (os_strcmp(argv[optind], "--") == 0) {
389 /* no more options */
394 optopt = argv[optind][optchr];
395 cp = os_strchr(optstring, optopt);
396 if (cp == NULL || optopt == ':') {
397 if (argv[optind][++optchr] == '\0') {
405 /* Argument required */
407 if (argv[optind][optchr + 1]) {
408 /* No space between option and argument */
409 optarg = &argv[optind++][optchr + 1];
410 } else if (++optind >= argc) {
411 /* option requires an argument */
414 /* Argument in the next argv */
415 optarg = argv[optind++];
419 if (argv[optind][++optchr] == '\0') {
427 #endif /* CONFIG_ANSI_C_EXTRA */
430 #ifdef CONFIG_NATIVE_WINDOWS
432 * wpa_unicode2ascii_inplace - Convert unicode string into ASCII
433 * @str: Pointer to string to convert
435 * This function converts a unicode string to ASCII using the same
436 * buffer for output. If UNICODE is not set, the buffer is not
439 void wpa_unicode2ascii_inplace(TCHAR *str)
442 char *dst = (char *) str;
444 *dst++ = (char) *str++;
450 TCHAR * wpa_strdup_tchar(const char *str)
454 buf = os_malloc((strlen(str) + 1) * sizeof(TCHAR));
457 wsprintf(buf, L"%S", str);
460 return os_strdup(str);
463 #endif /* CONFIG_NATIVE_WINDOWS */
466 void printf_encode(char *txt, size_t maxlen, const u8 *data, size_t len)
468 char *end = txt + maxlen;
471 for (i = 0; i < len; i++) {
501 if (data[i] >= 32 && data[i] <= 126) {
504 txt += os_snprintf(txt, end - txt, "\\x%02x",
515 size_t printf_decode(u8 *buf, size_t maxlen, const char *str)
517 const char *pos = str;
522 if (len + 1 >= maxlen)
575 if (*pos >= '0' && *pos <= '7')
576 val = val * 8 + (*pos++ - '0');
577 if (*pos >= '0' && *pos <= '7')
578 val = val * 8 + (*pos++ - '0');
598 * wpa_ssid_txt - Convert SSID to a printable string
599 * @ssid: SSID (32-octet string)
600 * @ssid_len: Length of ssid in octets
601 * Returns: Pointer to a printable string
603 * This function can be used to convert SSIDs into printable form. In most
604 * cases, SSIDs do not use unprintable characters, but IEEE 802.11 standard
605 * does not limit the used character set, so anything could be used in an SSID.
607 * This function uses a static buffer, so only one call can be used at the
608 * time, i.e., this is not re-entrant and the returned buffer must be used
609 * before calling this again.
611 const char * wpa_ssid_txt(const u8 *ssid, size_t ssid_len)
613 static char ssid_txt[SSID_MAX_LEN * 4 + 1];
620 printf_encode(ssid_txt, sizeof(ssid_txt), ssid, ssid_len);
625 void * __hide_aliasing_typecast(void *foo)
631 char * wpa_config_parse_string(const char *value, size_t *len)
637 pos = os_strrchr(value, '"');
638 if (pos == NULL || pos[1] != '\0')
641 str = dup_binstr(value, *len);
645 } else if (*value == 'P' && value[1] == '"') {
650 pos = os_strrchr(value, '"');
651 if (pos == NULL || pos[1] != '\0')
654 tstr = dup_binstr(value, tlen);
658 str = os_malloc(tlen + 1);
664 *len = printf_decode((u8 *) str, tlen + 1, tstr);
670 size_t tlen, hlen = os_strlen(value);
674 str = os_malloc(tlen + 1);
677 if (hexstr2bin(value, str, tlen)) {
688 int is_hex(const u8 *data, size_t len)
692 for (i = 0; i < len; i++) {
693 if (data[i] < 32 || data[i] >= 127)
700 int has_ctrl_char(const u8 *data, size_t len)
704 for (i = 0; i < len; i++) {
705 if (data[i] < 32 || data[i] == 127)
712 int has_newline(const char *str)
715 if (*str == '\n' || *str == '\r')
723 size_t merge_byte_arrays(u8 *res, size_t res_len,
724 const u8 *src1, size_t src1_len,
725 const u8 *src2, size_t src2_len)
729 os_memset(res, 0, res_len);
732 if (src1_len >= res_len) {
733 os_memcpy(res, src1, res_len);
737 os_memcpy(res, src1, src1_len);
742 if (len + src2_len >= res_len) {
743 os_memcpy(res + len, src2, res_len - len);
747 os_memcpy(res + len, src2, src2_len);
755 char * dup_binstr(const void *src, size_t len)
761 res = os_malloc(len + 1);
764 os_memcpy(res, src, len);
771 int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value)
773 struct wpa_freq_range *freq = NULL, *n;
774 unsigned int count = 0;
775 const char *pos, *pos2, *pos3;
778 * Comma separated list of frequency ranges.
779 * For example: 2412-2432,2462,5000-6000
782 while (pos && pos[0]) {
783 n = os_realloc_array(freq, count + 1,
784 sizeof(struct wpa_freq_range));
790 freq[count].min = atoi(pos);
791 pos2 = os_strchr(pos, '-');
792 pos3 = os_strchr(pos, ',');
793 if (pos2 && (!pos3 || pos2 < pos3)) {
795 freq[count].max = atoi(pos2);
797 freq[count].max = freq[count].min;
812 int freq_range_list_includes(const struct wpa_freq_range_list *list,
820 for (i = 0; i < list->num; i++) {
821 if (freq >= list->range[i].min && freq <= list->range[i].max)
829 char * freq_range_list_str(const struct wpa_freq_range_list *list)
831 char *buf, *pos, *end;
839 maxlen = list->num * 30;
840 buf = os_malloc(maxlen);
846 for (i = 0; i < list->num; i++) {
847 struct wpa_freq_range *range = &list->range[i];
849 if (range->min == range->max)
850 res = os_snprintf(pos, end - pos, "%s%u",
851 i == 0 ? "" : ",", range->min);
853 res = os_snprintf(pos, end - pos, "%s%u-%u",
855 range->min, range->max);
856 if (os_snprintf_error(end - pos, res)) {
867 int int_array_len(const int *a)
870 for (i = 0; a && a[i]; i++)
876 void int_array_concat(int **res, const int *a)
881 reslen = int_array_len(*res);
882 alen = int_array_len(a);
884 n = os_realloc_array(*res, reslen + alen + 1, sizeof(int));
890 for (i = 0; i <= alen; i++)
891 n[reslen + i] = a[i];
896 static int freq_cmp(const void *a, const void *b)
909 void int_array_sort_unique(int *a)
917 alen = int_array_len(a);
918 qsort(a, alen, sizeof(int), freq_cmp);
922 while (a[i] && a[j]) {
935 void int_array_add_unique(int **res, int a)
940 for (reslen = 0; *res && (*res)[reslen]; reslen++) {
941 if ((*res)[reslen] == a)
942 return; /* already in the list */
945 n = os_realloc_array(*res, reslen + 2, sizeof(int));
959 void str_clear_free(char *str)
962 size_t len = os_strlen(str);
963 os_memset(str, 0, len);
969 void bin_clear_free(void *bin, size_t len)
972 os_memset(bin, 0, len);
978 int random_mac_addr(u8 *addr)
980 if (os_get_random(addr, ETH_ALEN) < 0)
982 addr[0] &= 0xfe; /* unicast */
983 addr[0] |= 0x02; /* locally administered */
988 int random_mac_addr_keep_oui(u8 *addr)
990 if (os_get_random(addr + 3, 3) < 0)
992 addr[0] &= 0xfe; /* unicast */
993 addr[0] |= 0x02; /* locally administered */
999 * cstr_token - Get next token from const char string
1000 * @str: a constant string to tokenize
1001 * @delim: a string of delimiters
1002 * @last: a pointer to a character following the returned token
1003 * It has to be set to NULL for the first call and passed for any
1005 * Returns: a pointer to token position in str or NULL
1007 * This function is similar to str_token, but it can be used with both
1008 * char and const char strings. Differences:
1009 * - The str buffer remains unmodified
1010 * - The returned token is not a NULL terminated string, but a token
1011 * position in str buffer. If a return value is not NULL a size
1012 * of the returned token could be calculated as (last - token).
1014 const char * cstr_token(const char *str, const char *delim, const char **last)
1016 const char *end, *token = str;
1018 if (!str || !delim || !last)
1024 while (*token && os_strchr(delim, *token))
1032 while (*end && !os_strchr(delim, *end))
1041 * str_token - Get next token from a string
1042 * @buf: String to tokenize. Note that the string might be modified.
1043 * @delim: String of delimiters
1044 * @context: Pointer to save our context. Should be initialized with
1045 * NULL on the first call, and passed for any further call.
1046 * Returns: The next token, NULL if there are no more valid tokens.
1048 char * str_token(char *str, const char *delim, char **context)
1050 char *token = (char *) cstr_token(str, delim, (const char **) context);
1052 if (token && **context)
1053 *(*context)++ = '\0';
1059 size_t utf8_unescape(const char *inp, size_t in_size,
1060 char *outp, size_t out_size)
1062 size_t res_size = 0;
1068 in_size = os_strlen(inp);
1070 /* Advance past leading single quote */
1071 if (*inp == '\'' && in_size) {
1077 if (res_size >= out_size)
1082 /* Terminate on bare single quote */
1098 /* NUL terminate if space allows */
1099 if (res_size < out_size)
1106 size_t utf8_escape(const char *inp, size_t in_size,
1107 char *outp, size_t out_size)
1109 size_t res_size = 0;
1114 /* inp may or may not be NUL terminated, but must be if 0 size
1117 in_size = os_strlen(inp);
1120 if (res_size++ >= out_size)
1126 if (res_size++ >= out_size)
1137 /* NUL terminate if space allows */
1138 if (res_size < out_size)
1145 int is_ctrl_char(char c)
1147 return c > 0 && c < 32;
1152 * ssid_parse - Parse a string that contains SSID in hex or text format
1153 * @buf: Input NULL terminated string that contains the SSID
1154 * @ssid: Output SSID
1155 * Returns: 0 on success, -1 otherwise
1157 * The SSID has to be enclosed in double quotes for the text format or space
1158 * or NULL terminated string of hex digits for the hex format. buf can include
1159 * additional arguments after the SSID.
1161 int ssid_parse(const char *buf, struct wpa_ssid_value *ssid)
1163 char *tmp, *res, *end;
1168 tmp = os_strdup(buf);
1173 end = os_strchr(tmp, ' ');
1177 end = os_strchr(tmp + 1, '"');
1186 res = wpa_config_parse_string(tmp, &len);
1187 if (res && len <= SSID_MAX_LEN) {
1188 ssid->ssid_len = len;
1189 os_memcpy(ssid->ssid, res, len);
1195 return ssid->ssid_len ? 0 : -1;
1199 int str_starts(const char *str, const char *start)
1201 return os_strncmp(str, start, os_strlen(start)) == 0;