1 /*
2 * General purpose functions.
3 *
4 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
13 #if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
14 #define _GNU_SOURCE
15 #include <dlfcn.h>
16 #include <link.h>
17 #endif
18
19 #include <ctype.h>
20 #include <errno.h>
21 #include <netdb.h>
22 #include <stdarg.h>
23 #include <stdio.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <time.h>
27 #include <unistd.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/types.h>
31 #include <sys/un.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34
35 #include <common/chunk.h>
36 #include <common/config.h>
37 #include <common/standard.h>
38 #include <common/tools.h>
39 #include <types/global.h>
40 #include <proto/applet.h>
41 #include <proto/dns.h>
42 #include <proto/hlua.h>
43 #include <proto/listener.h>
44 #include <proto/proto_udp.h>
45 #include <proto/ssl_sock.h>
46 #include <proto/stream_interface.h>
47 #include <proto/task.h>
48
49 #include <eb32tree.h>
50 #include <eb32sctree.h>
51
52 /* This macro returns false if the test __x is false. Many
53 * of the following parsing function must be abort the processing
54 * if it returns 0, so this macro is useful for writing light code.
55 */
56 #define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
57
58 /* enough to store NB_ITOA_STR integers of :
59 * 2^64-1 = 18446744073709551615 or
60 * -2^63 = -9223372036854775808
61 *
62 * The HTML version needs room for adding the 25 characters
63 * '<span class="rls"></span>' around digits at positions 3N+1 in order
64 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
65 */
66 THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
67 THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
68
69 /* sometimes we'll need to quote strings (eg: in stats), and we don't expect
70 * to quote strings larger than a max configuration line.
71 */
72 THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
73 THREAD_LOCAL int quoted_idx = 0;
74
75 /*
76 * unsigned long long ASCII representation
77 *
78 * return the last char '\0' or NULL if no enough
79 * space in dst
80 */
ulltoa(unsigned long long n,char * dst,size_t size)81 char *ulltoa(unsigned long long n, char *dst, size_t size)
82 {
83 int i = 0;
84 char *res;
85
86 switch(n) {
87 case 1ULL ... 9ULL:
88 i = 0;
89 break;
90
91 case 10ULL ... 99ULL:
92 i = 1;
93 break;
94
95 case 100ULL ... 999ULL:
96 i = 2;
97 break;
98
99 case 1000ULL ... 9999ULL:
100 i = 3;
101 break;
102
103 case 10000ULL ... 99999ULL:
104 i = 4;
105 break;
106
107 case 100000ULL ... 999999ULL:
108 i = 5;
109 break;
110
111 case 1000000ULL ... 9999999ULL:
112 i = 6;
113 break;
114
115 case 10000000ULL ... 99999999ULL:
116 i = 7;
117 break;
118
119 case 100000000ULL ... 999999999ULL:
120 i = 8;
121 break;
122
123 case 1000000000ULL ... 9999999999ULL:
124 i = 9;
125 break;
126
127 case 10000000000ULL ... 99999999999ULL:
128 i = 10;
129 break;
130
131 case 100000000000ULL ... 999999999999ULL:
132 i = 11;
133 break;
134
135 case 1000000000000ULL ... 9999999999999ULL:
136 i = 12;
137 break;
138
139 case 10000000000000ULL ... 99999999999999ULL:
140 i = 13;
141 break;
142
143 case 100000000000000ULL ... 999999999999999ULL:
144 i = 14;
145 break;
146
147 case 1000000000000000ULL ... 9999999999999999ULL:
148 i = 15;
149 break;
150
151 case 10000000000000000ULL ... 99999999999999999ULL:
152 i = 16;
153 break;
154
155 case 100000000000000000ULL ... 999999999999999999ULL:
156 i = 17;
157 break;
158
159 case 1000000000000000000ULL ... 9999999999999999999ULL:
160 i = 18;
161 break;
162
163 case 10000000000000000000ULL ... ULLONG_MAX:
164 i = 19;
165 break;
166 }
167 if (i + 2 > size) // (i + 1) + '\0'
168 return NULL; // too long
169 res = dst + i + 1;
170 *res = '\0';
171 for (; i >= 0; i--) {
172 dst[i] = n % 10ULL + '0';
173 n /= 10ULL;
174 }
175 return res;
176 }
177
178 /*
179 * unsigned long ASCII representation
180 *
181 * return the last char '\0' or NULL if no enough
182 * space in dst
183 */
ultoa_o(unsigned long n,char * dst,size_t size)184 char *ultoa_o(unsigned long n, char *dst, size_t size)
185 {
186 int i = 0;
187 char *res;
188
189 switch (n) {
190 case 0U ... 9UL:
191 i = 0;
192 break;
193
194 case 10U ... 99UL:
195 i = 1;
196 break;
197
198 case 100U ... 999UL:
199 i = 2;
200 break;
201
202 case 1000U ... 9999UL:
203 i = 3;
204 break;
205
206 case 10000U ... 99999UL:
207 i = 4;
208 break;
209
210 case 100000U ... 999999UL:
211 i = 5;
212 break;
213
214 case 1000000U ... 9999999UL:
215 i = 6;
216 break;
217
218 case 10000000U ... 99999999UL:
219 i = 7;
220 break;
221
222 case 100000000U ... 999999999UL:
223 i = 8;
224 break;
225 #if __WORDSIZE == 32
226
227 case 1000000000ULL ... ULONG_MAX:
228 i = 9;
229 break;
230
231 #elif __WORDSIZE == 64
232
233 case 1000000000ULL ... 9999999999UL:
234 i = 9;
235 break;
236
237 case 10000000000ULL ... 99999999999UL:
238 i = 10;
239 break;
240
241 case 100000000000ULL ... 999999999999UL:
242 i = 11;
243 break;
244
245 case 1000000000000ULL ... 9999999999999UL:
246 i = 12;
247 break;
248
249 case 10000000000000ULL ... 99999999999999UL:
250 i = 13;
251 break;
252
253 case 100000000000000ULL ... 999999999999999UL:
254 i = 14;
255 break;
256
257 case 1000000000000000ULL ... 9999999999999999UL:
258 i = 15;
259 break;
260
261 case 10000000000000000ULL ... 99999999999999999UL:
262 i = 16;
263 break;
264
265 case 100000000000000000ULL ... 999999999999999999UL:
266 i = 17;
267 break;
268
269 case 1000000000000000000ULL ... 9999999999999999999UL:
270 i = 18;
271 break;
272
273 case 10000000000000000000ULL ... ULONG_MAX:
274 i = 19;
275 break;
276
277 #endif
278 }
279 if (i + 2 > size) // (i + 1) + '\0'
280 return NULL; // too long
281 res = dst + i + 1;
282 *res = '\0';
283 for (; i >= 0; i--) {
284 dst[i] = n % 10U + '0';
285 n /= 10U;
286 }
287 return res;
288 }
289
290 /*
291 * signed long ASCII representation
292 *
293 * return the last char '\0' or NULL if no enough
294 * space in dst
295 */
ltoa_o(long int n,char * dst,size_t size)296 char *ltoa_o(long int n, char *dst, size_t size)
297 {
298 char *pos = dst;
299
300 if (n < 0) {
301 if (size < 3)
302 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
303 *pos = '-';
304 pos++;
305 dst = ultoa_o(-n, pos, size - 1);
306 } else {
307 dst = ultoa_o(n, dst, size);
308 }
309 return dst;
310 }
311
312 /*
313 * signed long long ASCII representation
314 *
315 * return the last char '\0' or NULL if no enough
316 * space in dst
317 */
lltoa(long long n,char * dst,size_t size)318 char *lltoa(long long n, char *dst, size_t size)
319 {
320 char *pos = dst;
321
322 if (n < 0) {
323 if (size < 3)
324 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
325 *pos = '-';
326 pos++;
327 dst = ulltoa(-n, pos, size - 1);
328 } else {
329 dst = ulltoa(n, dst, size);
330 }
331 return dst;
332 }
333
334 /*
335 * write a ascii representation of a unsigned into dst,
336 * return a pointer to the last character
337 * Pad the ascii representation with '0', using size.
338 */
utoa_pad(unsigned int n,char * dst,size_t size)339 char *utoa_pad(unsigned int n, char *dst, size_t size)
340 {
341 int i = 0;
342 char *ret;
343
344 switch(n) {
345 case 0U ... 9U:
346 i = 0;
347 break;
348
349 case 10U ... 99U:
350 i = 1;
351 break;
352
353 case 100U ... 999U:
354 i = 2;
355 break;
356
357 case 1000U ... 9999U:
358 i = 3;
359 break;
360
361 case 10000U ... 99999U:
362 i = 4;
363 break;
364
365 case 100000U ... 999999U:
366 i = 5;
367 break;
368
369 case 1000000U ... 9999999U:
370 i = 6;
371 break;
372
373 case 10000000U ... 99999999U:
374 i = 7;
375 break;
376
377 case 100000000U ... 999999999U:
378 i = 8;
379 break;
380
381 case 1000000000U ... 4294967295U:
382 i = 9;
383 break;
384 }
385 if (i + 2 > size) // (i + 1) + '\0'
386 return NULL; // too long
387 if (i < size)
388 i = size - 2; // padding - '\0'
389
390 ret = dst + i + 1;
391 *ret = '\0';
392 for (; i >= 0; i--) {
393 dst[i] = n % 10U + '0';
394 n /= 10U;
395 }
396 return ret;
397 }
398
399 /*
400 * copies at most <size-1> chars from <src> to <dst>. Last char is always
401 * set to 0, unless <size> is 0. The number of chars copied is returned
402 * (excluding the terminating zero).
403 * This code has been optimized for size and speed : on x86, it's 45 bytes
404 * long, uses only registers, and consumes only 4 cycles per char.
405 */
strlcpy2(char * dst,const char * src,int size)406 int strlcpy2(char *dst, const char *src, int size)
407 {
408 char *orig = dst;
409 if (size) {
410 while (--size && (*dst = *src)) {
411 src++; dst++;
412 }
413 *dst = 0;
414 }
415 return dst - orig;
416 }
417
418 /*
419 * This function simply returns a locally allocated string containing
420 * the ascii representation for number 'n' in decimal.
421 */
ultoa_r(unsigned long n,char * buffer,int size)422 char *ultoa_r(unsigned long n, char *buffer, int size)
423 {
424 char *pos;
425
426 pos = buffer + size - 1;
427 *pos-- = '\0';
428
429 do {
430 *pos-- = '0' + n % 10;
431 n /= 10;
432 } while (n && pos >= buffer);
433 return pos + 1;
434 }
435
436 /*
437 * This function simply returns a locally allocated string containing
438 * the ascii representation for number 'n' in decimal.
439 */
lltoa_r(long long int in,char * buffer,int size)440 char *lltoa_r(long long int in, char *buffer, int size)
441 {
442 char *pos;
443 int neg = 0;
444 unsigned long long int n;
445
446 pos = buffer + size - 1;
447 *pos-- = '\0';
448
449 if (in < 0) {
450 neg = 1;
451 n = -in;
452 }
453 else
454 n = in;
455
456 do {
457 *pos-- = '0' + n % 10;
458 n /= 10;
459 } while (n && pos >= buffer);
460 if (neg && pos > buffer)
461 *pos-- = '-';
462 return pos + 1;
463 }
464
465 /*
466 * This function simply returns a locally allocated string containing
467 * the ascii representation for signed number 'n' in decimal.
468 */
sltoa_r(long n,char * buffer,int size)469 char *sltoa_r(long n, char *buffer, int size)
470 {
471 char *pos;
472
473 if (n >= 0)
474 return ultoa_r(n, buffer, size);
475
476 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
477 *pos = '-';
478 return pos;
479 }
480
481 /*
482 * This function simply returns a locally allocated string containing
483 * the ascii representation for number 'n' in decimal, formatted for
484 * HTML output with tags to create visual grouping by 3 digits. The
485 * output needs to support at least 171 characters.
486 */
ulltoh_r(unsigned long long n,char * buffer,int size)487 const char *ulltoh_r(unsigned long long n, char *buffer, int size)
488 {
489 char *start;
490 int digit = 0;
491
492 start = buffer + size;
493 *--start = '\0';
494
495 do {
496 if (digit == 3 && start >= buffer + 7)
497 memcpy(start -= 7, "</span>", 7);
498
499 if (start >= buffer + 1) {
500 *--start = '0' + n % 10;
501 n /= 10;
502 }
503
504 if (digit == 3 && start >= buffer + 18)
505 memcpy(start -= 18, "<span class=\"rls\">", 18);
506
507 if (digit++ == 3)
508 digit = 1;
509 } while (n && start > buffer);
510 return start;
511 }
512
513 /*
514 * This function simply returns a locally allocated string containing the ascii
515 * representation for number 'n' in decimal, unless n is 0 in which case it
516 * returns the alternate string (or an empty string if the alternate string is
517 * NULL). It use is intended for limits reported in reports, where it's
518 * desirable not to display anything if there is no limit. Warning! it shares
519 * the same vector as ultoa_r().
520 */
limit_r(unsigned long n,char * buffer,int size,const char * alt)521 const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
522 {
523 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
524 }
525
526 /* returns a locally allocated string containing the quoted encoding of the
527 * input string. The output may be truncated to QSTR_SIZE chars, but it is
528 * guaranteed that the string will always be properly terminated. Quotes are
529 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
530 * always be at least 4 chars.
531 */
qstr(const char * str)532 const char *qstr(const char *str)
533 {
534 char *ret = quoted_str[quoted_idx];
535 char *p, *end;
536
537 if (++quoted_idx >= NB_QSTR)
538 quoted_idx = 0;
539
540 p = ret;
541 end = ret + QSTR_SIZE;
542
543 *p++ = '"';
544
545 /* always keep 3 chars to support passing "" and the ending " */
546 while (*str && p < end - 3) {
547 if (*str == '"') {
548 *p++ = '"';
549 *p++ = '"';
550 }
551 else
552 *p++ = *str;
553 str++;
554 }
555 *p++ = '"';
556 return ret;
557 }
558
559 /*
560 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
561 *
562 * It looks like this one would be a good candidate for inlining, but this is
563 * not interesting because it around 35 bytes long and often called multiple
564 * times within the same function.
565 */
ishex(char s)566 int ishex(char s)
567 {
568 s -= '0';
569 if ((unsigned char)s <= 9)
570 return 1;
571 s -= 'A' - '0';
572 if ((unsigned char)s <= 5)
573 return 1;
574 s -= 'a' - 'A';
575 if ((unsigned char)s <= 5)
576 return 1;
577 return 0;
578 }
579
580 /* rounds <i> down to the closest value having max 2 digits */
round_2dig(unsigned int i)581 unsigned int round_2dig(unsigned int i)
582 {
583 unsigned int mul = 1;
584
585 while (i >= 100) {
586 i /= 10;
587 mul *= 10;
588 }
589 return i * mul;
590 }
591
592 /*
593 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
594 * invalid character is found, a pointer to it is returned. If everything is
595 * fine, NULL is returned.
596 */
invalid_char(const char * name)597 const char *invalid_char(const char *name)
598 {
599 if (!*name)
600 return name;
601
602 while (*name) {
603 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
604 *name != '_' && *name != '-')
605 return name;
606 name++;
607 }
608 return NULL;
609 }
610
611 /*
612 * Checks <name> for invalid characters. Valid chars are [_.-] and those
613 * accepted by <f> function.
614 * If an invalid character is found, a pointer to it is returned.
615 * If everything is fine, NULL is returned.
616 */
__invalid_char(const char * name,int (* f)(int))617 static inline const char *__invalid_char(const char *name, int (*f)(int)) {
618
619 if (!*name)
620 return name;
621
622 while (*name) {
623 if (!f((int)(unsigned char)*name) && *name != '.' &&
624 *name != '_' && *name != '-')
625 return name;
626
627 name++;
628 }
629
630 return NULL;
631 }
632
633 /*
634 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
635 * If an invalid character is found, a pointer to it is returned.
636 * If everything is fine, NULL is returned.
637 */
invalid_domainchar(const char * name)638 const char *invalid_domainchar(const char *name) {
639 return __invalid_char(name, isalnum);
640 }
641
642 /*
643 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
644 * If an invalid character is found, a pointer to it is returned.
645 * If everything is fine, NULL is returned.
646 */
invalid_prefix_char(const char * name)647 const char *invalid_prefix_char(const char *name) {
648 return __invalid_char(name, isalnum);
649 }
650
651 /*
652 * converts <str> to a struct sockaddr_storage* provided by the caller. The
653 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
654 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
655 * the function tries to guess the address family from the syntax. If the
656 * family is forced and the format doesn't match, an error is returned. The
657 * string is assumed to contain only an address, no port. The address can be a
658 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
659 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
660 * The return address will only have the address family and the address set,
661 * all other fields remain zero. The string is not supposed to be modified.
662 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
663 * is resolved, otherwise only IP addresses are resolved, and anything else
664 * returns NULL. If the address contains a port, this one is preserved.
665 */
str2ip2(const char * str,struct sockaddr_storage * sa,int resolve)666 struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
667 {
668 struct hostent *he;
669 /* max IPv6 length, including brackets and terminating NULL */
670 char tmpip[48];
671 int port = get_host_port(sa);
672
673 /* check IPv6 with square brackets */
674 if (str[0] == '[') {
675 size_t iplength = strlen(str);
676
677 if (iplength < 4) {
678 /* minimal size is 4 when using brackets "[::]" */
679 goto fail;
680 }
681 else if (iplength >= sizeof(tmpip)) {
682 /* IPv6 literal can not be larger than tmpip */
683 goto fail;
684 }
685 else {
686 if (str[iplength - 1] != ']') {
687 /* if address started with bracket, it should end with bracket */
688 goto fail;
689 }
690 else {
691 memcpy(tmpip, str + 1, iplength - 2);
692 tmpip[iplength - 2] = '\0';
693 str = tmpip;
694 }
695 }
696 }
697
698 /* Any IPv6 address */
699 if (str[0] == ':' && str[1] == ':' && !str[2]) {
700 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
701 sa->ss_family = AF_INET6;
702 else if (sa->ss_family != AF_INET6)
703 goto fail;
704 set_host_port(sa, port);
705 return sa;
706 }
707
708 /* Any address for the family, defaults to IPv4 */
709 if (!str[0] || (str[0] == '*' && !str[1])) {
710 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
711 sa->ss_family = AF_INET;
712 set_host_port(sa, port);
713 return sa;
714 }
715
716 /* check for IPv6 first */
717 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
718 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
719 sa->ss_family = AF_INET6;
720 set_host_port(sa, port);
721 return sa;
722 }
723
724 /* then check for IPv4 */
725 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
726 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
727 sa->ss_family = AF_INET;
728 set_host_port(sa, port);
729 return sa;
730 }
731
732 if (!resolve)
733 return NULL;
734
735 if (!dns_hostname_validation(str, NULL))
736 return NULL;
737
738 #ifdef USE_GETADDRINFO
739 if (global.tune.options & GTUNE_USE_GAI) {
740 struct addrinfo hints, *result;
741 int success = 0;
742
743 memset(&result, 0, sizeof(result));
744 memset(&hints, 0, sizeof(hints));
745 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
746 hints.ai_socktype = SOCK_DGRAM;
747 hints.ai_flags = 0;
748 hints.ai_protocol = 0;
749
750 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
751 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
752 sa->ss_family = result->ai_family;
753 else if (sa->ss_family != result->ai_family) {
754 freeaddrinfo(result);
755 goto fail;
756 }
757
758 switch (result->ai_family) {
759 case AF_INET:
760 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
761 set_host_port(sa, port);
762 success = 1;
763 break;
764 case AF_INET6:
765 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
766 set_host_port(sa, port);
767 success = 1;
768 break;
769 }
770 }
771
772 if (result)
773 freeaddrinfo(result);
774
775 if (success)
776 return sa;
777 }
778 #endif
779 /* try to resolve an IPv4/IPv6 hostname */
780 he = gethostbyname(str);
781 if (he) {
782 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
783 sa->ss_family = he->h_addrtype;
784 else if (sa->ss_family != he->h_addrtype)
785 goto fail;
786
787 switch (sa->ss_family) {
788 case AF_INET:
789 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
790 set_host_port(sa, port);
791 return sa;
792 case AF_INET6:
793 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
794 set_host_port(sa, port);
795 return sa;
796 }
797 }
798
799 /* unsupported address family */
800 fail:
801 return NULL;
802 }
803
804 /*
805 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
806 * range or offset consisting in two integers that the caller will have to
807 * check to find the relevant input format. The following format are supported :
808 *
809 * String format | address | port | low | high
810 * addr | <addr> | 0 | 0 | 0
811 * addr: | <addr> | 0 | 0 | 0
812 * addr:port | <addr> | <port> | <port> | <port>
813 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
814 * addr:+port | <addr> | <port> | 0 | <port>
815 * addr:-port | <addr> |-<port> | <port> | 0
816 *
817 * The detection of a port range or increment by the caller is made by
818 * comparing <low> and <high>. If both are equal, then port 0 means no port
819 * was specified. The caller may pass NULL for <low> and <high> if it is not
820 * interested in retrieving port ranges.
821 *
822 * Note that <addr> above may also be :
823 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
824 * - "*" => family will be AF_INET and address will be INADDR_ANY
825 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
826 * - a host name => family and address will depend on host name resolving.
827 *
828 * A prefix may be passed in before the address above to force the family :
829 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
830 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
831 * - "unix@" => force address to be a path to a UNIX socket even if the
832 * path does not start with a '/'
833 * - 'abns@' -> force address to belong to the abstract namespace (Linux
834 * only). These sockets are just like Unix sockets but without
835 * the need for an underlying file system. The address is a
836 * string. Technically it's like a Unix socket with a zero in
837 * the first byte of the address.
838 * - "fd@" => an integer must follow, and is a file descriptor number.
839 *
840 * IPv6 addresses can be declared with or without square brackets. When using
841 * square brackets for IPv6 addresses, the port separator (colon) is optional.
842 * If not using square brackets, and in order to avoid any ambiguity with
843 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
844 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
845 * are always initialized if non-null, even for non-IP families.
846 *
847 * If <pfx> is non-null, it is used as a string prefix before any path-based
848 * address (typically the path to a unix socket).
849 *
850 * if <fqdn> is non-null, it will be filled with :
851 * - a pointer to the FQDN of the server name to resolve if there's one, and
852 * that the caller will have to free(),
853 * - NULL if there was an explicit address that doesn't require resolution.
854 *
855 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
856 * is null, <fqdn> is still honnored so it is possible for the caller to know
857 * whether a resolution failed by setting <resolve> to null and checking if
858 * <fqdn> was filled, indicating the need for a resolution.
859 *
860 * When a file descriptor is passed, its value is put into the s_addr part of
861 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
862 */
str2sa_range(const char * str,int * port,int * low,int * high,char ** err,const char * pfx,char ** fqdn,int resolve)863 struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
864 {
865 static THREAD_LOCAL struct sockaddr_storage ss;
866 struct sockaddr_storage *ret = NULL;
867 char *back, *str2;
868 char *port1, *port2;
869 int portl, porth, porta;
870 int abstract = 0;
871
872 portl = porth = porta = 0;
873 if (fqdn)
874 *fqdn = NULL;
875
876 str2 = back = env_expand(strdup(str));
877 if (str2 == NULL) {
878 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
879 goto out;
880 }
881
882 if (!*str2) {
883 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
884 goto out;
885 }
886
887 memset(&ss, 0, sizeof(ss));
888
889 if (strncmp(str2, "unix@", 5) == 0) {
890 str2 += 5;
891 abstract = 0;
892 ss.ss_family = AF_UNIX;
893 }
894 else if (strncmp(str2, "abns@", 5) == 0) {
895 str2 += 5;
896 abstract = 1;
897 ss.ss_family = AF_UNIX;
898 }
899 else if (strncmp(str2, "ipv4@", 5) == 0) {
900 str2 += 5;
901 ss.ss_family = AF_INET;
902 }
903 else if (strncmp(str2, "ipv6@", 5) == 0) {
904 str2 += 5;
905 ss.ss_family = AF_INET6;
906 }
907 else if (*str2 == '/') {
908 ss.ss_family = AF_UNIX;
909 }
910 else
911 ss.ss_family = AF_UNSPEC;
912
913 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
914 char *endptr;
915
916 str2 += 9;
917
918 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
919 ((struct sockaddr_in *)&ss)->sin_port = 0;
920
921 if (!*str2 || *endptr) {
922 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
923 goto out;
924 }
925
926 ss.ss_family = AF_CUST_SOCKPAIR;
927
928 }
929 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
930 char *endptr;
931
932 str2 += 3;
933 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
934 ((struct sockaddr_in *)&ss)->sin_port = 0;
935
936 if (!*str2 || *endptr) {
937 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
938 goto out;
939 }
940
941 /* we return AF_UNSPEC if we use a file descriptor number */
942 ss.ss_family = AF_UNSPEC;
943 }
944 else if (ss.ss_family == AF_UNIX) {
945 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
946 int prefix_path_len;
947 int max_path_len;
948 int adr_len;
949
950 /* complete unix socket path name during startup or soft-restart is
951 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
952 */
953 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
954 max_path_len = (sizeof(un->sun_path) - 1) -
955 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
956
957 adr_len = strlen(str2);
958 if (adr_len > max_path_len) {
959 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
960 goto out;
961 }
962
963 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
964 memset(un->sun_path, 0, sizeof(un->sun_path));
965 if (prefix_path_len)
966 memcpy(un->sun_path, pfx, prefix_path_len);
967 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
968 }
969 else { /* IPv4 and IPv6 */
970 char *end = str2 + strlen(str2);
971 char *chr;
972
973 /* search for : or ] whatever comes first */
974 for (chr = end-1; chr > str2; chr--) {
975 if (*chr == ']' || *chr == ':')
976 break;
977 }
978
979 if (*chr == ':') {
980 /* Found a colon before a closing-bracket, must be a port separator.
981 * This guarantee backward compatibility.
982 */
983 *chr++ = '\0';
984 port1 = chr;
985 }
986 else {
987 /* Either no colon and no closing-bracket
988 * or directly ending with a closing-bracket.
989 * However, no port.
990 */
991 port1 = "";
992 }
993
994 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
995 port2 = strchr(port1, '-');
996 if (port2)
997 *port2++ = '\0';
998 else
999 port2 = port1;
1000 portl = atoi(port1);
1001 porth = atoi(port2);
1002 porta = portl;
1003 }
1004 else if (*port1 == '-') { /* negative offset */
1005 portl = atoi(port1 + 1);
1006 porta = -portl;
1007 }
1008 else if (*port1 == '+') { /* positive offset */
1009 porth = atoi(port1 + 1);
1010 porta = porth;
1011 }
1012 else if (*port1) { /* other any unexpected char */
1013 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
1014 goto out;
1015 }
1016
1017 /* first try to parse the IP without resolving. If it fails, it
1018 * tells us we need to keep a copy of the FQDN to resolve later
1019 * and to enable DNS. In this case we can proceed if <fqdn> is
1020 * set or if resolve is set, otherwise it's an error.
1021 */
1022 if (str2ip2(str2, &ss, 0) == NULL) {
1023 if ((!resolve && !fqdn) ||
1024 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1025 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1026 goto out;
1027 }
1028
1029 if (fqdn) {
1030 if (str2 != back)
1031 memmove(back, str2, strlen(str2) + 1);
1032 *fqdn = back;
1033 back = NULL;
1034 }
1035 }
1036 set_host_port(&ss, porta);
1037 }
1038
1039 ret = &ss;
1040 out:
1041 if (port)
1042 *port = porta;
1043 if (low)
1044 *low = portl;
1045 if (high)
1046 *high = porth;
1047 free(back);
1048 return ret;
1049 }
1050
1051 /* converts <str> to a struct in_addr containing a network mask. It can be
1052 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
1053 * if the conversion succeeds otherwise zero.
1054 */
str2mask(const char * str,struct in_addr * mask)1055 int str2mask(const char *str, struct in_addr *mask)
1056 {
1057 if (strchr(str, '.') != NULL) { /* dotted notation */
1058 if (!inet_pton(AF_INET, str, mask))
1059 return 0;
1060 }
1061 else { /* mask length */
1062 char *err;
1063 unsigned long len = strtol(str, &err, 10);
1064
1065 if (!*str || (err && *err) || (unsigned)len > 32)
1066 return 0;
1067
1068 len2mask4(len, mask);
1069 }
1070 return 1;
1071 }
1072
1073 /* converts <str> to a struct in6_addr containing a network mask. It can be
1074 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
1075 * if the conversion succeeds otherwise zero.
1076 */
str2mask6(const char * str,struct in6_addr * mask)1077 int str2mask6(const char *str, struct in6_addr *mask)
1078 {
1079 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1080 if (!inet_pton(AF_INET6, str, mask))
1081 return 0;
1082 }
1083 else { /* mask length */
1084 char *err;
1085 unsigned long len = strtol(str, &err, 10);
1086
1087 if (!*str || (err && *err) || (unsigned)len > 128)
1088 return 0;
1089
1090 len2mask6(len, mask);
1091 }
1092 return 1;
1093 }
1094
1095 /* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1096 * succeeds otherwise zero.
1097 */
cidr2dotted(int cidr,struct in_addr * mask)1098 int cidr2dotted(int cidr, struct in_addr *mask) {
1099
1100 if (cidr < 0 || cidr > 32)
1101 return 0;
1102
1103 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1104 return 1;
1105 }
1106
1107 /* Convert mask from bit length form to in_addr form.
1108 * This function never fails.
1109 */
len2mask4(int len,struct in_addr * addr)1110 void len2mask4(int len, struct in_addr *addr)
1111 {
1112 if (len >= 32) {
1113 addr->s_addr = 0xffffffff;
1114 return;
1115 }
1116 if (len <= 0) {
1117 addr->s_addr = 0x00000000;
1118 return;
1119 }
1120 addr->s_addr = 0xffffffff << (32 - len);
1121 addr->s_addr = htonl(addr->s_addr);
1122 }
1123
1124 /* Convert mask from bit length form to in6_addr form.
1125 * This function never fails.
1126 */
len2mask6(int len,struct in6_addr * addr)1127 void len2mask6(int len, struct in6_addr *addr)
1128 {
1129 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1130 len -= 32;
1131 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1132 len -= 32;
1133 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1134 len -= 32;
1135 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1136 }
1137
1138 /*
1139 * converts <str> to two struct in_addr* which must be pre-allocated.
1140 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1141 * is optionnal and either in the dotted or CIDR notation.
1142 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1143 */
str2net(const char * str,int resolve,struct in_addr * addr,struct in_addr * mask)1144 int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
1145 {
1146 __label__ out_free, out_err;
1147 char *c, *s;
1148 int ret_val;
1149
1150 s = strdup(str);
1151 if (!s)
1152 return 0;
1153
1154 memset(mask, 0, sizeof(*mask));
1155 memset(addr, 0, sizeof(*addr));
1156
1157 if ((c = strrchr(s, '/')) != NULL) {
1158 *c++ = '\0';
1159 /* c points to the mask */
1160 if (!str2mask(c, mask))
1161 goto out_err;
1162 }
1163 else {
1164 mask->s_addr = ~0U;
1165 }
1166 if (!inet_pton(AF_INET, s, addr)) {
1167 struct hostent *he;
1168
1169 if (!resolve)
1170 goto out_err;
1171
1172 if ((he = gethostbyname(s)) == NULL) {
1173 goto out_err;
1174 }
1175 else
1176 *addr = *(struct in_addr *) *(he->h_addr_list);
1177 }
1178
1179 ret_val = 1;
1180 out_free:
1181 free(s);
1182 return ret_val;
1183 out_err:
1184 ret_val = 0;
1185 goto out_free;
1186 }
1187
1188
1189 /*
1190 * converts <str> to two struct in6_addr* which must be pre-allocated.
1191 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1192 * is an optionnal number of bits (128 being the default).
1193 * Returns 1 if OK, 0 if error.
1194 */
str62net(const char * str,struct in6_addr * addr,unsigned char * mask)1195 int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1196 {
1197 char *c, *s;
1198 int ret_val = 0;
1199 char *err;
1200 unsigned long len = 128;
1201
1202 s = strdup(str);
1203 if (!s)
1204 return 0;
1205
1206 memset(mask, 0, sizeof(*mask));
1207 memset(addr, 0, sizeof(*addr));
1208
1209 if ((c = strrchr(s, '/')) != NULL) {
1210 *c++ = '\0'; /* c points to the mask */
1211 if (!*c)
1212 goto out_free;
1213
1214 len = strtoul(c, &err, 10);
1215 if ((err && *err) || (unsigned)len > 128)
1216 goto out_free;
1217 }
1218 *mask = len; /* OK we have a valid mask in <len> */
1219
1220 if (!inet_pton(AF_INET6, s, addr))
1221 goto out_free;
1222
1223 ret_val = 1;
1224 out_free:
1225 free(s);
1226 return ret_val;
1227 }
1228
1229
1230 /*
1231 * Parse IPv4 address found in url.
1232 */
url2ipv4(const char * addr,struct in_addr * dst)1233 int url2ipv4(const char *addr, struct in_addr *dst)
1234 {
1235 int saw_digit, octets, ch;
1236 u_char tmp[4], *tp;
1237 const char *cp = addr;
1238
1239 saw_digit = 0;
1240 octets = 0;
1241 *(tp = tmp) = 0;
1242
1243 while (*addr) {
1244 unsigned char digit = (ch = *addr++) - '0';
1245 if (digit > 9 && ch != '.')
1246 break;
1247 if (digit <= 9) {
1248 u_int new = *tp * 10 + digit;
1249 if (new > 255)
1250 return 0;
1251 *tp = new;
1252 if (!saw_digit) {
1253 if (++octets > 4)
1254 return 0;
1255 saw_digit = 1;
1256 }
1257 } else if (ch == '.' && saw_digit) {
1258 if (octets == 4)
1259 return 0;
1260 *++tp = 0;
1261 saw_digit = 0;
1262 } else
1263 return 0;
1264 }
1265
1266 if (octets < 4)
1267 return 0;
1268
1269 memcpy(&dst->s_addr, tmp, 4);
1270 return addr-cp-1;
1271 }
1272
1273 /*
1274 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1275 * <out> contain the code of the dectected scheme, the start and length of
1276 * the hostname. Actually only http and https are supported. <out> can be NULL.
1277 * This function returns the consumed length. It is useful if you parse complete
1278 * url like http://host:port/path, because the consumed length corresponds to
1279 * the first character of the path. If the conversion fails, it returns -1.
1280 *
1281 * This function tries to resolve the DNS name if haproxy is in starting mode.
1282 * So, this function may be used during the configuration parsing.
1283 */
url2sa(const char * url,int ulen,struct sockaddr_storage * addr,struct split_url * out)1284 int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
1285 {
1286 const char *curr = url, *cp = url;
1287 const char *end;
1288 int ret, url_code = 0;
1289 unsigned long long int http_code = 0;
1290 int default_port;
1291 struct hostent *he;
1292 char *p;
1293
1294 /* Firstly, try to find :// pattern */
1295 while (curr < url+ulen && url_code != 0x3a2f2f) {
1296 url_code = ((url_code & 0xffff) << 8);
1297 url_code += (unsigned char)*curr++;
1298 }
1299
1300 /* Secondly, if :// pattern is found, verify parsed stuff
1301 * before pattern is matching our http pattern.
1302 * If so parse ip address and port in uri.
1303 *
1304 * WARNING: Current code doesn't support dynamic async dns resolver.
1305 */
1306 if (url_code != 0x3a2f2f)
1307 return -1;
1308
1309 /* Copy scheme, and utrn to lower case. */
1310 while (cp < curr - 3)
1311 http_code = (http_code << 8) + *cp++;
1312 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
1313
1314 /* HTTP or HTTPS url matching */
1315 if (http_code == 0x2020202068747470ULL) {
1316 default_port = 80;
1317 if (out)
1318 out->scheme = SCH_HTTP;
1319 }
1320 else if (http_code == 0x2020206874747073ULL) {
1321 default_port = 443;
1322 if (out)
1323 out->scheme = SCH_HTTPS;
1324 }
1325 else
1326 return -1;
1327
1328 /* If the next char is '[', the host address is IPv6. */
1329 if (*curr == '[') {
1330 curr++;
1331
1332 /* Check trash size */
1333 if (trash.size < ulen)
1334 return -1;
1335
1336 /* Look for ']' and copy the address in a trash buffer. */
1337 p = trash.area;
1338 for (end = curr;
1339 end < url + ulen && *end != ']';
1340 end++, p++)
1341 *p = *end;
1342 if (*end != ']')
1343 return -1;
1344 *p = '\0';
1345
1346 /* Update out. */
1347 if (out) {
1348 out->host = curr;
1349 out->host_len = end - curr;
1350 }
1351
1352 /* Try IPv6 decoding. */
1353 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
1354 return -1;
1355 end++;
1356
1357 /* Decode port. */
1358 if (*end == ':') {
1359 end++;
1360 default_port = read_uint(&end, url + ulen);
1361 }
1362 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1363 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1364 return end - url;
1365 }
1366 else {
1367 /* We are looking for IP address. If you want to parse and
1368 * resolve hostname found in url, you can use str2sa_range(), but
1369 * be warned this can slow down global daemon performances
1370 * while handling lagging dns responses.
1371 */
1372 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1373 if (ret) {
1374 /* Update out. */
1375 if (out) {
1376 out->host = curr;
1377 out->host_len = ret;
1378 }
1379
1380 curr += ret;
1381
1382 /* Decode port. */
1383 if (*curr == ':') {
1384 curr++;
1385 default_port = read_uint(&curr, url + ulen);
1386 }
1387 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1388
1389 /* Set family. */
1390 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1391 return curr - url;
1392 }
1393 else if (global.mode & MODE_STARTING) {
1394 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1395 * synchronous DNS request only if HAProxy is in the start state.
1396 */
1397
1398 /* look for : or / or end */
1399 for (end = curr;
1400 end < url + ulen && *end != '/' && *end != ':';
1401 end++);
1402 memcpy(trash.area, curr, end - curr);
1403 trash.area[end - curr] = '\0';
1404
1405 /* try to resolve an IPv4/IPv6 hostname */
1406 he = gethostbyname(trash.area);
1407 if (!he)
1408 return -1;
1409
1410 /* Update out. */
1411 if (out) {
1412 out->host = curr;
1413 out->host_len = end - curr;
1414 }
1415
1416 /* Decode port. */
1417 if (*end == ':') {
1418 end++;
1419 default_port = read_uint(&end, url + ulen);
1420 }
1421
1422 /* Copy IP address, set port and family. */
1423 switch (he->h_addrtype) {
1424 case AF_INET:
1425 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1426 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1427 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1428 return end - url;
1429
1430 case AF_INET6:
1431 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1432 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1433 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1434 return end - url;
1435 }
1436 }
1437 }
1438 return -1;
1439 }
1440
1441 /* Tries to convert a sockaddr_storage address to text form. Upon success, the
1442 * address family is returned so that it's easy for the caller to adapt to the
1443 * output format. Zero is returned if the address family is not supported. -1
1444 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1445 * supported.
1446 */
addr_to_str(const struct sockaddr_storage * addr,char * str,int size)1447 int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
1448 {
1449
1450 const void *ptr;
1451
1452 if (size < 5)
1453 return 0;
1454 *str = '\0';
1455
1456 switch (addr->ss_family) {
1457 case AF_INET:
1458 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1459 break;
1460 case AF_INET6:
1461 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1462 break;
1463 case AF_UNIX:
1464 memcpy(str, "unix", 5);
1465 return addr->ss_family;
1466 default:
1467 return 0;
1468 }
1469
1470 if (inet_ntop(addr->ss_family, ptr, str, size))
1471 return addr->ss_family;
1472
1473 /* failed */
1474 return -1;
1475 }
1476
1477 /* Tries to convert a sockaddr_storage port to text form. Upon success, the
1478 * address family is returned so that it's easy for the caller to adapt to the
1479 * output format. Zero is returned if the address family is not supported. -1
1480 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1481 * supported.
1482 */
port_to_str(const struct sockaddr_storage * addr,char * str,int size)1483 int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
1484 {
1485
1486 uint16_t port;
1487
1488
1489 if (size < 6)
1490 return 0;
1491 *str = '\0';
1492
1493 switch (addr->ss_family) {
1494 case AF_INET:
1495 port = ((struct sockaddr_in *)addr)->sin_port;
1496 break;
1497 case AF_INET6:
1498 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1499 break;
1500 case AF_UNIX:
1501 memcpy(str, "unix", 5);
1502 return addr->ss_family;
1503 default:
1504 return 0;
1505 }
1506
1507 snprintf(str, size, "%u", ntohs(port));
1508 return addr->ss_family;
1509 }
1510
1511 /* check if the given address is local to the system or not. It will return
1512 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1513 * it is. We don't want to iterate over all interfaces for this (and it is not
1514 * portable). So instead we try to bind in UDP to this address on a free non
1515 * privileged port and to connect to the same address, port 0 (connect doesn't
1516 * care). If it succeeds, we own the address. Note that non-inet addresses are
1517 * considered local since they're most likely AF_UNIX.
1518 */
addr_is_local(const struct netns_entry * ns,const struct sockaddr_storage * orig)1519 int addr_is_local(const struct netns_entry *ns,
1520 const struct sockaddr_storage *orig)
1521 {
1522 struct sockaddr_storage addr;
1523 int result;
1524 int fd;
1525
1526 if (!is_inet_addr(orig))
1527 return 1;
1528
1529 memcpy(&addr, orig, sizeof(addr));
1530 set_host_port(&addr, 0);
1531
1532 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1533 if (fd < 0)
1534 return -1;
1535
1536 result = -1;
1537 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1538 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1539 result = 0; // fail, non-local address
1540 else
1541 result = 1; // success, local address
1542 }
1543 else {
1544 if (errno == EADDRNOTAVAIL)
1545 result = 0; // definitely not local :-)
1546 }
1547 close(fd);
1548
1549 return result;
1550 }
1551
1552 /* will try to encode the string <string> replacing all characters tagged in
1553 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1554 * prefixed by <escape>, and will store the result between <start> (included)
1555 * and <stop> (excluded), and will always terminate the string with a '\0'
1556 * before <stop>. The position of the '\0' is returned if the conversion
1557 * completes. If bytes are missing between <start> and <stop>, then the
1558 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1559 * cannot even be stored so we return <start> without writing the 0.
1560 * The input string must also be zero-terminated.
1561 */
1562 const char hextab[16] = "0123456789ABCDEF";
encode_string(char * start,char * stop,const char escape,const long * map,const char * string)1563 char *encode_string(char *start, char *stop,
1564 const char escape, const long *map,
1565 const char *string)
1566 {
1567 if (start < stop) {
1568 stop--; /* reserve one byte for the final '\0' */
1569 while (start < stop && *string != '\0') {
1570 if (!ha_bit_test((unsigned char)(*string), map))
1571 *start++ = *string;
1572 else {
1573 if (start + 3 >= stop)
1574 break;
1575 *start++ = escape;
1576 *start++ = hextab[(*string >> 4) & 15];
1577 *start++ = hextab[*string & 15];
1578 }
1579 string++;
1580 }
1581 *start = '\0';
1582 }
1583 return start;
1584 }
1585
1586 /*
1587 * Same behavior as encode_string() above, except that it encodes chunk
1588 * <chunk> instead of a string.
1589 */
encode_chunk(char * start,char * stop,const char escape,const long * map,const struct buffer * chunk)1590 char *encode_chunk(char *start, char *stop,
1591 const char escape, const long *map,
1592 const struct buffer *chunk)
1593 {
1594 char *str = chunk->area;
1595 char *end = chunk->area + chunk->data;
1596
1597 if (start < stop) {
1598 stop--; /* reserve one byte for the final '\0' */
1599 while (start < stop && str < end) {
1600 if (!ha_bit_test((unsigned char)(*str), map))
1601 *start++ = *str;
1602 else {
1603 if (start + 3 >= stop)
1604 break;
1605 *start++ = escape;
1606 *start++ = hextab[(*str >> 4) & 15];
1607 *start++ = hextab[*str & 15];
1608 }
1609 str++;
1610 }
1611 *start = '\0';
1612 }
1613 return start;
1614 }
1615
1616 /*
1617 * Tries to prefix characters tagged in the <map> with the <escape>
1618 * character. The input <string> must be zero-terminated. The result will
1619 * be stored between <start> (included) and <stop> (excluded). This
1620 * function will always try to terminate the resulting string with a '\0'
1621 * before <stop>, and will return its position if the conversion
1622 * completes.
1623 */
escape_string(char * start,char * stop,const char escape,const long * map,const char * string)1624 char *escape_string(char *start, char *stop,
1625 const char escape, const long *map,
1626 const char *string)
1627 {
1628 if (start < stop) {
1629 stop--; /* reserve one byte for the final '\0' */
1630 while (start < stop && *string != '\0') {
1631 if (!ha_bit_test((unsigned char)(*string), map))
1632 *start++ = *string;
1633 else {
1634 if (start + 2 >= stop)
1635 break;
1636 *start++ = escape;
1637 *start++ = *string;
1638 }
1639 string++;
1640 }
1641 *start = '\0';
1642 }
1643 return start;
1644 }
1645
1646 /*
1647 * Tries to prefix characters tagged in the <map> with the <escape>
1648 * character. <chunk> contains the input to be escaped. The result will be
1649 * stored between <start> (included) and <stop> (excluded). The function
1650 * will always try to terminate the resulting string with a '\0' before
1651 * <stop>, and will return its position if the conversion completes.
1652 */
escape_chunk(char * start,char * stop,const char escape,const long * map,const struct buffer * chunk)1653 char *escape_chunk(char *start, char *stop,
1654 const char escape, const long *map,
1655 const struct buffer *chunk)
1656 {
1657 char *str = chunk->area;
1658 char *end = chunk->area + chunk->data;
1659
1660 if (start < stop) {
1661 stop--; /* reserve one byte for the final '\0' */
1662 while (start < stop && str < end) {
1663 if (!ha_bit_test((unsigned char)(*str), map))
1664 *start++ = *str;
1665 else {
1666 if (start + 2 >= stop)
1667 break;
1668 *start++ = escape;
1669 *start++ = *str;
1670 }
1671 str++;
1672 }
1673 *start = '\0';
1674 }
1675 return start;
1676 }
1677
1678 /* Check a string for using it in a CSV output format. If the string contains
1679 * one of the following four char <">, <,>, CR or LF, the string is
1680 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1681 * <str> is the input string to be escaped. The function assumes that
1682 * the input string is null-terminated.
1683 *
1684 * If <quote> is 0, the result is returned escaped but without double quote.
1685 * It is useful if the escaped string is used between double quotes in the
1686 * format.
1687 *
1688 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
1689 *
1690 * If <quote> is 1, the converter puts the quotes only if any reserved character
1691 * is present. If <quote> is 2, the converter always puts the quotes.
1692 *
1693 * <output> is a struct buffer used for storing the output string.
1694 *
1695 * The function returns the converted string on its output. If an error
1696 * occurs, the function returns an empty string. This type of output is useful
1697 * for using the function directly as printf() argument.
1698 *
1699 * If the output buffer is too short to contain the input string, the result
1700 * is truncated.
1701 *
1702 * This function appends the encoding to the existing output chunk, and it
1703 * guarantees that it starts immediately at the first available character of
1704 * the chunk. Please use csv_enc() instead if you want to replace the output
1705 * chunk.
1706 */
csv_enc_append(const char * str,int quote,struct buffer * output)1707 const char *csv_enc_append(const char *str, int quote, struct buffer *output)
1708 {
1709 char *end = output->area + output->size;
1710 char *out = output->area + output->data;
1711 char *ptr = out;
1712
1713 if (quote == 1) {
1714 /* automatic quoting: first verify if we'll have to quote the string */
1715 if (!strpbrk(str, "\n\r,\""))
1716 quote = 0;
1717 }
1718
1719 if (quote)
1720 *ptr++ = '"';
1721
1722 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1723 *ptr = *str;
1724 if (*str == '"') {
1725 ptr++;
1726 if (ptr >= end - 2) {
1727 ptr--;
1728 break;
1729 }
1730 *ptr = '"';
1731 }
1732 ptr++;
1733 str++;
1734 }
1735
1736 if (quote)
1737 *ptr++ = '"';
1738
1739 *ptr = '\0';
1740 output->data = ptr - output->area;
1741 return out;
1742 }
1743
1744 /* Decode an URL-encoded string in-place. The resulting string might
1745 * be shorter. If some forbidden characters are found, the conversion is
1746 * aborted, the string is truncated before the issue and a negative value is
1747 * returned, otherwise the operation returns the length of the decoded string.
1748 * If the 'in_form' argument is non-nul the string is assumed to be part of
1749 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1750 * turned to a space. If it's zero, this will only be done after a question
1751 * mark ('?').
1752 */
url_decode(char * string,int in_form)1753 int url_decode(char *string, int in_form)
1754 {
1755 char *in, *out;
1756 int ret = -1;
1757
1758 in = string;
1759 out = string;
1760 while (*in) {
1761 switch (*in) {
1762 case '+' :
1763 *out++ = in_form ? ' ' : *in;
1764 break;
1765 case '%' :
1766 if (!ishex(in[1]) || !ishex(in[2]))
1767 goto end;
1768 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1769 in += 2;
1770 break;
1771 case '?':
1772 in_form = 1;
1773 /* fall through */
1774 default:
1775 *out++ = *in;
1776 break;
1777 }
1778 in++;
1779 }
1780 ret = out - string; /* success */
1781 end:
1782 *out = 0;
1783 return ret;
1784 }
1785
str2ui(const char * s)1786 unsigned int str2ui(const char *s)
1787 {
1788 return __str2ui(s);
1789 }
1790
str2uic(const char * s)1791 unsigned int str2uic(const char *s)
1792 {
1793 return __str2uic(s);
1794 }
1795
strl2ui(const char * s,int len)1796 unsigned int strl2ui(const char *s, int len)
1797 {
1798 return __strl2ui(s, len);
1799 }
1800
strl2uic(const char * s,int len)1801 unsigned int strl2uic(const char *s, int len)
1802 {
1803 return __strl2uic(s, len);
1804 }
1805
read_uint(const char ** s,const char * end)1806 unsigned int read_uint(const char **s, const char *end)
1807 {
1808 return __read_uint(s, end);
1809 }
1810
1811 /* This function reads an unsigned integer from the string pointed to by <s> and
1812 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1813 * function automatically stops at <end>. If the number overflows, the 2^64-1
1814 * value is returned.
1815 */
read_uint64(const char ** s,const char * end)1816 unsigned long long int read_uint64(const char **s, const char *end)
1817 {
1818 const char *ptr = *s;
1819 unsigned long long int i = 0, tmp;
1820 unsigned int j;
1821
1822 while (ptr < end) {
1823
1824 /* read next char */
1825 j = *ptr - '0';
1826 if (j > 9)
1827 goto read_uint64_end;
1828
1829 /* add char to the number and check overflow. */
1830 tmp = i * 10;
1831 if (tmp / 10 != i) {
1832 i = ULLONG_MAX;
1833 goto read_uint64_eat;
1834 }
1835 if (ULLONG_MAX - tmp < j) {
1836 i = ULLONG_MAX;
1837 goto read_uint64_eat;
1838 }
1839 i = tmp + j;
1840 ptr++;
1841 }
1842 read_uint64_eat:
1843 /* eat each numeric char */
1844 while (ptr < end) {
1845 if ((unsigned int)(*ptr - '0') > 9)
1846 break;
1847 ptr++;
1848 }
1849 read_uint64_end:
1850 *s = ptr;
1851 return i;
1852 }
1853
1854 /* This function reads an integer from the string pointed to by <s> and returns
1855 * it. The <s> pointer is adjusted to point to the first unread char. The function
1856 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1857 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1858 * returned.
1859 */
read_int64(const char ** s,const char * end)1860 long long int read_int64(const char **s, const char *end)
1861 {
1862 unsigned long long int i = 0;
1863 int neg = 0;
1864
1865 /* Look for minus char. */
1866 if (**s == '-') {
1867 neg = 1;
1868 (*s)++;
1869 }
1870 else if (**s == '+')
1871 (*s)++;
1872
1873 /* convert as positive number. */
1874 i = read_uint64(s, end);
1875
1876 if (neg) {
1877 if (i > 0x8000000000000000ULL)
1878 return LLONG_MIN;
1879 return -i;
1880 }
1881 if (i > 0x7fffffffffffffffULL)
1882 return LLONG_MAX;
1883 return i;
1884 }
1885
1886 /* This one is 7 times faster than strtol() on athlon with checks.
1887 * It returns the value of the number composed of all valid digits read,
1888 * and can process negative numbers too.
1889 */
strl2ic(const char * s,int len)1890 int strl2ic(const char *s, int len)
1891 {
1892 int i = 0;
1893 int j, k;
1894
1895 if (len > 0) {
1896 if (*s != '-') {
1897 /* positive number */
1898 while (len-- > 0) {
1899 j = (*s++) - '0';
1900 k = i * 10;
1901 if (j > 9)
1902 break;
1903 i = k + j;
1904 }
1905 } else {
1906 /* negative number */
1907 s++;
1908 while (--len > 0) {
1909 j = (*s++) - '0';
1910 k = i * 10;
1911 if (j > 9)
1912 break;
1913 i = k - j;
1914 }
1915 }
1916 }
1917 return i;
1918 }
1919
1920
1921 /* This function reads exactly <len> chars from <s> and converts them to a
1922 * signed integer which it stores into <ret>. It accurately detects any error
1923 * (truncated string, invalid chars, overflows). It is meant to be used in
1924 * applications designed for hostile environments. It returns zero when the
1925 * number has successfully been converted, non-zero otherwise. When an error
1926 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1927 * faster than strtol().
1928 */
strl2irc(const char * s,int len,int * ret)1929 int strl2irc(const char *s, int len, int *ret)
1930 {
1931 int i = 0;
1932 int j;
1933
1934 if (!len)
1935 return 1;
1936
1937 if (*s != '-') {
1938 /* positive number */
1939 while (len-- > 0) {
1940 j = (*s++) - '0';
1941 if (j > 9) return 1; /* invalid char */
1942 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1943 i = i * 10;
1944 if (i + j < i) return 1; /* check for addition overflow */
1945 i = i + j;
1946 }
1947 } else {
1948 /* negative number */
1949 s++;
1950 while (--len > 0) {
1951 j = (*s++) - '0';
1952 if (j > 9) return 1; /* invalid char */
1953 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1954 i = i * 10;
1955 if (i - j > i) return 1; /* check for subtract overflow */
1956 i = i - j;
1957 }
1958 }
1959 *ret = i;
1960 return 0;
1961 }
1962
1963
1964 /* This function reads exactly <len> chars from <s> and converts them to a
1965 * signed integer which it stores into <ret>. It accurately detects any error
1966 * (truncated string, invalid chars, overflows). It is meant to be used in
1967 * applications designed for hostile environments. It returns zero when the
1968 * number has successfully been converted, non-zero otherwise. When an error
1969 * is returned, the <ret> value is left untouched. It is about 3 times slower
1970 * than str2irc().
1971 */
1972
strl2llrc(const char * s,int len,long long * ret)1973 int strl2llrc(const char *s, int len, long long *ret)
1974 {
1975 long long i = 0;
1976 int j;
1977
1978 if (!len)
1979 return 1;
1980
1981 if (*s != '-') {
1982 /* positive number */
1983 while (len-- > 0) {
1984 j = (*s++) - '0';
1985 if (j > 9) return 1; /* invalid char */
1986 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1987 i = i * 10LL;
1988 if (i + j < i) return 1; /* check for addition overflow */
1989 i = i + j;
1990 }
1991 } else {
1992 /* negative number */
1993 s++;
1994 while (--len > 0) {
1995 j = (*s++) - '0';
1996 if (j > 9) return 1; /* invalid char */
1997 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1998 i = i * 10LL;
1999 if (i - j > i) return 1; /* check for subtract overflow */
2000 i = i - j;
2001 }
2002 }
2003 *ret = i;
2004 return 0;
2005 }
2006
2007 /* This function is used with pat_parse_dotted_ver(). It converts a string
2008 * composed by two number separated by a dot. Each part must contain in 16 bits
2009 * because internally they will be represented as a 32-bit quantity stored in
2010 * a 64-bit integer. It returns zero when the number has successfully been
2011 * converted, non-zero otherwise. When an error is returned, the <ret> value
2012 * is left untouched.
2013 *
2014 * "1.3" -> 0x0000000000010003
2015 * "65535.65535" -> 0x00000000ffffffff
2016 */
strl2llrc_dotted(const char * text,int len,long long * ret)2017 int strl2llrc_dotted(const char *text, int len, long long *ret)
2018 {
2019 const char *end = &text[len];
2020 const char *p;
2021 long long major, minor;
2022
2023 /* Look for dot. */
2024 for (p = text; p < end; p++)
2025 if (*p == '.')
2026 break;
2027
2028 /* Convert major. */
2029 if (strl2llrc(text, p - text, &major) != 0)
2030 return 1;
2031
2032 /* Check major. */
2033 if (major >= 65536)
2034 return 1;
2035
2036 /* Convert minor. */
2037 minor = 0;
2038 if (p < end)
2039 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2040 return 1;
2041
2042 /* Check minor. */
2043 if (minor >= 65536)
2044 return 1;
2045
2046 /* Compose value. */
2047 *ret = (major << 16) | (minor & 0xffff);
2048 return 0;
2049 }
2050
2051 /* This function parses a time value optionally followed by a unit suffix among
2052 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2053 * expected by the caller. The computation does its best to avoid overflows.
2054 * The value is returned in <ret> if everything is fine, and a NULL is returned
2055 * by the function. In case of error, a pointer to the error is returned and
2056 * <ret> is left untouched. Values are automatically rounded up when needed.
2057 * Values resulting in values larger than or equal to 2^31 after conversion are
2058 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2059 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
2060 */
parse_time_err(const char * text,unsigned * ret,unsigned unit_flags)2061 const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2062 {
2063 unsigned long long imult, idiv;
2064 unsigned long long omult, odiv;
2065 unsigned long long value, result;
2066 const char *str = text;
2067
2068 if (!isdigit((unsigned char)*text))
2069 return text;
2070
2071 omult = odiv = 1;
2072
2073 switch (unit_flags & TIME_UNIT_MASK) {
2074 case TIME_UNIT_US: omult = 1000000; break;
2075 case TIME_UNIT_MS: omult = 1000; break;
2076 case TIME_UNIT_S: break;
2077 case TIME_UNIT_MIN: odiv = 60; break;
2078 case TIME_UNIT_HOUR: odiv = 3600; break;
2079 case TIME_UNIT_DAY: odiv = 86400; break;
2080 default: break;
2081 }
2082
2083 value = 0;
2084
2085 while (1) {
2086 unsigned int j;
2087
2088 j = *text - '0';
2089 if (j > 9)
2090 break;
2091 text++;
2092 value *= 10;
2093 value += j;
2094 }
2095
2096 imult = idiv = 1;
2097 switch (*text) {
2098 case '\0': /* no unit = default unit */
2099 imult = omult = idiv = odiv = 1;
2100 goto end;
2101 case 's': /* second = unscaled unit */
2102 break;
2103 case 'u': /* microsecond : "us" */
2104 if (text[1] == 's') {
2105 idiv = 1000000;
2106 text++;
2107 }
2108 return text;
2109 case 'm': /* millisecond : "ms" or minute: "m" */
2110 if (text[1] == 's') {
2111 idiv = 1000;
2112 text++;
2113 } else
2114 imult = 60;
2115 break;
2116 case 'h': /* hour : "h" */
2117 imult = 3600;
2118 break;
2119 case 'd': /* day : "d" */
2120 imult = 86400;
2121 break;
2122 default:
2123 return text;
2124 break;
2125 }
2126 if (*(++text) != '\0') {
2127 ha_warning("unexpected character '%c' after the timer value '%s', only "
2128 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2129 " This will be reported as an error in next versions.\n", *text, str);
2130 }
2131
2132 end:
2133 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2134 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2135 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2136 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2137
2138 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2139 if (result >= 0x80000000)
2140 return PARSE_TIME_OVER;
2141 if (!result && value)
2142 return PARSE_TIME_UNDER;
2143 *ret = result;
2144 return NULL;
2145 }
2146
2147 /* this function converts the string starting at <text> to an unsigned int
2148 * stored in <ret>. If an error is detected, the pointer to the unexpected
2149 * character is returned. If the conversion is successful, NULL is returned.
2150 */
parse_size_err(const char * text,unsigned * ret)2151 const char *parse_size_err(const char *text, unsigned *ret) {
2152 unsigned value = 0;
2153
2154 if (!isdigit((unsigned char)*text))
2155 return text;
2156
2157 while (1) {
2158 unsigned int j;
2159
2160 j = *text - '0';
2161 if (j > 9)
2162 break;
2163 if (value > ~0U / 10)
2164 return text;
2165 value *= 10;
2166 if (value > (value + j))
2167 return text;
2168 value += j;
2169 text++;
2170 }
2171
2172 switch (*text) {
2173 case '\0':
2174 break;
2175 case 'K':
2176 case 'k':
2177 if (value > ~0U >> 10)
2178 return text;
2179 value = value << 10;
2180 break;
2181 case 'M':
2182 case 'm':
2183 if (value > ~0U >> 20)
2184 return text;
2185 value = value << 20;
2186 break;
2187 case 'G':
2188 case 'g':
2189 if (value > ~0U >> 30)
2190 return text;
2191 value = value << 30;
2192 break;
2193 default:
2194 return text;
2195 }
2196
2197 if (*text != '\0' && *++text != '\0')
2198 return text;
2199
2200 *ret = value;
2201 return NULL;
2202 }
2203
2204 /*
2205 * Parse binary string written in hexadecimal (source) and store the decoded
2206 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2207 * binstr is allocated by the function. In case of error, returns 0 with an
2208 * error message in err. In succes case, it returns the consumed length.
2209 */
parse_binary(const char * source,char ** binstr,int * binstrlen,char ** err)2210 int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2211 {
2212 int len;
2213 const char *p = source;
2214 int i,j;
2215 int alloc;
2216
2217 len = strlen(source);
2218 if (len % 2) {
2219 memprintf(err, "an even number of hex digit is expected");
2220 return 0;
2221 }
2222
2223 len = len >> 1;
2224
2225 if (!*binstr) {
2226 *binstr = calloc(len, sizeof(char));
2227 if (!*binstr) {
2228 memprintf(err, "out of memory while loading string pattern");
2229 return 0;
2230 }
2231 alloc = 1;
2232 }
2233 else {
2234 if (*binstrlen < len) {
2235 memprintf(err, "no space available in the buffer. expect %d, provides %d",
2236 len, *binstrlen);
2237 return 0;
2238 }
2239 alloc = 0;
2240 }
2241 *binstrlen = len;
2242
2243 i = j = 0;
2244 while (j < len) {
2245 if (!ishex(p[i++]))
2246 goto bad_input;
2247 if (!ishex(p[i++]))
2248 goto bad_input;
2249 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2250 }
2251 return len << 1;
2252
2253 bad_input:
2254 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
2255 if (alloc) {
2256 free(*binstr);
2257 *binstr = NULL;
2258 }
2259 return 0;
2260 }
2261
2262 /* copies at most <n> characters from <src> and always terminates with '\0' */
my_strndup(const char * src,int n)2263 char *my_strndup(const char *src, int n)
2264 {
2265 int len = 0;
2266 char *ret;
2267
2268 while (len < n && src[len])
2269 len++;
2270
2271 ret = malloc(len + 1);
2272 if (!ret)
2273 return ret;
2274 memcpy(ret, src, len);
2275 ret[len] = '\0';
2276 return ret;
2277 }
2278
2279 /*
2280 * search needle in haystack
2281 * returns the pointer if found, returns NULL otherwise
2282 */
my_memmem(const void * haystack,size_t haystacklen,const void * needle,size_t needlelen)2283 const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2284 {
2285 const void *c = NULL;
2286 unsigned char f;
2287
2288 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2289 return NULL;
2290
2291 f = *(char *)needle;
2292 c = haystack;
2293 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2294 if ((haystacklen - (c - haystack)) < needlelen)
2295 return NULL;
2296
2297 if (memcmp(c, needle, needlelen) == 0)
2298 return c;
2299 ++c;
2300 }
2301 return NULL;
2302 }
2303
2304 /* This function returns the first unused key greater than or equal to <key> in
2305 * ID tree <root>. Zero is returned if no place is found.
2306 */
get_next_id(struct eb_root * root,unsigned int key)2307 unsigned int get_next_id(struct eb_root *root, unsigned int key)
2308 {
2309 struct eb32_node *used;
2310
2311 do {
2312 used = eb32_lookup_ge(root, key);
2313 if (!used || used->key > key)
2314 return key; /* key is available */
2315 key++;
2316 } while (key);
2317 return key;
2318 }
2319
2320 /* dump the full tree to <file> in DOT format for debugging purposes. Will
2321 * optionally highlight node <subj> if found, depending on operation <op> :
2322 * 0 : nothing
2323 * >0 : insertion, node/leaf are surrounded in red
2324 * <0 : removal, node/leaf are dashed with no background
2325 * Will optionally add "desc" as a label on the graph if set and non-null.
2326 */
eb32sc_to_file(FILE * file,struct eb_root * root,const struct eb32sc_node * subj,int op,const char * desc)2327 void eb32sc_to_file(FILE *file, struct eb_root *root, const struct eb32sc_node *subj, int op, const char *desc)
2328 {
2329 struct eb32sc_node *node;
2330 unsigned long scope = -1;
2331
2332 fprintf(file, "digraph ebtree {\n");
2333
2334 if (desc && *desc) {
2335 fprintf(file,
2336 " fontname=\"fixed\";\n"
2337 " fontsize=8;\n"
2338 " label=\"%s\";\n", desc);
2339 }
2340
2341 fprintf(file,
2342 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2343 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
2344 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2345 );
2346
2347 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2348 (long)eb_root_to_node(root),
2349 (long)eb_root_to_node(eb_clrtag(root->b[0])),
2350 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2351
2352 node = eb32sc_first(root, scope);
2353 while (node) {
2354 if (node->node.node_p) {
2355 /* node part is used */
2356 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2357 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2358 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2359
2360 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2361 (long)node,
2362 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
2363 eb_gettag(node->node.node_p) ? 'R' : 'L');
2364
2365 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2366 (long)node,
2367 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
2368 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2369
2370 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
2371 (long)node,
2372 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
2373 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2374 }
2375
2376 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2377 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2378 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2379
2380 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2381 (long)node,
2382 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
2383 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
2384 node = eb32sc_next(node, scope);
2385 }
2386 fprintf(file, "}\n");
2387 }
2388
2389 /* This function compares a sample word possibly followed by blanks to another
2390 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2391 * otherwise zero. This intends to be used when checking HTTP headers for some
2392 * values. Note that it validates a word followed only by blanks but does not
2393 * validate a word followed by blanks then other chars.
2394 */
word_match(const char * sample,int slen,const char * word,int wlen)2395 int word_match(const char *sample, int slen, const char *word, int wlen)
2396 {
2397 if (slen < wlen)
2398 return 0;
2399
2400 while (wlen) {
2401 char c = *sample ^ *word;
2402 if (c && c != ('A' ^ 'a'))
2403 return 0;
2404 sample++;
2405 word++;
2406 slen--;
2407 wlen--;
2408 }
2409
2410 while (slen) {
2411 if (*sample != ' ' && *sample != '\t')
2412 return 0;
2413 sample++;
2414 slen--;
2415 }
2416 return 1;
2417 }
2418
2419 /* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2420 * is particularly fast because it avoids expensive operations such as
2421 * multiplies, which are optimized away at the end. It requires a properly
2422 * formated address though (3 points).
2423 */
inetaddr_host(const char * text)2424 unsigned int inetaddr_host(const char *text)
2425 {
2426 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2427 register unsigned int dig100, dig10, dig1;
2428 int s;
2429 const char *p, *d;
2430
2431 dig1 = dig10 = dig100 = ascii_zero;
2432 s = 24;
2433
2434 p = text;
2435 while (1) {
2436 if (((unsigned)(*p - '0')) <= 9) {
2437 p++;
2438 continue;
2439 }
2440
2441 /* here, we have a complete byte between <text> and <p> (exclusive) */
2442 if (p == text)
2443 goto end;
2444
2445 d = p - 1;
2446 dig1 |= (unsigned int)(*d << s);
2447 if (d == text)
2448 goto end;
2449
2450 d--;
2451 dig10 |= (unsigned int)(*d << s);
2452 if (d == text)
2453 goto end;
2454
2455 d--;
2456 dig100 |= (unsigned int)(*d << s);
2457 end:
2458 if (!s || *p != '.')
2459 break;
2460
2461 s -= 8;
2462 text = ++p;
2463 }
2464
2465 dig100 -= ascii_zero;
2466 dig10 -= ascii_zero;
2467 dig1 -= ascii_zero;
2468 return ((dig100 * 10) + dig10) * 10 + dig1;
2469 }
2470
2471 /*
2472 * Idem except the first unparsed character has to be passed in <stop>.
2473 */
inetaddr_host_lim(const char * text,const char * stop)2474 unsigned int inetaddr_host_lim(const char *text, const char *stop)
2475 {
2476 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2477 register unsigned int dig100, dig10, dig1;
2478 int s;
2479 const char *p, *d;
2480
2481 dig1 = dig10 = dig100 = ascii_zero;
2482 s = 24;
2483
2484 p = text;
2485 while (1) {
2486 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2487 p++;
2488 continue;
2489 }
2490
2491 /* here, we have a complete byte between <text> and <p> (exclusive) */
2492 if (p == text)
2493 goto end;
2494
2495 d = p - 1;
2496 dig1 |= (unsigned int)(*d << s);
2497 if (d == text)
2498 goto end;
2499
2500 d--;
2501 dig10 |= (unsigned int)(*d << s);
2502 if (d == text)
2503 goto end;
2504
2505 d--;
2506 dig100 |= (unsigned int)(*d << s);
2507 end:
2508 if (!s || p == stop || *p != '.')
2509 break;
2510
2511 s -= 8;
2512 text = ++p;
2513 }
2514
2515 dig100 -= ascii_zero;
2516 dig10 -= ascii_zero;
2517 dig1 -= ascii_zero;
2518 return ((dig100 * 10) + dig10) * 10 + dig1;
2519 }
2520
2521 /*
2522 * Idem except the pointer to first unparsed byte is returned into <ret> which
2523 * must not be NULL.
2524 */
inetaddr_host_lim_ret(char * text,char * stop,char ** ret)2525 unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
2526 {
2527 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2528 register unsigned int dig100, dig10, dig1;
2529 int s;
2530 char *p, *d;
2531
2532 dig1 = dig10 = dig100 = ascii_zero;
2533 s = 24;
2534
2535 p = text;
2536 while (1) {
2537 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2538 p++;
2539 continue;
2540 }
2541
2542 /* here, we have a complete byte between <text> and <p> (exclusive) */
2543 if (p == text)
2544 goto end;
2545
2546 d = p - 1;
2547 dig1 |= (unsigned int)(*d << s);
2548 if (d == text)
2549 goto end;
2550
2551 d--;
2552 dig10 |= (unsigned int)(*d << s);
2553 if (d == text)
2554 goto end;
2555
2556 d--;
2557 dig100 |= (unsigned int)(*d << s);
2558 end:
2559 if (!s || p == stop || *p != '.')
2560 break;
2561
2562 s -= 8;
2563 text = ++p;
2564 }
2565
2566 *ret = p;
2567 dig100 -= ascii_zero;
2568 dig10 -= ascii_zero;
2569 dig1 -= ascii_zero;
2570 return ((dig100 * 10) + dig10) * 10 + dig1;
2571 }
2572
2573 /* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2574 * or the number of chars read in case of success. Maybe this could be replaced
2575 * by one of the functions above. Also, apparently this function does not support
2576 * hosts above 255 and requires exactly 4 octets.
2577 * The destination is only modified on success.
2578 */
buf2ip(const char * buf,size_t len,struct in_addr * dst)2579 int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2580 {
2581 const char *addr;
2582 int saw_digit, octets, ch;
2583 u_char tmp[4], *tp;
2584 const char *cp = buf;
2585
2586 saw_digit = 0;
2587 octets = 0;
2588 *(tp = tmp) = 0;
2589
2590 for (addr = buf; addr - buf < len; addr++) {
2591 unsigned char digit = (ch = *addr) - '0';
2592
2593 if (digit > 9 && ch != '.')
2594 break;
2595
2596 if (digit <= 9) {
2597 u_int new = *tp * 10 + digit;
2598
2599 if (new > 255)
2600 return 0;
2601
2602 *tp = new;
2603
2604 if (!saw_digit) {
2605 if (++octets > 4)
2606 return 0;
2607 saw_digit = 1;
2608 }
2609 } else if (ch == '.' && saw_digit) {
2610 if (octets == 4)
2611 return 0;
2612
2613 *++tp = 0;
2614 saw_digit = 0;
2615 } else
2616 return 0;
2617 }
2618
2619 if (octets < 4)
2620 return 0;
2621
2622 memcpy(&dst->s_addr, tmp, 4);
2623 return addr - cp;
2624 }
2625
2626 /* This function converts the string in <buf> of the len <len> to
2627 * struct in6_addr <dst> which must be allocated by the caller.
2628 * This function returns 1 in success case, otherwise zero.
2629 * The destination is only modified on success.
2630 */
buf2ip6(const char * buf,size_t len,struct in6_addr * dst)2631 int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2632 {
2633 char null_term_ip6[INET6_ADDRSTRLEN + 1];
2634 struct in6_addr out;
2635
2636 if (len > INET6_ADDRSTRLEN)
2637 return 0;
2638
2639 memcpy(null_term_ip6, buf, len);
2640 null_term_ip6[len] = '\0';
2641
2642 if (!inet_pton(AF_INET6, null_term_ip6, &out))
2643 return 0;
2644
2645 *dst = out;
2646 return 1;
2647 }
2648
2649 /* To be used to quote config arg positions. Returns the short string at <ptr>
2650 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2651 * if ptr is NULL or empty. The string is locally allocated.
2652 */
quote_arg(const char * ptr)2653 const char *quote_arg(const char *ptr)
2654 {
2655 static THREAD_LOCAL char val[32];
2656 int i;
2657
2658 if (!ptr || !*ptr)
2659 return "end of line";
2660 val[0] = '\'';
2661 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
2662 val[i] = *ptr++;
2663 val[i++] = '\'';
2664 val[i] = '\0';
2665 return val;
2666 }
2667
2668 /* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
get_std_op(const char * str)2669 int get_std_op(const char *str)
2670 {
2671 int ret = -1;
2672
2673 if (*str == 'e' && str[1] == 'q')
2674 ret = STD_OP_EQ;
2675 else if (*str == 'n' && str[1] == 'e')
2676 ret = STD_OP_NE;
2677 else if (*str == 'l') {
2678 if (str[1] == 'e') ret = STD_OP_LE;
2679 else if (str[1] == 't') ret = STD_OP_LT;
2680 }
2681 else if (*str == 'g') {
2682 if (str[1] == 'e') ret = STD_OP_GE;
2683 else if (str[1] == 't') ret = STD_OP_GT;
2684 }
2685
2686 if (ret == -1 || str[2] != '\0')
2687 return -1;
2688 return ret;
2689 }
2690
2691 /* hash a 32-bit integer to another 32-bit integer */
full_hash(unsigned int a)2692 unsigned int full_hash(unsigned int a)
2693 {
2694 return __full_hash(a);
2695 }
2696
2697 /* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2698 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2699 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2700 * a popcount variant and is described here :
2701 * https://graphics.stanford.edu/~seander/bithacks.html
2702 */
mask_find_rank_bit(unsigned int r,unsigned long m)2703 unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2704 {
2705 unsigned long a, b, c, d;
2706 unsigned int s;
2707 unsigned int t;
2708
2709 a = m - ((m >> 1) & ~0UL/3);
2710 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2711 c = (b + (b >> 4)) & ~0UL/0x11;
2712 d = (c + (c >> 8)) & ~0UL/0x101;
2713
2714 r++; // make r be 1..64
2715
2716 t = 0;
2717 s = LONGBITS;
2718 if (s > 32) {
2719 unsigned long d2 = (d >> 16) >> 16;
2720 t = d2 + (d2 >> 16);
2721 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2722 }
2723
2724 t = (d >> (s - 16)) & 0xff;
2725 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2726 t = (c >> (s - 8)) & 0xf;
2727 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2728 t = (b >> (s - 4)) & 0x7;
2729 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2730 t = (a >> (s - 2)) & 0x3;
2731 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2732 t = (m >> (s - 1)) & 0x1;
2733 s -= ((t - r) & 256) >> 8;
2734
2735 return s - 1;
2736 }
2737
2738 /* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2739 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2740 * using mask_prep_rank_map() below.
2741 */
mask_find_rank_bit_fast(unsigned int r,unsigned long m,unsigned long a,unsigned long b,unsigned long c,unsigned long d)2742 unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2743 unsigned long a, unsigned long b,
2744 unsigned long c, unsigned long d)
2745 {
2746 unsigned int s;
2747 unsigned int t;
2748
2749 r++; // make r be 1..64
2750
2751 t = 0;
2752 s = LONGBITS;
2753 if (s > 32) {
2754 unsigned long d2 = (d >> 16) >> 16;
2755 t = d2 + (d2 >> 16);
2756 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2757 }
2758
2759 t = (d >> (s - 16)) & 0xff;
2760 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2761 t = (c >> (s - 8)) & 0xf;
2762 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2763 t = (b >> (s - 4)) & 0x7;
2764 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2765 t = (a >> (s - 2)) & 0x3;
2766 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2767 t = (m >> (s - 1)) & 0x1;
2768 s -= ((t - r) & 256) >> 8;
2769
2770 return s - 1;
2771 }
2772
2773 /* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2774 * above.
2775 */
mask_prep_rank_map(unsigned long m,unsigned long * a,unsigned long * b,unsigned long * c,unsigned long * d)2776 void mask_prep_rank_map(unsigned long m,
2777 unsigned long *a, unsigned long *b,
2778 unsigned long *c, unsigned long *d)
2779 {
2780 *a = m - ((m >> 1) & ~0UL/3);
2781 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2782 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2783 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2784 }
2785
2786 /* Return non-zero if IPv4 address is part of the network,
2787 * otherwise zero. Note that <addr> may not necessarily be aligned
2788 * while the two other ones must.
2789 */
in_net_ipv4(const void * addr,const struct in_addr * mask,const struct in_addr * net)2790 int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
2791 {
2792 struct in_addr addr_copy;
2793
2794 memcpy(&addr_copy, addr, sizeof(addr_copy));
2795 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
2796 }
2797
2798 /* Return non-zero if IPv6 address is part of the network,
2799 * otherwise zero. Note that <addr> may not necessarily be aligned
2800 * while the two other ones must.
2801 */
in_net_ipv6(const void * addr,const struct in6_addr * mask,const struct in6_addr * net)2802 int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
2803 {
2804 int i;
2805 struct in6_addr addr_copy;
2806
2807 memcpy(&addr_copy, addr, sizeof(addr_copy));
2808 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2809 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
2810 (((int *)net)[i] & ((int *)mask)[i]))
2811 return 0;
2812 return 1;
2813 }
2814
2815 /* RFC 4291 prefix */
2816 const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2817 0x00, 0x00, 0x00, 0x00,
2818 0x00, 0x00, 0xFF, 0xFF };
2819
2820 /* Map IPv4 address on IPv6 address, as specified in RFC 3513.
2821 * Input and output may overlap.
2822 */
v4tov6(struct in6_addr * sin6_addr,struct in_addr * sin_addr)2823 void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2824 {
2825 struct in_addr tmp_addr;
2826
2827 tmp_addr.s_addr = sin_addr->s_addr;
2828 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
2829 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
2830 }
2831
2832 /* Map IPv6 address on IPv4 address, as specified in RFC 3513.
2833 * Return true if conversion is possible and false otherwise.
2834 */
v6tov4(struct in_addr * sin_addr,struct in6_addr * sin6_addr)2835 int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2836 {
2837 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2838 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2839 sizeof(struct in_addr));
2840 return 1;
2841 }
2842
2843 return 0;
2844 }
2845
2846 /* compare two struct sockaddr_storage and return:
2847 * 0 (true) if the addr is the same in both
2848 * 1 (false) if the addr is not the same in both
2849 * -1 (unable) if one of the addr is not AF_INET*
2850 */
ipcmp(struct sockaddr_storage * ss1,struct sockaddr_storage * ss2)2851 int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2852 {
2853 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2854 return -1;
2855
2856 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2857 return -1;
2858
2859 if (ss1->ss_family != ss2->ss_family)
2860 return 1;
2861
2862 switch (ss1->ss_family) {
2863 case AF_INET:
2864 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2865 &((struct sockaddr_in *)ss2)->sin_addr,
2866 sizeof(struct in_addr)) != 0;
2867 case AF_INET6:
2868 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2869 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2870 sizeof(struct in6_addr)) != 0;
2871 }
2872
2873 return 1;
2874 }
2875
2876 /* copy IP address from <source> into <dest>
2877 * The caller must allocate and clear <dest> before calling.
2878 * The source must be in either AF_INET or AF_INET6 family, or the destination
2879 * address will be undefined. If the destination address used to hold a port,
2880 * it is preserved, so that this function can be used to switch to another
2881 * address family with no risk. Returns a pointer to the destination.
2882 */
ipcpy(struct sockaddr_storage * source,struct sockaddr_storage * dest)2883 struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2884 {
2885 int prev_port;
2886
2887 prev_port = get_net_port(dest);
2888 memset(dest, 0, sizeof(*dest));
2889 dest->ss_family = source->ss_family;
2890
2891 /* copy new addr and apply it */
2892 switch (source->ss_family) {
2893 case AF_INET:
2894 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
2895 ((struct sockaddr_in *)dest)->sin_port = prev_port;
2896 break;
2897 case AF_INET6:
2898 memcpy(((struct sockaddr_in6 *)dest)->sin6_addr.s6_addr, ((struct sockaddr_in6 *)source)->sin6_addr.s6_addr, sizeof(struct in6_addr));
2899 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
2900 break;
2901 }
2902
2903 return dest;
2904 }
2905
human_time(int t,short hz_div)2906 char *human_time(int t, short hz_div) {
2907 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2908 char *p = rv;
2909 char *end = rv + sizeof(rv);
2910 int cnt=2; // print two numbers
2911
2912 if (unlikely(t < 0 || hz_div <= 0)) {
2913 snprintf(p, end - p, "?");
2914 return rv;
2915 }
2916
2917 if (unlikely(hz_div > 1))
2918 t /= hz_div;
2919
2920 if (t >= DAY) {
2921 p += snprintf(p, end - p, "%dd", t / DAY);
2922 cnt--;
2923 }
2924
2925 if (cnt && t % DAY / HOUR) {
2926 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
2927 cnt--;
2928 }
2929
2930 if (cnt && t % HOUR / MINUTE) {
2931 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
2932 cnt--;
2933 }
2934
2935 if ((cnt && t % MINUTE) || !t) // also display '0s'
2936 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
2937
2938 return rv;
2939 }
2940
2941 const char *monthname[12] = {
2942 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2943 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2944 };
2945
2946 /* date2str_log: write a date in the format :
2947 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2948 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2949 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2950 *
2951 * without using sprintf. return a pointer to the last char written (\0) or
2952 * NULL if there isn't enough space.
2953 */
date2str_log(char * dst,const struct tm * tm,const struct timeval * date,size_t size)2954 char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
2955 {
2956
2957 if (size < 25) /* the size is fixed: 24 chars + \0 */
2958 return NULL;
2959
2960 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2961 if (!dst)
2962 return NULL;
2963 *dst++ = '/';
2964
2965 memcpy(dst, monthname[tm->tm_mon], 3); // month
2966 dst += 3;
2967 *dst++ = '/';
2968
2969 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2970 if (!dst)
2971 return NULL;
2972 *dst++ = ':';
2973
2974 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2975 if (!dst)
2976 return NULL;
2977 *dst++ = ':';
2978
2979 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2980 if (!dst)
2981 return NULL;
2982 *dst++ = ':';
2983
2984 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2985 if (!dst)
2986 return NULL;
2987 *dst++ = '.';
2988
2989 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2990 if (!dst)
2991 return NULL;
2992 dst += 3; // only the 3 first digits
2993 *dst = '\0';
2994
2995 return dst;
2996 }
2997
2998 /* Base year used to compute leap years */
2999 #define TM_YEAR_BASE 1900
3000
3001 /* Return the difference in seconds between two times (leap seconds are ignored).
3002 * Retrieved from glibc 2.18 source code.
3003 */
my_tm_diff(const struct tm * a,const struct tm * b)3004 static int my_tm_diff(const struct tm *a, const struct tm *b)
3005 {
3006 /* Compute intervening leap days correctly even if year is negative.
3007 * Take care to avoid int overflow in leap day calculations,
3008 * but it's OK to assume that A and B are close to each other.
3009 */
3010 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3011 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3012 int a100 = a4 / 25 - (a4 % 25 < 0);
3013 int b100 = b4 / 25 - (b4 % 25 < 0);
3014 int a400 = a100 >> 2;
3015 int b400 = b100 >> 2;
3016 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3017 int years = a->tm_year - b->tm_year;
3018 int days = (365 * years + intervening_leap_days
3019 + (a->tm_yday - b->tm_yday));
3020 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3021 + (a->tm_min - b->tm_min))
3022 + (a->tm_sec - b->tm_sec));
3023 }
3024
3025 /* Return the GMT offset for a specific local time.
3026 * Both t and tm must represent the same time.
3027 * The string returned has the same format as returned by strftime(... "%z", tm).
3028 * Offsets are kept in an internal cache for better performances.
3029 */
get_gmt_offset(time_t t,struct tm * tm)3030 const char *get_gmt_offset(time_t t, struct tm *tm)
3031 {
3032 /* Cache offsets from GMT (depending on whether DST is active or not) */
3033 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
3034
3035 char *gmt_offset;
3036 struct tm tm_gmt;
3037 int diff;
3038 int isdst = tm->tm_isdst;
3039
3040 /* Pretend DST not active if its status is unknown */
3041 if (isdst < 0)
3042 isdst = 0;
3043
3044 /* Fetch the offset and initialize it if needed */
3045 gmt_offset = gmt_offsets[isdst & 0x01];
3046 if (unlikely(!*gmt_offset)) {
3047 get_gmtime(t, &tm_gmt);
3048 diff = my_tm_diff(tm, &tm_gmt);
3049 if (diff < 0) {
3050 diff = -diff;
3051 *gmt_offset = '-';
3052 } else {
3053 *gmt_offset = '+';
3054 }
3055 diff %= 86400U;
3056 diff /= 60; /* Convert to minutes */
3057 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3058 }
3059
3060 return gmt_offset;
3061 }
3062
3063 /* gmt2str_log: write a date in the format :
3064 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3065 * return a pointer to the last char written (\0) or
3066 * NULL if there isn't enough space.
3067 */
gmt2str_log(char * dst,struct tm * tm,size_t size)3068 char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3069 {
3070 if (size < 27) /* the size is fixed: 26 chars + \0 */
3071 return NULL;
3072
3073 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
3074 if (!dst)
3075 return NULL;
3076 *dst++ = '/';
3077
3078 memcpy(dst, monthname[tm->tm_mon], 3); // month
3079 dst += 3;
3080 *dst++ = '/';
3081
3082 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
3083 if (!dst)
3084 return NULL;
3085 *dst++ = ':';
3086
3087 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
3088 if (!dst)
3089 return NULL;
3090 *dst++ = ':';
3091
3092 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
3093 if (!dst)
3094 return NULL;
3095 *dst++ = ':';
3096
3097 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
3098 if (!dst)
3099 return NULL;
3100 *dst++ = ' ';
3101 *dst++ = '+';
3102 *dst++ = '0';
3103 *dst++ = '0';
3104 *dst++ = '0';
3105 *dst++ = '0';
3106 *dst = '\0';
3107
3108 return dst;
3109 }
3110
3111 /* localdate2str_log: write a date in the format :
3112 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
3113 * Both t and tm must represent the same time.
3114 * return a pointer to the last char written (\0) or
3115 * NULL if there isn't enough space.
3116 */
localdate2str_log(char * dst,time_t t,struct tm * tm,size_t size)3117 char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
3118 {
3119 const char *gmt_offset;
3120 if (size < 27) /* the size is fixed: 26 chars + \0 */
3121 return NULL;
3122
3123 gmt_offset = get_gmt_offset(t, tm);
3124
3125 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
3126 if (!dst)
3127 return NULL;
3128 *dst++ = '/';
3129
3130 memcpy(dst, monthname[tm->tm_mon], 3); // month
3131 dst += 3;
3132 *dst++ = '/';
3133
3134 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
3135 if (!dst)
3136 return NULL;
3137 *dst++ = ':';
3138
3139 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
3140 if (!dst)
3141 return NULL;
3142 *dst++ = ':';
3143
3144 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
3145 if (!dst)
3146 return NULL;
3147 *dst++ = ':';
3148
3149 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
3150 if (!dst)
3151 return NULL;
3152 *dst++ = ' ';
3153
3154 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
3155 dst += 5;
3156 *dst = '\0';
3157
3158 return dst;
3159 }
3160
3161 /* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3162 * It is meant as a portable replacement for timegm() for use with valid inputs.
3163 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3164 */
my_timegm(const struct tm * tm)3165 time_t my_timegm(const struct tm *tm)
3166 {
3167 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3168 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3169 * sum of the extra N days for elapsed months. The sum of all these N
3170 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3171 * in a 5-bit word. This means that with 60 bits we can represent a
3172 * matrix of all these values at once, which is fast and efficient to
3173 * access. The extra February day for leap years is not counted here.
3174 *
3175 * Jan : none = 0 (0)
3176 * Feb : Jan = 3 (3)
3177 * Mar : Jan..Feb = 3 (3 + 0)
3178 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3179 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3180 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3181 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3182 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3183 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3184 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3185 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3186 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3187 */
3188 uint64_t extra =
3189 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3190 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3191 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3192 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3193
3194 unsigned int y = tm->tm_year + 1900;
3195 unsigned int m = tm->tm_mon;
3196 unsigned long days = 0;
3197
3198 /* days since 1/1/1970 for full years */
3199 days += days_since_zero(y) - days_since_zero(1970);
3200
3201 /* days for full months in the current year */
3202 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3203
3204 /* count + 1 after March for leap years. A leap year is a year multiple
3205 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3206 * is leap, 1900 isn't, 1904 is.
3207 */
3208 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3209 days++;
3210
3211 days += tm->tm_mday - 1;
3212 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3213 }
3214
3215 /* This function check a char. It returns true and updates
3216 * <date> and <len> pointer to the new position if the
3217 * character is found.
3218 */
parse_expect_char(const char ** date,int * len,char c)3219 static inline int parse_expect_char(const char **date, int *len, char c)
3220 {
3221 if (*len < 1 || **date != c)
3222 return 0;
3223 (*len)--;
3224 (*date)++;
3225 return 1;
3226 }
3227
3228 /* This function expects a string <str> of len <l>. It return true and updates.
3229 * <date> and <len> if the string matches, otherwise, it returns false.
3230 */
parse_strcmp(const char ** date,int * len,char * str,int l)3231 static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3232 {
3233 if (*len < l || strncmp(*date, str, l) != 0)
3234 return 0;
3235 (*len) -= l;
3236 (*date) += l;
3237 return 1;
3238 }
3239
3240 /* This macro converts 3 chars name in integer. */
3241 #define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3242
3243 /* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3244 * / %x54.75.65 ; "Tue", case-sensitive
3245 * / %x57.65.64 ; "Wed", case-sensitive
3246 * / %x54.68.75 ; "Thu", case-sensitive
3247 * / %x46.72.69 ; "Fri", case-sensitive
3248 * / %x53.61.74 ; "Sat", case-sensitive
3249 * / %x53.75.6E ; "Sun", case-sensitive
3250 *
3251 * This array must be alphabetically sorted
3252 */
parse_http_dayname(const char ** date,int * len,struct tm * tm)3253 static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3254 {
3255 if (*len < 3)
3256 return 0;
3257 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3258 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3259 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3260 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3261 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3262 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3263 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3264 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3265 default: return 0;
3266 }
3267 *len -= 3;
3268 *date += 3;
3269 return 1;
3270 }
3271
3272 /* month = %x4A.61.6E ; "Jan", case-sensitive
3273 * / %x46.65.62 ; "Feb", case-sensitive
3274 * / %x4D.61.72 ; "Mar", case-sensitive
3275 * / %x41.70.72 ; "Apr", case-sensitive
3276 * / %x4D.61.79 ; "May", case-sensitive
3277 * / %x4A.75.6E ; "Jun", case-sensitive
3278 * / %x4A.75.6C ; "Jul", case-sensitive
3279 * / %x41.75.67 ; "Aug", case-sensitive
3280 * / %x53.65.70 ; "Sep", case-sensitive
3281 * / %x4F.63.74 ; "Oct", case-sensitive
3282 * / %x4E.6F.76 ; "Nov", case-sensitive
3283 * / %x44.65.63 ; "Dec", case-sensitive
3284 *
3285 * This array must be alphabetically sorted
3286 */
parse_http_monthname(const char ** date,int * len,struct tm * tm)3287 static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3288 {
3289 if (*len < 3)
3290 return 0;
3291 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3292 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3293 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3294 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3295 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3296 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3297 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3298 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3299 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3300 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3301 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3302 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3303 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3304 default: return 0;
3305 }
3306 *len -= 3;
3307 *date += 3;
3308 return 1;
3309 }
3310
3311 /* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3312 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3313 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3314 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3315 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3316 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3317 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3318 *
3319 * This array must be alphabetically sorted
3320 */
parse_http_ldayname(const char ** date,int * len,struct tm * tm)3321 static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3322 {
3323 if (*len < 6) /* Minimum length. */
3324 return 0;
3325 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3326 case STR2I3('M','o','n'):
3327 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3328 tm->tm_wday = 1;
3329 return 1;
3330 case STR2I3('T','u','e'):
3331 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3332 tm->tm_wday = 2;
3333 return 1;
3334 case STR2I3('W','e','d'):
3335 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3336 tm->tm_wday = 3;
3337 return 1;
3338 case STR2I3('T','h','u'):
3339 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3340 tm->tm_wday = 4;
3341 return 1;
3342 case STR2I3('F','r','i'):
3343 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3344 tm->tm_wday = 5;
3345 return 1;
3346 case STR2I3('S','a','t'):
3347 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3348 tm->tm_wday = 6;
3349 return 1;
3350 case STR2I3('S','u','n'):
3351 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3352 tm->tm_wday = 7;
3353 return 1;
3354 }
3355 return 0;
3356 }
3357
3358 /* This function parses exactly 1 digit and returns the numeric value in "digit". */
parse_digit(const char ** date,int * len,int * digit)3359 static inline int parse_digit(const char **date, int *len, int *digit)
3360 {
3361 if (*len < 1 || **date < '0' || **date > '9')
3362 return 0;
3363 *digit = (**date - '0');
3364 (*date)++;
3365 (*len)--;
3366 return 1;
3367 }
3368
3369 /* This function parses exactly 2 digits and returns the numeric value in "digit". */
parse_2digit(const char ** date,int * len,int * digit)3370 static inline int parse_2digit(const char **date, int *len, int *digit)
3371 {
3372 int value;
3373
3374 RET0_UNLESS(parse_digit(date, len, &value));
3375 (*digit) = value * 10;
3376 RET0_UNLESS(parse_digit(date, len, &value));
3377 (*digit) += value;
3378
3379 return 1;
3380 }
3381
3382 /* This function parses exactly 4 digits and returns the numeric value in "digit". */
parse_4digit(const char ** date,int * len,int * digit)3383 static inline int parse_4digit(const char **date, int *len, int *digit)
3384 {
3385 int value;
3386
3387 RET0_UNLESS(parse_digit(date, len, &value));
3388 (*digit) = value * 1000;
3389
3390 RET0_UNLESS(parse_digit(date, len, &value));
3391 (*digit) += value * 100;
3392
3393 RET0_UNLESS(parse_digit(date, len, &value));
3394 (*digit) += value * 10;
3395
3396 RET0_UNLESS(parse_digit(date, len, &value));
3397 (*digit) += value;
3398
3399 return 1;
3400 }
3401
3402 /* time-of-day = hour ":" minute ":" second
3403 * ; 00:00:00 - 23:59:60 (leap second)
3404 *
3405 * hour = 2DIGIT
3406 * minute = 2DIGIT
3407 * second = 2DIGIT
3408 */
parse_http_time(const char ** date,int * len,struct tm * tm)3409 static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3410 {
3411 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3412 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3413 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3414 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3415 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3416 return 1;
3417 }
3418
3419 /* From RFC7231
3420 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3421 *
3422 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3423 * ; fixed length/zone/capitalization subset of the format
3424 * ; see Section 3.3 of [RFC5322]
3425 *
3426 *
3427 * date1 = day SP month SP year
3428 * ; e.g., 02 Jun 1982
3429 *
3430 * day = 2DIGIT
3431 * year = 4DIGIT
3432 *
3433 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3434 *
3435 * time-of-day = hour ":" minute ":" second
3436 * ; 00:00:00 - 23:59:60 (leap second)
3437 *
3438 * hour = 2DIGIT
3439 * minute = 2DIGIT
3440 * second = 2DIGIT
3441 *
3442 * DIGIT = decimal 0-9
3443 */
parse_imf_date(const char * date,int len,struct tm * tm)3444 int parse_imf_date(const char *date, int len, struct tm *tm)
3445 {
3446 /* tm_gmtoff, if present, ought to be zero'ed */
3447 memset(tm, 0, sizeof(*tm));
3448
3449 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3450 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3451 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3452 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3453 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3454 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3455 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3456 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3457 tm->tm_year -= 1900;
3458 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3459 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3460 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3461 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3462 tm->tm_isdst = -1;
3463 return 1;
3464 }
3465
3466 /* From RFC7231
3467 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3468 *
3469 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3470 * date2 = day "-" month "-" 2DIGIT
3471 * ; e.g., 02-Jun-82
3472 *
3473 * day = 2DIGIT
3474 */
parse_rfc850_date(const char * date,int len,struct tm * tm)3475 int parse_rfc850_date(const char *date, int len, struct tm *tm)
3476 {
3477 int year;
3478
3479 /* tm_gmtoff, if present, ought to be zero'ed */
3480 memset(tm, 0, sizeof(*tm));
3481
3482 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3483 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3484 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3485 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3486 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3487 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3488 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3489
3490 /* year = 2DIGIT
3491 *
3492 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3493 * two-digit year, MUST interpret a timestamp that appears to be more
3494 * than 50 years in the future as representing the most recent year in
3495 * the past that had the same last two digits.
3496 */
3497 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3498
3499 /* expect SP */
3500 if (!parse_expect_char(&date, &len, ' ')) {
3501 /* Maybe we have the date with 4 digits. */
3502 RET0_UNLESS(parse_2digit(&date, &len, &year));
3503 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3504 /* expect SP */
3505 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3506 } else {
3507 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3508 * tm_year is the number of year since 1900, so for +1900, we
3509 * do nothing, and for +2000, we add 100.
3510 */
3511 if (tm->tm_year <= 60)
3512 tm->tm_year += 100;
3513 }
3514
3515 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3516 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3517 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3518 tm->tm_isdst = -1;
3519
3520 return 1;
3521 }
3522
3523 /* From RFC7231
3524 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3525 *
3526 * asctime-date = day-name SP date3 SP time-of-day SP year
3527 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3528 * ; e.g., Jun 2
3529 *
3530 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3531 * whitespace in an HTTP-date beyond that specifically included as SP in
3532 * the grammar.
3533 */
parse_asctime_date(const char * date,int len,struct tm * tm)3534 int parse_asctime_date(const char *date, int len, struct tm *tm)
3535 {
3536 /* tm_gmtoff, if present, ought to be zero'ed */
3537 memset(tm, 0, sizeof(*tm));
3538
3539 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3540 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3541 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3542 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3543
3544 /* expect SP and 1DIGIT or 2DIGIT */
3545 if (parse_expect_char(&date, &len, ' '))
3546 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3547 else
3548 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3549
3550 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3551 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3552 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3553 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3554 tm->tm_year -= 1900;
3555 tm->tm_isdst = -1;
3556 return 1;
3557 }
3558
3559 /* From RFC7231
3560 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3561 *
3562 * HTTP-date = IMF-fixdate / obs-date
3563 * obs-date = rfc850-date / asctime-date
3564 *
3565 * parses an HTTP date in the RFC format and is accepted
3566 * alternatives. <date> is the strinf containing the date,
3567 * len is the len of the string. <tm> is filled with the
3568 * parsed time. We must considers this time as GMT.
3569 */
parse_http_date(const char * date,int len,struct tm * tm)3570 int parse_http_date(const char *date, int len, struct tm *tm)
3571 {
3572 if (parse_imf_date(date, len, tm))
3573 return 1;
3574
3575 if (parse_rfc850_date(date, len, tm))
3576 return 1;
3577
3578 if (parse_asctime_date(date, len, tm))
3579 return 1;
3580
3581 return 0;
3582 }
3583
3584 /* Dynamically allocates a string of the proper length to hold the formatted
3585 * output. NULL is returned on error. The caller is responsible for freeing the
3586 * memory area using free(). The resulting string is returned in <out> if the
3587 * pointer is not NULL. A previous version of <out> might be used to build the
3588 * new string, and it will be freed before returning if it is not NULL, which
3589 * makes it possible to build complex strings from iterative calls without
3590 * having to care about freeing intermediate values, as in the example below :
3591 *
3592 * memprintf(&err, "invalid argument: '%s'", arg);
3593 * ...
3594 * memprintf(&err, "parser said : <%s>\n", *err);
3595 * ...
3596 * free(*err);
3597 *
3598 * This means that <err> must be initialized to NULL before first invocation.
3599 * The return value also holds the allocated string, which eases error checking
3600 * and immediate consumption. If the output pointer is not used, NULL must be
3601 * passed instead and it will be ignored. The returned message will then also
3602 * be NULL so that the caller does not have to bother with freeing anything.
3603 *
3604 * It is also convenient to use it without any free except the last one :
3605 * err = NULL;
3606 * if (!fct1(err)) report(*err);
3607 * if (!fct2(err)) report(*err);
3608 * if (!fct3(err)) report(*err);
3609 * free(*err);
3610 *
3611 * memprintf relies on memvprintf. This last version can be called from any
3612 * function with variadic arguments.
3613 */
memvprintf(char ** out,const char * format,va_list orig_args)3614 char *memvprintf(char **out, const char *format, va_list orig_args)
3615 {
3616 va_list args;
3617 char *ret = NULL;
3618 int allocated = 0;
3619 int needed = 0;
3620
3621 if (!out)
3622 return NULL;
3623
3624 do {
3625 char buf1;
3626
3627 /* vsnprintf() will return the required length even when the
3628 * target buffer is NULL. We do this in a loop just in case
3629 * intermediate evaluations get wrong.
3630 */
3631 va_copy(args, orig_args);
3632 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
3633 va_end(args);
3634 if (needed < allocated) {
3635 /* Note: on Solaris 8, the first iteration always
3636 * returns -1 if allocated is zero, so we force a
3637 * retry.
3638 */
3639 if (!allocated)
3640 needed = 0;
3641 else
3642 break;
3643 }
3644
3645 allocated = needed + 1;
3646 ret = my_realloc2(ret, allocated);
3647 } while (ret);
3648
3649 if (needed < 0) {
3650 /* an error was encountered */
3651 free(ret);
3652 ret = NULL;
3653 }
3654
3655 if (out) {
3656 free(*out);
3657 *out = ret;
3658 }
3659
3660 return ret;
3661 }
3662
memprintf(char ** out,const char * format,...)3663 char *memprintf(char **out, const char *format, ...)
3664 {
3665 va_list args;
3666 char *ret = NULL;
3667
3668 va_start(args, format);
3669 ret = memvprintf(out, format, args);
3670 va_end(args);
3671
3672 return ret;
3673 }
3674
3675 /* Used to add <level> spaces before each line of <out>, unless there is only one line.
3676 * The input argument is automatically freed and reassigned. The result will have to be
3677 * freed by the caller. It also supports being passed a NULL which results in the same
3678 * output.
3679 * Example of use :
3680 * parse(cmd, &err); (callee: memprintf(&err, ...))
3681 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3682 * free(err);
3683 */
indent_msg(char ** out,int level)3684 char *indent_msg(char **out, int level)
3685 {
3686 char *ret, *in, *p;
3687 int needed = 0;
3688 int lf = 0;
3689 int lastlf = 0;
3690 int len;
3691
3692 if (!out || !*out)
3693 return NULL;
3694
3695 in = *out - 1;
3696 while ((in = strchr(in + 1, '\n')) != NULL) {
3697 lastlf = in - *out;
3698 lf++;
3699 }
3700
3701 if (!lf) /* single line, no LF, return it as-is */
3702 return *out;
3703
3704 len = strlen(*out);
3705
3706 if (lf == 1 && lastlf == len - 1) {
3707 /* single line, LF at end, strip it and return as-is */
3708 (*out)[lastlf] = 0;
3709 return *out;
3710 }
3711
3712 /* OK now we have at least one LF, we need to process the whole string
3713 * as a multi-line string. What we'll do :
3714 * - prefix with an LF if there is none
3715 * - add <level> spaces before each line
3716 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3717 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3718 */
3719
3720 needed = 1 + level * (lf + 1) + len + 1;
3721 p = ret = malloc(needed);
3722 in = *out;
3723
3724 /* skip initial LFs */
3725 while (*in == '\n')
3726 in++;
3727
3728 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3729 while (*in) {
3730 *p++ = '\n';
3731 memset(p, ' ', level);
3732 p += level;
3733 do {
3734 *p++ = *in++;
3735 } while (*in && *in != '\n');
3736 if (*in)
3737 in++;
3738 }
3739 *p = 0;
3740
3741 free(*out);
3742 *out = ret;
3743
3744 return ret;
3745 }
3746
3747 /* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3748 * and end of lines replaced with <eol> if not 0. The first line to indent has
3749 * to be indicated in <first> (starts at zero), so that it is possible to skip
3750 * indenting the first line if it has to be appended after an existing message.
3751 * Empty strings are never indented, and NULL strings are considered empty both
3752 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3753 * character, non-zero otherwise.
3754 */
append_prefixed_str(struct buffer * out,const char * in,const char * pfx,char eol,int first)3755 int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3756 {
3757 int bol, lf;
3758 int pfxlen = pfx ? strlen(pfx) : 0;
3759
3760 if (!in)
3761 return 0;
3762
3763 bol = 1;
3764 lf = 0;
3765 while (*in) {
3766 if (bol && pfxlen) {
3767 if (first > 0)
3768 first--;
3769 else
3770 b_putblk(out, pfx, pfxlen);
3771 bol = 0;
3772 }
3773
3774 lf = (*in == '\n');
3775 bol |= lf;
3776 b_putchr(out, (lf && eol) ? eol : *in);
3777 in++;
3778 }
3779 return lf;
3780 }
3781
3782 /* removes environment variable <name> from the environment as found in
3783 * environ. This is only provided as an alternative for systems without
3784 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
3785 * The principle is to scan environ for each occurence of variable name
3786 * <name> and to replace the matching pointers with the last pointer of
3787 * the array (since variables are not ordered).
3788 * It always returns 0 (success).
3789 */
my_unsetenv(const char * name)3790 int my_unsetenv(const char *name)
3791 {
3792 extern char **environ;
3793 char **p = environ;
3794 int vars;
3795 int next;
3796 int len;
3797
3798 len = strlen(name);
3799 for (vars = 0; p[vars]; vars++)
3800 ;
3801 next = 0;
3802 while (next < vars) {
3803 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3804 next++;
3805 continue;
3806 }
3807 if (next < vars - 1)
3808 p[next] = p[vars - 1];
3809 p[--vars] = NULL;
3810 }
3811 return 0;
3812 }
3813
3814 /* Convert occurrences of environment variables in the input string to their
3815 * corresponding value. A variable is identified as a series of alphanumeric
3816 * characters or underscores following a '$' sign. The <in> string must be
3817 * free()able. NULL returns NULL. The resulting string might be reallocated if
3818 * some expansion is made. Variable names may also be enclosed into braces if
3819 * needed (eg: to concatenate alphanum characters).
3820 */
env_expand(char * in)3821 char *env_expand(char *in)
3822 {
3823 char *txt_beg;
3824 char *out;
3825 char *txt_end;
3826 char *var_beg;
3827 char *var_end;
3828 char *value;
3829 char *next;
3830 int out_len;
3831 int val_len;
3832
3833 if (!in)
3834 return in;
3835
3836 value = out = NULL;
3837 out_len = 0;
3838
3839 txt_beg = in;
3840 do {
3841 /* look for next '$' sign in <in> */
3842 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3843
3844 if (!*txt_end && !out) /* end and no expansion performed */
3845 return in;
3846
3847 val_len = 0;
3848 next = txt_end;
3849 if (*txt_end == '$') {
3850 char save;
3851
3852 var_beg = txt_end + 1;
3853 if (*var_beg == '{')
3854 var_beg++;
3855
3856 var_end = var_beg;
3857 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3858 var_end++;
3859 }
3860
3861 next = var_end;
3862 if (*var_end == '}' && (var_beg > txt_end + 1))
3863 next++;
3864
3865 /* get value of the variable name at this location */
3866 save = *var_end;
3867 *var_end = '\0';
3868 value = getenv(var_beg);
3869 *var_end = save;
3870 val_len = value ? strlen(value) : 0;
3871 }
3872
3873 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
3874 if (txt_end > txt_beg) {
3875 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3876 out_len += txt_end - txt_beg;
3877 }
3878 if (val_len) {
3879 memcpy(out + out_len, value, val_len);
3880 out_len += val_len;
3881 }
3882 out[out_len] = 0;
3883 txt_beg = next;
3884 } while (*txt_beg);
3885
3886 /* here we know that <out> was allocated and that we don't need <in> anymore */
3887 free(in);
3888 return out;
3889 }
3890
3891
3892 /* same as strstr() but case-insensitive and with limit length */
strnistr(const char * str1,int len_str1,const char * str2,int len_str2)3893 const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3894 {
3895 char *pptr, *sptr, *start;
3896 unsigned int slen, plen;
3897 unsigned int tmp1, tmp2;
3898
3899 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3900 return NULL;
3901
3902 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3903 return str1;
3904
3905 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3906 return NULL;
3907
3908 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3909 while (toupper(*start) != toupper(*str2)) {
3910 start++;
3911 slen--;
3912 tmp1++;
3913
3914 if (tmp1 >= len_str1)
3915 return NULL;
3916
3917 /* if pattern longer than string */
3918 if (slen < plen)
3919 return NULL;
3920 }
3921
3922 sptr = start;
3923 pptr = (char *)str2;
3924
3925 tmp2 = 0;
3926 while (toupper(*sptr) == toupper(*pptr)) {
3927 sptr++;
3928 pptr++;
3929 tmp2++;
3930
3931 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3932 return start;
3933 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3934 return NULL;
3935 }
3936 }
3937 return NULL;
3938 }
3939
3940 /* This function read the next valid utf8 char.
3941 * <s> is the byte srray to be decode, <len> is its length.
3942 * The function returns decoded char encoded like this:
3943 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3944 * are the length read. The decoded character is stored in <c>.
3945 */
utf8_next(const char * s,int len,unsigned int * c)3946 unsigned char utf8_next(const char *s, int len, unsigned int *c)
3947 {
3948 const unsigned char *p = (unsigned char *)s;
3949 int dec;
3950 unsigned char code = UTF8_CODE_OK;
3951
3952 if (len < 1)
3953 return UTF8_CODE_OK;
3954
3955 /* Check the type of UTF8 sequence
3956 *
3957 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3958 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3959 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3960 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3961 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3962 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3963 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3964 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3965 */
3966 switch (*p) {
3967 case 0x00 ... 0x7f:
3968 *c = *p;
3969 return UTF8_CODE_OK | 1;
3970
3971 case 0x80 ... 0xbf:
3972 *c = *p;
3973 return UTF8_CODE_BADSEQ | 1;
3974
3975 case 0xc0 ... 0xdf:
3976 if (len < 2) {
3977 *c = *p;
3978 return UTF8_CODE_BADSEQ | 1;
3979 }
3980 *c = *p & 0x1f;
3981 dec = 1;
3982 break;
3983
3984 case 0xe0 ... 0xef:
3985 if (len < 3) {
3986 *c = *p;
3987 return UTF8_CODE_BADSEQ | 1;
3988 }
3989 *c = *p & 0x0f;
3990 dec = 2;
3991 break;
3992
3993 case 0xf0 ... 0xf7:
3994 if (len < 4) {
3995 *c = *p;
3996 return UTF8_CODE_BADSEQ | 1;
3997 }
3998 *c = *p & 0x07;
3999 dec = 3;
4000 break;
4001
4002 case 0xf8 ... 0xfb:
4003 if (len < 5) {
4004 *c = *p;
4005 return UTF8_CODE_BADSEQ | 1;
4006 }
4007 *c = *p & 0x03;
4008 dec = 4;
4009 break;
4010
4011 case 0xfc ... 0xfd:
4012 if (len < 6) {
4013 *c = *p;
4014 return UTF8_CODE_BADSEQ | 1;
4015 }
4016 *c = *p & 0x01;
4017 dec = 5;
4018 break;
4019
4020 case 0xfe ... 0xff:
4021 default:
4022 *c = *p;
4023 return UTF8_CODE_BADSEQ | 1;
4024 }
4025
4026 p++;
4027
4028 while (dec > 0) {
4029
4030 /* need 0x10 for the 2 first bits */
4031 if ( ( *p & 0xc0 ) != 0x80 )
4032 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4033
4034 /* add data at char */
4035 *c = ( *c << 6 ) | ( *p & 0x3f );
4036
4037 dec--;
4038 p++;
4039 }
4040
4041 /* Check ovelong encoding.
4042 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4043 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4044 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4045 */
4046 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
4047 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4048 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4049 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4050 code |= UTF8_CODE_OVERLONG;
4051
4052 /* Check invalid UTF8 range. */
4053 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4054 (*c >= 0xfffe && *c <= 0xffff))
4055 code |= UTF8_CODE_INVRANGE;
4056
4057 return code | ((p-(unsigned char *)s)&0x0f);
4058 }
4059
4060 /* append a copy of string <str> (in a wordlist) at the end of the list <li>
4061 * On failure : return 0 and <err> filled with an error message.
4062 * The caller is responsible for freeing the <err> and <str> copy
4063 * memory area using free()
4064 */
list_append_word(struct list * li,const char * str,char ** err)4065 int list_append_word(struct list *li, const char *str, char **err)
4066 {
4067 struct wordlist *wl;
4068
4069 wl = calloc(1, sizeof(*wl));
4070 if (!wl) {
4071 memprintf(err, "out of memory");
4072 goto fail_wl;
4073 }
4074
4075 wl->s = strdup(str);
4076 if (!wl->s) {
4077 memprintf(err, "out of memory");
4078 goto fail_wl_s;
4079 }
4080
4081 LIST_ADDQ(li, &wl->list);
4082
4083 return 1;
4084
4085 fail_wl_s:
4086 free(wl->s);
4087 fail_wl:
4088 free(wl);
4089 return 0;
4090 }
4091
4092 /* indicates if a memory location may safely be read or not. The trick consists
4093 * in performing a harmless syscall using this location as an input and letting
4094 * the operating system report whether it's OK or not. For this we have the
4095 * stat() syscall, which will return EFAULT when the memory location supposed
4096 * to contain the file name is not readable. If it is readable it will then
4097 * either return 0 if the area contains an existing file name, or -1 with
4098 * another code. This must not be abused, and some audit systems might detect
4099 * this as abnormal activity. It's used only for unsafe dumps.
4100 */
may_access(const void * ptr)4101 int may_access(const void *ptr)
4102 {
4103 struct stat buf;
4104
4105 if (stat(ptr, &buf) == 0)
4106 return 1;
4107 if (errno == EFAULT)
4108 return 0;
4109 return 1;
4110 }
4111
4112 /* print a string of text buffer to <out>. The format is :
4113 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4114 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4115 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4116 */
dump_text(struct buffer * out,const char * buf,int bsize)4117 int dump_text(struct buffer *out, const char *buf, int bsize)
4118 {
4119 unsigned char c;
4120 int ptr = 0;
4121
4122 while (buf[ptr] && ptr < bsize) {
4123 c = buf[ptr];
4124 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
4125 if (out->data > out->size - 1)
4126 break;
4127 out->area[out->data++] = c;
4128 }
4129 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
4130 if (out->data > out->size - 2)
4131 break;
4132 out->area[out->data++] = '\\';
4133 switch (c) {
4134 case ' ': c = ' '; break;
4135 case '\t': c = 't'; break;
4136 case '\n': c = 'n'; break;
4137 case '\r': c = 'r'; break;
4138 case '\e': c = 'e'; break;
4139 case '\\': c = '\\'; break;
4140 case '=': c = '='; break;
4141 }
4142 out->area[out->data++] = c;
4143 }
4144 else {
4145 if (out->data > out->size - 4)
4146 break;
4147 out->area[out->data++] = '\\';
4148 out->area[out->data++] = 'x';
4149 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4150 out->area[out->data++] = hextab[c & 0xF];
4151 }
4152 ptr++;
4153 }
4154
4155 return ptr;
4156 }
4157
4158 /* print a buffer in hexa.
4159 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4160 */
dump_binary(struct buffer * out,const char * buf,int bsize)4161 int dump_binary(struct buffer *out, const char *buf, int bsize)
4162 {
4163 unsigned char c;
4164 int ptr = 0;
4165
4166 while (ptr < bsize) {
4167 c = buf[ptr];
4168
4169 if (out->data > out->size - 2)
4170 break;
4171 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4172 out->area[out->data++] = hextab[c & 0xF];
4173
4174 ptr++;
4175 }
4176 return ptr;
4177 }
4178
4179 /* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4180 * prepending each line with prefix <pfx>. The output is *not* initialized.
4181 * The output will not wrap pas the buffer's end so it is more optimal if the
4182 * caller makes sure the buffer is aligned first. A trailing zero will always
4183 * be appended (and not counted) if there is room for it. The caller must make
4184 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4185 * locations are checked first for being readable.
4186 */
dump_hex(struct buffer * out,const char * pfx,const void * buf,int len,int unsafe)4187 void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
4188 {
4189 const unsigned char *d = buf;
4190 int i, j, start;
4191
4192 d = (const unsigned char *)(((unsigned long)buf) & -16);
4193 start = ((unsigned long)buf) & 15;
4194
4195 for (i = 0; i < start + len; i += 16) {
4196 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4197
4198 // 0: unchecked, 1: checked safe, 2: danger
4199 unsafe = !!unsafe;
4200 if (unsafe && !may_access(d + i))
4201 unsafe = 2;
4202
4203 for (j = 0; j < 16; j++) {
4204 if ((i + j < start) || (i + j >= start + len))
4205 chunk_strcat(out, "'' ");
4206 else if (unsafe > 1)
4207 chunk_strcat(out, "** ");
4208 else
4209 chunk_appendf(out, "%02x ", d[i + j]);
4210
4211 if (j == 7)
4212 chunk_strcat(out, "- ");
4213 }
4214 chunk_strcat(out, " ");
4215 for (j = 0; j < 16; j++) {
4216 if ((i + j < start) || (i + j >= start + len))
4217 chunk_strcat(out, "'");
4218 else if (unsafe > 1)
4219 chunk_strcat(out, "*");
4220 else if (isprint(d[i + j]))
4221 chunk_appendf(out, "%c", d[i + j]);
4222 else
4223 chunk_strcat(out, ".");
4224 }
4225 chunk_strcat(out, "\n");
4226 }
4227 }
4228
4229 /* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4230 * enclosed in brackets after the address itself, formatted on 14 chars
4231 * including the "0x" prefix. This is meant to be used as a prefix for code
4232 * areas. For example:
4233 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4234 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4235 * is emitted. A NULL <pfx> will be considered empty.
4236 */
dump_addr_and_bytes(struct buffer * buf,const char * pfx,const void * addr,int n)4237 void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4238 {
4239 int ok = 0;
4240 int i;
4241
4242 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4243
4244 for (i = 0; i < n; i++) {
4245 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4246 ok = may_access(addr + i);
4247 if (ok)
4248 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4249 else
4250 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4251 }
4252 }
4253
4254 /* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4255 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4256 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4257 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4258 * lines are respected within the limit of 70 output chars. Lines that are
4259 * continuation of a previous truncated line begin with "+" instead of " "
4260 * after the offset. The new pointer is returned.
4261 */
dump_text_line(struct buffer * out,const char * buf,int bsize,int len,int * line,int ptr)4262 int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
4263 int *line, int ptr)
4264 {
4265 int end;
4266 unsigned char c;
4267
4268 end = out->data + 80;
4269 if (end > out->size)
4270 return ptr;
4271
4272 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4273
4274 while (ptr < len && ptr < bsize) {
4275 c = buf[ptr];
4276 if (isprint(c) && isascii(c) && c != '\\') {
4277 if (out->data > end - 2)
4278 break;
4279 out->area[out->data++] = c;
4280 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
4281 if (out->data > end - 3)
4282 break;
4283 out->area[out->data++] = '\\';
4284 switch (c) {
4285 case '\t': c = 't'; break;
4286 case '\n': c = 'n'; break;
4287 case '\r': c = 'r'; break;
4288 case '\e': c = 'e'; break;
4289 case '\\': c = '\\'; break;
4290 }
4291 out->area[out->data++] = c;
4292 } else {
4293 if (out->data > end - 5)
4294 break;
4295 out->area[out->data++] = '\\';
4296 out->area[out->data++] = 'x';
4297 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4298 out->area[out->data++] = hextab[c & 0xF];
4299 }
4300 if (buf[ptr++] == '\n') {
4301 /* we had a line break, let's return now */
4302 out->area[out->data++] = '\n';
4303 *line = ptr;
4304 return ptr;
4305 }
4306 }
4307 /* we have an incomplete line, we return it as-is */
4308 out->area[out->data++] = '\n';
4309 return ptr;
4310 }
4311
4312 /* displays a <len> long memory block at <buf>, assuming first byte of <buf>
4313 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4314 * each line. It may be NULL if unused. The output is emitted to file <out>.
4315 */
debug_hexdump(FILE * out,const char * pfx,const char * buf,unsigned int baseaddr,int len)4316 void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4317 unsigned int baseaddr, int len)
4318 {
4319 unsigned int i;
4320 int b, j;
4321
4322 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4323 b = i - (baseaddr & 15);
4324 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
4325 for (j = 0; j < 8; j++) {
4326 if (b + j >= 0 && b + j < len)
4327 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4328 else
4329 fprintf(out, " ");
4330 }
4331
4332 if (b + j >= 0 && b + j < len)
4333 fputc('-', out);
4334 else
4335 fputc(' ', out);
4336
4337 for (j = 8; j < 16; j++) {
4338 if (b + j >= 0 && b + j < len)
4339 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4340 else
4341 fprintf(out, " ");
4342 }
4343
4344 fprintf(out, " ");
4345 for (j = 0; j < 16; j++) {
4346 if (b + j >= 0 && b + j < len) {
4347 if (isprint((unsigned char)buf[b + j]))
4348 fputc((unsigned char)buf[b + j], out);
4349 else
4350 fputc('.', out);
4351 }
4352 else
4353 fputc(' ', out);
4354 }
4355 fputc('\n', out);
4356 }
4357 }
4358
4359 #if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
4360 /* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4361 * also returns the symbol size in <size>, otherwise returns 0 there.
4362 */
dladdr_and_size(const void * addr,Dl_info * dli,size_t * size)4363 static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4364 {
4365 int ret;
4366 #if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
4367 const ElfW(Sym) *sym;
4368
4369 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4370 if (ret)
4371 *size = sym ? sym->st_size : 0;
4372 #else
4373 ret = dladdr(addr, dli);
4374 *size = 0;
4375 #endif
4376 return ret;
4377 }
4378 #endif
4379
4380 /* Tries to append to buffer <buf> some indications about the symbol at address
4381 * <addr> using the following form:
4382 * lib:+0xoffset (unresolvable address from lib's base)
4383 * main+0xoffset (unresolvable address from main (+/-))
4384 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4385 * name (resolved exact exec address)
4386 * lib:name (resolved exact lib address)
4387 * name+0xoffset/0xsize (resolved address within exec symbol)
4388 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4389 *
4390 * The file name (lib or executable) is limited to what lies between the last
4391 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4392 * the output if not null. The file is not dumped when it's the same as the one
4393 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
4394 *
4395 * The symbol's base address is returned, or NULL when unresolved, in order to
4396 * allow the caller to match it against known ones.
4397 */
resolve_sym_name(struct buffer * buf,const char * pfx,void * addr)4398 void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
4399 {
4400 const struct {
4401 const void *func;
4402 const char *name;
4403 } fcts[] = {
4404 { .func = process_stream, .name = "process_stream" },
4405 { .func = task_run_applet, .name = "task_run_applet" },
4406 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4407 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4408 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4409 { .func = listener_accept, .name = "listener_accept" },
4410 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4411 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4412 #ifdef USE_LUA
4413 { .func = hlua_process_task, .name = "hlua_process_task" },
4414 #endif
4415 #if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4416 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4417 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4418 #endif
4419 };
4420
4421 #if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
4422 Dl_info dli, dli_main;
4423 size_t size;
4424 const char *fname, *p;
4425 #endif
4426 int i;
4427
4428 if (pfx)
4429 chunk_appendf(buf, "%s", pfx);
4430
4431 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4432 if (addr == fcts[i].func) {
4433 chunk_appendf(buf, "%s", fcts[i].name);
4434 return addr;
4435 }
4436 }
4437
4438 #if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
4439 /* Now let's try to be smarter */
4440 if (!dladdr_and_size(addr, &dli, &size))
4441 goto unknown;
4442
4443 /* 1. prefix the library name if it's not the same object as the one
4444 * that contains the main function. The name is picked between last '/'
4445 * and first following '.'.
4446 */
4447 if (!dladdr(main, &dli_main))
4448 dli_main.dli_fbase = NULL;
4449
4450 if (dli_main.dli_fbase != dli.dli_fbase) {
4451 fname = dli.dli_fname;
4452 p = strrchr(fname, '/');
4453 if (p++)
4454 fname = p;
4455 p = strchr(fname, '.');
4456 if (!p)
4457 p = fname + strlen(fname);
4458
4459 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4460 }
4461
4462 /* 2. symbol name */
4463 if (dli.dli_sname) {
4464 /* known, dump it and return symbol's address (exact or relative) */
4465 chunk_appendf(buf, "%s", dli.dli_sname);
4466 if (addr != dli.dli_saddr) {
4467 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
4468 if (size)
4469 chunk_appendf(buf, "/%#lx", (long)size);
4470 }
4471 return dli.dli_saddr;
4472 }
4473 else if (dli_main.dli_fbase != dli.dli_fbase) {
4474 /* unresolved symbol from a known library, report relative offset */
4475 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4476 return NULL;
4477 }
4478 #endif /* __ELF__ && !__linux__ || USE_DL */
4479 unknown:
4480 /* unresolved symbol from the main file, report relative offset to main */
4481 if ((void*)addr < (void*)main)
4482 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4483 else
4484 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4485 return NULL;
4486 }
4487
4488 /*
4489 * Allocate an array of unsigned int with <nums> as address from <str> string
4490 * made of integer sepereated by dot characters.
4491 *
4492 * First, initializes the value with <sz> as address to 0 and initializes the
4493 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4494 * address updating <sz> pointed value to the size of this array.
4495 *
4496 * Returns 1 if succeeded, 0 if not.
4497 */
parse_dotted_uints(const char * str,unsigned int ** nums,size_t * sz)4498 int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4499 {
4500 unsigned int *n;
4501 const char *s, *end;
4502
4503 s = str;
4504 *sz = 0;
4505 end = str + strlen(str);
4506 *nums = n = NULL;
4507
4508 while (1) {
4509 unsigned int r;
4510
4511 if (s >= end)
4512 break;
4513
4514 r = read_uint(&s, end);
4515 /* Expected characters after having read an uint: '\0' or '.',
4516 * if '.', must not be terminal.
4517 */
4518 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4519 free(n);
4520 return 0;
4521 }
4522
4523 n = my_realloc2(n, (*sz + 1) * sizeof *n);
4524 if (!n)
4525 return 0;
4526
4527 n[(*sz)++] = r;
4528 }
4529 *nums = n;
4530
4531 return 1;
4532 }
4533
4534
4535 /* returns the number of bytes needed to encode <v> as a varint. An inline
4536 * version exists for use with constants (__varint_bytes()).
4537 */
varint_bytes(uint64_t v)4538 int varint_bytes(uint64_t v)
4539 {
4540 int len = 1;
4541
4542 if (v >= 240) {
4543 v = (v - 240) >> 4;
4544 while (1) {
4545 len++;
4546 if (v < 128)
4547 break;
4548 v = (v - 128) >> 7;
4549 }
4550 }
4551 return len;
4552 }
4553
4554 /* Random number generator state, see below */
4555 static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
4556
4557 /* This is a thread-safe implementation of xoroshiro128** described below:
4558 * http://prng.di.unimi.it/
4559 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4560 * supports fast jumps and passes all common quality tests. It is thread-safe,
4561 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4562 * local lock on other ones.
4563 */
ha_random64()4564 uint64_t ha_random64()
4565 {
4566 uint64_t result;
4567 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4568 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
4569
4570 #if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4571 static HA_SPINLOCK_T rand_lock;
4572
4573 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4574 #endif
4575
4576 old[0] = ha_random_state[0];
4577 old[1] = ha_random_state[1];
4578
4579 #if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4580 do {
4581 #endif
4582 result = rotl64(old[0] * 5, 7) * 9;
4583 new[1] = old[0] ^ old[1];
4584 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4585 new[1] = rotl64(new[1], 37); // c
4586
4587 #if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4588 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4589 #else
4590 ha_random_state[0] = new[0];
4591 ha_random_state[1] = new[1];
4592 #if defined(USE_THREAD)
4593 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4594 #endif
4595 #endif
4596 return result;
4597 }
4598
4599 /* seeds the random state using up to <len> bytes from <seed>, starting with
4600 * the first non-zero byte.
4601 */
ha_random_seed(const unsigned char * seed,size_t len)4602 void ha_random_seed(const unsigned char *seed, size_t len)
4603 {
4604 size_t pos;
4605
4606 /* the seed must not be all zeroes, so we pre-fill it with alternating
4607 * bits and overwrite part of them with the block starting at the first
4608 * non-zero byte from the seed.
4609 */
4610 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4611
4612 for (pos = 0; pos < len; pos++)
4613 if (seed[pos] != 0)
4614 break;
4615
4616 if (pos == len)
4617 return;
4618
4619 seed += pos;
4620 len -= pos;
4621
4622 if (len > sizeof(ha_random_state))
4623 len = sizeof(ha_random_state);
4624
4625 memcpy(ha_random_state, seed, len);
4626 }
4627
4628 /* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4629 * and is equivalent to calling ha_random64() as many times. It is used to
4630 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4631 * different generators (i.e. different processes after a fork). The <dist>
4632 * argument is the distance to jump to and is used in a loop so it rather not
4633 * be too large if the processing time is a concern.
4634 *
4635 * BEWARE: this function is NOT thread-safe and must not be called during
4636 * concurrent accesses to ha_random64().
4637 */
ha_random_jump96(uint32_t dist)4638 void ha_random_jump96(uint32_t dist)
4639 {
4640 while (dist--) {
4641 uint64_t s0 = 0;
4642 uint64_t s1 = 0;
4643 int b;
4644
4645 for (b = 0; b < 64; b++) {
4646 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4647 s0 ^= ha_random_state[0];
4648 s1 ^= ha_random_state[1];
4649 }
4650 ha_random64();
4651 }
4652
4653 for (b = 0; b < 64; b++) {
4654 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4655 s0 ^= ha_random_state[0];
4656 s1 ^= ha_random_state[1];
4657 }
4658 ha_random64();
4659 }
4660 ha_random_state[0] = s0;
4661 ha_random_state[1] = s1;
4662 }
4663 }
4664
4665 /*
4666 * Local variables:
4667 * c-indent-level: 8
4668 * c-basic-offset: 8
4669 * End:
4670 */
4671