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