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