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