f062ecf7861cb3597d128cb6ae451f47a72e2987
[freeradius.git] / src / lib / misc.c
1 /*
2  * misc.c       Various miscellaneous functions.
3  *
4  * Version:     $Id$
5  *
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.
10  *
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.
15  *
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
19  *
20  * Copyright 2000,2006  The FreeRADIUS server project
21  */
22
23 RCSID("$Id$")
24
25 #include <freeradius-devel/libradius.h>
26
27 #include <ctype.h>
28 #include <sys/file.h>
29 #include <fcntl.h>
30 #include <grp.h>
31 #include <pwd.h>
32 #include <sys/uio.h>
33
34 #define FR_PUT_LE16(a, val)\
35         do {\
36                 a[1] = ((uint16_t) (val)) >> 8;\
37                 a[0] = ((uint16_t) (val)) & 0xff;\
38         } while (0)
39
40 bool    fr_dns_lookups = false;     /* IP -> hostname lookups? */
41 bool    fr_hostname_lookups = true; /* hostname -> IP lookups? */
42 int     fr_debug_lvl = 0;
43
44 static char const *months[] = {
45         "jan", "feb", "mar", "apr", "may", "jun",
46         "jul", "aug", "sep", "oct", "nov", "dec" };
47
48 fr_thread_local_setup(char *, fr_inet_ntop_buffer)      /* macro */
49
50 typedef struct fr_talloc_link {
51         bool armed;
52         TALLOC_CTX *child;
53 } fr_talloc_link_t;
54
55 /** Sets a signal handler using sigaction if available, else signal
56  *
57  * @param sig to set handler for.
58  * @param func handler to set.
59  */
60 int fr_set_signal(int sig, sig_t func)
61 {
62 #ifdef HAVE_SIGACTION
63         struct sigaction act;
64
65         memset(&act, 0, sizeof(act));
66         act.sa_flags = 0;
67         sigemptyset(&act.sa_mask);
68         act.sa_handler = func;
69
70         if (sigaction(sig, &act, NULL) < 0) {
71                 fr_strerror_printf("Failed setting signal %i handler via sigaction(): %s", sig, fr_syserror(errno));
72                 return -1;
73         }
74 #else
75         if (signal(sig, func) < 0) {
76                 fr_strerror_printf("Failed setting signal %i handler via signal(): %s", sig, fr_syserror(errno));
77                 return -1;
78         }
79 #endif
80         return 0;
81 }
82
83 /** Uninstall a signal for a specific handler
84  *
85  * man sigaction says these are fine to call from a signal handler.
86  *
87  * @param sig SIGNAL
88  */
89 int fr_unset_signal(int sig)
90 {
91 #ifdef HAVE_SIGACTION
92         struct sigaction act;
93
94         memset(&act, 0, sizeof(act));
95         act.sa_flags = 0;
96         sigemptyset(&act.sa_mask);
97         act.sa_handler = SIG_DFL;
98
99         return sigaction(sig, &act, NULL);
100 #else
101         return signal(sig, SIG_DFL);
102 #endif
103 }
104
105 static int _fr_trigger_talloc_ctx_free(fr_talloc_link_t *trigger)
106 {
107         if (trigger->armed) talloc_free(trigger->child);
108
109         return 0;
110 }
111
112 static int _fr_disarm_talloc_ctx_free(bool **armed)
113 {
114         **armed = false;
115         return 0;
116 }
117
118 /** Link a parent and a child context, so the child is freed before the parent
119  *
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.
122  *
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.
126  */
127 int fr_link_talloc_ctx_free(TALLOC_CTX *parent, TALLOC_CTX *child)
128 {
129         fr_talloc_link_t *trigger;
130         bool **disarm;
131
132         trigger = talloc(parent, fr_talloc_link_t);
133         if (!trigger) return -1;
134
135         disarm = talloc(child, bool *);
136         if (!disarm) {
137                 talloc_free(trigger);
138                 return -1;
139         }
140
141         trigger->child = child;
142         trigger->armed = true;
143         *disarm = &trigger->armed;
144
145         talloc_set_destructor(trigger, _fr_trigger_talloc_ctx_free);
146         talloc_set_destructor(disarm, _fr_disarm_talloc_ctx_free);
147
148         return 0;
149 }
150
151 /*
152  *      Explicitly cleanup the memory allocated to the error inet_ntop
153  *      buffer.
154  */
155 static void _fr_inet_ntop_free(void *arg)
156 {
157         free(arg);
158 }
159
160 /** Wrapper around inet_ntop, prints IPv4/IPv6 addresses
161  *
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.
165  *
166  * So as with lib/log.c use TLS to allocate thread specific buffers, and
167  * write the IP address there instead.
168  *
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.
172  */
173 char const *fr_inet_ntop(int af, void const *src)
174 {
175         char *buffer;
176
177         if (!src) {
178                 return NULL;
179         }
180
181         buffer = fr_thread_local_init(fr_inet_ntop_buffer, _fr_inet_ntop_free);
182         if (!buffer) {
183                 int ret;
184
185                 /*
186                  *      malloc is thread safe, talloc is not
187                  */
188                 buffer = malloc(sizeof(char) * INET6_ADDRSTRLEN);
189                 if (!buffer) {
190                         fr_perror("Failed allocating memory for inet_ntop buffer");
191                         return NULL;
192                 }
193
194                 ret = fr_thread_local_set(fr_inet_ntop_buffer, buffer);
195                 if (ret != 0) {
196                         fr_perror("Failed setting up TLS for inet_ntop buffer: %s", fr_syserror(ret));
197                         free(buffer);
198                         return NULL;
199                 }
200         }
201         buffer[0] = '\0';
202
203         return inet_ntop(af, src, buffer, INET6_ADDRSTRLEN);
204 }
205
206 /*
207  *      Return an IP address in standard dot notation
208  *
209  *      FIXME: DELETE THIS
210  */
211 char const *ip_ntoa(char *buffer, uint32_t ipaddr)
212 {
213         ipaddr = ntohl(ipaddr);
214
215         sprintf(buffer, "%d.%d.%d.%d",
216                 (ipaddr >> 24) & 0xff,
217                 (ipaddr >> 16) & 0xff,
218                 (ipaddr >>  8) & 0xff,
219                 (ipaddr      ) & 0xff);
220         return buffer;
221 }
222
223 /*
224  *      Parse decimal digits until we run out of decimal digits.
225  */
226 static int ip_octet_from_str(char const *str, uint32_t *poctet)
227 {
228         uint32_t octet;
229         char const *p = str;
230
231         if ((*p < '0') || (*p > '9')) {
232                 return -1;
233         }
234
235         octet = 0;
236
237         while ((*p >= '0') && (*p <= '9')) {
238                 octet *= 10;
239                 octet += *p - '0';
240                 p++;
241
242                 if (octet > 255) return -1;
243         }
244
245
246         *poctet = octet;
247         return p - str;
248 }
249
250 static int ip_prefix_from_str(char const *str, uint32_t *paddr)
251 {
252         int shift, length;
253         uint32_t octet;
254         uint32_t addr;
255         char const *p = str;
256
257         addr = 0;
258
259         for (shift = 24; shift >= 0; shift -= 8) {
260                 length = ip_octet_from_str(p, &octet);
261                 if (length <= 0) return -1;
262
263                 addr |= octet << shift;
264                 p += length;
265
266                 /*
267                  *      EOS or / means we're done.
268                  */
269                 if (!*p || (*p == '/')) break;
270
271                 /*
272                  *      We require dots between octets.
273                  */
274                 if (*p != '.') return -1;
275                 p++;
276         }
277
278         *paddr = htonl(addr);
279         return p - str;
280 }
281
282
283 /** Parse an IPv4 address or IPv4 prefix in presentation format (and others)
284  *
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.
291  */
292 int fr_pton4(fr_ipaddr_t *out, char const *value, ssize_t inlen, bool resolve, bool fallback)
293 {
294         char *p;
295         unsigned int mask;
296         char *eptr;
297
298         /* Dotted quad + / + [0-9]{1,2} */
299         char buffer[INET_ADDRSTRLEN + 3];
300
301         /*
302          *      Copy to intermediary buffer if we were given a length
303          */
304         if (inlen >= 0) {
305                 if (inlen >= (ssize_t)sizeof(buffer)) {
306                         fr_strerror_printf("Invalid IPv4 address string \"%s\"", value);
307                         return -1;
308                 }
309                 memcpy(buffer, value, inlen);
310                 buffer[inlen] = '\0';
311                 value = buffer;
312         }
313
314         p = strchr(value, '/');
315
316         /*
317          *      192.0.2.2 is parsed as if it was /32
318          */
319         if (!p) {
320                 out->prefix = 32;
321                 out->af = AF_INET;
322
323                 /*
324                  *      Allow '*' as the wildcard address usually 0.0.0.0
325                  */
326                 if ((value[0] == '*') && (value[1] == '\0')) {
327                         out->ipaddr.ip4addr.s_addr = htonl(INADDR_ANY);
328
329                 /*
330                  *      Convert things which are obviously integers to IP addresses
331                  *
332                  *      We assume the number is the bigendian representation of the
333                  *      IP address.
334                  */
335                 } else if (is_integer(value) || ((value[0] == '0') && (value[1] == 'x'))) {
336                         out->ipaddr.ip4addr.s_addr = htonl(strtoul(value, NULL, 0));
337
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);
341                                 return -1;
342                         }
343                 } else if (ip_hton(out, AF_INET, value, fallback) < 0) return -1;
344
345                 return 0;
346         }
347
348         /*
349          *      Copy the IP portion into a temporary buffer if we haven't already.
350          */
351         if (inlen < 0) memcpy(buffer, value, p - value);
352         buffer[p - value] = '\0';
353
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);
356                 return -1;
357         }
358
359         mask = strtoul(p + 1, &eptr, 10);
360         if (mask > 32) {
361                 fr_strerror_printf("Invalid IPv4 mask length \"%s\".  Should be between 0-32", p);
362                 return -1;
363         }
364
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);
368                 return -1;
369         }
370
371         if (mask < 32) {
372                 out->ipaddr.ip4addr = fr_inaddr_mask(&out->ipaddr.ip4addr, mask);
373         }
374
375         out->prefix = (uint8_t) mask;
376         out->af = AF_INET;
377
378         return 0;
379 }
380
381 /** Parse an IPv6 address or IPv6 prefix in presentation format (and others)
382  *
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.
389  */
390 int fr_pton6(fr_ipaddr_t *out, char const *value, ssize_t inlen, bool resolve, bool fallback)
391 {
392         char const *p;
393         unsigned int prefix;
394         char *eptr;
395
396         /* IPv6  + / + [0-9]{1,3} */
397         char buffer[INET6_ADDRSTRLEN + 4];
398
399         /*
400          *      Copy to intermediary buffer if we were given a length
401          */
402         if (inlen >= 0) {
403                 if (inlen >= (ssize_t)sizeof(buffer)) {
404                         fr_strerror_printf("Invalid IPv6 address string \"%s\"", value);
405                         return -1;
406                 }
407                 memcpy(buffer, value, inlen);
408                 buffer[inlen] = '\0';
409                 value = buffer;
410         }
411
412         p = strchr(value, '/');
413         if (!p) {
414                 out->prefix = 128;
415                 out->af = AF_INET6;
416
417                 /*
418                  *      Allow '*' as the wildcard address
419                  */
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);
425                                 return -1;
426                         }
427                 } else if (ip_hton(out, AF_INET6, value, fallback) < 0) return -1;
428
429                 return 0;
430         }
431
432         if ((p - value) >= INET6_ADDRSTRLEN) {
433                 fr_strerror_printf("Invalid IPv6 address string \"%s\"", value);
434                 return -1;
435         }
436
437         /*
438          *      Copy string to temporary buffer if we didn't do it earlier
439          */
440         if (inlen < 0) memcpy(buffer, value, p - value);
441         buffer[p - value] = '\0';
442
443         if (!resolve) {
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);
446                         return -1;
447                 }
448         } else if (ip_hton(out, AF_INET6, buffer, fallback) < 0) return -1;
449
450         prefix = strtoul(p + 1, &eptr, 10);
451         if (prefix > 128) {
452                 fr_strerror_printf("Invalid IPv6 mask length \"%s\".  Should be between 0-128", p);
453                 return -1;
454         }
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);
458                 return -1;
459         }
460
461         if (prefix < 128) {
462                 struct in6_addr addr;
463
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));
466         }
467
468         out->prefix = (uint8_t) prefix;
469         out->af = AF_INET6;
470
471         return 0;
472 }
473
474 /** Simple wrapper to decide whether an IP value is v4 or v6 and call the appropriate parser.
475  *
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
480  *      hostname.
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.
484  * @return
485  *      - 0 if ip address was parsed successfully.
486  *      - -1 on failure.
487  */
488 int fr_pton(fr_ipaddr_t *out, char const *value, ssize_t inlen, int af, bool resolve)
489 {
490         size_t len, i;
491
492         len = (inlen >= 0) ? (size_t)inlen : strlen(value);
493         for (i = 0; i < len; i++) switch (value[i]) {
494         /*
495          *      ':' is illegal in domain names and IPv4 addresses.
496          *      Must be v6 and cannot be a domain.
497          */
498         case ':':
499                 return fr_pton6(out, value, inlen, false, false);
500
501         /*
502          *      Chars which don't really tell us anything
503          */
504         case '.':
505         case '/':
506                 continue;
507
508         default:
509                 /*
510                  *      Outside the range of IPv4 chars, must be a domain
511                  *      Use A record in preference to AAAA record.
512                  */
513                 if ((value[i] < '0') || (value[i] > '9')) {
514                         if (!resolve) {
515                                 fr_strerror_printf("Not IPv4/6 address, and asked not to resolve");
516                                 return -1;
517                         }
518                         switch (af) {
519                         case AF_UNSPEC:
520                                 return fr_pton4(out, value, inlen, resolve, true);
521
522                         case AF_INET:
523                                 return fr_pton4(out, value, inlen, resolve, false);
524
525                         case AF_INET6:
526                                 return fr_pton6(out, value, inlen, resolve, false);
527
528                         default:
529                                 fr_strerror_printf("Invalid address family %i", af);
530                                 return -1;
531                         }
532                 }
533                 break;
534         }
535
536         /*
537          *      All chars were in the IPv4 set [0-9/.], must be an IPv4
538          *      address.
539          */
540         return fr_pton4(out, value, inlen, false, false);
541 }
542
543 /** Parses IPv4/6 address + port, to fr_ipaddr_t and integer
544  *
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
553  *      hostname.
554  */
555 int fr_pton_port(fr_ipaddr_t *out, uint16_t *port_out, char const *value, ssize_t inlen, int af, bool resolve)
556 {
557         char const      *p = value, *q;
558         char            *end;
559         unsigned long   port;
560         char            buffer[6];
561         size_t          len;
562
563         *port_out = 0;
564
565         len = (inlen >= 0) ? (size_t)inlen : strlen(value);
566
567         if (*p == '[') {
568                 if (!(q = memchr(p + 1, ']', len - 1))) {
569                         fr_strerror_printf("Missing closing ']' for IPv6 address");
570                         return -1;
571                 }
572
573                 /*
574                  *      inet_pton doesn't like the address being wrapped in []
575                  */
576                 if (fr_pton6(out, p + 1, (q - p) - 1, false, false) < 0) return -1;
577
578                 if (q[1] == ':') {
579                         q++;
580                         goto do_port;
581                 }
582
583                 return 0;
584         }
585
586         /*
587          *      Host, IPv4 or IPv6 with no port
588          */
589         q = memchr(p, ':', len);
590         if (!q) return fr_pton(out, p, len, af, resolve);
591
592         /*
593          *      IPv4 or host, with port
594          */
595         if (fr_pton(out, p, (q - p), af, resolve) < 0) return -1;
596
597 do_port:
598         /*
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.
602          */
603         if (inlen > ((q + sizeof(buffer)) - value)) {
604         error:
605                 fr_strerror_printf("IP string contains trailing garbage after port delimiter");
606                 return -1;
607         }
608
609         p = q + 1;                      /* Move to first digit */
610
611         strlcpy(buffer, p, (len - (p - value)) + 1);
612         port = strtoul(buffer, &end, 10);
613         if (*end != '\0') goto error;   /* Trailing garbage after integer */
614
615         if ((port > UINT16_MAX) || (port == 0)) {
616                 fr_strerror_printf("Port %lu outside valid port range 1-" STRINGIFY(UINT16_MAX), port);
617                 return -1;
618         }
619         *port_out = port;
620
621         return 0;
622 }
623
624 int fr_ntop(char *out, size_t outlen, fr_ipaddr_t *addr)
625 {
626         char buffer[INET6_ADDRSTRLEN];
627
628         if (inet_ntop(addr->af, &(addr->ipaddr), buffer, sizeof(buffer)) == NULL) return -1;
629
630         return snprintf(out, outlen, "%s/%i", buffer, addr->prefix);
631 }
632
633 /*
634  *      cppcheck apparently can't pick this up from the system headers.
635  */
636 #ifdef CPPCHECK
637 #define F_WRLCK
638 #endif
639
640 /*
641  *      Internal wrapper for locking, to minimize the number of ifdef's
642  *
643  *      Use fcntl or error
644  */
645 int rad_lockfd(int fd, int lock_len)
646 {
647 #ifdef F_WRLCK
648         struct flock fl;
649
650         fl.l_start = 0;
651         fl.l_len = lock_len;
652         fl.l_pid = getpid();
653         fl.l_type = F_WRLCK;
654         fl.l_whence = SEEK_CUR;
655
656         return fcntl(fd, F_SETLKW, (void *)&fl);
657 #else
658 #error "missing definition for F_WRLCK, all file locks will fail"
659
660         return -1;
661 #endif
662 }
663
664 /*
665  *      Internal wrapper for locking, to minimize the number of ifdef's
666  *
667  *      Lock an fd, prefer lockf() over flock()
668  *      Nonblocking version.
669  */
670 int rad_lockfd_nonblock(int fd, int lock_len)
671 {
672 #ifdef F_WRLCK
673         struct flock fl;
674
675         fl.l_start = 0;
676         fl.l_len = lock_len;
677         fl.l_pid = getpid();
678         fl.l_type = F_WRLCK;
679         fl.l_whence = SEEK_CUR;
680
681         return fcntl(fd, F_SETLK, (void *)&fl);
682 #else
683 #error "missing definition for F_WRLCK, all file locks will fail"
684
685         return -1;
686 #endif
687 }
688
689 /*
690  *      Internal wrapper for unlocking, to minimize the number of ifdef's
691  *      in the source.
692  *
693  *      Unlock an fd, prefer lockf() over flock()
694  */
695 int rad_unlockfd(int fd, int lock_len)
696 {
697 #ifdef F_WRLCK
698         struct flock fl;
699
700         fl.l_start = 0;
701         fl.l_len = lock_len;
702         fl.l_pid = getpid();
703         fl.l_type = F_WRLCK;
704         fl.l_whence = SEEK_CUR;
705
706         return fcntl(fd, F_UNLCK, (void *)&fl);
707 #else
708 #error "missing definition for F_WRLCK, all file locks will fail"
709
710         return -1;
711 #endif
712 }
713
714 /*
715  *      Return an interface-id in standard colon notation
716  */
717 char *ifid_ntoa(char *buffer, size_t size, uint8_t const *ifid)
718 {
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]);
722         return buffer;
723 }
724
725
726 /*
727  *      Return an interface-id from
728  *      one supplied in standard colon notation.
729  */
730 uint8_t *ifid_aton(char const *ifid_str, uint8_t *ifid)
731 {
732         static char const xdigits[] = "0123456789abcdef";
733         char const *p, *pch;
734         int num_id = 0, val = 0, idx = 0;
735
736         for (p = ifid_str; ; ++p) {
737                 if (*p == ':' || *p == '\0') {
738                         if (num_id <= 0)
739                                 return NULL;
740
741                         /*
742                          *      Drop 'val' into the array.
743                          */
744                         ifid[idx] = (val >> 8) & 0xff;
745                         ifid[idx + 1] = val & 0xff;
746                         if (*p == '\0') {
747                                 /*
748                                  *      Must have all entries before
749                                  *      end of the string.
750                                  */
751                                 if (idx != 6)
752                                         return NULL;
753                                 break;
754                         }
755                         val = 0;
756                         num_id = 0;
757                         if ((idx += 2) > 6)
758                                 return NULL;
759                 } else if ((pch = strchr(xdigits, tolower(*p))) != NULL) {
760                         if (++num_id > 4)
761                                 return NULL;
762                         /*
763                          *      Dumb version of 'scanf'
764                          */
765                         val <<= 4;
766                         val |= (pch - xdigits);
767                 } else
768                         return NULL;
769         }
770         return ifid;
771 }
772
773
774 #ifndef HAVE_INET_PTON
775 static int inet_pton4(char const *src, struct in_addr *dst)
776 {
777         int octet;
778         unsigned int num;
779         char const *p, *off;
780         uint8_t tmp[4];
781         static char const digits[] = "0123456789";
782
783         octet = 0;
784         p = src;
785         while (1) {
786                 num = 0;
787                 while (*p && ((off = strchr(digits, *p)) != NULL)) {
788                         num *= 10;
789                         num += (off - digits);
790
791                         if (num > 255) return 0;
792
793                         p++;
794                 }
795                 if (!*p) break;
796
797                 /*
798                  *      Not a digit, MUST be a dot, else we
799                  *      die.
800                  */
801                 if (*p != '.') {
802                         return 0;
803                 }
804
805                 tmp[octet++] = num;
806                 p++;
807         }
808
809         /*
810          *      End of the string.  At the fourth
811          *      octet is OK, anything else is an
812          *      error.
813          */
814         if (octet != 3) {
815                 return 0;
816         }
817         tmp[3] = num;
818
819         memcpy(dst, &tmp, sizeof(tmp));
820         return 1;
821 }
822
823
824 #ifdef HAVE_STRUCT_SOCKADDR_IN6
825 /** Convert presentation level address to network order binary form
826  *
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.
831  *
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.
835  */
836 static int inet_pton6(char const *src, unsigned char *dst)
837 {
838         static char const xdigits_l[] = "0123456789abcdef",
839                           xdigits_u[] = "0123456789ABCDEF";
840         u_char tmp[IN6ADDRSZ], *tp, *endp, *colonp;
841         char const *xdigits, *curtok;
842         int ch, saw_xdigit;
843         u_int val;
844
845         memset((tp = tmp), 0, IN6ADDRSZ);
846         endp = tp + IN6ADDRSZ;
847         colonp = NULL;
848         /* Leading :: requires some special handling. */
849         if (*src == ':')
850                 if (*++src != ':')
851                         return (0);
852         curtok = src;
853         saw_xdigit = 0;
854         val = 0;
855         while ((ch = *src++) != '\0') {
856                 char const *pch;
857
858                 if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
859                         pch = strchr((xdigits = xdigits_u), ch);
860                 if (pch != NULL) {
861                         val <<= 4;
862                         val |= (pch - xdigits);
863                         if (val > 0xffff)
864                                 return (0);
865                         saw_xdigit = 1;
866                         continue;
867                 }
868                 if (ch == ':') {
869                         curtok = src;
870                         if (!saw_xdigit) {
871                                 if (colonp)
872                                         return (0);
873                                 colonp = tp;
874                                 continue;
875                         }
876                         if (tp + INT16SZ > endp)
877                                 return (0);
878                         *tp++ = (u_char) (val >> 8) & 0xff;
879                         *tp++ = (u_char) val & 0xff;
880                         saw_xdigit = 0;
881                         val = 0;
882                         continue;
883                 }
884                 if (ch == '.' && ((tp + INADDRSZ) <= endp) &&
885                     inet_pton4(curtok, (struct in_addr *) tp) > 0) {
886                         tp += INADDRSZ;
887                         saw_xdigit = 0;
888                         break;  /* '\0' was seen by inet_pton4(). */
889                 }
890                 return (0);
891         }
892         if (saw_xdigit) {
893                 if (tp + INT16SZ > endp)
894                         return (0);
895                 *tp++ = (u_char) (val >> 8) & 0xff;
896                 *tp++ = (u_char) val & 0xff;
897         }
898         if (colonp != NULL) {
899                 /*
900                  * Since some memmove()'s erroneously fail to handle
901                  * overlapping regions, we'll do the shift by hand.
902                  */
903                 int const n = tp - colonp;
904                 int i;
905
906                 for (i = 1; i <= n; i++) {
907                         endp[- i] = colonp[n - i];
908                         colonp[n - i] = 0;
909                 }
910                 tp = endp;
911         }
912         if (tp != endp)
913                 return (0);
914         /* bcopy(tmp, dst, IN6ADDRSZ); */
915         memcpy(dst, tmp, IN6ADDRSZ);
916         return (1);
917 }
918 #endif
919
920 /*
921  *      Utility function, so that the rest of the server doesn't
922  *      have ifdef's around IPv6 support
923  */
924 int inet_pton(int af, char const *src, void *dst)
925 {
926         if (af == AF_INET) {
927                 return inet_pton4(src, dst);
928         }
929 #ifdef HAVE_STRUCT_SOCKADDR_IN6
930
931         if (af == AF_INET6) {
932                 return inet_pton6(src, dst);
933         }
934 #endif
935
936         return -1;
937 }
938 #endif
939
940 #ifndef HAVE_INET_NTOP
941 /*
942  *      Utility function, so that the rest of the server doesn't
943  *      have ifdef's around IPv6 support
944  */
945 char const *inet_ntop(int af, void const *src, char *dst, size_t cnt)
946 {
947         if (af == AF_INET) {
948                 uint8_t const *ipaddr = src;
949
950                 if (cnt <= INET_ADDRSTRLEN) return NULL;
951
952                 snprintf(dst, cnt, "%d.%d.%d.%d",
953                          ipaddr[0], ipaddr[1],
954                          ipaddr[2], ipaddr[3]);
955                 return dst;
956         }
957
958         /*
959          *      If the system doesn't define this, we define it
960          *      in missing.h
961          */
962         if (af == AF_INET6) {
963                 struct in6_addr const *ipaddr = src;
964
965                 if (cnt <= INET6_ADDRSTRLEN) return NULL;
966
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]);
976                 return dst;
977         }
978
979         return NULL;            /* don't support IPv6 */
980 }
981 #endif
982
983 /** Wrappers for IPv4/IPv6 host to IP address lookup
984  *
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.
987  *
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.
990  *
991  * If fallback is specified and af is AF_INET6, and a record with AF_INET4 exists
992  * that record will be returned instead.
993  *
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.
999  */
1000 int ip_hton(fr_ipaddr_t *out, int af, char const *hostname, bool fallback)
1001 {
1002         int rcode;
1003         struct addrinfo hints, *ai = NULL, *alt = NULL, *res = NULL;
1004
1005         /*
1006          *      Avoid malloc for IP addresses.  This helps us debug
1007          *      memory errors when using talloc.
1008          */
1009 #ifdef TALLOC_DEBUG
1010         if (true) {
1011 #else
1012         if (!fr_hostname_lookups) {
1013 #endif
1014 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1015                 if (af == AF_UNSPEC) {
1016                         char const *p;
1017
1018                         for (p = hostname; *p != '\0'; p++) {
1019                                 if ((*p == ':') ||
1020                                     (*p == '[') ||
1021                                     (*p == ']')) {
1022                                         af = AF_INET6;
1023                                         break;
1024                                 }
1025                         }
1026                 }
1027 #endif
1028
1029                 if (af == AF_UNSPEC) af = AF_INET;
1030
1031                 if (!inet_pton(af, hostname, &(out->ipaddr))) return -1;
1032
1033                 out->af = af;
1034                 return 0;
1035         }
1036
1037         memset(&hints, 0, sizeof(hints));
1038
1039         /*
1040          *      If we're falling back we need both IPv4 and IPv6 records
1041          */
1042         if (fallback) {
1043                 hints.ai_family = AF_UNSPEC;
1044         } else {
1045                 hints.ai_family = af;
1046         }
1047
1048         if ((rcode = getaddrinfo(hostname, NULL, &hints, &res)) != 0) {
1049                 switch (af) {
1050                 default:
1051                 case AF_UNSPEC:
1052                         fr_strerror_printf("Failed resolving \"%s\" to IP address: %s",
1053                                            hostname, gai_strerror(rcode));
1054                         return -1;
1055
1056                 case AF_INET:
1057                         fr_strerror_printf("Failed resolving \"%s\" to IPv4 address: %s",
1058                                            hostname, gai_strerror(rcode));
1059                         return -1;
1060
1061                 case AF_INET6:
1062                         fr_strerror_printf("Failed resolving \"%s\" to IPv6 address: %s",
1063                                            hostname, gai_strerror(rcode));
1064                         return -1;
1065                 }
1066         }
1067
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;
1071         }
1072
1073         if (!ai) ai = alt;
1074         if (!ai) {
1075                 fr_strerror_printf("ip_hton failed to find requested information for host %.100s", hostname);
1076                 freeaddrinfo(res);
1077                 return -1;
1078         }
1079
1080         rcode = fr_sockaddr2ipaddr((struct sockaddr_storage *)ai->ai_addr,
1081                                    ai->ai_addrlen, out, NULL);
1082         freeaddrinfo(res);
1083         if (!rcode) {
1084                 fr_strerror_printf("Failed converting sockaddr to ipaddr");
1085                 return -1;
1086         }
1087
1088         return 0;
1089 }
1090
1091 /*
1092  *      Look IP addresses up, and print names (depending on DNS config)
1093  */
1094 char const *ip_ntoh(fr_ipaddr_t const *src, char *dst, size_t cnt)
1095 {
1096         struct sockaddr_storage ss;
1097         int error;
1098         socklen_t salen;
1099
1100         /*
1101          *      No DNS lookups
1102          */
1103         if (!fr_dns_lookups) {
1104                 return inet_ntop(src->af, &(src->ipaddr), dst, cnt);
1105         }
1106
1107         if (!fr_ipaddr2sockaddr(src, 0, &ss, &salen)) {
1108                 return NULL;
1109         }
1110
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));
1114                 return NULL;
1115         }
1116         return dst;
1117 }
1118
1119 /** Mask off a portion of an IPv4 address
1120  *
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.
1124  */
1125 struct in_addr fr_inaddr_mask(struct in_addr const *ipaddr, uint8_t prefix)
1126 {
1127         uint32_t ret;
1128
1129         if (prefix > 32) prefix = 32;
1130
1131         /* Short circuit */
1132         if (prefix == 32) return *ipaddr;
1133
1134         if (prefix == 0) ret = 0;
1135         else ret = htonl(~((0x00000001UL << (32 - prefix)) - 1)) & ipaddr->s_addr;
1136
1137         return (*(struct in_addr *)&ret);
1138 }
1139
1140 /** Mask off a portion of an IPv6 address
1141  *
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.
1145  */
1146 struct in6_addr fr_in6addr_mask(struct in6_addr const *ipaddr, uint8_t prefix)
1147 {
1148         uint64_t const *p = (uint64_t const *) ipaddr;
1149         uint64_t ret[2], *o = ret;
1150
1151         if (prefix > 128) prefix = 128;
1152
1153         /* Short circuit */
1154         if (prefix == 128) return *ipaddr;
1155
1156         if (prefix >= 64) {
1157                 prefix -= 64;
1158                 *o++ = 0xffffffffffffffffULL & *p++;    /* lhs portion masked */
1159         } else {
1160                 ret[1] = 0;                             /* rhs portion zeroed */
1161         }
1162
1163         /* Max left shift is 63 else we get overflow */
1164         if (prefix > 0) {
1165                 *o = htonll(~((uint64_t)(0x0000000000000001ULL << (64 - prefix)) - 1)) & *p;
1166         } else {
1167                 *o = 0;
1168         }
1169
1170         return *(struct in6_addr *) &ret;
1171 }
1172
1173 /** Zeroes out the host portion of an fr_ipaddr_t
1174  *
1175  * @param[in,out] addr to mask
1176  * @param[in] prefix Length of the network portion.
1177  */
1178 void fr_ipaddr_mask(fr_ipaddr_t *addr, uint8_t prefix)
1179 {
1180
1181         switch (addr->af) {
1182         case AF_INET:
1183                 addr->ipaddr.ip4addr = fr_inaddr_mask(&addr->ipaddr.ip4addr, prefix);
1184                 break;
1185
1186         case AF_INET6:
1187                 addr->ipaddr.ip6addr = fr_in6addr_mask(&addr->ipaddr.ip6addr, prefix);
1188                 break;
1189
1190         default:
1191                 return;
1192         }
1193         addr->prefix = prefix;
1194 }
1195
1196 static char const hextab[] = "0123456789abcdef";
1197
1198 /** Convert hex strings to binary data
1199  *
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.
1205  */
1206 size_t fr_hex2bin(uint8_t *bin, size_t outlen, char const *hex, size_t inlen)
1207 {
1208         size_t i;
1209         size_t len;
1210         char *c1, *c2;
1211
1212         /*
1213          *      Smartly truncate output, caller should check number of bytes
1214          *      written.
1215          */
1216         len = inlen >> 1;
1217         if (len > outlen) len = outlen;
1218
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))))
1222                         break;
1223                 bin[i] = ((c1-hextab)<<4) + (c2-hextab);
1224         }
1225
1226         return i;
1227 }
1228
1229 /** Convert binary data to a hex string
1230  *
1231  * Ascii encoded hex string will not be prefixed with '0x'
1232  *
1233  * @warning If the output buffer isn't long enough, we have a buffer overflow.
1234  *
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.
1239  */
1240 size_t fr_bin2hex(char *hex, uint8_t const *bin, size_t inlen)
1241 {
1242         size_t i;
1243
1244         for (i = 0; i < inlen; i++) {
1245                 hex[0] = hextab[((*bin) >> 4) & 0x0f];
1246                 hex[1] = hextab[*bin & 0x0f];
1247                 hex += 2;
1248                 bin++;
1249         }
1250
1251         *hex = '\0';
1252         return inlen * 2;
1253 }
1254
1255 /** Convert binary data to a hex string
1256  *
1257  * Ascii encoded hex string will not be prefixed with '0x'
1258  *
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.
1263  */
1264 char *fr_abin2hex(TALLOC_CTX *ctx, uint8_t const *bin, size_t inlen)
1265 {
1266         char *buff;
1267
1268         buff = talloc_array(ctx, char, (inlen << 2));
1269         if (!buff) return NULL;
1270
1271         fr_bin2hex(buff, bin, inlen);
1272
1273         return buff;
1274 }
1275
1276 /** Consume the integer (or hex) portion of a value string
1277  *
1278  * @param value string to parse.
1279  * @param end pointer to the first non numeric char.
1280  * @return integer value.
1281  */
1282 uint32_t fr_strtoul(char const *value, char **end)
1283 {
1284         if ((value[0] == '0') && (value[1] == 'x')) {
1285                 return strtoul(value, end, 16);
1286         }
1287
1288         return strtoul(value, end, 10);
1289 }
1290
1291 /** Check whether the string is all whitespace
1292  *
1293  * @return true if the entirety of the string is whitespace, else false.
1294  */
1295 bool is_whitespace(char const *value)
1296 {
1297         do {
1298                 if (!isspace(*value)) return false;
1299         } while (*++value);
1300
1301         return true;
1302 }
1303
1304 /** Check whether the string is made up of printable UTF8 chars
1305  *
1306  * @param value to check.
1307  * @param len of value.
1308  *
1309  * @return
1310  *      - true if the string is printable.
1311  *      - false if the string contains non printable chars
1312  */
1313  bool is_printable(void const *value, size_t len)
1314  {
1315         uint8_t const *p = value;
1316         int     clen;
1317         size_t  i;
1318
1319         for (i = 0; i < len; i++) {
1320                 clen = fr_utf8_char(p, len - i);
1321                 if (clen == 0) return false;
1322                 i += (size_t)clen;
1323                 p += clen;
1324         }
1325         return true;
1326  }
1327
1328 /** Check whether the string is all numbers
1329  *
1330  * @return true if the entirety of the string is all numbers, else false.
1331  */
1332 bool is_integer(char const *value)
1333 {
1334         do {
1335                 if (!isdigit(*value)) return false;
1336         } while (*++value);
1337
1338         return true;
1339 }
1340
1341 /** Check whether the string is allzeros
1342  *
1343  * @return true if the entirety of the string is all zeros, else false.
1344  */
1345 bool is_zero(char const *value)
1346 {
1347         do {
1348                 if (*value != '0') return false;
1349         } while (*++value);
1350
1351         return true;
1352 }
1353
1354 /*
1355  *      So we don't have ifdef's in the rest of the code
1356  */
1357 #ifndef HAVE_CLOSEFROM
1358 int closefrom(int fd)
1359 {
1360         int i;
1361         int maxfd = 256;
1362
1363 #ifdef F_CLOSEM
1364         if (fcntl(fd, F_CLOSEM) == 0) {
1365                 return 0;
1366         }
1367 #endif
1368
1369 #ifdef F_MAXFD
1370         maxfd = fcntl(fd, F_F_MAXFD);
1371         if (maxfd >= 0) goto do_close;
1372 #endif
1373
1374 #ifdef _SC_OPEN_MAX
1375         maxfd = sysconf(_SC_OPEN_MAX);
1376         if (maxfd < 0) {
1377                 maxfd = 256;
1378         }
1379 #endif
1380
1381 #ifdef F_MAXFD
1382 do_close:
1383 #endif
1384
1385         if (fd > maxfd) return 0;
1386
1387         /*
1388          *      FIXME: return EINTR?
1389          */
1390         for (i = fd; i < maxfd; i++) {
1391                 close(i);
1392         }
1393
1394         return 0;
1395 }
1396 #endif
1397
1398 int fr_ipaddr_cmp(fr_ipaddr_t const *a, fr_ipaddr_t const *b)
1399 {
1400         if (a->af < b->af) return -1;
1401         if (a->af > b->af) return +1;
1402
1403         if (a->prefix < b->prefix) return -1;
1404         if (a->prefix > b->prefix) return +1;
1405
1406         switch (a->af) {
1407         case AF_INET:
1408                 return memcmp(&a->ipaddr.ip4addr,
1409                               &b->ipaddr.ip4addr,
1410                               sizeof(a->ipaddr.ip4addr));
1411
1412 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1413         case AF_INET6:
1414                 if (a->scope < b->scope) return -1;
1415                 if (a->scope > b->scope) return +1;
1416
1417                 return memcmp(&a->ipaddr.ip6addr,
1418                               &b->ipaddr.ip6addr,
1419                               sizeof(a->ipaddr.ip6addr));
1420 #endif
1421
1422         default:
1423                 break;
1424         }
1425
1426         return -1;
1427 }
1428
1429 int fr_ipaddr2sockaddr(fr_ipaddr_t const *ipaddr, uint16_t port,
1430                        struct sockaddr_storage *sa, socklen_t *salen)
1431 {
1432         memset(sa, 0, sizeof(*sa));
1433
1434         if (ipaddr->af == AF_INET) {
1435                 struct sockaddr_in s4;
1436
1437                 *salen = sizeof(s4);
1438
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));
1445
1446 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1447         } else if (ipaddr->af == AF_INET6) {
1448                 struct sockaddr_in6 s6;
1449
1450                 *salen = sizeof(s6);
1451
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));
1459 #endif
1460         } else {
1461                 return 0;
1462         }
1463
1464         return 1;
1465 }
1466
1467
1468 int fr_sockaddr2ipaddr(struct sockaddr_storage const *sa, socklen_t salen,
1469                        fr_ipaddr_t *ipaddr, uint16_t *port)
1470 {
1471         memset(ipaddr, 0, sizeof(*ipaddr));
1472
1473         if (sa->ss_family == AF_INET) {
1474                 struct sockaddr_in      s4;
1475
1476                 if (salen < sizeof(s4)) {
1477                         fr_strerror_printf("IPv4 address is too small");
1478                         return 0;
1479                 }
1480
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);
1486
1487 #ifdef HAVE_STRUCT_SOCKADDR_IN6
1488         } else if (sa->ss_family == AF_INET6) {
1489                 struct sockaddr_in6     s6;
1490
1491                 if (salen < sizeof(s6)) {
1492                         fr_strerror_printf("IPv6 address is too small");
1493                         return 0;
1494                 }
1495
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;
1502 #endif
1503
1504         } else {
1505                 fr_strerror_printf("Unsupported address famility %d",
1506                                    sa->ss_family);
1507                 return 0;
1508         }
1509
1510         return 1;
1511 }
1512
1513 #ifdef O_NONBLOCK
1514 /** Set O_NONBLOCK on a socket
1515  *
1516  * @note O_NONBLOCK is POSIX.
1517  *
1518  * @param fd to set nonblocking flag on.
1519  * @return flags set on the socket, or -1 on error.
1520  */
1521 int fr_nonblock(int fd)
1522 {
1523         int flags;
1524
1525         flags = fcntl(fd, F_GETFL, NULL);
1526         if (flags < 0)  {
1527                 fr_strerror_printf("Failure getting socket flags: %s", fr_syserror(errno));
1528                 return -1;
1529         }
1530
1531         flags |= O_NONBLOCK;
1532         if (fcntl(fd, F_SETFL, flags) < 0) {
1533                 fr_strerror_printf("Failure setting socket flags: %s", fr_syserror(errno));
1534                 return -1;
1535         }
1536
1537         return flags;
1538 }
1539
1540 /** Unset O_NONBLOCK on a socket
1541  *
1542  * @note O_NONBLOCK is POSIX.
1543  *
1544  * @param fd to set nonblocking flag on.
1545  * @return flags set on the socket, or -1 on error.
1546  */
1547 int fr_blocking(int fd)
1548 {
1549         int flags;
1550
1551         flags = fcntl(fd, F_GETFL, NULL);
1552         if (flags < 0)  {
1553                 fr_strerror_printf("Failure getting socket flags: %s", fr_syserror(errno));
1554                 return -1;
1555         }
1556
1557         flags ^= O_NONBLOCK;
1558         if (fcntl(fd, F_SETFL, flags) < 0) {
1559                 fr_strerror_printf("Failure setting socket flags: %s", fr_syserror(errno));
1560                 return -1;
1561         }
1562
1563         return flags;
1564 }
1565 #else
1566 int fr_nonblock(UNUSED int fd)
1567 {
1568         fr_strerror_printf("Non blocking sockets are not supported");
1569         return -1;
1570 }
1571 int fr_blocking(UNUSED int fd)
1572 {
1573         fr_strerror_printf("Non blocking sockets are not supported");
1574         return -1;
1575 }
1576 #endif
1577
1578 /** Write out a vector to a file descriptor
1579  *
1580  * Wraps writev, calling it as necessary. If timeout is not NULL,
1581  * timeout is applied to each call that returns EAGAIN or EWOULDBLOCK
1582  *
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.
1587  *
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.
1593  */
1594 ssize_t fr_writev(int fd, struct iovec vector[], int iovcnt, struct timeval *timeout)
1595 {
1596         struct iovec *vector_p = vector;
1597         ssize_t total = 0;
1598
1599         while (iovcnt > 0) {
1600                 ssize_t wrote;
1601
1602                 wrote = writev(fd, vector_p, iovcnt);
1603                 if (wrote > 0) {
1604                         total += wrote;
1605                         while (wrote > 0) {
1606                                 /*
1607                                  *      An entire vector element was written
1608                                  */
1609                                 if (wrote >= (ssize_t)vector_p->iov_len) {
1610                                         iovcnt--;
1611                                         wrote -= vector_p->iov_len;
1612                                         vector_p++;
1613                                         continue;
1614                                 }
1615
1616                                 /*
1617                                  *      Partial vector element was written
1618                                  */
1619                                 vector_p->iov_len -= wrote;
1620                                 vector_p->iov_base = ((char *)vector_p->iov_base) + wrote;
1621                                 break;
1622                         }
1623                         continue;
1624                 } else if (wrote == 0) return total;
1625
1626                 switch (errno) {
1627                 /* Write operation would block, use select() to implement a timeout */
1628 #if EWOULDBLOCK != EAGAIN
1629                 case EWOULDBLOCK:
1630                 case EAGAIN:
1631 #else
1632                 case EAGAIN:
1633 #endif
1634                 {
1635                         int     ret;
1636                         fd_set  write_set;
1637
1638                         FD_ZERO(&write_set);
1639                         FD_SET(fd, &write_set);
1640
1641                         /* Don't let signals mess up the select */
1642                         do {
1643                                 ret = select(fd + 1, NULL, &write_set, NULL, timeout);
1644                         } while ((ret == -1) && (errno == EINTR));
1645
1646                         /* Select returned 0 which means it reached the timeout */
1647                         if (ret == 0) {
1648                                 fr_strerror_printf("Write timed out");
1649                                 return -1;
1650                         }
1651
1652                         /* Other select error */
1653                         if (ret < 0) {
1654                                 fr_strerror_printf("Failed waiting on socket: %s", fr_syserror(errno));
1655                                 return -1;
1656                         }
1657
1658                         /* select said a file descriptor was ready for writing */
1659                         if (!fr_assert(FD_ISSET(fd, &write_set))) return -1;
1660
1661                         break;
1662                 }
1663
1664                 default:
1665                         return -1;
1666                 }
1667         }
1668
1669         return total;
1670 }
1671
1672 /** Convert UTF8 string to UCS2 encoding
1673  *
1674  * @note Borrowed from src/crypto/ms_funcs.c of wpa_supplicant project (http://hostap.epitest.fi/wpa_supplicant/)
1675  *
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).
1681  */
1682 ssize_t fr_utf8_to_ucs2(uint8_t *out, size_t outlen, char const *in, size_t inlen)
1683 {
1684         size_t i;
1685         uint8_t *start = out;
1686
1687         for (i = 0; i < inlen; i++) {
1688                 uint8_t c, c2, c3;
1689
1690                 c = in[i];
1691                 if ((size_t)(out - start) >= outlen) {
1692                         /* input too long */
1693                         return -1;
1694                 }
1695
1696                 /* One-byte encoding */
1697                 if (c <= 0x7f) {
1698                         FR_PUT_LE16(out, c);
1699                         out += 2;
1700                         continue;
1701                 } else if ((i == (inlen - 1)) || ((size_t)(out - start) >= (outlen - 1))) {
1702                         /* Incomplete surrogate */
1703                         return -1;
1704                 }
1705
1706                 c2 = in[++i];
1707                 /* Two-byte encoding */
1708                 if ((c & 0xe0) == 0xc0) {
1709                         FR_PUT_LE16(out, ((c & 0x1f) << 6) | (c2 & 0x3f));
1710                         out += 2;
1711                         continue;
1712                 }
1713                 if ((i == inlen) || ((size_t)(out - start) >= (outlen - 1))) {
1714                         /* Incomplete surrogate */
1715                         return -1;
1716                 }
1717
1718                 /* Three-byte encoding */
1719                 c3 = in[++i];
1720                 FR_PUT_LE16(out, ((c & 0xf) << 12) | ((c2 & 0x3f) << 6) | (c3 & 0x3f));
1721                 out += 2;
1722         }
1723
1724         return out - start;
1725 }
1726
1727 /** Write 128bit unsigned integer to buffer
1728  *
1729  * @author Alexey Frunze
1730  *
1731  * @param out where to write result to.
1732  * @param outlen size of out.
1733  * @param num 128 bit integer.
1734  */
1735 size_t fr_prints_uint128(char *out, size_t outlen, uint128_t const num)
1736 {
1737         char buff[128 / 3 + 1 + 1];
1738         uint64_t n[2];
1739         char *p = buff;
1740         int i;
1741 #ifdef FR_LITTLE_ENDIAN
1742         const size_t l = 0;
1743         const size_t h = 1;
1744 #else
1745         const size_t l = 1;
1746         const size_t h = 0;
1747 #endif
1748
1749         memset(buff, '0', sizeof(buff) - 1);
1750         buff[sizeof(buff) - 1] = '\0';
1751
1752         memcpy(n, &num, sizeof(n));
1753
1754         for (i = 0; i < 128; i++) {
1755                 ssize_t j;
1756                 int carry;
1757
1758                 carry = (n[h] >= 0x8000000000000000);
1759
1760                 // Shift n[] left, doubling it
1761                 n[h] = ((n[h] << 1) & 0xffffffffffffffff) + (n[l] >= 0x8000000000000000);
1762                 n[l] = ((n[l] << 1) & 0xffffffffffffffff);
1763
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');
1768                         if (carry) {
1769                                 buff[j] -= 10;
1770                         }
1771                 }
1772         }
1773
1774         while ((*p == '0') && (p < &buff[sizeof(buff) - 2])) {
1775                 p++;
1776         }
1777
1778         return strlcpy(out, p, outlen);
1779 }
1780
1781 /*
1782  *      Sort of strtok/strsep function.
1783  */
1784 static char *mystrtok(char **ptr, char const *sep)
1785 {
1786         char    *res;
1787
1788         if (**ptr == 0) {
1789                 return NULL;
1790         }
1791
1792         while (**ptr && strchr(sep, **ptr)) {
1793                 (*ptr)++;
1794         }
1795         if (**ptr == 0) {
1796                 return NULL;
1797         }
1798
1799         res = *ptr;
1800         while (**ptr && strchr(sep, **ptr) == NULL) {
1801                 (*ptr)++;
1802         }
1803
1804         if (**ptr != 0) {
1805                 *(*ptr)++ = 0;
1806         }
1807         return res;
1808 }
1809
1810 /** Convert string in various formats to a time_t
1811  *
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.
1815  */
1816 int fr_get_time(char const *date_str, time_t *date)
1817 {
1818         int             i;
1819         time_t          t;
1820         struct tm       *tm, s_tm;
1821         char            buf[64];
1822         char            *p;
1823         char            *f[4];
1824         char            *tail = NULL;
1825
1826         /*
1827          * Test for unix timestamp date
1828          */
1829         *date = strtoul(date_str, &tail, 10);
1830         if (*tail == '\0') {
1831                 return 0;
1832         }
1833
1834         tm = &s_tm;
1835         memset(tm, 0, sizeof(*tm));
1836         tm->tm_isdst = -1;      /* don't know, and don't care about DST */
1837
1838         strlcpy(buf, date_str, sizeof(buf));
1839
1840         p = 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;
1846
1847         /*
1848          *      The time has a colon, where nothing else does.
1849          *      So if we find it, bubble it to the back of the list.
1850          */
1851         if (f[3]) {
1852                 for (i = 0; i < 3; i++) {
1853                         if (strchr(f[i], ':')) {
1854                                 p = f[3];
1855                                 f[3] = f[i];
1856                                 f[i] = p;
1857                                 break;
1858                         }
1859                 }
1860         }
1861
1862         /*
1863          *  The month is text, which allows us to find it easily.
1864          */
1865         tm->tm_mon = 12;
1866         for (i = 0; i < 3; i++) {
1867                 if (isalpha( (int) *f[i])) {
1868                         /*
1869                          *  Bubble the month to the front of the list
1870                          */
1871                         p = f[0];
1872                         f[0] = f[i];
1873                         f[i] = p;
1874
1875                         for (i = 0; i < 12; i++) {
1876                                 if (strncasecmp(months[i], f[0], 3) == 0) {
1877                                         tm->tm_mon = i;
1878                                         break;
1879                                 }
1880                         }
1881                 }
1882         }
1883
1884         /* month not found? */
1885         if (tm->tm_mon == 12) return -1;
1886
1887         /*
1888          *  The year may be in f[1], or in f[2]
1889          */
1890         tm->tm_year = atoi(f[1]);
1891         tm->tm_mday = atoi(f[2]);
1892
1893         if (tm->tm_year >= 1900) {
1894                 tm->tm_year -= 1900;
1895
1896         } else {
1897                 /*
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.
1900                  */
1901                 if (tm->tm_mday < 1900) return -1;
1902
1903                 /*
1904                  *  Swap the year and the day.
1905                  */
1906                 i = tm->tm_year;
1907                 tm->tm_year = tm->tm_mday - 1900;
1908                 tm->tm_mday = i;
1909         }
1910
1911         /*
1912          *  If the day is out of range, die.
1913          */
1914         if ((tm->tm_mday < 1) || (tm->tm_mday > 31)) {
1915                 return -1;
1916         }
1917
1918         /*
1919          *      There may be %H:%M:%S.  Parse it in a hacky way.
1920          */
1921         if (f[3]) {
1922                 f[0] = f[3];    /* HH */
1923                 f[1] = strchr(f[0], ':'); /* find : separator */
1924                 if (!f[1]) return -1;
1925
1926                 *(f[1]++) = '\0'; /* nuke it, and point to MM:SS */
1927
1928                 f[2] = strchr(f[1], ':'); /* find : separator */
1929                 if (f[2]) {
1930                   *(f[2]++) = '\0';     /* nuke it, and point to SS */
1931                   tm->tm_sec = atoi(f[2]);
1932                 }                       /* else leave it as zero */
1933
1934                 tm->tm_hour = atoi(f[0]);
1935                 tm->tm_min = atoi(f[1]);
1936         }
1937
1938         /*
1939          *  Returns -1 on error.
1940          */
1941         t = mktime(tm);
1942         if (t == (time_t) -1) return -1;
1943
1944         *date = t;
1945
1946         return 0;
1947 }
1948
1949 /** Compares two pointers
1950  *
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.
1954  */
1955 int8_t fr_pointer_cmp(void const *a, void const *b)
1956 {
1957         if (a < b) return -1;
1958         if (a == b) return 0;
1959
1960         return 1;
1961 }
1962
1963 static int _quick_partition(void const *to_sort[], int min, int max, fr_cmp_t cmp) {
1964         void const *pivot = to_sort[min];
1965         int i = min;
1966         int j = max + 1;
1967         void const *tmp;
1968
1969         for (;;) {
1970                 do ++i; while((cmp(to_sort[i], pivot) <= 0) && i <= max);
1971                 do --j; while(cmp(to_sort[j], pivot) > 0);
1972
1973                 if (i >= j) break;
1974
1975                 tmp = to_sort[i];
1976                 to_sort[i] = to_sort[j];
1977                 to_sort[j] = tmp;
1978         }
1979
1980         tmp = to_sort[min];
1981         to_sort[min] = to_sort[j];
1982         to_sort[j] = tmp;
1983
1984         return j;
1985 }
1986
1987 /** Quick sort an array of pointers using a comparator
1988  *
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.
1993  */
1994 void fr_quick_sort(void const *to_sort[], int min_idx, int max_idx, fr_cmp_t cmp)
1995 {
1996         int part;
1997
1998         if (min_idx >= max_idx) return;
1999
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);
2003 }
2004
2005 #ifdef TALLOC_DEBUG
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)
2009 {
2010         /* do nothing */
2011 }
2012 #endif