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(*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] <= 127) {
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 size_t merge_byte_arrays(u8 *res, size_t res_len,
701 const u8 *src1, size_t src1_len,
702 const u8 *src2, size_t src2_len)
706 os_memset(res, 0, res_len);
709 if (src1_len >= res_len) {
710 os_memcpy(res, src1, res_len);
714 os_memcpy(res, src1, src1_len);
719 if (len + src2_len >= res_len) {
720 os_memcpy(res + len, src2, res_len - len);
724 os_memcpy(res + len, src2, src2_len);
732 char * dup_binstr(const void *src, size_t len)
738 res = os_malloc(len + 1);
741 os_memcpy(res, src, len);
748 int freq_range_list_parse(struct wpa_freq_range_list *res, const char *value)
750 struct wpa_freq_range *freq = NULL, *n;
751 unsigned int count = 0;
752 const char *pos, *pos2, *pos3;
755 * Comma separated list of frequency ranges.
756 * For example: 2412-2432,2462,5000-6000
759 while (pos && pos[0]) {
760 n = os_realloc_array(freq, count + 1,
761 sizeof(struct wpa_freq_range));
767 freq[count].min = atoi(pos);
768 pos2 = os_strchr(pos, '-');
769 pos3 = os_strchr(pos, ',');
770 if (pos2 && (!pos3 || pos2 < pos3)) {
772 freq[count].max = atoi(pos2);
774 freq[count].max = freq[count].min;
789 int freq_range_list_includes(const struct wpa_freq_range_list *list,
797 for (i = 0; i < list->num; i++) {
798 if (freq >= list->range[i].min && freq <= list->range[i].max)
806 char * freq_range_list_str(const struct wpa_freq_range_list *list)
808 char *buf, *pos, *end;
816 maxlen = list->num * 30;
817 buf = os_malloc(maxlen);
823 for (i = 0; i < list->num; i++) {
824 struct wpa_freq_range *range = &list->range[i];
826 if (range->min == range->max)
827 res = os_snprintf(pos, end - pos, "%s%u",
828 i == 0 ? "" : ",", range->min);
830 res = os_snprintf(pos, end - pos, "%s%u-%u",
832 range->min, range->max);
833 if (os_snprintf_error(end - pos, res)) {
844 int int_array_len(const int *a)
847 for (i = 0; a && a[i]; i++)
853 void int_array_concat(int **res, const int *a)
858 reslen = int_array_len(*res);
859 alen = int_array_len(a);
861 n = os_realloc_array(*res, reslen + alen + 1, sizeof(int));
867 for (i = 0; i <= alen; i++)
868 n[reslen + i] = a[i];
873 static int freq_cmp(const void *a, const void *b)
886 void int_array_sort_unique(int *a)
894 alen = int_array_len(a);
895 qsort(a, alen, sizeof(int), freq_cmp);
899 while (a[i] && a[j]) {
912 void int_array_add_unique(int **res, int a)
917 for (reslen = 0; *res && (*res)[reslen]; reslen++) {
918 if ((*res)[reslen] == a)
919 return; /* already in the list */
922 n = os_realloc_array(*res, reslen + 2, sizeof(int));
936 void str_clear_free(char *str)
939 size_t len = os_strlen(str);
940 os_memset(str, 0, len);
946 void bin_clear_free(void *bin, size_t len)
949 os_memset(bin, 0, len);
955 int random_mac_addr(u8 *addr)
957 if (os_get_random(addr, ETH_ALEN) < 0)
959 addr[0] &= 0xfe; /* unicast */
960 addr[0] |= 0x02; /* locally administered */
965 int random_mac_addr_keep_oui(u8 *addr)
967 if (os_get_random(addr + 3, 3) < 0)
969 addr[0] &= 0xfe; /* unicast */
970 addr[0] |= 0x02; /* locally administered */
976 * cstr_token - Get next token from const char string
977 * @str: a constant string to tokenize
978 * @delim: a string of delimiters
979 * @last: a pointer to a character following the returned token
980 * It has to be set to NULL for the first call and passed for any
982 * Returns: a pointer to token position in str or NULL
984 * This function is similar to str_token, but it can be used with both
985 * char and const char strings. Differences:
986 * - The str buffer remains unmodified
987 * - The returned token is not a NULL terminated string, but a token
988 * position in str buffer. If a return value is not NULL a size
989 * of the returned token could be calculated as (last - token).
991 const char * cstr_token(const char *str, const char *delim, const char **last)
993 const char *end, *token = str;
995 if (!str || !delim || !last)
1001 while (*token && os_strchr(delim, *token))
1009 while (*end && !os_strchr(delim, *end))
1018 * str_token - Get next token from a string
1019 * @buf: String to tokenize. Note that the string might be modified.
1020 * @delim: String of delimiters
1021 * @context: Pointer to save our context. Should be initialized with
1022 * NULL on the first call, and passed for any further call.
1023 * Returns: The next token, NULL if there are no more valid tokens.
1025 char * str_token(char *str, const char *delim, char **context)
1027 char *token = (char *) cstr_token(str, delim, (const char **) context);
1029 if (token && **context)
1030 *(*context)++ = '\0';
1036 size_t utf8_unescape(const char *inp, size_t in_size,
1037 char *outp, size_t out_size)
1039 size_t res_size = 0;
1045 in_size = os_strlen(inp);
1047 /* Advance past leading single quote */
1048 if (*inp == '\'' && in_size) {
1054 if (res_size >= out_size)
1059 /* Terminate on bare single quote */
1075 /* NUL terminate if space allows */
1076 if (res_size < out_size)
1083 size_t utf8_escape(const char *inp, size_t in_size,
1084 char *outp, size_t out_size)
1086 size_t res_size = 0;
1091 /* inp may or may not be NUL terminated, but must be if 0 size
1094 in_size = os_strlen(inp);
1097 if (res_size++ >= out_size)
1103 if (res_size++ >= out_size)
1114 /* NUL terminate if space allows */
1115 if (res_size < out_size)
1122 int is_ctrl_char(char c)
1124 return c > 0 && c < 32;