2 * misc.c Various miscellaneous functions.
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
20 * Copyright 2000,2006 The FreeRADIUS server project
25 #include <freeradius-devel/libradius.h>
34 #define FR_PUT_LE16(a, val)\
36 a[1] = ((uint16_t) (val)) >> 8;\
37 a[0] = ((uint16_t) (val)) & 0xff;\
40 bool fr_dns_lookups = false; /* IP -> hostname lookups? */
41 bool fr_hostname_lookups = true; /* hostname -> IP lookups? */
44 static char const *months[] = {
45 "jan", "feb", "mar", "apr", "may", "jun",
46 "jul", "aug", "sep", "oct", "nov", "dec" };
48 fr_thread_local_setup(char *, fr_inet_ntop_buffer) /* macro */
50 typedef struct fr_talloc_link {
55 /** Sets a signal handler using sigaction if available, else signal
57 * @param sig to set handler for.
58 * @param func handler to set.
60 int fr_set_signal(int sig, sig_t func)
65 memset(&act, 0, sizeof(act));
67 sigemptyset(&act.sa_mask);
68 act.sa_handler = func;
70 if (sigaction(sig, &act, NULL) < 0) {
71 fr_strerror_printf("Failed setting signal %i handler via sigaction(): %s", sig, fr_syserror(errno));
75 if (signal(sig, func) < 0) {
76 fr_strerror_printf("Failed setting signal %i handler via signal(): %s", sig, fr_syserror(errno));
83 /** Uninstall a signal for a specific handler
85 * man sigaction says these are fine to call from a signal handler.
89 int fr_unset_signal(int sig)
94 memset(&act, 0, sizeof(act));
96 sigemptyset(&act.sa_mask);
97 act.sa_handler = SIG_DFL;
99 return sigaction(sig, &act, NULL);
101 return signal(sig, SIG_DFL);
105 static int _fr_trigger_talloc_ctx_free(fr_talloc_link_t *trigger)
107 if (trigger->armed) talloc_free(trigger->child);
112 static int _fr_disarm_talloc_ctx_free(bool **armed)
118 /** Link a parent and a child context, so the child is freed before the parent
120 * @note This is not thread safe. Do not free parent before threads are joined, do not call from a child thread.
121 * @note It's OK to free the child before threads are joined, but this will leak memory until the parent is freed.
123 * @param parent who's fate the child should share.
124 * @param child bound to parent's lifecycle.
125 * @return 0 on success -1 on failure.
127 int fr_link_talloc_ctx_free(TALLOC_CTX *parent, TALLOC_CTX *child)
129 fr_talloc_link_t *trigger;
132 trigger = talloc(parent, fr_talloc_link_t);
133 if (!trigger) return -1;
135 disarm = talloc(child, bool *);
137 talloc_free(trigger);
141 trigger->child = child;
142 trigger->armed = true;
143 *disarm = &trigger->armed;
145 talloc_set_destructor(trigger, _fr_trigger_talloc_ctx_free);
146 talloc_set_destructor(disarm, _fr_disarm_talloc_ctx_free);
152 * Explicitly cleanup the memory allocated to the error inet_ntop
155 static void _fr_inet_ntop_free(void *arg)
160 /** Wrapper around inet_ntop, prints IPv4/IPv6 addresses
162 * inet_ntop requires the caller pass in a buffer for the address.
163 * This would be annoying and cumbersome, seeing as quite often the ASCII
164 * address is only used for logging output.
166 * So as with lib/log.c use TLS to allocate thread specific buffers, and
167 * write the IP address there instead.
169 * @param af address family, either AF_INET or AF_INET6.
170 * @param src pointer to network address structure.
171 * @return NULL on error, else pointer to ASCII buffer containing text version of address.
173 char const *fr_inet_ntop(int af, void const *src)
181 buffer = fr_thread_local_init(fr_inet_ntop_buffer, _fr_inet_ntop_free);
186 * malloc is thread safe, talloc is not
188 buffer = malloc(sizeof(char) * INET6_ADDRSTRLEN);
190 fr_perror("Failed allocating memory for inet_ntop buffer");
194 ret = fr_thread_local_set(fr_inet_ntop_buffer, buffer);
196 fr_perror("Failed setting up TLS for inet_ntop buffer: %s", fr_syserror(ret));
203 return inet_ntop(af, src, buffer, INET6_ADDRSTRLEN);
207 * Return an IP address in standard dot notation
211 char const *ip_ntoa(char *buffer, uint32_t ipaddr)
213 ipaddr = ntohl(ipaddr);
215 sprintf(buffer, "%d.%d.%d.%d",
216 (ipaddr >> 24) & 0xff,
217 (ipaddr >> 16) & 0xff,
218 (ipaddr >> 8) & 0xff,
224 * Parse decimal digits until we run out of decimal digits.
226 static int ip_octet_from_str(char const *str, uint32_t *poctet)
231 if ((*p < '0') || (*p > '9')) {
237 while ((*p >= '0') && (*p <= '9')) {
242 if (octet > 255) return -1;
250 static int ip_prefix_from_str(char const *str, uint32_t *paddr)
259 for (shift = 24; shift >= 0; shift -= 8) {
260 length = ip_octet_from_str(p, &octet);
261 if (length <= 0) return -1;
263 addr |= octet << shift;
267 * EOS or / means we're done.
269 if (!*p || (*p == '/')) break;
272 * We require dots between octets.
274 if (*p != '.') return -1;
278 *paddr = htonl(addr);
283 /** Parse an IPv4 address or IPv4 prefix in presentation format (and others)
285 * @param out Where to write the ip address value.
286 * @param value to parse, may be dotted quad [+ prefix], or integer, or octal number, or '*' (INADDR_ANY).
287 * @param inlen Length of value, if value is \0 terminated inlen may be -1.
288 * @param resolve If true and value doesn't look like an IP address, try and resolve value as a hostname.
289 * @param fallback to IPv6 resolution if no A records can be found.
290 * @return 0 if ip address was parsed successfully, else -1 on error.
292 int fr_pton4(fr_ipaddr_t *out, char const *value, ssize_t inlen, bool resolve, bool fallback)
298 /* Dotted quad + / + [0-9]{1,2} */
299 char buffer[INET_ADDRSTRLEN + 3];
302 * Copy to intermediary buffer if we were given a length
305 if (inlen >= (ssize_t)sizeof(buffer)) {
306 fr_strerror_printf("Invalid IPv4 address string \"%s\"", value);
309 memcpy(buffer, value, inlen);
310 buffer[inlen] = '\0';
314 p = strchr(value, '/');
317 * 192.0.2.2 is parsed as if it was /32
324 * Allow '*' as the wildcard address usually 0.0.0.0
326 if ((value[0] == '*') && (value[1] == '\0')) {
327 out->ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
330 * Convert things which are obviously integers to IP addresses
332 * We assume the number is the bigendian representation of the
335 } else if (is_integer(value) || ((value[0] == '0') && (value[1] == 'x'))) {
336 out->ipaddr.ip4addr.s_addr = htonl(strtoul(value, NULL, 0));
338 } else if (!resolve) {
339 if (inet_pton(AF_INET, value, &out->ipaddr.ip4addr.s_addr) <= 0) {
340 fr_strerror_printf("Failed to parse IPv4 addreess string \"%s\"", value);
343 } else if (ip_hton(out, AF_INET, value, fallback) < 0) return -1;
349 * Copy the IP portion into a temporary buffer if we haven't already.
351 if (inlen < 0) memcpy(buffer, value, p - value);
352 buffer[p - value] = '\0';
354 if (ip_prefix_from_str(buffer, &out->ipaddr.ip4addr.s_addr) <= 0) {
355 fr_strerror_printf("Failed to parse IPv4 address string \"%s\"", value);
359 mask = strtoul(p + 1, &eptr, 10);
361 fr_strerror_printf("Invalid IPv4 mask length \"%s\". Should be between 0-32", p);
365 if (eptr[0] != '\0') {
366 fr_strerror_printf("Failed to parse IPv4 address string \"%s\", "
367 "got garbage after mask length \"%s\"", value, eptr);
372 out->ipaddr.ip4addr = fr_inaddr_mask(&out->ipaddr.ip4addr, mask);
375 out->prefix = (uint8_t) mask;
381 /** Parse an IPv6 address or IPv6 prefix in presentation format (and others)
383 * @param out Where to write the ip address value.
384 * @param value to parse.
385 * @param inlen Length of value, if value is \0 terminated inlen may be -1.
386 * @param resolve If true and value doesn't look like an IP address, try and resolve value as a hostname.
387 * @param fallback to IPv4 resolution if no AAAA records can be found.
388 * @return 0 if ip address was parsed successfully, else -1 on error.
390 int fr_pton6(fr_ipaddr_t *out, char const *value, ssize_t inlen, bool resolve, bool fallback)
396 /* IPv6 + / + [0-9]{1,3} */
397 char buffer[INET6_ADDRSTRLEN + 4];
400 * Copy to intermediary buffer if we were given a length
403 if (inlen >= (ssize_t)sizeof(buffer)) {
404 fr_strerror_printf("Invalid IPv6 address string \"%s\"", value);
407 memcpy(buffer, value, inlen);
408 buffer[inlen] = '\0';
412 p = strchr(value, '/');
418 * Allow '*' as the wildcard address
420 if ((value[0] == '*') && (value[1] == '\0')) {
421 memset(out->ipaddr.ip6addr.s6_addr, 0, sizeof(out->ipaddr.ip6addr.s6_addr));
422 } else if (!resolve) {
423 if (inet_pton(AF_INET6, value, out->ipaddr.ip6addr.s6_addr) <= 0) {
424 fr_strerror_printf("Failed to parse IPv6 address string \"%s\"", value);
427 } else if (ip_hton(out, AF_INET6, value, fallback) < 0) return -1;
432 if ((p - value) >= INET6_ADDRSTRLEN) {
433 fr_strerror_printf("Invalid IPv6 address string \"%s\"", value);
438 * Copy string to temporary buffer if we didn't do it earlier
440 if (inlen < 0) memcpy(buffer, value, p - value);
441 buffer[p - value] = '\0';
444 if (inet_pton(AF_INET6, buffer, out->ipaddr.ip6addr.s6_addr) <= 0) {
445 fr_strerror_printf("Failed to parse IPv6 address string \"%s\"", value);
448 } else if (ip_hton(out, AF_INET6, buffer, fallback) < 0) return -1;
450 prefix = strtoul(p + 1, &eptr, 10);
452 fr_strerror_printf("Invalid IPv6 mask length \"%s\". Should be between 0-128", p);
455 if (eptr[0] != '\0') {
456 fr_strerror_printf("Failed to parse IPv6 address string \"%s\", "
457 "got garbage after mask length \"%s\"", value, eptr);
462 struct in6_addr addr;
464 addr = fr_in6addr_mask(&out->ipaddr.ip6addr, prefix);
465 memcpy(out->ipaddr.ip6addr.s6_addr, addr.s6_addr, sizeof(out->ipaddr.ip6addr.s6_addr));
468 out->prefix = (uint8_t) prefix;
474 /** Simple wrapper to decide whether an IP value is v4 or v6 and call the appropriate parser.
476 * @param[out] out Where to write the ip address value.
477 * @param[in] value to parse.
478 * @param[in] inlen Length of value, if value is \0 terminated inlen may be -1.
479 * @param[in] resolve If true and value doesn't look like an IP address, try and resolve value as a
481 * @param[in] af If the address type is not obvious from the format, and resolve is true, the DNS
482 * record (A or AAAA) we require. Also controls which parser we pass the address to if
483 * we have no idea what it is.
485 * - 0 if ip address was parsed successfully.
488 int fr_pton(fr_ipaddr_t *out, char const *value, ssize_t inlen, int af, bool resolve)
492 len = (inlen >= 0) ? (size_t)inlen : strlen(value);
493 for (i = 0; i < len; i++) switch (value[i]) {
495 * ':' is illegal in domain names and IPv4 addresses.
496 * Must be v6 and cannot be a domain.
499 return fr_pton6(out, value, inlen, false, false);
502 * Chars which don't really tell us anything
510 * Outside the range of IPv4 chars, must be a domain
511 * Use A record in preference to AAAA record.
513 if ((value[i] < '0') || (value[i] > '9')) {
515 fr_strerror_printf("Not IPv4/6 address, and asked not to resolve");
520 return fr_pton4(out, value, inlen, resolve, true);
523 return fr_pton4(out, value, inlen, resolve, false);
526 return fr_pton6(out, value, inlen, resolve, false);
529 fr_strerror_printf("Invalid address family %i", af);
537 * All chars were in the IPv4 set [0-9/.], must be an IPv4
540 return fr_pton4(out, value, inlen, false, false);
543 /** Parses IPv4/6 address + port, to fr_ipaddr_t and integer
545 * @param[out] out Where to write the ip address value.
546 * @param[out] port_out Where to write the port (0 if no port found).
547 * @param[in] value to parse.
548 * @param[in] inlen Length of value, if value is \0 terminated inlen may be -1.
549 * @param[in] af If the address type is not obvious from the format, and resolve is true, the DNS
550 * record (A or AAAA) we require. Also controls which parser we pass the address to if
551 * we have no idea what it is.
552 * @param[in] resolve If true and value doesn't look like an IP address, try and resolve value as a
555 int fr_pton_port(fr_ipaddr_t *out, uint16_t *port_out, char const *value, ssize_t inlen, int af, bool resolve)
557 char const *p = value, *q;
565 len = (inlen >= 0) ? (size_t)inlen : strlen(value);
568 if (!(q = memchr(p + 1, ']', len - 1))) {
569 fr_strerror_printf("Missing closing ']' for IPv6 address");
574 * inet_pton doesn't like the address being wrapped in []
576 if (fr_pton6(out, p + 1, (q - p) - 1, false, false) < 0) return -1;
587 * Host, IPv4 or IPv6 with no port
589 q = memchr(p, ':', len);
590 if (!q) return fr_pton(out, p, len, af, resolve);
593 * IPv4 or host, with port
595 if (fr_pton(out, p, (q - p), af, resolve) < 0) return -1;
599 * Valid ports are a maximum of 5 digits, so if the
600 * input length indicates there are more than 5 chars
601 * after the ':' then there's an issue.
603 if (inlen > ((q + sizeof(buffer)) - value)) {
605 fr_strerror_printf("IP string contains trailing garbage after port delimiter");
609 p = q + 1; /* Move to first digit */
611 strlcpy(buffer, p, (len - (p - value)) + 1);
612 port = strtoul(buffer, &end, 10);
613 if (*end != '\0') goto error; /* Trailing garbage after integer */
615 if ((port > UINT16_MAX) || (port == 0)) {
616 fr_strerror_printf("Port %lu outside valid port range 1-" STRINGIFY(UINT16_MAX), port);
624 int fr_ntop(char *out, size_t outlen, fr_ipaddr_t *addr)
626 char buffer[INET6_ADDRSTRLEN];
628 if (inet_ntop(addr->af, &(addr->ipaddr), buffer, sizeof(buffer)) == NULL) return -1;
630 return snprintf(out, outlen, "%s/%i", buffer, addr->prefix);
634 * cppcheck apparently can't pick this up from the system headers.
641 * Internal wrapper for locking, to minimize the number of ifdef's
645 int rad_lockfd(int fd, int lock_len)
654 fl.l_whence = SEEK_CUR;
656 return fcntl(fd, F_SETLKW, (void *)&fl);
658 #error "missing definition for F_WRLCK, all file locks will fail"
665 * Internal wrapper for locking, to minimize the number of ifdef's
667 * Lock an fd, prefer lockf() over flock()
668 * Nonblocking version.
670 int rad_lockfd_nonblock(int fd, int lock_len)
679 fl.l_whence = SEEK_CUR;
681 return fcntl(fd, F_SETLK, (void *)&fl);
683 #error "missing definition for F_WRLCK, all file locks will fail"
690 * Internal wrapper for unlocking, to minimize the number of ifdef's
693 * Unlock an fd, prefer lockf() over flock()
695 int rad_unlockfd(int fd, int lock_len)
704 fl.l_whence = SEEK_CUR;
706 return fcntl(fd, F_UNLCK, (void *)&fl);
708 #error "missing definition for F_WRLCK, all file locks will fail"
715 * Return an interface-id in standard colon notation
717 char *ifid_ntoa(char *buffer, size_t size, uint8_t const *ifid)
719 snprintf(buffer, size, "%x:%x:%x:%x",
720 (ifid[0] << 8) + ifid[1], (ifid[2] << 8) + ifid[3],
721 (ifid[4] << 8) + ifid[5], (ifid[6] << 8) + ifid[7]);
727 * Return an interface-id from
728 * one supplied in standard colon notation.
730 uint8_t *ifid_aton(char const *ifid_str, uint8_t *ifid)
732 static char const xdigits[] = "0123456789abcdef";
734 int num_id = 0, val = 0, idx = 0;
736 for (p = ifid_str; ; ++p) {
737 if (*p == ':' || *p == '\0') {
742 * Drop 'val' into the array.
744 ifid[idx] = (val >> 8) & 0xff;
745 ifid[idx + 1] = val & 0xff;
748 * Must have all entries before
759 } else if ((pch = strchr(xdigits, tolower(*p))) != NULL) {
763 * Dumb version of 'scanf'
766 val |= (pch - xdigits);
774 #ifndef HAVE_INET_PTON
775 static int inet_pton4(char const *src, struct in_addr *dst)
781 static char const digits[] = "0123456789";
787 while (*p && ((off = strchr(digits, *p)) != NULL)) {
789 num += (off - digits);
791 if (num > 255) return 0;
798 * Not a digit, MUST be a dot, else we
810 * End of the string. At the fourth
811 * octet is OK, anything else is an
819 memcpy(dst, &tmp, sizeof(tmp));
824 #ifdef HAVE_STRUCT_SOCKADDR_IN6
825 /** Convert presentation level address to network order binary form
827 * @note Does not touch dst unless it's returning 1.
828 * @note :: in a full address is silently ignored.
829 * @note Inspired by Mark Andrews.
830 * @author Paul Vixie, 1996.
832 * @param src presentation level address.
833 * @param dst where to write output address.
834 * @return 1 if `src' is a valid [RFC1884 2.2] address, else 0.
836 static int inet_pton6(char const *src, unsigned char *dst)
838 static char const xdigits_l[] = "0123456789abcdef",
839 xdigits_u[] = "0123456789ABCDEF";
840 u_char tmp[IN6ADDRSZ], *tp, *endp, *colonp;
841 char const *xdigits, *curtok;
845 memset((tp = tmp), 0, IN6ADDRSZ);
846 endp = tp + IN6ADDRSZ;
848 /* Leading :: requires some special handling. */
855 while ((ch = *src++) != '\0') {
858 if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
859 pch = strchr((xdigits = xdigits_u), ch);
862 val |= (pch - xdigits);
876 if (tp + INT16SZ > endp)
878 *tp++ = (u_char) (val >> 8) & 0xff;
879 *tp++ = (u_char) val & 0xff;
884 if (ch == '.' && ((tp + INADDRSZ) <= endp) &&
885 inet_pton4(curtok, (struct in_addr *) tp) > 0) {
888 break; /* '\0' was seen by inet_pton4(). */
893 if (tp + INT16SZ > endp)
895 *tp++ = (u_char) (val >> 8) & 0xff;
896 *tp++ = (u_char) val & 0xff;
898 if (colonp != NULL) {
900 * Since some memmove()'s erroneously fail to handle
901 * overlapping regions, we'll do the shift by hand.
903 int const n = tp - colonp;
906 for (i = 1; i <= n; i++) {
907 endp[- i] = colonp[n - i];
914 /* bcopy(tmp, dst, IN6ADDRSZ); */
915 memcpy(dst, tmp, IN6ADDRSZ);
921 * Utility function, so that the rest of the server doesn't
922 * have ifdef's around IPv6 support
924 int inet_pton(int af, char const *src, void *dst)
927 return inet_pton4(src, dst);
929 #ifdef HAVE_STRUCT_SOCKADDR_IN6
931 if (af == AF_INET6) {
932 return inet_pton6(src, dst);
940 #ifndef HAVE_INET_NTOP
942 * Utility function, so that the rest of the server doesn't
943 * have ifdef's around IPv6 support
945 char const *inet_ntop(int af, void const *src, char *dst, size_t cnt)
948 uint8_t const *ipaddr = src;
950 if (cnt <= INET_ADDRSTRLEN) return NULL;
952 snprintf(dst, cnt, "%d.%d.%d.%d",
953 ipaddr[0], ipaddr[1],
954 ipaddr[2], ipaddr[3]);
959 * If the system doesn't define this, we define it
962 if (af == AF_INET6) {
963 struct in6_addr const *ipaddr = src;
965 if (cnt <= INET6_ADDRSTRLEN) return NULL;
967 snprintf(dst, cnt, "%x:%x:%x:%x:%x:%x:%x:%x",
968 (ipaddr->s6_addr[0] << 8) | ipaddr->s6_addr[1],
969 (ipaddr->s6_addr[2] << 8) | ipaddr->s6_addr[3],
970 (ipaddr->s6_addr[4] << 8) | ipaddr->s6_addr[5],
971 (ipaddr->s6_addr[6] << 8) | ipaddr->s6_addr[7],
972 (ipaddr->s6_addr[8] << 8) | ipaddr->s6_addr[9],
973 (ipaddr->s6_addr[10] << 8) | ipaddr->s6_addr[11],
974 (ipaddr->s6_addr[12] << 8) | ipaddr->s6_addr[13],
975 (ipaddr->s6_addr[14] << 8) | ipaddr->s6_addr[15]);
979 return NULL; /* don't support IPv6 */
983 /** Wrappers for IPv4/IPv6 host to IP address lookup
985 * This function returns only one IP address, of the specified address family,
986 * or the first address (of whatever family), if AF_UNSPEC is used.
988 * If fallback is specified and af is AF_INET, but no AF_INET records were
989 * found and a record for AF_INET6 exists that record will be returned.
991 * If fallback is specified and af is AF_INET6, and a record with AF_INET4 exists
992 * that record will be returned instead.
994 * @param out Where to write result.
995 * @param af To search for in preference.
996 * @param hostname to search for.
997 * @param fallback to the other adress family, if no records matching af, found.
998 * @return 0 on success, else -1 on failure.
1000 int ip_hton(fr_ipaddr_t *out, int af, char const *hostname, bool fallback)
1003 struct addrinfo hints, *ai = NULL, *alt = NULL, *res = NULL;
1006 * Avoid malloc for IP addresses. This helps us debug
1007 * memory errors when using talloc.
1012 if (!fr_hostname_lookups) {
1014 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1015 if (af == AF_UNSPEC) {
1018 for (p = hostname; *p != '\0'; p++) {
1029 if (af == AF_UNSPEC) af = AF_INET;
1031 if (!inet_pton(af, hostname, &(out->ipaddr))) return -1;
1037 memset(&hints, 0, sizeof(hints));
1040 * If we're falling back we need both IPv4 and IPv6 records
1043 hints.ai_family = AF_UNSPEC;
1045 hints.ai_family = af;
1048 if ((rcode = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
1052 fr_strerror_printf("Failed resolving \"%s\" to IP address: %s",
1053 hostname, gai_strerror(rcode));
1057 fr_strerror_printf("Failed resolving \"%s\" to IPv4 address: %s",
1058 hostname, gai_strerror(rcode));
1062 fr_strerror_printf("Failed resolving \"%s\" to IPv6 address: %s",
1063 hostname, gai_strerror(rcode));
1068 for (ai = res; ai; ai = ai->ai_next) {
1069 if ((af == ai->ai_family) || (af == AF_UNSPEC)) break;
1070 if (!alt && fallback && ((ai->ai_family == AF_INET) || (ai->ai_family == AF_INET6))) alt = ai;
1075 fr_strerror_printf("ip_hton failed to find requested information for host %.100s", hostname);
1080 rcode = fr_sockaddr2ipaddr((struct sockaddr_storage *)ai->ai_addr,
1081 ai->ai_addrlen, out, NULL);
1084 fr_strerror_printf("Failed converting sockaddr to ipaddr");
1092 * Look IP addresses up, and print names (depending on DNS config)
1094 char const *ip_ntoh(fr_ipaddr_t const *src, char *dst, size_t cnt)
1096 struct sockaddr_storage ss;
1103 if (!fr_dns_lookups) {
1104 return inet_ntop(src->af, &(src->ipaddr), dst, cnt);
1107 if (!fr_ipaddr2sockaddr(src, 0, &ss, &salen)) {
1111 if ((error = getnameinfo((struct sockaddr *)&ss, salen, dst, cnt, NULL, 0,
1112 NI_NUMERICHOST | NI_NUMERICSERV)) != 0) {
1113 fr_strerror_printf("ip_ntoh: %s", gai_strerror(error));
1119 /** Mask off a portion of an IPv4 address
1121 * @param ipaddr to mask.
1122 * @param prefix Number of contiguous bits to mask.
1123 * @return an ipv4 address with the host portion zeroed out.
1125 struct in_addr fr_inaddr_mask(struct in_addr const *ipaddr, uint8_t prefix)
1129 if (prefix > 32) prefix = 32;
1132 if (prefix == 32) return *ipaddr;
1134 if (prefix == 0) ret = 0;
1135 else ret = htonl(~((0x00000001UL << (32 - prefix)) - 1)) & ipaddr->s_addr;
1137 return (*(struct in_addr *)&ret);
1140 /** Mask off a portion of an IPv6 address
1142 * @param ipaddr to mask.
1143 * @param prefix Number of contiguous bits to mask.
1144 * @return an ipv6 address with the host portion zeroed out.
1146 struct in6_addr fr_in6addr_mask(struct in6_addr const *ipaddr, uint8_t prefix)
1148 uint64_t const *p = (uint64_t const *) ipaddr;
1149 uint64_t ret[2], *o = ret;
1151 if (prefix > 128) prefix = 128;
1154 if (prefix == 128) return *ipaddr;
1158 *o++ = 0xffffffffffffffffULL & *p++; /* lhs portion masked */
1160 ret[1] = 0; /* rhs portion zeroed */
1163 /* Max left shift is 63 else we get overflow */
1165 *o = htonll(~((uint64_t)(0x0000000000000001ULL << (64 - prefix)) - 1)) & *p;
1170 return *(struct in6_addr *) &ret;
1173 /** Zeroes out the host portion of an fr_ipaddr_t
1175 * @param[in,out] addr to mask
1176 * @param[in] prefix Length of the network portion.
1178 void fr_ipaddr_mask(fr_ipaddr_t *addr, uint8_t prefix)
1183 addr->ipaddr.ip4addr = fr_inaddr_mask(&addr->ipaddr.ip4addr, prefix);
1187 addr->ipaddr.ip6addr = fr_in6addr_mask(&addr->ipaddr.ip6addr, prefix);
1193 addr->prefix = prefix;
1196 static char const hextab[] = "0123456789abcdef";
1198 /** Convert hex strings to binary data
1200 * @param bin Buffer to write output to.
1201 * @param outlen length of output buffer (or length of input string / 2).
1202 * @param hex input string.
1203 * @param inlen length of the input string
1204 * @return length of data written to buffer.
1206 size_t fr_hex2bin(uint8_t *bin, size_t outlen, char const *hex, size_t inlen)
1213 * Smartly truncate output, caller should check number of bytes
1217 if (len > outlen) len = outlen;
1219 for (i = 0; i < len; i++) {
1220 if(!(c1 = memchr(hextab, tolower((int) hex[i << 1]), sizeof(hextab))) ||
1221 !(c2 = memchr(hextab, tolower((int) hex[(i << 1) + 1]), sizeof(hextab))))
1223 bin[i] = ((c1-hextab)<<4) + (c2-hextab);
1229 /** Convert binary data to a hex string
1231 * Ascii encoded hex string will not be prefixed with '0x'
1233 * @warning If the output buffer isn't long enough, we have a buffer overflow.
1235 * @param[out] hex Buffer to write hex output.
1236 * @param[in] bin input.
1237 * @param[in] inlen of bin input.
1238 * @return length of data written to buffer.
1240 size_t fr_bin2hex(char *hex, uint8_t const *bin, size_t inlen)
1244 for (i = 0; i < inlen; i++) {
1245 hex[0] = hextab[((*bin) >> 4) & 0x0f];
1246 hex[1] = hextab[*bin & 0x0f];
1255 /** Convert binary data to a hex string
1257 * Ascii encoded hex string will not be prefixed with '0x'
1259 * @param[in] ctx to alloc buffer in.
1260 * @param[in] bin input.
1261 * @param[in] inlen of bin input.
1262 * @return length of data written to buffer.
1264 char *fr_abin2hex(TALLOC_CTX *ctx, uint8_t const *bin, size_t inlen)
1268 buff = talloc_array(ctx, char, (inlen << 2));
1269 if (!buff) return NULL;
1271 fr_bin2hex(buff, bin, inlen);
1276 /** Consume the integer (or hex) portion of a value string
1278 * @param value string to parse.
1279 * @param end pointer to the first non numeric char.
1280 * @return integer value.
1282 uint32_t fr_strtoul(char const *value, char **end)
1284 if ((value[0] == '0') && (value[1] == 'x')) {
1285 return strtoul(value, end, 16);
1288 return strtoul(value, end, 10);
1291 /** Check whether the string is all whitespace
1293 * @return true if the entirety of the string is whitespace, else false.
1295 bool is_whitespace(char const *value)
1298 if (!isspace(*value)) return false;
1304 /** Check whether the string is made up of printable UTF8 chars
1306 * @param value to check.
1307 * @param len of value.
1310 * - true if the string is printable.
1311 * - false if the string contains non printable chars
1313 bool is_printable(void const *value, size_t len)
1315 uint8_t const *p = value;
1319 for (i = 0; i < len; i++) {
1320 clen = fr_utf8_char(p, len - i);
1321 if (clen == 0) return false;
1328 /** Check whether the string is all numbers
1330 * @return true if the entirety of the string is all numbers, else false.
1332 bool is_integer(char const *value)
1335 if (!isdigit(*value)) return false;
1341 /** Check whether the string is allzeros
1343 * @return true if the entirety of the string is all zeros, else false.
1345 bool is_zero(char const *value)
1348 if (*value != '0') return false;
1355 * So we don't have ifdef's in the rest of the code
1357 #ifndef HAVE_CLOSEFROM
1358 int closefrom(int fd)
1364 if (fcntl(fd, F_CLOSEM) == 0) {
1370 maxfd = fcntl(fd, F_F_MAXFD);
1371 if (maxfd >= 0) goto do_close;
1375 maxfd = sysconf(_SC_OPEN_MAX);
1385 if (fd > maxfd) return 0;
1388 * FIXME: return EINTR?
1390 for (i = fd; i < maxfd; i++) {
1398 int fr_ipaddr_cmp(fr_ipaddr_t const *a, fr_ipaddr_t const *b)
1400 if (a->af < b->af) return -1;
1401 if (a->af > b->af) return +1;
1403 if (a->prefix < b->prefix) return -1;
1404 if (a->prefix > b->prefix) return +1;
1408 return memcmp(&a->ipaddr.ip4addr,
1410 sizeof(a->ipaddr.ip4addr));
1412 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1414 if (a->scope < b->scope) return -1;
1415 if (a->scope > b->scope) return +1;
1417 return memcmp(&a->ipaddr.ip6addr,
1419 sizeof(a->ipaddr.ip6addr));
1429 int fr_ipaddr2sockaddr(fr_ipaddr_t const *ipaddr, uint16_t port,
1430 struct sockaddr_storage *sa, socklen_t *salen)
1432 memset(sa, 0, sizeof(*sa));
1434 if (ipaddr->af == AF_INET) {
1435 struct sockaddr_in s4;
1437 *salen = sizeof(s4);
1439 memset(&s4, 0, sizeof(s4));
1440 s4.sin_family = AF_INET;
1441 s4.sin_addr = ipaddr->ipaddr.ip4addr;
1442 s4.sin_port = htons(port);
1443 memset(sa, 0, sizeof(*sa));
1444 memcpy(sa, &s4, sizeof(s4));
1446 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1447 } else if (ipaddr->af == AF_INET6) {
1448 struct sockaddr_in6 s6;
1450 *salen = sizeof(s6);
1452 memset(&s6, 0, sizeof(s6));
1453 s6.sin6_family = AF_INET6;
1454 s6.sin6_addr = ipaddr->ipaddr.ip6addr;
1455 s6.sin6_port = htons(port);
1456 s6.sin6_scope_id = ipaddr->scope;
1457 memset(sa, 0, sizeof(*sa));
1458 memcpy(sa, &s6, sizeof(s6));
1468 int fr_sockaddr2ipaddr(struct sockaddr_storage const *sa, socklen_t salen,
1469 fr_ipaddr_t *ipaddr, uint16_t *port)
1471 memset(ipaddr, 0, sizeof(*ipaddr));
1473 if (sa->ss_family == AF_INET) {
1474 struct sockaddr_in s4;
1476 if (salen < sizeof(s4)) {
1477 fr_strerror_printf("IPv4 address is too small");
1481 memcpy(&s4, sa, sizeof(s4));
1482 ipaddr->af = AF_INET;
1483 ipaddr->prefix = 32;
1484 ipaddr->ipaddr.ip4addr = s4.sin_addr;
1485 if (port) *port = ntohs(s4.sin_port);
1487 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1488 } else if (sa->ss_family == AF_INET6) {
1489 struct sockaddr_in6 s6;
1491 if (salen < sizeof(s6)) {
1492 fr_strerror_printf("IPv6 address is too small");
1496 memcpy(&s6, sa, sizeof(s6));
1497 ipaddr->af = AF_INET6;
1498 ipaddr->prefix = 128;
1499 ipaddr->ipaddr.ip6addr = s6.sin6_addr;
1500 if (port) *port = ntohs(s6.sin6_port);
1501 ipaddr->scope = s6.sin6_scope_id;
1505 fr_strerror_printf("Unsupported address famility %d",
1514 /** Set O_NONBLOCK on a socket
1516 * @note O_NONBLOCK is POSIX.
1518 * @param fd to set nonblocking flag on.
1519 * @return flags set on the socket, or -1 on error.
1521 int fr_nonblock(int fd)
1525 flags = fcntl(fd, F_GETFL, NULL);
1527 fr_strerror_printf("Failure getting socket flags: %s", fr_syserror(errno));
1531 flags |= O_NONBLOCK;
1532 if (fcntl(fd, F_SETFL, flags) < 0) {
1533 fr_strerror_printf("Failure setting socket flags: %s", fr_syserror(errno));
1540 /** Unset O_NONBLOCK on a socket
1542 * @note O_NONBLOCK is POSIX.
1544 * @param fd to set nonblocking flag on.
1545 * @return flags set on the socket, or -1 on error.
1547 int fr_blocking(int fd)
1551 flags = fcntl(fd, F_GETFL, NULL);
1553 fr_strerror_printf("Failure getting socket flags: %s", fr_syserror(errno));
1557 flags ^= O_NONBLOCK;
1558 if (fcntl(fd, F_SETFL, flags) < 0) {
1559 fr_strerror_printf("Failure setting socket flags: %s", fr_syserror(errno));
1566 int fr_nonblock(UNUSED int fd)
1568 fr_strerror_printf("Non blocking sockets are not supported");
1571 int fr_blocking(UNUSED int fd)
1573 fr_strerror_printf("Non blocking sockets are not supported");
1578 /** Write out a vector to a file descriptor
1580 * Wraps writev, calling it as necessary. If timeout is not NULL,
1581 * timeout is applied to each call that returns EAGAIN or EWOULDBLOCK
1583 * @note Should only be used on nonblocking file descriptors.
1584 * @note Socket should likely be closed on timeout.
1585 * @note iovec may be modified in such a way that it's not re-usable.
1586 * @note Leaves errno set to the last error that ocurred.
1588 * @param fd to write to.
1589 * @param vector to write.
1590 * @param iovcnt number of elements in iovec.
1591 * @param timeout how long to wait for fd to become writeable before timing out.
1592 * @return number of bytes written, -1 on error.
1594 ssize_t fr_writev(int fd, struct iovec vector[], int iovcnt, struct timeval *timeout)
1596 struct iovec *vector_p = vector;
1599 while (iovcnt > 0) {
1602 wrote = writev(fd, vector_p, iovcnt);
1607 * An entire vector element was written
1609 if (wrote >= (ssize_t)vector_p->iov_len) {
1611 wrote -= vector_p->iov_len;
1617 * Partial vector element was written
1619 vector_p->iov_len -= wrote;
1620 vector_p->iov_base = ((char *)vector_p->iov_base) + wrote;
1624 } else if (wrote == 0) return total;
1627 /* Write operation would block, use select() to implement a timeout */
1628 #if EWOULDBLOCK != EAGAIN
1638 FD_ZERO(&write_set);
1639 FD_SET(fd, &write_set);
1641 /* Don't let signals mess up the select */
1643 ret = select(fd + 1, NULL, &write_set, NULL, timeout);
1644 } while ((ret == -1) && (errno == EINTR));
1646 /* Select returned 0 which means it reached the timeout */
1648 fr_strerror_printf("Write timed out");
1652 /* Other select error */
1654 fr_strerror_printf("Failed waiting on socket: %s", fr_syserror(errno));
1658 /* select said a file descriptor was ready for writing */
1659 if (!fr_assert(FD_ISSET(fd, &write_set))) return -1;
1672 /** Convert UTF8 string to UCS2 encoding
1674 * @note Borrowed from src/crypto/ms_funcs.c of wpa_supplicant project (http://hostap.epitest.fi/wpa_supplicant/)
1676 * @param[out] out Where to write the ucs2 string.
1677 * @param[in] outlen Size of output buffer.
1678 * @param[in] in UTF8 string to convert.
1679 * @param[in] inlen length of UTF8 string.
1680 * @return the size of the UCS2 string written to the output buffer (in bytes).
1682 ssize_t fr_utf8_to_ucs2(uint8_t *out, size_t outlen, char const *in, size_t inlen)
1685 uint8_t *start = out;
1687 for (i = 0; i < inlen; i++) {
1691 if ((size_t)(out - start) >= outlen) {
1692 /* input too long */
1696 /* One-byte encoding */
1698 FR_PUT_LE16(out, c);
1701 } else if ((i == (inlen - 1)) || ((size_t)(out - start) >= (outlen - 1))) {
1702 /* Incomplete surrogate */
1707 /* Two-byte encoding */
1708 if ((c & 0xe0) == 0xc0) {
1709 FR_PUT_LE16(out, ((c & 0x1f) << 6) | (c2 & 0x3f));
1713 if ((i == inlen) || ((size_t)(out - start) >= (outlen - 1))) {
1714 /* Incomplete surrogate */
1718 /* Three-byte encoding */
1720 FR_PUT_LE16(out, ((c & 0xf) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f));
1727 /** Write 128bit unsigned integer to buffer
1729 * @author Alexey Frunze
1731 * @param out where to write result to.
1732 * @param outlen size of out.
1733 * @param num 128 bit integer.
1735 size_t fr_prints_uint128(char *out, size_t outlen, uint128_t const num)
1737 char buff[128 / 3 + 1 + 1];
1741 #ifdef FR_LITTLE_ENDIAN
1749 memset(buff, '0', sizeof(buff) - 1);
1750 buff[sizeof(buff) - 1] = '\0';
1752 memcpy(n, &num, sizeof(n));
1754 for (i = 0; i < 128; i++) {
1758 carry = (n[h] >= 0x8000000000000000);
1760 // Shift n[] left, doubling it
1761 n[h] = ((n[h] << 1) & 0xffffffffffffffff) + (n[l] >= 0x8000000000000000);
1762 n[l] = ((n[l] << 1) & 0xffffffffffffffff);
1764 // Add s[] to itself in decimal, doubling it
1765 for (j = sizeof(buff) - 2; j >= 0; j--) {
1766 buff[j] += buff[j] - '0' + carry;
1767 carry = (buff[j] > '9');
1774 while ((*p == '0') && (p < &buff[sizeof(buff) - 2])) {
1778 return strlcpy(out, p, outlen);
1782 * Sort of strtok/strsep function.
1784 static char *mystrtok(char **ptr, char const *sep)
1792 while (**ptr && strchr(sep, **ptr)) {
1800 while (**ptr && strchr(sep, **ptr) == NULL) {
1810 /** Convert string in various formats to a time_t
1812 * @param date_str input date string.
1813 * @param date time_t to write result to.
1814 * @return 0 on success or -1 on error.
1816 int fr_get_time(char const *date_str, time_t *date)
1820 struct tm *tm, s_tm;
1827 * Test for unix timestamp date
1829 *date = strtoul(date_str, &tail, 10);
1830 if (*tail == '\0') {
1835 memset(tm, 0, sizeof(*tm));
1836 tm->tm_isdst = -1; /* don't know, and don't care about DST */
1838 strlcpy(buf, date_str, sizeof(buf));
1841 f[0] = mystrtok(&p, " \t");
1842 f[1] = mystrtok(&p, " \t");
1843 f[2] = mystrtok(&p, " \t");
1844 f[3] = mystrtok(&p, " \t"); /* may, or may not, be present */
1845 if (!f[0] || !f[1] || !f[2]) return -1;
1848 * The time has a colon, where nothing else does.
1849 * So if we find it, bubble it to the back of the list.
1852 for (i = 0; i < 3; i++) {
1853 if (strchr(f[i], ':')) {
1863 * The month is text, which allows us to find it easily.
1866 for (i = 0; i < 3; i++) {
1867 if (isalpha( (int) *f[i])) {
1869 * Bubble the month to the front of the list
1875 for (i = 0; i < 12; i++) {
1876 if (strncasecmp(months[i], f[0], 3) == 0) {
1884 /* month not found? */
1885 if (tm->tm_mon == 12) return -1;
1888 * The year may be in f[1], or in f[2]
1890 tm->tm_year = atoi(f[1]);
1891 tm->tm_mday = atoi(f[2]);
1893 if (tm->tm_year >= 1900) {
1894 tm->tm_year -= 1900;
1898 * We can't use 2-digit years any more, they make it
1899 * impossible to tell what's the day, and what's the year.
1901 if (tm->tm_mday < 1900) return -1;
1904 * Swap the year and the day.
1907 tm->tm_year = tm->tm_mday - 1900;
1912 * If the day is out of range, die.
1914 if ((tm->tm_mday < 1) || (tm->tm_mday > 31)) {
1919 * There may be %H:%M:%S. Parse it in a hacky way.
1922 f[0] = f[3]; /* HH */
1923 f[1] = strchr(f[0], ':'); /* find : separator */
1924 if (!f[1]) return -1;
1926 *(f[1]++) = '\0'; /* nuke it, and point to MM:SS */
1928 f[2] = strchr(f[1], ':'); /* find : separator */
1930 *(f[2]++) = '\0'; /* nuke it, and point to SS */
1931 tm->tm_sec = atoi(f[2]);
1932 } /* else leave it as zero */
1934 tm->tm_hour = atoi(f[0]);
1935 tm->tm_min = atoi(f[1]);
1939 * Returns -1 on error.
1942 if (t == (time_t) -1) return -1;
1949 /** Compares two pointers
1951 * @param a first pointer to compare.
1952 * @param b second pointer to compare.
1953 * @return -1 if a < b, +1 if b > a, or 0 if both equal.
1955 int8_t fr_pointer_cmp(void const *a, void const *b)
1957 if (a < b) return -1;
1958 if (a == b) return 0;
1963 static int _quick_partition(void const *to_sort[], int min, int max, fr_cmp_t cmp) {
1964 void const *pivot = to_sort[min];
1970 do ++i; while((cmp(to_sort[i], pivot) <= 0) && i <= max);
1971 do --j; while(cmp(to_sort[j], pivot) > 0);
1976 to_sort[i] = to_sort[j];
1981 to_sort[min] = to_sort[j];
1987 /** Quick sort an array of pointers using a comparator
1989 * @param to_sort array of pointers to sort.
1990 * @param min_idx the lowest index (usually 0).
1991 * @param max_idx the highest index (usually length of array - 1).
1992 * @param cmp the comparison function to use to sort the array elements.
1994 void fr_quick_sort(void const *to_sort[], int min_idx, int max_idx, fr_cmp_t cmp)
1998 if (min_idx >= max_idx) return;
2000 part = _quick_partition(to_sort, min_idx, max_idx, cmp);
2001 fr_quick_sort(to_sort, min_idx, part - 1, cmp);
2002 fr_quick_sort(to_sort, part + 1, max_idx, cmp);
2006 void fr_talloc_verify_cb(UNUSED const void *ptr, UNUSED int depth,
2007 UNUSED int max_depth, UNUSED int is_ref,
2008 UNUSED void *private_data)