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