blob: 33067bb73a51be7292aea20ad6bd521446f4e62e [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
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
Willy Tarreau109201f2020-03-04 10:31:58 +010013#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
Willy Tarreaubb869862020-04-16 10:52:41 +020019#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
20#include <sys/auxv.h>
21#endif
22
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010023#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020024#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020025#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020026#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020027#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020028#include <stdlib.h>
29#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010030#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010032#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020033#include <sys/stat.h>
34#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010035#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020036#include <netinet/in.h>
37#include <arpa/inet.h>
38
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010039#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020040#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020041#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010042#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010043#include <types/global.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010044#include <proto/applet.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020045#include <proto/dns.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010046#include <proto/hlua.h>
47#include <proto/listener.h>
48#include <proto/proto_udp.h>
49#include <proto/ssl_sock.h>
50#include <proto/stream_interface.h>
51#include <proto/task.h>
52
Willy Tarreau8d2b7772020-05-27 10:58:19 +020053#include <import/eb32tree.h>
54#include <import/eb32sctree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020055
Thierry Fournier93127942016-01-20 18:49:45 +010056/* This macro returns false if the test __x is false. Many
57 * of the following parsing function must be abort the processing
58 * if it returns 0, so this macro is useful for writing light code.
59 */
60#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
61
Willy Tarreau56adcf22012-12-23 18:00:29 +010062/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020063 * 2^64-1 = 18446744073709551615 or
64 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020065 *
66 * The HTML version needs room for adding the 25 characters
67 * '<span class="rls"></span>' around digits at positions 3N+1 in order
68 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020069 */
Christopher Faulet99bca652017-11-14 16:47:26 +010070THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
71THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020072
Willy Tarreau588297f2014-06-16 15:16:40 +020073/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
74 * to quote strings larger than a max configuration line.
75 */
Christopher Faulet99bca652017-11-14 16:47:26 +010076THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
77THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020078
Willy Tarreaubaaee002006-06-26 02:48:02 +020079/*
William Lallemande7340ec2012-01-24 11:15:39 +010080 * unsigned long long ASCII representation
81 *
82 * return the last char '\0' or NULL if no enough
83 * space in dst
84 */
85char *ulltoa(unsigned long long n, char *dst, size_t size)
86{
87 int i = 0;
88 char *res;
89
90 switch(n) {
91 case 1ULL ... 9ULL:
92 i = 0;
93 break;
94
95 case 10ULL ... 99ULL:
96 i = 1;
97 break;
98
99 case 100ULL ... 999ULL:
100 i = 2;
101 break;
102
103 case 1000ULL ... 9999ULL:
104 i = 3;
105 break;
106
107 case 10000ULL ... 99999ULL:
108 i = 4;
109 break;
110
111 case 100000ULL ... 999999ULL:
112 i = 5;
113 break;
114
115 case 1000000ULL ... 9999999ULL:
116 i = 6;
117 break;
118
119 case 10000000ULL ... 99999999ULL:
120 i = 7;
121 break;
122
123 case 100000000ULL ... 999999999ULL:
124 i = 8;
125 break;
126
127 case 1000000000ULL ... 9999999999ULL:
128 i = 9;
129 break;
130
131 case 10000000000ULL ... 99999999999ULL:
132 i = 10;
133 break;
134
135 case 100000000000ULL ... 999999999999ULL:
136 i = 11;
137 break;
138
139 case 1000000000000ULL ... 9999999999999ULL:
140 i = 12;
141 break;
142
143 case 10000000000000ULL ... 99999999999999ULL:
144 i = 13;
145 break;
146
147 case 100000000000000ULL ... 999999999999999ULL:
148 i = 14;
149 break;
150
151 case 1000000000000000ULL ... 9999999999999999ULL:
152 i = 15;
153 break;
154
155 case 10000000000000000ULL ... 99999999999999999ULL:
156 i = 16;
157 break;
158
159 case 100000000000000000ULL ... 999999999999999999ULL:
160 i = 17;
161 break;
162
163 case 1000000000000000000ULL ... 9999999999999999999ULL:
164 i = 18;
165 break;
166
167 case 10000000000000000000ULL ... ULLONG_MAX:
168 i = 19;
169 break;
170 }
171 if (i + 2 > size) // (i + 1) + '\0'
172 return NULL; // too long
173 res = dst + i + 1;
174 *res = '\0';
175 for (; i >= 0; i--) {
176 dst[i] = n % 10ULL + '0';
177 n /= 10ULL;
178 }
179 return res;
180}
181
182/*
183 * unsigned long ASCII representation
184 *
185 * return the last char '\0' or NULL if no enough
186 * space in dst
187 */
188char *ultoa_o(unsigned long n, char *dst, size_t size)
189{
190 int i = 0;
191 char *res;
192
193 switch (n) {
194 case 0U ... 9UL:
195 i = 0;
196 break;
197
198 case 10U ... 99UL:
199 i = 1;
200 break;
201
202 case 100U ... 999UL:
203 i = 2;
204 break;
205
206 case 1000U ... 9999UL:
207 i = 3;
208 break;
209
210 case 10000U ... 99999UL:
211 i = 4;
212 break;
213
214 case 100000U ... 999999UL:
215 i = 5;
216 break;
217
218 case 1000000U ... 9999999UL:
219 i = 6;
220 break;
221
222 case 10000000U ... 99999999UL:
223 i = 7;
224 break;
225
226 case 100000000U ... 999999999UL:
227 i = 8;
228 break;
229#if __WORDSIZE == 32
230
231 case 1000000000ULL ... ULONG_MAX:
232 i = 9;
233 break;
234
235#elif __WORDSIZE == 64
236
237 case 1000000000ULL ... 9999999999UL:
238 i = 9;
239 break;
240
241 case 10000000000ULL ... 99999999999UL:
242 i = 10;
243 break;
244
245 case 100000000000ULL ... 999999999999UL:
246 i = 11;
247 break;
248
249 case 1000000000000ULL ... 9999999999999UL:
250 i = 12;
251 break;
252
253 case 10000000000000ULL ... 99999999999999UL:
254 i = 13;
255 break;
256
257 case 100000000000000ULL ... 999999999999999UL:
258 i = 14;
259 break;
260
261 case 1000000000000000ULL ... 9999999999999999UL:
262 i = 15;
263 break;
264
265 case 10000000000000000ULL ... 99999999999999999UL:
266 i = 16;
267 break;
268
269 case 100000000000000000ULL ... 999999999999999999UL:
270 i = 17;
271 break;
272
273 case 1000000000000000000ULL ... 9999999999999999999UL:
274 i = 18;
275 break;
276
277 case 10000000000000000000ULL ... ULONG_MAX:
278 i = 19;
279 break;
280
281#endif
282 }
283 if (i + 2 > size) // (i + 1) + '\0'
284 return NULL; // too long
285 res = dst + i + 1;
286 *res = '\0';
287 for (; i >= 0; i--) {
288 dst[i] = n % 10U + '0';
289 n /= 10U;
290 }
291 return res;
292}
293
294/*
295 * signed long ASCII representation
296 *
297 * return the last char '\0' or NULL if no enough
298 * space in dst
299 */
300char *ltoa_o(long int n, char *dst, size_t size)
301{
302 char *pos = dst;
303
304 if (n < 0) {
305 if (size < 3)
306 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
307 *pos = '-';
308 pos++;
309 dst = ultoa_o(-n, pos, size - 1);
310 } else {
311 dst = ultoa_o(n, dst, size);
312 }
313 return dst;
314}
315
316/*
317 * signed long long ASCII representation
318 *
319 * return the last char '\0' or NULL if no enough
320 * space in dst
321 */
322char *lltoa(long long n, char *dst, size_t size)
323{
324 char *pos = dst;
325
326 if (n < 0) {
327 if (size < 3)
328 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
329 *pos = '-';
330 pos++;
331 dst = ulltoa(-n, pos, size - 1);
332 } else {
333 dst = ulltoa(n, dst, size);
334 }
335 return dst;
336}
337
338/*
339 * write a ascii representation of a unsigned into dst,
340 * return a pointer to the last character
341 * Pad the ascii representation with '0', using size.
342 */
343char *utoa_pad(unsigned int n, char *dst, size_t size)
344{
345 int i = 0;
346 char *ret;
347
348 switch(n) {
349 case 0U ... 9U:
350 i = 0;
351 break;
352
353 case 10U ... 99U:
354 i = 1;
355 break;
356
357 case 100U ... 999U:
358 i = 2;
359 break;
360
361 case 1000U ... 9999U:
362 i = 3;
363 break;
364
365 case 10000U ... 99999U:
366 i = 4;
367 break;
368
369 case 100000U ... 999999U:
370 i = 5;
371 break;
372
373 case 1000000U ... 9999999U:
374 i = 6;
375 break;
376
377 case 10000000U ... 99999999U:
378 i = 7;
379 break;
380
381 case 100000000U ... 999999999U:
382 i = 8;
383 break;
384
385 case 1000000000U ... 4294967295U:
386 i = 9;
387 break;
388 }
389 if (i + 2 > size) // (i + 1) + '\0'
390 return NULL; // too long
391 if (i < size)
392 i = size - 2; // padding - '\0'
393
394 ret = dst + i + 1;
395 *ret = '\0';
396 for (; i >= 0; i--) {
397 dst[i] = n % 10U + '0';
398 n /= 10U;
399 }
400 return ret;
401}
402
403/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404 * copies at most <size-1> chars from <src> to <dst>. Last char is always
405 * set to 0, unless <size> is 0. The number of chars copied is returned
406 * (excluding the terminating zero).
407 * This code has been optimized for size and speed : on x86, it's 45 bytes
408 * long, uses only registers, and consumes only 4 cycles per char.
409 */
410int strlcpy2(char *dst, const char *src, int size)
411{
412 char *orig = dst;
413 if (size) {
414 while (--size && (*dst = *src)) {
415 src++; dst++;
416 }
417 *dst = 0;
418 }
419 return dst - orig;
420}
421
422/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200423 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200424 * the ascii representation for number 'n' in decimal.
425 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100426char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200427{
428 char *pos;
429
Willy Tarreau72d759c2007-10-25 12:14:10 +0200430 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200431 *pos-- = '\0';
432
433 do {
434 *pos-- = '0' + n % 10;
435 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200436 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200437 return pos + 1;
438}
439
Willy Tarreau91092e52007-10-25 16:58:42 +0200440/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200441 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200442 * the ascii representation for number 'n' in decimal.
443 */
444char *lltoa_r(long long int in, char *buffer, int size)
445{
446 char *pos;
447 int neg = 0;
448 unsigned long long int n;
449
450 pos = buffer + size - 1;
451 *pos-- = '\0';
452
453 if (in < 0) {
454 neg = 1;
455 n = -in;
456 }
457 else
458 n = in;
459
460 do {
461 *pos-- = '0' + n % 10;
462 n /= 10;
463 } while (n && pos >= buffer);
464 if (neg && pos > buffer)
465 *pos-- = '-';
466 return pos + 1;
467}
468
469/*
470 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200471 * the ascii representation for signed number 'n' in decimal.
472 */
473char *sltoa_r(long n, char *buffer, int size)
474{
475 char *pos;
476
477 if (n >= 0)
478 return ultoa_r(n, buffer, size);
479
480 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
481 *pos = '-';
482 return pos;
483}
484
485/*
486 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200487 * the ascii representation for number 'n' in decimal, formatted for
488 * HTML output with tags to create visual grouping by 3 digits. The
489 * output needs to support at least 171 characters.
490 */
491const char *ulltoh_r(unsigned long long n, char *buffer, int size)
492{
493 char *start;
494 int digit = 0;
495
496 start = buffer + size;
497 *--start = '\0';
498
499 do {
500 if (digit == 3 && start >= buffer + 7)
501 memcpy(start -= 7, "</span>", 7);
502
503 if (start >= buffer + 1) {
504 *--start = '0' + n % 10;
505 n /= 10;
506 }
507
508 if (digit == 3 && start >= buffer + 18)
509 memcpy(start -= 18, "<span class=\"rls\">", 18);
510
511 if (digit++ == 3)
512 digit = 1;
513 } while (n && start > buffer);
514 return start;
515}
516
517/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200518 * This function simply returns a locally allocated string containing the ascii
519 * representation for number 'n' in decimal, unless n is 0 in which case it
520 * returns the alternate string (or an empty string if the alternate string is
521 * NULL). It use is intended for limits reported in reports, where it's
522 * desirable not to display anything if there is no limit. Warning! it shares
523 * the same vector as ultoa_r().
524 */
525const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
526{
527 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
528}
529
Willy Tarreau588297f2014-06-16 15:16:40 +0200530/* returns a locally allocated string containing the quoted encoding of the
531 * input string. The output may be truncated to QSTR_SIZE chars, but it is
532 * guaranteed that the string will always be properly terminated. Quotes are
533 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
534 * always be at least 4 chars.
535 */
536const char *qstr(const char *str)
537{
538 char *ret = quoted_str[quoted_idx];
539 char *p, *end;
540
541 if (++quoted_idx >= NB_QSTR)
542 quoted_idx = 0;
543
544 p = ret;
545 end = ret + QSTR_SIZE;
546
547 *p++ = '"';
548
549 /* always keep 3 chars to support passing "" and the ending " */
550 while (*str && p < end - 3) {
551 if (*str == '"') {
552 *p++ = '"';
553 *p++ = '"';
554 }
555 else
556 *p++ = *str;
557 str++;
558 }
559 *p++ = '"';
560 return ret;
561}
562
Robert Tsai81ae1952007-12-05 10:47:29 +0100563/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200564 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
565 *
566 * It looks like this one would be a good candidate for inlining, but this is
567 * not interesting because it around 35 bytes long and often called multiple
568 * times within the same function.
569 */
570int ishex(char s)
571{
572 s -= '0';
573 if ((unsigned char)s <= 9)
574 return 1;
575 s -= 'A' - '0';
576 if ((unsigned char)s <= 5)
577 return 1;
578 s -= 'a' - 'A';
579 if ((unsigned char)s <= 5)
580 return 1;
581 return 0;
582}
583
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100584/* rounds <i> down to the closest value having max 2 digits */
585unsigned int round_2dig(unsigned int i)
586{
587 unsigned int mul = 1;
588
589 while (i >= 100) {
590 i /= 10;
591 mul *= 10;
592 }
593 return i * mul;
594}
595
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100596/*
597 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
598 * invalid character is found, a pointer to it is returned. If everything is
599 * fine, NULL is returned.
600 */
601const char *invalid_char(const char *name)
602{
603 if (!*name)
604 return name;
605
606 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100607 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100608 *name != '_' && *name != '-')
609 return name;
610 name++;
611 }
612 return NULL;
613}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200614
615/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200616 * Checks <name> for invalid characters. Valid chars are [_.-] and those
617 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200618 * If an invalid character is found, a pointer to it is returned.
619 * If everything is fine, NULL is returned.
620 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200621static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200622
623 if (!*name)
624 return name;
625
626 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100627 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200628 *name != '_' && *name != '-')
629 return name;
630
631 name++;
632 }
633
634 return NULL;
635}
636
637/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200638 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
639 * If an invalid character is found, a pointer to it is returned.
640 * If everything is fine, NULL is returned.
641 */
642const char *invalid_domainchar(const char *name) {
643 return __invalid_char(name, isalnum);
644}
645
646/*
647 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
648 * If an invalid character is found, a pointer to it is returned.
649 * If everything is fine, NULL is returned.
650 */
651const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200652 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200653}
654
655/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100656 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100657 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
658 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
659 * the function tries to guess the address family from the syntax. If the
660 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100661 * string is assumed to contain only an address, no port. The address can be a
662 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
663 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
664 * The return address will only have the address family and the address set,
665 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100666 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
667 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100668 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200669 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100670struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200671{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100672 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100673 /* max IPv6 length, including brackets and terminating NULL */
674 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100675 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100676
677 /* check IPv6 with square brackets */
678 if (str[0] == '[') {
679 size_t iplength = strlen(str);
680
681 if (iplength < 4) {
682 /* minimal size is 4 when using brackets "[::]" */
683 goto fail;
684 }
685 else if (iplength >= sizeof(tmpip)) {
686 /* IPv6 literal can not be larger than tmpip */
687 goto fail;
688 }
689 else {
690 if (str[iplength - 1] != ']') {
691 /* if address started with bracket, it should end with bracket */
692 goto fail;
693 }
694 else {
695 memcpy(tmpip, str + 1, iplength - 2);
696 tmpip[iplength - 2] = '\0';
697 str = tmpip;
698 }
699 }
700 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100701
Willy Tarreaufab5a432011-03-04 15:31:53 +0100702 /* Any IPv6 address */
703 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100704 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
705 sa->ss_family = AF_INET6;
706 else if (sa->ss_family != AF_INET6)
707 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100708 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100709 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100710 }
711
Willy Tarreau24709282013-03-10 21:32:12 +0100712 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100713 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100714 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
715 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100716 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100717 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100718 }
719
720 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100721 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
722 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100723 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100724 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100726 }
727
728 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100729 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
730 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100731 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100732 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100733 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100734 }
735
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100736 if (!resolve)
737 return NULL;
738
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200739 if (!dns_hostname_validation(str, NULL))
740 return NULL;
741
David du Colombierd5f43282011-03-17 10:40:16 +0100742#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200743 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100744 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100745 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100746
747 memset(&result, 0, sizeof(result));
748 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100749 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100750 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200751 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100752 hints.ai_protocol = 0;
753
754 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100755 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
756 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100757 else if (sa->ss_family != result->ai_family) {
758 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100759 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100760 }
Willy Tarreau24709282013-03-10 21:32:12 +0100761
David du Colombierd5f43282011-03-17 10:40:16 +0100762 switch (result->ai_family) {
763 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100764 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100765 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100766 success = 1;
767 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100768 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100769 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100770 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100771 success = 1;
772 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100773 }
774 }
775
Sean Carey58ea0392013-02-15 23:39:18 +0100776 if (result)
777 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100778
779 if (success)
780 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100781 }
David du Colombierd5f43282011-03-17 10:40:16 +0100782#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200783 /* try to resolve an IPv4/IPv6 hostname */
784 he = gethostbyname(str);
785 if (he) {
786 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
787 sa->ss_family = he->h_addrtype;
788 else if (sa->ss_family != he->h_addrtype)
789 goto fail;
790
791 switch (sa->ss_family) {
792 case AF_INET:
793 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100794 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200795 return sa;
796 case AF_INET6:
797 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100798 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200799 return sa;
800 }
801 }
802
David du Colombierd5f43282011-03-17 10:40:16 +0100803 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100804 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100805 return NULL;
806}
807
808/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100809 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
810 * range or offset consisting in two integers that the caller will have to
811 * check to find the relevant input format. The following format are supported :
812 *
813 * String format | address | port | low | high
814 * addr | <addr> | 0 | 0 | 0
815 * addr: | <addr> | 0 | 0 | 0
816 * addr:port | <addr> | <port> | <port> | <port>
817 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
818 * addr:+port | <addr> | <port> | 0 | <port>
819 * addr:-port | <addr> |-<port> | <port> | 0
820 *
821 * The detection of a port range or increment by the caller is made by
822 * comparing <low> and <high>. If both are equal, then port 0 means no port
823 * was specified. The caller may pass NULL for <low> and <high> if it is not
824 * interested in retrieving port ranges.
825 *
826 * Note that <addr> above may also be :
827 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
828 * - "*" => family will be AF_INET and address will be INADDR_ANY
829 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
830 * - a host name => family and address will depend on host name resolving.
831 *
Willy Tarreau24709282013-03-10 21:32:12 +0100832 * A prefix may be passed in before the address above to force the family :
833 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
834 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
835 * - "unix@" => force address to be a path to a UNIX socket even if the
836 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200837 * - 'abns@' -> force address to belong to the abstract namespace (Linux
838 * only). These sockets are just like Unix sockets but without
839 * the need for an underlying file system. The address is a
840 * string. Technically it's like a Unix socket with a zero in
841 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100842 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100843 *
mildisff5d5102015-10-26 18:50:08 +0100844 * IPv6 addresses can be declared with or without square brackets. When using
845 * square brackets for IPv6 addresses, the port separator (colon) is optional.
846 * If not using square brackets, and in order to avoid any ambiguity with
847 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
848 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
849 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100850 *
851 * If <pfx> is non-null, it is used as a string prefix before any path-based
852 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100853 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200854 * if <fqdn> is non-null, it will be filled with :
855 * - a pointer to the FQDN of the server name to resolve if there's one, and
856 * that the caller will have to free(),
857 * - NULL if there was an explicit address that doesn't require resolution.
858 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100859 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
860 * is null, <fqdn> is still honnored so it is possible for the caller to know
861 * whether a resolution failed by setting <resolve> to null and checking if
862 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200863 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100864 * When a file descriptor is passed, its value is put into the s_addr part of
865 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100866 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100867struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100868{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100869 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100870 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100871 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100872 char *port1, *port2;
873 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200874 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100875
876 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200877 if (fqdn)
878 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200879
Willy Tarreaudad36a32013-03-11 01:20:04 +0100880 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100881 if (str2 == NULL) {
882 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100883 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100884 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200885
Willy Tarreau9f69f462015-09-08 16:01:25 +0200886 if (!*str2) {
887 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
888 goto out;
889 }
890
Willy Tarreau24709282013-03-10 21:32:12 +0100891 memset(&ss, 0, sizeof(ss));
892
893 if (strncmp(str2, "unix@", 5) == 0) {
894 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200895 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100896 ss.ss_family = AF_UNIX;
897 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200898 else if (strncmp(str2, "abns@", 5) == 0) {
899 str2 += 5;
900 abstract = 1;
901 ss.ss_family = AF_UNIX;
902 }
Willy Tarreau24709282013-03-10 21:32:12 +0100903 else if (strncmp(str2, "ipv4@", 5) == 0) {
904 str2 += 5;
905 ss.ss_family = AF_INET;
906 }
907 else if (strncmp(str2, "ipv6@", 5) == 0) {
908 str2 += 5;
909 ss.ss_family = AF_INET6;
910 }
911 else if (*str2 == '/') {
912 ss.ss_family = AF_UNIX;
913 }
914 else
915 ss.ss_family = AF_UNSPEC;
916
William Lallemand2fe7dd02018-09-11 16:51:29 +0200917 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
918 char *endptr;
919
920 str2 += 9;
921
922 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100923 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200924
925 if (!*str2 || *endptr) {
926 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
927 goto out;
928 }
929
930 ss.ss_family = AF_CUST_SOCKPAIR;
931
932 }
933 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100934 char *endptr;
935
936 str2 += 3;
937 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100938 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100939
940 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100941 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100942 goto out;
943 }
944
945 /* we return AF_UNSPEC if we use a file descriptor number */
946 ss.ss_family = AF_UNSPEC;
947 }
948 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200949 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100950 int prefix_path_len;
951 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200952 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100953
954 /* complete unix socket path name during startup or soft-restart is
955 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
956 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200957 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +0200958 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +0100959 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +0100960
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200961 adr_len = strlen(str2);
962 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100963 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
964 goto out;
965 }
966
Willy Tarreauccfccef2014-05-10 01:49:15 +0200967 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +0200968 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200969 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +0200970 memcpy(un->sun_path, pfx, prefix_path_len);
971 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100972 }
Willy Tarreau24709282013-03-10 21:32:12 +0100973 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100974 char *end = str2 + strlen(str2);
975 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200976
mildisff5d5102015-10-26 18:50:08 +0100977 /* search for : or ] whatever comes first */
978 for (chr = end-1; chr > str2; chr--) {
979 if (*chr == ']' || *chr == ':')
980 break;
981 }
982
983 if (*chr == ':') {
984 /* Found a colon before a closing-bracket, must be a port separator.
985 * This guarantee backward compatibility.
986 */
987 *chr++ = '\0';
988 port1 = chr;
989 }
990 else {
991 /* Either no colon and no closing-bracket
992 * or directly ending with a closing-bracket.
993 * However, no port.
994 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100995 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100996 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200997
Willy Tarreau90807112020-02-25 08:16:33 +0100998 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100999 port2 = strchr(port1, '-');
1000 if (port2)
1001 *port2++ = '\0';
1002 else
1003 port2 = port1;
1004 portl = atoi(port1);
1005 porth = atoi(port2);
1006 porta = portl;
1007 }
1008 else if (*port1 == '-') { /* negative offset */
1009 portl = atoi(port1 + 1);
1010 porta = -portl;
1011 }
1012 else if (*port1 == '+') { /* positive offset */
1013 porth = atoi(port1 + 1);
1014 porta = porth;
1015 }
1016 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001017 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001018 goto out;
1019 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001020
1021 /* first try to parse the IP without resolving. If it fails, it
1022 * tells us we need to keep a copy of the FQDN to resolve later
1023 * and to enable DNS. In this case we can proceed if <fqdn> is
1024 * set or if resolve is set, otherwise it's an error.
1025 */
1026 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001027 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001028 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1029 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1030 goto out;
1031 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001032
Willy Tarreauceccdd72016-11-02 22:27:10 +01001033 if (fqdn) {
1034 if (str2 != back)
1035 memmove(back, str2, strlen(str2) + 1);
1036 *fqdn = back;
1037 back = NULL;
1038 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001039 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001040 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001041 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001042
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001043 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001044 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001045 if (port)
1046 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001047 if (low)
1048 *low = portl;
1049 if (high)
1050 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001051 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001052 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001053}
1054
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001055/* converts <str> to a struct in_addr containing a network mask. It can be
1056 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001057 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001058 */
1059int str2mask(const char *str, struct in_addr *mask)
1060{
1061 if (strchr(str, '.') != NULL) { /* dotted notation */
1062 if (!inet_pton(AF_INET, str, mask))
1063 return 0;
1064 }
1065 else { /* mask length */
1066 char *err;
1067 unsigned long len = strtol(str, &err, 10);
1068
1069 if (!*str || (err && *err) || (unsigned)len > 32)
1070 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001071
1072 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001073 }
1074 return 1;
1075}
1076
Tim Duesterhus47185172018-01-25 16:24:49 +01001077/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001078 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001079 * if the conversion succeeds otherwise zero.
1080 */
1081int str2mask6(const char *str, struct in6_addr *mask)
1082{
1083 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1084 if (!inet_pton(AF_INET6, str, mask))
1085 return 0;
1086 }
1087 else { /* mask length */
1088 char *err;
1089 unsigned long len = strtol(str, &err, 10);
1090
1091 if (!*str || (err && *err) || (unsigned)len > 128)
1092 return 0;
1093
1094 len2mask6(len, mask);
1095 }
1096 return 1;
1097}
1098
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001099/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1100 * succeeds otherwise zero.
1101 */
1102int cidr2dotted(int cidr, struct in_addr *mask) {
1103
1104 if (cidr < 0 || cidr > 32)
1105 return 0;
1106
1107 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1108 return 1;
1109}
1110
Thierry Fournier70473a52016-02-17 17:12:14 +01001111/* Convert mask from bit length form to in_addr form.
1112 * This function never fails.
1113 */
1114void len2mask4(int len, struct in_addr *addr)
1115{
1116 if (len >= 32) {
1117 addr->s_addr = 0xffffffff;
1118 return;
1119 }
1120 if (len <= 0) {
1121 addr->s_addr = 0x00000000;
1122 return;
1123 }
1124 addr->s_addr = 0xffffffff << (32 - len);
1125 addr->s_addr = htonl(addr->s_addr);
1126}
1127
1128/* Convert mask from bit length form to in6_addr form.
1129 * This function never fails.
1130 */
1131void len2mask6(int len, struct in6_addr *addr)
1132{
1133 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1134 len -= 32;
1135 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1136 len -= 32;
1137 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1138 len -= 32;
1139 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1140}
1141
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001142/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001143 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001144 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001145 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001146 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1147 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001148int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001149{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001150 __label__ out_free, out_err;
1151 char *c, *s;
1152 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001153
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001154 s = strdup(str);
1155 if (!s)
1156 return 0;
1157
Willy Tarreaubaaee002006-06-26 02:48:02 +02001158 memset(mask, 0, sizeof(*mask));
1159 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001160
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001161 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001162 *c++ = '\0';
1163 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001164 if (!str2mask(c, mask))
1165 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001166 }
1167 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001168 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001169 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001170 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001171 struct hostent *he;
1172
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001173 if (!resolve)
1174 goto out_err;
1175
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001176 if ((he = gethostbyname(s)) == NULL) {
1177 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001178 }
1179 else
1180 *addr = *(struct in_addr *) *(he->h_addr_list);
1181 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001182
1183 ret_val = 1;
1184 out_free:
1185 free(s);
1186 return ret_val;
1187 out_err:
1188 ret_val = 0;
1189 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001190}
1191
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001192
1193/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001194 * converts <str> to two struct in6_addr* which must be pre-allocated.
1195 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001196 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001197 * Returns 1 if OK, 0 if error.
1198 */
1199int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1200{
1201 char *c, *s;
1202 int ret_val = 0;
1203 char *err;
1204 unsigned long len = 128;
1205
1206 s = strdup(str);
1207 if (!s)
1208 return 0;
1209
1210 memset(mask, 0, sizeof(*mask));
1211 memset(addr, 0, sizeof(*addr));
1212
1213 if ((c = strrchr(s, '/')) != NULL) {
1214 *c++ = '\0'; /* c points to the mask */
1215 if (!*c)
1216 goto out_free;
1217
1218 len = strtoul(c, &err, 10);
1219 if ((err && *err) || (unsigned)len > 128)
1220 goto out_free;
1221 }
1222 *mask = len; /* OK we have a valid mask in <len> */
1223
1224 if (!inet_pton(AF_INET6, s, addr))
1225 goto out_free;
1226
1227 ret_val = 1;
1228 out_free:
1229 free(s);
1230 return ret_val;
1231}
1232
1233
1234/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001235 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001236 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001237int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001238{
1239 int saw_digit, octets, ch;
1240 u_char tmp[4], *tp;
1241 const char *cp = addr;
1242
1243 saw_digit = 0;
1244 octets = 0;
1245 *(tp = tmp) = 0;
1246
1247 while (*addr) {
1248 unsigned char digit = (ch = *addr++) - '0';
1249 if (digit > 9 && ch != '.')
1250 break;
1251 if (digit <= 9) {
1252 u_int new = *tp * 10 + digit;
1253 if (new > 255)
1254 return 0;
1255 *tp = new;
1256 if (!saw_digit) {
1257 if (++octets > 4)
1258 return 0;
1259 saw_digit = 1;
1260 }
1261 } else if (ch == '.' && saw_digit) {
1262 if (octets == 4)
1263 return 0;
1264 *++tp = 0;
1265 saw_digit = 0;
1266 } else
1267 return 0;
1268 }
1269
1270 if (octets < 4)
1271 return 0;
1272
1273 memcpy(&dst->s_addr, tmp, 4);
1274 return addr-cp-1;
1275}
1276
1277/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001278 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001279 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001280 * the hostname. Actually only http and https are supported. <out> can be NULL.
1281 * This function returns the consumed length. It is useful if you parse complete
1282 * url like http://host:port/path, because the consumed length corresponds to
1283 * the first character of the path. If the conversion fails, it returns -1.
1284 *
1285 * This function tries to resolve the DNS name if haproxy is in starting mode.
1286 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001287 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001288int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001289{
1290 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001291 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001292 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001293 unsigned long long int http_code = 0;
1294 int default_port;
1295 struct hostent *he;
1296 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001297
1298 /* Firstly, try to find :// pattern */
1299 while (curr < url+ulen && url_code != 0x3a2f2f) {
1300 url_code = ((url_code & 0xffff) << 8);
1301 url_code += (unsigned char)*curr++;
1302 }
1303
1304 /* Secondly, if :// pattern is found, verify parsed stuff
1305 * before pattern is matching our http pattern.
1306 * If so parse ip address and port in uri.
1307 *
1308 * WARNING: Current code doesn't support dynamic async dns resolver.
1309 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001310 if (url_code != 0x3a2f2f)
1311 return -1;
1312
1313 /* Copy scheme, and utrn to lower case. */
1314 while (cp < curr - 3)
1315 http_code = (http_code << 8) + *cp++;
1316 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001317
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001318 /* HTTP or HTTPS url matching */
1319 if (http_code == 0x2020202068747470ULL) {
1320 default_port = 80;
1321 if (out)
1322 out->scheme = SCH_HTTP;
1323 }
1324 else if (http_code == 0x2020206874747073ULL) {
1325 default_port = 443;
1326 if (out)
1327 out->scheme = SCH_HTTPS;
1328 }
1329 else
1330 return -1;
1331
1332 /* If the next char is '[', the host address is IPv6. */
1333 if (*curr == '[') {
1334 curr++;
1335
1336 /* Check trash size */
1337 if (trash.size < ulen)
1338 return -1;
1339
1340 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001341 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001342 for (end = curr;
1343 end < url + ulen && *end != ']';
1344 end++, p++)
1345 *p = *end;
1346 if (*end != ']')
1347 return -1;
1348 *p = '\0';
1349
1350 /* Update out. */
1351 if (out) {
1352 out->host = curr;
1353 out->host_len = end - curr;
1354 }
1355
1356 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001357 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001358 return -1;
1359 end++;
1360
1361 /* Decode port. */
1362 if (*end == ':') {
1363 end++;
1364 default_port = read_uint(&end, url + ulen);
1365 }
1366 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1367 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1368 return end - url;
1369 }
1370 else {
1371 /* We are looking for IP address. If you want to parse and
1372 * resolve hostname found in url, you can use str2sa_range(), but
1373 * be warned this can slow down global daemon performances
1374 * while handling lagging dns responses.
1375 */
1376 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1377 if (ret) {
1378 /* Update out. */
1379 if (out) {
1380 out->host = curr;
1381 out->host_len = ret;
1382 }
1383
1384 curr += ret;
1385
1386 /* Decode port. */
1387 if (*curr == ':') {
1388 curr++;
1389 default_port = read_uint(&curr, url + ulen);
1390 }
1391 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1392
1393 /* Set family. */
1394 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1395 return curr - url;
1396 }
1397 else if (global.mode & MODE_STARTING) {
1398 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1399 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001400 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001401
1402 /* look for : or / or end */
1403 for (end = curr;
1404 end < url + ulen && *end != '/' && *end != ':';
1405 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001406 memcpy(trash.area, curr, end - curr);
1407 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001408
1409 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001410 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001411 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001412 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001413
1414 /* Update out. */
1415 if (out) {
1416 out->host = curr;
1417 out->host_len = end - curr;
1418 }
1419
1420 /* Decode port. */
1421 if (*end == ':') {
1422 end++;
1423 default_port = read_uint(&end, url + ulen);
1424 }
1425
1426 /* Copy IP address, set port and family. */
1427 switch (he->h_addrtype) {
1428 case AF_INET:
1429 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1430 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1431 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1432 return end - url;
1433
1434 case AF_INET6:
1435 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1436 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1437 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1438 return end - url;
1439 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001440 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001441 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001442 return -1;
1443}
1444
Willy Tarreau631f01c2011-09-05 00:36:48 +02001445/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1446 * address family is returned so that it's easy for the caller to adapt to the
1447 * output format. Zero is returned if the address family is not supported. -1
1448 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1449 * supported.
1450 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001451int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001452{
1453
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001454 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001455
1456 if (size < 5)
1457 return 0;
1458 *str = '\0';
1459
1460 switch (addr->ss_family) {
1461 case AF_INET:
1462 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1463 break;
1464 case AF_INET6:
1465 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1466 break;
1467 case AF_UNIX:
1468 memcpy(str, "unix", 5);
1469 return addr->ss_family;
1470 default:
1471 return 0;
1472 }
1473
1474 if (inet_ntop(addr->ss_family, ptr, str, size))
1475 return addr->ss_family;
1476
1477 /* failed */
1478 return -1;
1479}
1480
Simon Horman75ab8bd2014-06-16 09:39:41 +09001481/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1482 * address family is returned so that it's easy for the caller to adapt to the
1483 * output format. Zero is returned if the address family is not supported. -1
1484 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1485 * supported.
1486 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001487int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001488{
1489
1490 uint16_t port;
1491
1492
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001493 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001494 return 0;
1495 *str = '\0';
1496
1497 switch (addr->ss_family) {
1498 case AF_INET:
1499 port = ((struct sockaddr_in *)addr)->sin_port;
1500 break;
1501 case AF_INET6:
1502 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1503 break;
1504 case AF_UNIX:
1505 memcpy(str, "unix", 5);
1506 return addr->ss_family;
1507 default:
1508 return 0;
1509 }
1510
1511 snprintf(str, size, "%u", ntohs(port));
1512 return addr->ss_family;
1513}
1514
Willy Tarreau16e01562016-08-09 16:46:18 +02001515/* check if the given address is local to the system or not. It will return
1516 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1517 * it is. We don't want to iterate over all interfaces for this (and it is not
1518 * portable). So instead we try to bind in UDP to this address on a free non
1519 * privileged port and to connect to the same address, port 0 (connect doesn't
1520 * care). If it succeeds, we own the address. Note that non-inet addresses are
1521 * considered local since they're most likely AF_UNIX.
1522 */
1523int addr_is_local(const struct netns_entry *ns,
1524 const struct sockaddr_storage *orig)
1525{
1526 struct sockaddr_storage addr;
1527 int result;
1528 int fd;
1529
1530 if (!is_inet_addr(orig))
1531 return 1;
1532
1533 memcpy(&addr, orig, sizeof(addr));
1534 set_host_port(&addr, 0);
1535
1536 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1537 if (fd < 0)
1538 return -1;
1539
1540 result = -1;
1541 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1542 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1543 result = 0; // fail, non-local address
1544 else
1545 result = 1; // success, local address
1546 }
1547 else {
1548 if (errno == EADDRNOTAVAIL)
1549 result = 0; // definitely not local :-)
1550 }
1551 close(fd);
1552
1553 return result;
1554}
1555
Willy Tarreaubaaee002006-06-26 02:48:02 +02001556/* will try to encode the string <string> replacing all characters tagged in
1557 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1558 * prefixed by <escape>, and will store the result between <start> (included)
1559 * and <stop> (excluded), and will always terminate the string with a '\0'
1560 * before <stop>. The position of the '\0' is returned if the conversion
1561 * completes. If bytes are missing between <start> and <stop>, then the
1562 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1563 * cannot even be stored so we return <start> without writing the 0.
1564 * The input string must also be zero-terminated.
1565 */
1566const char hextab[16] = "0123456789ABCDEF";
1567char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001568 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001569 const char *string)
1570{
1571 if (start < stop) {
1572 stop--; /* reserve one byte for the final '\0' */
1573 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001574 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001575 *start++ = *string;
1576 else {
1577 if (start + 3 >= stop)
1578 break;
1579 *start++ = escape;
1580 *start++ = hextab[(*string >> 4) & 15];
1581 *start++ = hextab[*string & 15];
1582 }
1583 string++;
1584 }
1585 *start = '\0';
1586 }
1587 return start;
1588}
1589
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001590/*
1591 * Same behavior as encode_string() above, except that it encodes chunk
1592 * <chunk> instead of a string.
1593 */
1594char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001595 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001596 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001597{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001598 char *str = chunk->area;
1599 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001600
1601 if (start < stop) {
1602 stop--; /* reserve one byte for the final '\0' */
1603 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001604 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001605 *start++ = *str;
1606 else {
1607 if (start + 3 >= stop)
1608 break;
1609 *start++ = escape;
1610 *start++ = hextab[(*str >> 4) & 15];
1611 *start++ = hextab[*str & 15];
1612 }
1613 str++;
1614 }
1615 *start = '\0';
1616 }
1617 return start;
1618}
1619
Dragan Dosen0edd1092016-02-12 13:23:02 +01001620/*
1621 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001622 * character. The input <string> must be zero-terminated. The result will
1623 * be stored between <start> (included) and <stop> (excluded). This
1624 * function will always try to terminate the resulting string with a '\0'
1625 * before <stop>, and will return its position if the conversion
1626 * completes.
1627 */
1628char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001629 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001630 const char *string)
1631{
1632 if (start < stop) {
1633 stop--; /* reserve one byte for the final '\0' */
1634 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001635 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001636 *start++ = *string;
1637 else {
1638 if (start + 2 >= stop)
1639 break;
1640 *start++ = escape;
1641 *start++ = *string;
1642 }
1643 string++;
1644 }
1645 *start = '\0';
1646 }
1647 return start;
1648}
1649
1650/*
1651 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001652 * character. <chunk> contains the input to be escaped. The result will be
1653 * stored between <start> (included) and <stop> (excluded). The function
1654 * will always try to terminate the resulting string with a '\0' before
1655 * <stop>, and will return its position if the conversion completes.
1656 */
1657char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001658 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001659 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001660{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001661 char *str = chunk->area;
1662 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001663
1664 if (start < stop) {
1665 stop--; /* reserve one byte for the final '\0' */
1666 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001667 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001668 *start++ = *str;
1669 else {
1670 if (start + 2 >= stop)
1671 break;
1672 *start++ = escape;
1673 *start++ = *str;
1674 }
1675 str++;
1676 }
1677 *start = '\0';
1678 }
1679 return start;
1680}
1681
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001682/* Check a string for using it in a CSV output format. If the string contains
1683 * one of the following four char <">, <,>, CR or LF, the string is
1684 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1685 * <str> is the input string to be escaped. The function assumes that
1686 * the input string is null-terminated.
1687 *
1688 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001689 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001690 * format.
1691 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001692 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001693 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001694 * If <quote> is 1, the converter puts the quotes only if any reserved character
1695 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001696 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001697 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001698 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001699 * The function returns the converted string on its output. If an error
1700 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001701 * for using the function directly as printf() argument.
1702 *
1703 * If the output buffer is too short to contain the input string, the result
1704 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001705 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001706 * This function appends the encoding to the existing output chunk, and it
1707 * guarantees that it starts immediately at the first available character of
1708 * the chunk. Please use csv_enc() instead if you want to replace the output
1709 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001710 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001711const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001712{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001713 char *end = output->area + output->size;
1714 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001715 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001716
Willy Tarreaub631c292016-01-08 10:04:08 +01001717 if (quote == 1) {
1718 /* automatic quoting: first verify if we'll have to quote the string */
1719 if (!strpbrk(str, "\n\r,\""))
1720 quote = 0;
1721 }
1722
1723 if (quote)
1724 *ptr++ = '"';
1725
Willy Tarreau898529b2016-01-06 18:07:04 +01001726 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1727 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001728 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001729 ptr++;
1730 if (ptr >= end - 2) {
1731 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001732 break;
1733 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001734 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001735 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001736 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001737 str++;
1738 }
1739
Willy Tarreaub631c292016-01-08 10:04:08 +01001740 if (quote)
1741 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001742
Willy Tarreau898529b2016-01-06 18:07:04 +01001743 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001744 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001745 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001746}
1747
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001748/* Decode an URL-encoded string in-place. The resulting string might
1749 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001750 * aborted, the string is truncated before the issue and a negative value is
1751 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001752 * If the 'in_form' argument is non-nul the string is assumed to be part of
1753 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1754 * turned to a space. If it's zero, this will only be done after a question
1755 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001756 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001757int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001758{
1759 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001760 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001761
1762 in = string;
1763 out = string;
1764 while (*in) {
1765 switch (*in) {
1766 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001767 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001768 break;
1769 case '%' :
1770 if (!ishex(in[1]) || !ishex(in[2]))
1771 goto end;
1772 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1773 in += 2;
1774 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001775 case '?':
1776 in_form = 1;
1777 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001778 default:
1779 *out++ = *in;
1780 break;
1781 }
1782 in++;
1783 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001784 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001785 end:
1786 *out = 0;
1787 return ret;
1788}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001789
Willy Tarreau6911fa42007-03-04 18:06:08 +01001790unsigned int str2ui(const char *s)
1791{
1792 return __str2ui(s);
1793}
1794
1795unsigned int str2uic(const char *s)
1796{
1797 return __str2uic(s);
1798}
1799
1800unsigned int strl2ui(const char *s, int len)
1801{
1802 return __strl2ui(s, len);
1803}
1804
1805unsigned int strl2uic(const char *s, int len)
1806{
1807 return __strl2uic(s, len);
1808}
1809
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001810unsigned int read_uint(const char **s, const char *end)
1811{
1812 return __read_uint(s, end);
1813}
1814
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001815/* This function reads an unsigned integer from the string pointed to by <s> and
1816 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1817 * function automatically stops at <end>. If the number overflows, the 2^64-1
1818 * value is returned.
1819 */
1820unsigned long long int read_uint64(const char **s, const char *end)
1821{
1822 const char *ptr = *s;
1823 unsigned long long int i = 0, tmp;
1824 unsigned int j;
1825
1826 while (ptr < end) {
1827
1828 /* read next char */
1829 j = *ptr - '0';
1830 if (j > 9)
1831 goto read_uint64_end;
1832
1833 /* add char to the number and check overflow. */
1834 tmp = i * 10;
1835 if (tmp / 10 != i) {
1836 i = ULLONG_MAX;
1837 goto read_uint64_eat;
1838 }
1839 if (ULLONG_MAX - tmp < j) {
1840 i = ULLONG_MAX;
1841 goto read_uint64_eat;
1842 }
1843 i = tmp + j;
1844 ptr++;
1845 }
1846read_uint64_eat:
1847 /* eat each numeric char */
1848 while (ptr < end) {
1849 if ((unsigned int)(*ptr - '0') > 9)
1850 break;
1851 ptr++;
1852 }
1853read_uint64_end:
1854 *s = ptr;
1855 return i;
1856}
1857
1858/* This function reads an integer from the string pointed to by <s> and returns
1859 * it. The <s> pointer is adjusted to point to the first unread char. The function
1860 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1861 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1862 * returned.
1863 */
1864long long int read_int64(const char **s, const char *end)
1865{
1866 unsigned long long int i = 0;
1867 int neg = 0;
1868
1869 /* Look for minus char. */
1870 if (**s == '-') {
1871 neg = 1;
1872 (*s)++;
1873 }
1874 else if (**s == '+')
1875 (*s)++;
1876
1877 /* convert as positive number. */
1878 i = read_uint64(s, end);
1879
1880 if (neg) {
1881 if (i > 0x8000000000000000ULL)
1882 return LLONG_MIN;
1883 return -i;
1884 }
1885 if (i > 0x7fffffffffffffffULL)
1886 return LLONG_MAX;
1887 return i;
1888}
1889
Willy Tarreau6911fa42007-03-04 18:06:08 +01001890/* This one is 7 times faster than strtol() on athlon with checks.
1891 * It returns the value of the number composed of all valid digits read,
1892 * and can process negative numbers too.
1893 */
1894int strl2ic(const char *s, int len)
1895{
1896 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001897 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001898
1899 if (len > 0) {
1900 if (*s != '-') {
1901 /* positive number */
1902 while (len-- > 0) {
1903 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001904 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001905 if (j > 9)
1906 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001907 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001908 }
1909 } else {
1910 /* negative number */
1911 s++;
1912 while (--len > 0) {
1913 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001914 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001915 if (j > 9)
1916 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001917 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001918 }
1919 }
1920 }
1921 return i;
1922}
1923
1924
1925/* This function reads exactly <len> chars from <s> and converts them to a
1926 * signed integer which it stores into <ret>. It accurately detects any error
1927 * (truncated string, invalid chars, overflows). It is meant to be used in
1928 * applications designed for hostile environments. It returns zero when the
1929 * number has successfully been converted, non-zero otherwise. When an error
1930 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1931 * faster than strtol().
1932 */
1933int strl2irc(const char *s, int len, int *ret)
1934{
1935 int i = 0;
1936 int j;
1937
1938 if (!len)
1939 return 1;
1940
1941 if (*s != '-') {
1942 /* positive number */
1943 while (len-- > 0) {
1944 j = (*s++) - '0';
1945 if (j > 9) return 1; /* invalid char */
1946 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1947 i = i * 10;
1948 if (i + j < i) return 1; /* check for addition overflow */
1949 i = i + j;
1950 }
1951 } else {
1952 /* negative number */
1953 s++;
1954 while (--len > 0) {
1955 j = (*s++) - '0';
1956 if (j > 9) return 1; /* invalid char */
1957 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1958 i = i * 10;
1959 if (i - j > i) return 1; /* check for subtract overflow */
1960 i = i - j;
1961 }
1962 }
1963 *ret = i;
1964 return 0;
1965}
1966
1967
1968/* This function reads exactly <len> chars from <s> and converts them to a
1969 * signed integer which it stores into <ret>. It accurately detects any error
1970 * (truncated string, invalid chars, overflows). It is meant to be used in
1971 * applications designed for hostile environments. It returns zero when the
1972 * number has successfully been converted, non-zero otherwise. When an error
1973 * is returned, the <ret> value is left untouched. It is about 3 times slower
1974 * than str2irc().
1975 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001976
1977int strl2llrc(const char *s, int len, long long *ret)
1978{
1979 long long i = 0;
1980 int j;
1981
1982 if (!len)
1983 return 1;
1984
1985 if (*s != '-') {
1986 /* positive number */
1987 while (len-- > 0) {
1988 j = (*s++) - '0';
1989 if (j > 9) return 1; /* invalid char */
1990 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1991 i = i * 10LL;
1992 if (i + j < i) return 1; /* check for addition overflow */
1993 i = i + j;
1994 }
1995 } else {
1996 /* negative number */
1997 s++;
1998 while (--len > 0) {
1999 j = (*s++) - '0';
2000 if (j > 9) return 1; /* invalid char */
2001 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2002 i = i * 10LL;
2003 if (i - j > i) return 1; /* check for subtract overflow */
2004 i = i - j;
2005 }
2006 }
2007 *ret = i;
2008 return 0;
2009}
2010
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002011/* This function is used with pat_parse_dotted_ver(). It converts a string
2012 * composed by two number separated by a dot. Each part must contain in 16 bits
2013 * because internally they will be represented as a 32-bit quantity stored in
2014 * a 64-bit integer. It returns zero when the number has successfully been
2015 * converted, non-zero otherwise. When an error is returned, the <ret> value
2016 * is left untouched.
2017 *
2018 * "1.3" -> 0x0000000000010003
2019 * "65535.65535" -> 0x00000000ffffffff
2020 */
2021int strl2llrc_dotted(const char *text, int len, long long *ret)
2022{
2023 const char *end = &text[len];
2024 const char *p;
2025 long long major, minor;
2026
2027 /* Look for dot. */
2028 for (p = text; p < end; p++)
2029 if (*p == '.')
2030 break;
2031
2032 /* Convert major. */
2033 if (strl2llrc(text, p - text, &major) != 0)
2034 return 1;
2035
2036 /* Check major. */
2037 if (major >= 65536)
2038 return 1;
2039
2040 /* Convert minor. */
2041 minor = 0;
2042 if (p < end)
2043 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2044 return 1;
2045
2046 /* Check minor. */
2047 if (minor >= 65536)
2048 return 1;
2049
2050 /* Compose value. */
2051 *ret = (major << 16) | (minor & 0xffff);
2052 return 0;
2053}
2054
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002055/* This function parses a time value optionally followed by a unit suffix among
2056 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2057 * expected by the caller. The computation does its best to avoid overflows.
2058 * The value is returned in <ret> if everything is fine, and a NULL is returned
2059 * by the function. In case of error, a pointer to the error is returned and
2060 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002061 * Values resulting in values larger than or equal to 2^31 after conversion are
2062 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2063 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002064 */
2065const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2066{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002067 unsigned long long imult, idiv;
2068 unsigned long long omult, odiv;
2069 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002070
2071 omult = odiv = 1;
2072
2073 switch (unit_flags & TIME_UNIT_MASK) {
2074 case TIME_UNIT_US: omult = 1000000; break;
2075 case TIME_UNIT_MS: omult = 1000; break;
2076 case TIME_UNIT_S: break;
2077 case TIME_UNIT_MIN: odiv = 60; break;
2078 case TIME_UNIT_HOUR: odiv = 3600; break;
2079 case TIME_UNIT_DAY: odiv = 86400; break;
2080 default: break;
2081 }
2082
2083 value = 0;
2084
2085 while (1) {
2086 unsigned int j;
2087
2088 j = *text - '0';
2089 if (j > 9)
2090 break;
2091 text++;
2092 value *= 10;
2093 value += j;
2094 }
2095
2096 imult = idiv = 1;
2097 switch (*text) {
2098 case '\0': /* no unit = default unit */
2099 imult = omult = idiv = odiv = 1;
2100 break;
2101 case 's': /* second = unscaled unit */
2102 break;
2103 case 'u': /* microsecond : "us" */
2104 if (text[1] == 's') {
2105 idiv = 1000000;
2106 text++;
2107 }
2108 break;
2109 case 'm': /* millisecond : "ms" or minute: "m" */
2110 if (text[1] == 's') {
2111 idiv = 1000;
2112 text++;
2113 } else
2114 imult = 60;
2115 break;
2116 case 'h': /* hour : "h" */
2117 imult = 3600;
2118 break;
2119 case 'd': /* day : "d" */
2120 imult = 86400;
2121 break;
2122 default:
2123 return text;
2124 break;
2125 }
2126
2127 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2128 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2129 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2130 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2131
Willy Tarreau9faebe32019-06-07 19:00:37 +02002132 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2133 if (result >= 0x80000000)
2134 return PARSE_TIME_OVER;
2135 if (!result && value)
2136 return PARSE_TIME_UNDER;
2137 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002138 return NULL;
2139}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002140
Emeric Brun39132b22010-01-04 14:57:24 +01002141/* this function converts the string starting at <text> to an unsigned int
2142 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002143 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002144 */
2145const char *parse_size_err(const char *text, unsigned *ret) {
2146 unsigned value = 0;
2147
2148 while (1) {
2149 unsigned int j;
2150
2151 j = *text - '0';
2152 if (j > 9)
2153 break;
2154 if (value > ~0U / 10)
2155 return text;
2156 value *= 10;
2157 if (value > (value + j))
2158 return text;
2159 value += j;
2160 text++;
2161 }
2162
2163 switch (*text) {
2164 case '\0':
2165 break;
2166 case 'K':
2167 case 'k':
2168 if (value > ~0U >> 10)
2169 return text;
2170 value = value << 10;
2171 break;
2172 case 'M':
2173 case 'm':
2174 if (value > ~0U >> 20)
2175 return text;
2176 value = value << 20;
2177 break;
2178 case 'G':
2179 case 'g':
2180 if (value > ~0U >> 30)
2181 return text;
2182 value = value << 30;
2183 break;
2184 default:
2185 return text;
2186 }
2187
Godbach58048a22015-01-28 17:36:16 +08002188 if (*text != '\0' && *++text != '\0')
2189 return text;
2190
Emeric Brun39132b22010-01-04 14:57:24 +01002191 *ret = value;
2192 return NULL;
2193}
2194
Willy Tarreau126d4062013-12-03 17:50:47 +01002195/*
2196 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002197 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002198 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002199 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002200 */
2201int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2202{
2203 int len;
2204 const char *p = source;
2205 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002206 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002207
2208 len = strlen(source);
2209 if (len % 2) {
2210 memprintf(err, "an even number of hex digit is expected");
2211 return 0;
2212 }
2213
2214 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002215
Willy Tarreau126d4062013-12-03 17:50:47 +01002216 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002217 *binstr = calloc(len, sizeof(char));
2218 if (!*binstr) {
2219 memprintf(err, "out of memory while loading string pattern");
2220 return 0;
2221 }
2222 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002223 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002224 else {
2225 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002226 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002227 len, *binstrlen);
2228 return 0;
2229 }
2230 alloc = 0;
2231 }
2232 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002233
2234 i = j = 0;
2235 while (j < len) {
2236 if (!ishex(p[i++]))
2237 goto bad_input;
2238 if (!ishex(p[i++]))
2239 goto bad_input;
2240 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2241 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002242 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002243
2244bad_input:
2245 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002246 if (alloc) {
2247 free(*binstr);
2248 *binstr = NULL;
2249 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002250 return 0;
2251}
2252
Willy Tarreau946ba592009-05-10 15:41:18 +02002253/* copies at most <n> characters from <src> and always terminates with '\0' */
2254char *my_strndup(const char *src, int n)
2255{
2256 int len = 0;
2257 char *ret;
2258
2259 while (len < n && src[len])
2260 len++;
2261
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002262 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002263 if (!ret)
2264 return ret;
2265 memcpy(ret, src, len);
2266 ret[len] = '\0';
2267 return ret;
2268}
2269
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002270/*
2271 * search needle in haystack
2272 * returns the pointer if found, returns NULL otherwise
2273 */
2274const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2275{
2276 const void *c = NULL;
2277 unsigned char f;
2278
2279 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2280 return NULL;
2281
2282 f = *(char *)needle;
2283 c = haystack;
2284 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2285 if ((haystacklen - (c - haystack)) < needlelen)
2286 return NULL;
2287
2288 if (memcmp(c, needle, needlelen) == 0)
2289 return c;
2290 ++c;
2291 }
2292 return NULL;
2293}
2294
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002295/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002296size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2297{
2298 size_t ret = 0;
2299
2300 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2301 str++;
2302 ret++;
2303 }
2304 return ret;
2305}
2306
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002307/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002308size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2309{
2310 size_t ret = 0;
2311
2312 while (ret < len) {
2313 if(memchr(reject, *((int *)str), rejectlen))
2314 return ret;
2315 str++;
2316 ret++;
2317 }
2318 return ret;
2319}
2320
Willy Tarreau482b00d2009-10-04 22:48:42 +02002321/* This function returns the first unused key greater than or equal to <key> in
2322 * ID tree <root>. Zero is returned if no place is found.
2323 */
2324unsigned int get_next_id(struct eb_root *root, unsigned int key)
2325{
2326 struct eb32_node *used;
2327
2328 do {
2329 used = eb32_lookup_ge(root, key);
2330 if (!used || used->key > key)
2331 return key; /* key is available */
2332 key++;
2333 } while (key);
2334 return key;
2335}
2336
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002337/* dump the full tree to <file> in DOT format for debugging purposes. Will
2338 * optionally highlight node <subj> if found, depending on operation <op> :
2339 * 0 : nothing
2340 * >0 : insertion, node/leaf are surrounded in red
2341 * <0 : removal, node/leaf are dashed with no background
2342 * Will optionally add "desc" as a label on the graph if set and non-null.
2343 */
2344void eb32sc_to_file(FILE *file, struct eb_root *root, const struct eb32sc_node *subj, int op, const char *desc)
Willy Tarreaued3cda02017-11-15 15:04:05 +01002345{
2346 struct eb32sc_node *node;
2347 unsigned long scope = -1;
2348
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002349 fprintf(file, "digraph ebtree {\n");
2350
2351 if (desc && *desc) {
2352 fprintf(file,
2353 " fontname=\"fixed\";\n"
2354 " fontsize=8;\n"
2355 " label=\"%s\";\n", desc);
2356 }
2357
Willy Tarreaued3cda02017-11-15 15:04:05 +01002358 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002359 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2360 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002361 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2362 );
2363
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002364 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002365 (long)eb_root_to_node(root),
2366 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002367 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2368
2369 node = eb32sc_first(root, scope);
2370 while (node) {
2371 if (node->node.node_p) {
2372 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002373 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2374 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2375 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002376
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002377 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002378 (long)node,
2379 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002380 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002381
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002382 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002383 (long)node,
2384 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002385 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2386
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002387 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002388 (long)node,
2389 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002390 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2391 }
2392
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002393 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2394 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2395 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002396
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002397 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002398 (long)node,
2399 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002400 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002401 node = eb32sc_next(node, scope);
2402 }
2403 fprintf(file, "}\n");
2404}
2405
Willy Tarreau348238b2010-01-18 15:05:57 +01002406/* This function compares a sample word possibly followed by blanks to another
2407 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2408 * otherwise zero. This intends to be used when checking HTTP headers for some
2409 * values. Note that it validates a word followed only by blanks but does not
2410 * validate a word followed by blanks then other chars.
2411 */
2412int word_match(const char *sample, int slen, const char *word, int wlen)
2413{
2414 if (slen < wlen)
2415 return 0;
2416
2417 while (wlen) {
2418 char c = *sample ^ *word;
2419 if (c && c != ('A' ^ 'a'))
2420 return 0;
2421 sample++;
2422 word++;
2423 slen--;
2424 wlen--;
2425 }
2426
2427 while (slen) {
2428 if (*sample != ' ' && *sample != '\t')
2429 return 0;
2430 sample++;
2431 slen--;
2432 }
2433 return 1;
2434}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002435
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002436/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2437 * is particularly fast because it avoids expensive operations such as
2438 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002439 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002440 */
2441unsigned int inetaddr_host(const char *text)
2442{
2443 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2444 register unsigned int dig100, dig10, dig1;
2445 int s;
2446 const char *p, *d;
2447
2448 dig1 = dig10 = dig100 = ascii_zero;
2449 s = 24;
2450
2451 p = text;
2452 while (1) {
2453 if (((unsigned)(*p - '0')) <= 9) {
2454 p++;
2455 continue;
2456 }
2457
2458 /* here, we have a complete byte between <text> and <p> (exclusive) */
2459 if (p == text)
2460 goto end;
2461
2462 d = p - 1;
2463 dig1 |= (unsigned int)(*d << s);
2464 if (d == text)
2465 goto end;
2466
2467 d--;
2468 dig10 |= (unsigned int)(*d << s);
2469 if (d == text)
2470 goto end;
2471
2472 d--;
2473 dig100 |= (unsigned int)(*d << s);
2474 end:
2475 if (!s || *p != '.')
2476 break;
2477
2478 s -= 8;
2479 text = ++p;
2480 }
2481
2482 dig100 -= ascii_zero;
2483 dig10 -= ascii_zero;
2484 dig1 -= ascii_zero;
2485 return ((dig100 * 10) + dig10) * 10 + dig1;
2486}
2487
2488/*
2489 * Idem except the first unparsed character has to be passed in <stop>.
2490 */
2491unsigned int inetaddr_host_lim(const char *text, const char *stop)
2492{
2493 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2494 register unsigned int dig100, dig10, dig1;
2495 int s;
2496 const char *p, *d;
2497
2498 dig1 = dig10 = dig100 = ascii_zero;
2499 s = 24;
2500
2501 p = text;
2502 while (1) {
2503 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2504 p++;
2505 continue;
2506 }
2507
2508 /* here, we have a complete byte between <text> and <p> (exclusive) */
2509 if (p == text)
2510 goto end;
2511
2512 d = p - 1;
2513 dig1 |= (unsigned int)(*d << s);
2514 if (d == text)
2515 goto end;
2516
2517 d--;
2518 dig10 |= (unsigned int)(*d << s);
2519 if (d == text)
2520 goto end;
2521
2522 d--;
2523 dig100 |= (unsigned int)(*d << s);
2524 end:
2525 if (!s || p == stop || *p != '.')
2526 break;
2527
2528 s -= 8;
2529 text = ++p;
2530 }
2531
2532 dig100 -= ascii_zero;
2533 dig10 -= ascii_zero;
2534 dig1 -= ascii_zero;
2535 return ((dig100 * 10) + dig10) * 10 + dig1;
2536}
2537
2538/*
2539 * Idem except the pointer to first unparsed byte is returned into <ret> which
2540 * must not be NULL.
2541 */
Willy Tarreau74172752010-10-15 23:21:42 +02002542unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002543{
2544 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2545 register unsigned int dig100, dig10, dig1;
2546 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002547 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002548
2549 dig1 = dig10 = dig100 = ascii_zero;
2550 s = 24;
2551
2552 p = text;
2553 while (1) {
2554 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2555 p++;
2556 continue;
2557 }
2558
2559 /* here, we have a complete byte between <text> and <p> (exclusive) */
2560 if (p == text)
2561 goto end;
2562
2563 d = p - 1;
2564 dig1 |= (unsigned int)(*d << s);
2565 if (d == text)
2566 goto end;
2567
2568 d--;
2569 dig10 |= (unsigned int)(*d << s);
2570 if (d == text)
2571 goto end;
2572
2573 d--;
2574 dig100 |= (unsigned int)(*d << s);
2575 end:
2576 if (!s || p == stop || *p != '.')
2577 break;
2578
2579 s -= 8;
2580 text = ++p;
2581 }
2582
2583 *ret = p;
2584 dig100 -= ascii_zero;
2585 dig10 -= ascii_zero;
2586 dig1 -= ascii_zero;
2587 return ((dig100 * 10) + dig10) * 10 + dig1;
2588}
2589
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002590/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2591 * or the number of chars read in case of success. Maybe this could be replaced
2592 * by one of the functions above. Also, apparently this function does not support
2593 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002594 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002595 */
2596int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2597{
2598 const char *addr;
2599 int saw_digit, octets, ch;
2600 u_char tmp[4], *tp;
2601 const char *cp = buf;
2602
2603 saw_digit = 0;
2604 octets = 0;
2605 *(tp = tmp) = 0;
2606
2607 for (addr = buf; addr - buf < len; addr++) {
2608 unsigned char digit = (ch = *addr) - '0';
2609
2610 if (digit > 9 && ch != '.')
2611 break;
2612
2613 if (digit <= 9) {
2614 u_int new = *tp * 10 + digit;
2615
2616 if (new > 255)
2617 return 0;
2618
2619 *tp = new;
2620
2621 if (!saw_digit) {
2622 if (++octets > 4)
2623 return 0;
2624 saw_digit = 1;
2625 }
2626 } else if (ch == '.' && saw_digit) {
2627 if (octets == 4)
2628 return 0;
2629
2630 *++tp = 0;
2631 saw_digit = 0;
2632 } else
2633 return 0;
2634 }
2635
2636 if (octets < 4)
2637 return 0;
2638
2639 memcpy(&dst->s_addr, tmp, 4);
2640 return addr - cp;
2641}
2642
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002643/* This function converts the string in <buf> of the len <len> to
2644 * struct in6_addr <dst> which must be allocated by the caller.
2645 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002646 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002647 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002648int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2649{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002650 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002651 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002652
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002653 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002654 return 0;
2655
2656 memcpy(null_term_ip6, buf, len);
2657 null_term_ip6[len] = '\0';
2658
Willy Tarreau075415a2013-12-12 11:29:39 +01002659 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002660 return 0;
2661
Willy Tarreau075415a2013-12-12 11:29:39 +01002662 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002663 return 1;
2664}
2665
Willy Tarreauacf95772010-06-14 19:09:21 +02002666/* To be used to quote config arg positions. Returns the short string at <ptr>
2667 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2668 * if ptr is NULL or empty. The string is locally allocated.
2669 */
2670const char *quote_arg(const char *ptr)
2671{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002672 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002673 int i;
2674
2675 if (!ptr || !*ptr)
2676 return "end of line";
2677 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002678 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002679 val[i] = *ptr++;
2680 val[i++] = '\'';
2681 val[i] = '\0';
2682 return val;
2683}
2684
Willy Tarreau5b180202010-07-18 10:40:48 +02002685/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2686int get_std_op(const char *str)
2687{
2688 int ret = -1;
2689
2690 if (*str == 'e' && str[1] == 'q')
2691 ret = STD_OP_EQ;
2692 else if (*str == 'n' && str[1] == 'e')
2693 ret = STD_OP_NE;
2694 else if (*str == 'l') {
2695 if (str[1] == 'e') ret = STD_OP_LE;
2696 else if (str[1] == 't') ret = STD_OP_LT;
2697 }
2698 else if (*str == 'g') {
2699 if (str[1] == 'e') ret = STD_OP_GE;
2700 else if (str[1] == 't') ret = STD_OP_GT;
2701 }
2702
2703 if (ret == -1 || str[2] != '\0')
2704 return -1;
2705 return ret;
2706}
2707
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002708/* hash a 32-bit integer to another 32-bit integer */
2709unsigned int full_hash(unsigned int a)
2710{
2711 return __full_hash(a);
2712}
2713
Willy Tarreauf3241112019-02-26 09:56:22 +01002714/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2715 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2716 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2717 * a popcount variant and is described here :
2718 * https://graphics.stanford.edu/~seander/bithacks.html
2719 */
2720unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2721{
2722 unsigned long a, b, c, d;
2723 unsigned int s;
2724 unsigned int t;
2725
2726 a = m - ((m >> 1) & ~0UL/3);
2727 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2728 c = (b + (b >> 4)) & ~0UL/0x11;
2729 d = (c + (c >> 8)) & ~0UL/0x101;
2730
2731 r++; // make r be 1..64
2732
2733 t = 0;
2734 s = LONGBITS;
2735 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002736 unsigned long d2 = (d >> 16) >> 16;
2737 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002738 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2739 }
2740
2741 t = (d >> (s - 16)) & 0xff;
2742 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2743 t = (c >> (s - 8)) & 0xf;
2744 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2745 t = (b >> (s - 4)) & 0x7;
2746 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2747 t = (a >> (s - 2)) & 0x3;
2748 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2749 t = (m >> (s - 1)) & 0x1;
2750 s -= ((t - r) & 256) >> 8;
2751
2752 return s - 1;
2753}
2754
2755/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2756 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2757 * using mask_prep_rank_map() below.
2758 */
2759unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2760 unsigned long a, unsigned long b,
2761 unsigned long c, unsigned long d)
2762{
2763 unsigned int s;
2764 unsigned int t;
2765
2766 r++; // make r be 1..64
2767
2768 t = 0;
2769 s = LONGBITS;
2770 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002771 unsigned long d2 = (d >> 16) >> 16;
2772 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002773 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2774 }
2775
2776 t = (d >> (s - 16)) & 0xff;
2777 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2778 t = (c >> (s - 8)) & 0xf;
2779 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2780 t = (b >> (s - 4)) & 0x7;
2781 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2782 t = (a >> (s - 2)) & 0x3;
2783 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2784 t = (m >> (s - 1)) & 0x1;
2785 s -= ((t - r) & 256) >> 8;
2786
2787 return s - 1;
2788}
2789
2790/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2791 * above.
2792 */
2793void mask_prep_rank_map(unsigned long m,
2794 unsigned long *a, unsigned long *b,
2795 unsigned long *c, unsigned long *d)
2796{
2797 *a = m - ((m >> 1) & ~0UL/3);
2798 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2799 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2800 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2801}
2802
David du Colombier4f92d322011-03-24 11:09:31 +01002803/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002804 * otherwise zero. Note that <addr> may not necessarily be aligned
2805 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002806 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002807int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002808{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002809 struct in_addr addr_copy;
2810
2811 memcpy(&addr_copy, addr, sizeof(addr_copy));
2812 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002813}
2814
2815/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002816 * otherwise zero. Note that <addr> may not necessarily be aligned
2817 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002818 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002819int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002820{
2821 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002822 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002823
Willy Tarreaueec1d382016-07-13 11:59:39 +02002824 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002825 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002826 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002827 (((int *)net)[i] & ((int *)mask)[i]))
2828 return 0;
2829 return 1;
2830}
2831
2832/* RFC 4291 prefix */
2833const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2834 0x00, 0x00, 0x00, 0x00,
2835 0x00, 0x00, 0xFF, 0xFF };
2836
Joseph Herlant32b83272018-11-15 11:58:28 -08002837/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002838 * Input and output may overlap.
2839 */
David du Colombier4f92d322011-03-24 11:09:31 +01002840void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2841{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002842 struct in_addr tmp_addr;
2843
2844 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002845 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002846 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002847}
2848
Joseph Herlant32b83272018-11-15 11:58:28 -08002849/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002850 * Return true if conversion is possible and false otherwise.
2851 */
2852int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2853{
2854 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2855 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2856 sizeof(struct in_addr));
2857 return 1;
2858 }
2859
2860 return 0;
2861}
2862
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002863/* compare two struct sockaddr_storage and return:
2864 * 0 (true) if the addr is the same in both
2865 * 1 (false) if the addr is not the same in both
2866 * -1 (unable) if one of the addr is not AF_INET*
2867 */
2868int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2869{
2870 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2871 return -1;
2872
2873 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2874 return -1;
2875
2876 if (ss1->ss_family != ss2->ss_family)
2877 return 1;
2878
2879 switch (ss1->ss_family) {
2880 case AF_INET:
2881 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2882 &((struct sockaddr_in *)ss2)->sin_addr,
2883 sizeof(struct in_addr)) != 0;
2884 case AF_INET6:
2885 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2886 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2887 sizeof(struct in6_addr)) != 0;
2888 }
2889
2890 return 1;
2891}
2892
Baptiste Assmann08396c82016-01-31 00:27:17 +01002893/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002894 * The caller must allocate and clear <dest> before calling.
2895 * The source must be in either AF_INET or AF_INET6 family, or the destination
2896 * address will be undefined. If the destination address used to hold a port,
2897 * it is preserved, so that this function can be used to switch to another
2898 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002899 */
2900struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2901{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002902 int prev_port;
2903
2904 prev_port = get_net_port(dest);
2905 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002906 dest->ss_family = source->ss_family;
2907
2908 /* copy new addr and apply it */
2909 switch (source->ss_family) {
2910 case AF_INET:
2911 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002912 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002913 break;
2914 case AF_INET6:
2915 memcpy(((struct sockaddr_in6 *)dest)->sin6_addr.s6_addr, ((struct sockaddr_in6 *)source)->sin6_addr.s6_addr, sizeof(struct in6_addr));
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002916 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002917 break;
2918 }
2919
2920 return dest;
2921}
2922
William Lallemand421f5b52012-02-06 18:15:57 +01002923char *human_time(int t, short hz_div) {
2924 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2925 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002926 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002927 int cnt=2; // print two numbers
2928
2929 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002930 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002931 return rv;
2932 }
2933
2934 if (unlikely(hz_div > 1))
2935 t /= hz_div;
2936
2937 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002938 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002939 cnt--;
2940 }
2941
2942 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002943 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002944 cnt--;
2945 }
2946
2947 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002948 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002949 cnt--;
2950 }
2951
2952 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002953 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002954
2955 return rv;
2956}
2957
2958const char *monthname[12] = {
2959 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2960 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2961};
2962
2963/* date2str_log: write a date in the format :
2964 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2965 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2966 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2967 *
2968 * without using sprintf. return a pointer to the last char written (\0) or
2969 * NULL if there isn't enough space.
2970 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002971char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002972{
2973
2974 if (size < 25) /* the size is fixed: 24 chars + \0 */
2975 return NULL;
2976
2977 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002978 if (!dst)
2979 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002980 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002981
William Lallemand421f5b52012-02-06 18:15:57 +01002982 memcpy(dst, monthname[tm->tm_mon], 3); // month
2983 dst += 3;
2984 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002985
William Lallemand421f5b52012-02-06 18:15:57 +01002986 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002987 if (!dst)
2988 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002989 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002990
William Lallemand421f5b52012-02-06 18:15:57 +01002991 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002992 if (!dst)
2993 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002994 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002995
William Lallemand421f5b52012-02-06 18:15:57 +01002996 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002997 if (!dst)
2998 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002999 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003000
William Lallemand421f5b52012-02-06 18:15:57 +01003001 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003002 if (!dst)
3003 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003004 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003005
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003006 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003007 if (!dst)
3008 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003009 *dst = '\0';
3010
3011 return dst;
3012}
3013
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003014/* Base year used to compute leap years */
3015#define TM_YEAR_BASE 1900
3016
3017/* Return the difference in seconds between two times (leap seconds are ignored).
3018 * Retrieved from glibc 2.18 source code.
3019 */
3020static int my_tm_diff(const struct tm *a, const struct tm *b)
3021{
3022 /* Compute intervening leap days correctly even if year is negative.
3023 * Take care to avoid int overflow in leap day calculations,
3024 * but it's OK to assume that A and B are close to each other.
3025 */
3026 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3027 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3028 int a100 = a4 / 25 - (a4 % 25 < 0);
3029 int b100 = b4 / 25 - (b4 % 25 < 0);
3030 int a400 = a100 >> 2;
3031 int b400 = b100 >> 2;
3032 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3033 int years = a->tm_year - b->tm_year;
3034 int days = (365 * years + intervening_leap_days
3035 + (a->tm_yday - b->tm_yday));
3036 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3037 + (a->tm_min - b->tm_min))
3038 + (a->tm_sec - b->tm_sec));
3039}
3040
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003041/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003042 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003043 * The string returned has the same format as returned by strftime(... "%z", tm).
3044 * Offsets are kept in an internal cache for better performances.
3045 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003046const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003047{
3048 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003049 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003050
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003051 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003052 struct tm tm_gmt;
3053 int diff;
3054 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003055
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003056 /* Pretend DST not active if its status is unknown */
3057 if (isdst < 0)
3058 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003059
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003060 /* Fetch the offset and initialize it if needed */
3061 gmt_offset = gmt_offsets[isdst & 0x01];
3062 if (unlikely(!*gmt_offset)) {
3063 get_gmtime(t, &tm_gmt);
3064 diff = my_tm_diff(tm, &tm_gmt);
3065 if (diff < 0) {
3066 diff = -diff;
3067 *gmt_offset = '-';
3068 } else {
3069 *gmt_offset = '+';
3070 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003071 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003072 diff /= 60; /* Convert to minutes */
3073 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3074 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003075
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003076 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003077}
3078
William Lallemand421f5b52012-02-06 18:15:57 +01003079/* gmt2str_log: write a date in the format :
3080 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3081 * return a pointer to the last char written (\0) or
3082 * NULL if there isn't enough space.
3083 */
3084char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3085{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003086 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003087 return NULL;
3088
3089 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003090 if (!dst)
3091 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003092 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003093
William Lallemand421f5b52012-02-06 18:15:57 +01003094 memcpy(dst, monthname[tm->tm_mon], 3); // month
3095 dst += 3;
3096 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003097
William Lallemand421f5b52012-02-06 18:15:57 +01003098 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003099 if (!dst)
3100 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003101 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003102
William Lallemand421f5b52012-02-06 18:15:57 +01003103 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003104 if (!dst)
3105 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003106 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003107
William Lallemand421f5b52012-02-06 18:15:57 +01003108 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003109 if (!dst)
3110 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003111 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003112
William Lallemand421f5b52012-02-06 18:15:57 +01003113 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003114 if (!dst)
3115 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003116 *dst++ = ' ';
3117 *dst++ = '+';
3118 *dst++ = '0';
3119 *dst++ = '0';
3120 *dst++ = '0';
3121 *dst++ = '0';
3122 *dst = '\0';
3123
3124 return dst;
3125}
3126
Yuxans Yao4e25b012012-10-19 10:36:09 +08003127/* localdate2str_log: write a date in the format :
3128 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003129 * Both t and tm must represent the same time.
3130 * return a pointer to the last char written (\0) or
3131 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003132 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003133char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003134{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003135 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003136 if (size < 27) /* the size is fixed: 26 chars + \0 */
3137 return NULL;
3138
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003139 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003140
Yuxans Yao4e25b012012-10-19 10:36:09 +08003141 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003142 if (!dst)
3143 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003144 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003145
Yuxans Yao4e25b012012-10-19 10:36:09 +08003146 memcpy(dst, monthname[tm->tm_mon], 3); // month
3147 dst += 3;
3148 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003149
Yuxans Yao4e25b012012-10-19 10:36:09 +08003150 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003151 if (!dst)
3152 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003153 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003154
Yuxans Yao4e25b012012-10-19 10:36:09 +08003155 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003156 if (!dst)
3157 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003158 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003159
Yuxans Yao4e25b012012-10-19 10:36:09 +08003160 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003161 if (!dst)
3162 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003163 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003164
Yuxans Yao4e25b012012-10-19 10:36:09 +08003165 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003166 if (!dst)
3167 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003168 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003169
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003170 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003171 dst += 5;
3172 *dst = '\0';
3173
3174 return dst;
3175}
3176
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003177/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3178 * It is meant as a portable replacement for timegm() for use with valid inputs.
3179 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3180 */
3181time_t my_timegm(const struct tm *tm)
3182{
3183 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3184 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3185 * sum of the extra N days for elapsed months. The sum of all these N
3186 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3187 * in a 5-bit word. This means that with 60 bits we can represent a
3188 * matrix of all these values at once, which is fast and efficient to
3189 * access. The extra February day for leap years is not counted here.
3190 *
3191 * Jan : none = 0 (0)
3192 * Feb : Jan = 3 (3)
3193 * Mar : Jan..Feb = 3 (3 + 0)
3194 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3195 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3196 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3197 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3198 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3199 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3200 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3201 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3202 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3203 */
3204 uint64_t extra =
3205 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3206 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3207 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3208 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3209
3210 unsigned int y = tm->tm_year + 1900;
3211 unsigned int m = tm->tm_mon;
3212 unsigned long days = 0;
3213
3214 /* days since 1/1/1970 for full years */
3215 days += days_since_zero(y) - days_since_zero(1970);
3216
3217 /* days for full months in the current year */
3218 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3219
3220 /* count + 1 after March for leap years. A leap year is a year multiple
3221 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3222 * is leap, 1900 isn't, 1904 is.
3223 */
3224 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3225 days++;
3226
3227 days += tm->tm_mday - 1;
3228 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3229}
3230
Thierry Fournier93127942016-01-20 18:49:45 +01003231/* This function check a char. It returns true and updates
3232 * <date> and <len> pointer to the new position if the
3233 * character is found.
3234 */
3235static inline int parse_expect_char(const char **date, int *len, char c)
3236{
3237 if (*len < 1 || **date != c)
3238 return 0;
3239 (*len)--;
3240 (*date)++;
3241 return 1;
3242}
3243
3244/* This function expects a string <str> of len <l>. It return true and updates.
3245 * <date> and <len> if the string matches, otherwise, it returns false.
3246 */
3247static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3248{
3249 if (*len < l || strncmp(*date, str, l) != 0)
3250 return 0;
3251 (*len) -= l;
3252 (*date) += l;
3253 return 1;
3254}
3255
3256/* This macro converts 3 chars name in integer. */
3257#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3258
3259/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3260 * / %x54.75.65 ; "Tue", case-sensitive
3261 * / %x57.65.64 ; "Wed", case-sensitive
3262 * / %x54.68.75 ; "Thu", case-sensitive
3263 * / %x46.72.69 ; "Fri", case-sensitive
3264 * / %x53.61.74 ; "Sat", case-sensitive
3265 * / %x53.75.6E ; "Sun", case-sensitive
3266 *
3267 * This array must be alphabetically sorted
3268 */
3269static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3270{
3271 if (*len < 3)
3272 return 0;
3273 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3274 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3275 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3276 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3277 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3278 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3279 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3280 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3281 default: return 0;
3282 }
3283 *len -= 3;
3284 *date += 3;
3285 return 1;
3286}
3287
3288/* month = %x4A.61.6E ; "Jan", case-sensitive
3289 * / %x46.65.62 ; "Feb", case-sensitive
3290 * / %x4D.61.72 ; "Mar", case-sensitive
3291 * / %x41.70.72 ; "Apr", case-sensitive
3292 * / %x4D.61.79 ; "May", case-sensitive
3293 * / %x4A.75.6E ; "Jun", case-sensitive
3294 * / %x4A.75.6C ; "Jul", case-sensitive
3295 * / %x41.75.67 ; "Aug", case-sensitive
3296 * / %x53.65.70 ; "Sep", case-sensitive
3297 * / %x4F.63.74 ; "Oct", case-sensitive
3298 * / %x4E.6F.76 ; "Nov", case-sensitive
3299 * / %x44.65.63 ; "Dec", case-sensitive
3300 *
3301 * This array must be alphabetically sorted
3302 */
3303static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3304{
3305 if (*len < 3)
3306 return 0;
3307 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3308 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3309 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3310 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3311 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3312 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3313 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3314 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3315 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3316 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3317 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3318 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3319 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3320 default: return 0;
3321 }
3322 *len -= 3;
3323 *date += 3;
3324 return 1;
3325}
3326
3327/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3328 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3329 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3330 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3331 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3332 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3333 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3334 *
3335 * This array must be alphabetically sorted
3336 */
3337static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3338{
3339 if (*len < 6) /* Minimum length. */
3340 return 0;
3341 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3342 case STR2I3('M','o','n'):
3343 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3344 tm->tm_wday = 1;
3345 return 1;
3346 case STR2I3('T','u','e'):
3347 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3348 tm->tm_wday = 2;
3349 return 1;
3350 case STR2I3('W','e','d'):
3351 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3352 tm->tm_wday = 3;
3353 return 1;
3354 case STR2I3('T','h','u'):
3355 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3356 tm->tm_wday = 4;
3357 return 1;
3358 case STR2I3('F','r','i'):
3359 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3360 tm->tm_wday = 5;
3361 return 1;
3362 case STR2I3('S','a','t'):
3363 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3364 tm->tm_wday = 6;
3365 return 1;
3366 case STR2I3('S','u','n'):
3367 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3368 tm->tm_wday = 7;
3369 return 1;
3370 }
3371 return 0;
3372}
3373
3374/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3375static inline int parse_digit(const char **date, int *len, int *digit)
3376{
3377 if (*len < 1 || **date < '0' || **date > '9')
3378 return 0;
3379 *digit = (**date - '0');
3380 (*date)++;
3381 (*len)--;
3382 return 1;
3383}
3384
3385/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3386static inline int parse_2digit(const char **date, int *len, int *digit)
3387{
3388 int value;
3389
3390 RET0_UNLESS(parse_digit(date, len, &value));
3391 (*digit) = value * 10;
3392 RET0_UNLESS(parse_digit(date, len, &value));
3393 (*digit) += value;
3394
3395 return 1;
3396}
3397
3398/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3399static inline int parse_4digit(const char **date, int *len, int *digit)
3400{
3401 int value;
3402
3403 RET0_UNLESS(parse_digit(date, len, &value));
3404 (*digit) = value * 1000;
3405
3406 RET0_UNLESS(parse_digit(date, len, &value));
3407 (*digit) += value * 100;
3408
3409 RET0_UNLESS(parse_digit(date, len, &value));
3410 (*digit) += value * 10;
3411
3412 RET0_UNLESS(parse_digit(date, len, &value));
3413 (*digit) += value;
3414
3415 return 1;
3416}
3417
3418/* time-of-day = hour ":" minute ":" second
3419 * ; 00:00:00 - 23:59:60 (leap second)
3420 *
3421 * hour = 2DIGIT
3422 * minute = 2DIGIT
3423 * second = 2DIGIT
3424 */
3425static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3426{
3427 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3428 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3429 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3430 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3431 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3432 return 1;
3433}
3434
3435/* From RFC7231
3436 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3437 *
3438 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3439 * ; fixed length/zone/capitalization subset of the format
3440 * ; see Section 3.3 of [RFC5322]
3441 *
3442 *
3443 * date1 = day SP month SP year
3444 * ; e.g., 02 Jun 1982
3445 *
3446 * day = 2DIGIT
3447 * year = 4DIGIT
3448 *
3449 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3450 *
3451 * time-of-day = hour ":" minute ":" second
3452 * ; 00:00:00 - 23:59:60 (leap second)
3453 *
3454 * hour = 2DIGIT
3455 * minute = 2DIGIT
3456 * second = 2DIGIT
3457 *
3458 * DIGIT = decimal 0-9
3459 */
3460int parse_imf_date(const char *date, int len, struct tm *tm)
3461{
David Carlier327298c2016-11-20 10:42:38 +00003462 /* tm_gmtoff, if present, ought to be zero'ed */
3463 memset(tm, 0, sizeof(*tm));
3464
Thierry Fournier93127942016-01-20 18:49:45 +01003465 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3466 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3467 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3468 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3469 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3470 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3471 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3472 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3473 tm->tm_year -= 1900;
3474 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3475 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3476 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3477 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3478 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003479 return 1;
3480}
3481
3482/* From RFC7231
3483 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3484 *
3485 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3486 * date2 = day "-" month "-" 2DIGIT
3487 * ; e.g., 02-Jun-82
3488 *
3489 * day = 2DIGIT
3490 */
3491int parse_rfc850_date(const char *date, int len, struct tm *tm)
3492{
3493 int year;
3494
David Carlier327298c2016-11-20 10:42:38 +00003495 /* tm_gmtoff, if present, ought to be zero'ed */
3496 memset(tm, 0, sizeof(*tm));
3497
Thierry Fournier93127942016-01-20 18:49:45 +01003498 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3499 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3500 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3501 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3502 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3503 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3504 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3505
3506 /* year = 2DIGIT
3507 *
3508 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3509 * two-digit year, MUST interpret a timestamp that appears to be more
3510 * than 50 years in the future as representing the most recent year in
3511 * the past that had the same last two digits.
3512 */
3513 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3514
3515 /* expect SP */
3516 if (!parse_expect_char(&date, &len, ' ')) {
3517 /* Maybe we have the date with 4 digits. */
3518 RET0_UNLESS(parse_2digit(&date, &len, &year));
3519 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3520 /* expect SP */
3521 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3522 } else {
3523 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3524 * tm_year is the number of year since 1900, so for +1900, we
3525 * do nothing, and for +2000, we add 100.
3526 */
3527 if (tm->tm_year <= 60)
3528 tm->tm_year += 100;
3529 }
3530
3531 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3532 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3533 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3534 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003535
3536 return 1;
3537}
3538
3539/* From RFC7231
3540 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3541 *
3542 * asctime-date = day-name SP date3 SP time-of-day SP year
3543 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3544 * ; e.g., Jun 2
3545 *
3546 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3547 * whitespace in an HTTP-date beyond that specifically included as SP in
3548 * the grammar.
3549 */
3550int parse_asctime_date(const char *date, int len, struct tm *tm)
3551{
David Carlier327298c2016-11-20 10:42:38 +00003552 /* tm_gmtoff, if present, ought to be zero'ed */
3553 memset(tm, 0, sizeof(*tm));
3554
Thierry Fournier93127942016-01-20 18:49:45 +01003555 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3556 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3557 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3558 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3559
3560 /* expect SP and 1DIGIT or 2DIGIT */
3561 if (parse_expect_char(&date, &len, ' '))
3562 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3563 else
3564 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3565
3566 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3567 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3568 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3569 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3570 tm->tm_year -= 1900;
3571 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003572 return 1;
3573}
3574
3575/* From RFC7231
3576 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3577 *
3578 * HTTP-date = IMF-fixdate / obs-date
3579 * obs-date = rfc850-date / asctime-date
3580 *
3581 * parses an HTTP date in the RFC format and is accepted
3582 * alternatives. <date> is the strinf containing the date,
3583 * len is the len of the string. <tm> is filled with the
3584 * parsed time. We must considers this time as GMT.
3585 */
3586int parse_http_date(const char *date, int len, struct tm *tm)
3587{
3588 if (parse_imf_date(date, len, tm))
3589 return 1;
3590
3591 if (parse_rfc850_date(date, len, tm))
3592 return 1;
3593
3594 if (parse_asctime_date(date, len, tm))
3595 return 1;
3596
3597 return 0;
3598}
3599
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003600/* Dynamically allocates a string of the proper length to hold the formatted
3601 * output. NULL is returned on error. The caller is responsible for freeing the
3602 * memory area using free(). The resulting string is returned in <out> if the
3603 * pointer is not NULL. A previous version of <out> might be used to build the
3604 * new string, and it will be freed before returning if it is not NULL, which
3605 * makes it possible to build complex strings from iterative calls without
3606 * having to care about freeing intermediate values, as in the example below :
3607 *
3608 * memprintf(&err, "invalid argument: '%s'", arg);
3609 * ...
3610 * memprintf(&err, "parser said : <%s>\n", *err);
3611 * ...
3612 * free(*err);
3613 *
3614 * This means that <err> must be initialized to NULL before first invocation.
3615 * The return value also holds the allocated string, which eases error checking
3616 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003617 * passed instead and it will be ignored. The returned message will then also
3618 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003619 *
3620 * It is also convenient to use it without any free except the last one :
3621 * err = NULL;
3622 * if (!fct1(err)) report(*err);
3623 * if (!fct2(err)) report(*err);
3624 * if (!fct3(err)) report(*err);
3625 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003626 *
3627 * memprintf relies on memvprintf. This last version can be called from any
3628 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003629 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003630char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003631{
3632 va_list args;
3633 char *ret = NULL;
3634 int allocated = 0;
3635 int needed = 0;
3636
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003637 if (!out)
3638 return NULL;
3639
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003640 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003641 char buf1;
3642
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003643 /* vsnprintf() will return the required length even when the
3644 * target buffer is NULL. We do this in a loop just in case
3645 * intermediate evaluations get wrong.
3646 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003647 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003648 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003649 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003650 if (needed < allocated) {
3651 /* Note: on Solaris 8, the first iteration always
3652 * returns -1 if allocated is zero, so we force a
3653 * retry.
3654 */
3655 if (!allocated)
3656 needed = 0;
3657 else
3658 break;
3659 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003660
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003661 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003662 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003663 } while (ret);
3664
3665 if (needed < 0) {
3666 /* an error was encountered */
3667 free(ret);
3668 ret = NULL;
3669 }
3670
3671 if (out) {
3672 free(*out);
3673 *out = ret;
3674 }
3675
3676 return ret;
3677}
William Lallemand421f5b52012-02-06 18:15:57 +01003678
Christopher Faulet93a518f2017-10-24 11:25:33 +02003679char *memprintf(char **out, const char *format, ...)
3680{
3681 va_list args;
3682 char *ret = NULL;
3683
3684 va_start(args, format);
3685 ret = memvprintf(out, format, args);
3686 va_end(args);
3687
3688 return ret;
3689}
3690
Willy Tarreau21c705b2012-09-14 11:40:36 +02003691/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3692 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003693 * freed by the caller. It also supports being passed a NULL which results in the same
3694 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003695 * Example of use :
3696 * parse(cmd, &err); (callee: memprintf(&err, ...))
3697 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3698 * free(err);
3699 */
3700char *indent_msg(char **out, int level)
3701{
3702 char *ret, *in, *p;
3703 int needed = 0;
3704 int lf = 0;
3705 int lastlf = 0;
3706 int len;
3707
Willy Tarreau70eec382012-10-10 08:56:47 +02003708 if (!out || !*out)
3709 return NULL;
3710
Willy Tarreau21c705b2012-09-14 11:40:36 +02003711 in = *out - 1;
3712 while ((in = strchr(in + 1, '\n')) != NULL) {
3713 lastlf = in - *out;
3714 lf++;
3715 }
3716
3717 if (!lf) /* single line, no LF, return it as-is */
3718 return *out;
3719
3720 len = strlen(*out);
3721
3722 if (lf == 1 && lastlf == len - 1) {
3723 /* single line, LF at end, strip it and return as-is */
3724 (*out)[lastlf] = 0;
3725 return *out;
3726 }
3727
3728 /* OK now we have at least one LF, we need to process the whole string
3729 * as a multi-line string. What we'll do :
3730 * - prefix with an LF if there is none
3731 * - add <level> spaces before each line
3732 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3733 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3734 */
3735
3736 needed = 1 + level * (lf + 1) + len + 1;
3737 p = ret = malloc(needed);
3738 in = *out;
3739
3740 /* skip initial LFs */
3741 while (*in == '\n')
3742 in++;
3743
3744 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3745 while (*in) {
3746 *p++ = '\n';
3747 memset(p, ' ', level);
3748 p += level;
3749 do {
3750 *p++ = *in++;
3751 } while (*in && *in != '\n');
3752 if (*in)
3753 in++;
3754 }
3755 *p = 0;
3756
3757 free(*out);
3758 *out = ret;
3759
3760 return ret;
3761}
3762
Willy Tarreaua2c99112019-08-21 13:17:37 +02003763/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3764 * and end of lines replaced with <eol> if not 0. The first line to indent has
3765 * to be indicated in <first> (starts at zero), so that it is possible to skip
3766 * indenting the first line if it has to be appended after an existing message.
3767 * Empty strings are never indented, and NULL strings are considered empty both
3768 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3769 * character, non-zero otherwise.
3770 */
3771int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3772{
3773 int bol, lf;
3774 int pfxlen = pfx ? strlen(pfx) : 0;
3775
3776 if (!in)
3777 return 0;
3778
3779 bol = 1;
3780 lf = 0;
3781 while (*in) {
3782 if (bol && pfxlen) {
3783 if (first > 0)
3784 first--;
3785 else
3786 b_putblk(out, pfx, pfxlen);
3787 bol = 0;
3788 }
3789
3790 lf = (*in == '\n');
3791 bol |= lf;
3792 b_putchr(out, (lf && eol) ? eol : *in);
3793 in++;
3794 }
3795 return lf;
3796}
3797
Willy Tarreau9d22e562019-03-29 18:49:09 +01003798/* removes environment variable <name> from the environment as found in
3799 * environ. This is only provided as an alternative for systems without
3800 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003801 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003802 * <name> and to replace the matching pointers with the last pointer of
3803 * the array (since variables are not ordered).
3804 * It always returns 0 (success).
3805 */
3806int my_unsetenv(const char *name)
3807{
3808 extern char **environ;
3809 char **p = environ;
3810 int vars;
3811 int next;
3812 int len;
3813
3814 len = strlen(name);
3815 for (vars = 0; p[vars]; vars++)
3816 ;
3817 next = 0;
3818 while (next < vars) {
3819 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3820 next++;
3821 continue;
3822 }
3823 if (next < vars - 1)
3824 p[next] = p[vars - 1];
3825 p[--vars] = NULL;
3826 }
3827 return 0;
3828}
3829
Willy Tarreaudad36a32013-03-11 01:20:04 +01003830/* Convert occurrences of environment variables in the input string to their
3831 * corresponding value. A variable is identified as a series of alphanumeric
3832 * characters or underscores following a '$' sign. The <in> string must be
3833 * free()able. NULL returns NULL. The resulting string might be reallocated if
3834 * some expansion is made. Variable names may also be enclosed into braces if
3835 * needed (eg: to concatenate alphanum characters).
3836 */
3837char *env_expand(char *in)
3838{
3839 char *txt_beg;
3840 char *out;
3841 char *txt_end;
3842 char *var_beg;
3843 char *var_end;
3844 char *value;
3845 char *next;
3846 int out_len;
3847 int val_len;
3848
3849 if (!in)
3850 return in;
3851
3852 value = out = NULL;
3853 out_len = 0;
3854
3855 txt_beg = in;
3856 do {
3857 /* look for next '$' sign in <in> */
3858 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3859
3860 if (!*txt_end && !out) /* end and no expansion performed */
3861 return in;
3862
3863 val_len = 0;
3864 next = txt_end;
3865 if (*txt_end == '$') {
3866 char save;
3867
3868 var_beg = txt_end + 1;
3869 if (*var_beg == '{')
3870 var_beg++;
3871
3872 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003873 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003874 var_end++;
3875 }
3876
3877 next = var_end;
3878 if (*var_end == '}' && (var_beg > txt_end + 1))
3879 next++;
3880
3881 /* get value of the variable name at this location */
3882 save = *var_end;
3883 *var_end = '\0';
3884 value = getenv(var_beg);
3885 *var_end = save;
3886 val_len = value ? strlen(value) : 0;
3887 }
3888
Hubert Verstraete831962e2016-06-28 22:44:26 +02003889 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003890 if (txt_end > txt_beg) {
3891 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3892 out_len += txt_end - txt_beg;
3893 }
3894 if (val_len) {
3895 memcpy(out + out_len, value, val_len);
3896 out_len += val_len;
3897 }
3898 out[out_len] = 0;
3899 txt_beg = next;
3900 } while (*txt_beg);
3901
3902 /* here we know that <out> was allocated and that we don't need <in> anymore */
3903 free(in);
3904 return out;
3905}
3906
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003907
3908/* same as strstr() but case-insensitive and with limit length */
3909const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3910{
3911 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003912 unsigned int slen, plen;
3913 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003914
3915 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3916 return NULL;
3917
3918 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3919 return str1;
3920
3921 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3922 return NULL;
3923
3924 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3925 while (toupper(*start) != toupper(*str2)) {
3926 start++;
3927 slen--;
3928 tmp1++;
3929
3930 if (tmp1 >= len_str1)
3931 return NULL;
3932
3933 /* if pattern longer than string */
3934 if (slen < plen)
3935 return NULL;
3936 }
3937
3938 sptr = start;
3939 pptr = (char *)str2;
3940
3941 tmp2 = 0;
3942 while (toupper(*sptr) == toupper(*pptr)) {
3943 sptr++;
3944 pptr++;
3945 tmp2++;
3946
3947 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3948 return start;
3949 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3950 return NULL;
3951 }
3952 }
3953 return NULL;
3954}
3955
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003956/* This function read the next valid utf8 char.
3957 * <s> is the byte srray to be decode, <len> is its length.
3958 * The function returns decoded char encoded like this:
3959 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3960 * are the length read. The decoded character is stored in <c>.
3961 */
3962unsigned char utf8_next(const char *s, int len, unsigned int *c)
3963{
3964 const unsigned char *p = (unsigned char *)s;
3965 int dec;
3966 unsigned char code = UTF8_CODE_OK;
3967
3968 if (len < 1)
3969 return UTF8_CODE_OK;
3970
3971 /* Check the type of UTF8 sequence
3972 *
3973 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3974 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3975 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3976 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3977 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3978 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3979 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3980 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3981 */
3982 switch (*p) {
3983 case 0x00 ... 0x7f:
3984 *c = *p;
3985 return UTF8_CODE_OK | 1;
3986
3987 case 0x80 ... 0xbf:
3988 *c = *p;
3989 return UTF8_CODE_BADSEQ | 1;
3990
3991 case 0xc0 ... 0xdf:
3992 if (len < 2) {
3993 *c = *p;
3994 return UTF8_CODE_BADSEQ | 1;
3995 }
3996 *c = *p & 0x1f;
3997 dec = 1;
3998 break;
3999
4000 case 0xe0 ... 0xef:
4001 if (len < 3) {
4002 *c = *p;
4003 return UTF8_CODE_BADSEQ | 1;
4004 }
4005 *c = *p & 0x0f;
4006 dec = 2;
4007 break;
4008
4009 case 0xf0 ... 0xf7:
4010 if (len < 4) {
4011 *c = *p;
4012 return UTF8_CODE_BADSEQ | 1;
4013 }
4014 *c = *p & 0x07;
4015 dec = 3;
4016 break;
4017
4018 case 0xf8 ... 0xfb:
4019 if (len < 5) {
4020 *c = *p;
4021 return UTF8_CODE_BADSEQ | 1;
4022 }
4023 *c = *p & 0x03;
4024 dec = 4;
4025 break;
4026
4027 case 0xfc ... 0xfd:
4028 if (len < 6) {
4029 *c = *p;
4030 return UTF8_CODE_BADSEQ | 1;
4031 }
4032 *c = *p & 0x01;
4033 dec = 5;
4034 break;
4035
4036 case 0xfe ... 0xff:
4037 default:
4038 *c = *p;
4039 return UTF8_CODE_BADSEQ | 1;
4040 }
4041
4042 p++;
4043
4044 while (dec > 0) {
4045
4046 /* need 0x10 for the 2 first bits */
4047 if ( ( *p & 0xc0 ) != 0x80 )
4048 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4049
4050 /* add data at char */
4051 *c = ( *c << 6 ) | ( *p & 0x3f );
4052
4053 dec--;
4054 p++;
4055 }
4056
4057 /* Check ovelong encoding.
4058 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4059 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4060 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4061 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004062 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004063 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4064 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4065 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4066 code |= UTF8_CODE_OVERLONG;
4067
4068 /* Check invalid UTF8 range. */
4069 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4070 (*c >= 0xfffe && *c <= 0xffff))
4071 code |= UTF8_CODE_INVRANGE;
4072
4073 return code | ((p-(unsigned char *)s)&0x0f);
4074}
4075
Maxime de Roucydc887852016-05-13 23:52:54 +02004076/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4077 * On failure : return 0 and <err> filled with an error message.
4078 * The caller is responsible for freeing the <err> and <str> copy
4079 * memory area using free()
4080 */
4081int list_append_word(struct list *li, const char *str, char **err)
4082{
4083 struct wordlist *wl;
4084
4085 wl = calloc(1, sizeof(*wl));
4086 if (!wl) {
4087 memprintf(err, "out of memory");
4088 goto fail_wl;
4089 }
4090
4091 wl->s = strdup(str);
4092 if (!wl->s) {
4093 memprintf(err, "out of memory");
4094 goto fail_wl_s;
4095 }
4096
4097 LIST_ADDQ(li, &wl->list);
4098
4099 return 1;
4100
4101fail_wl_s:
4102 free(wl->s);
4103fail_wl:
4104 free(wl);
4105 return 0;
4106}
4107
Willy Tarreau37101052019-05-20 16:48:20 +02004108/* indicates if a memory location may safely be read or not. The trick consists
4109 * in performing a harmless syscall using this location as an input and letting
4110 * the operating system report whether it's OK or not. For this we have the
4111 * stat() syscall, which will return EFAULT when the memory location supposed
4112 * to contain the file name is not readable. If it is readable it will then
4113 * either return 0 if the area contains an existing file name, or -1 with
4114 * another code. This must not be abused, and some audit systems might detect
4115 * this as abnormal activity. It's used only for unsafe dumps.
4116 */
4117int may_access(const void *ptr)
4118{
4119 struct stat buf;
4120
4121 if (stat(ptr, &buf) == 0)
4122 return 1;
4123 if (errno == EFAULT)
4124 return 0;
4125 return 1;
4126}
4127
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004128/* print a string of text buffer to <out>. The format is :
4129 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4130 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4131 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4132 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004133int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004134{
4135 unsigned char c;
4136 int ptr = 0;
4137
4138 while (buf[ptr] && ptr < bsize) {
4139 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004140 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004141 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004142 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004143 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004144 }
4145 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004146 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004147 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004148 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004149 switch (c) {
4150 case ' ': c = ' '; break;
4151 case '\t': c = 't'; break;
4152 case '\n': c = 'n'; break;
4153 case '\r': c = 'r'; break;
4154 case '\e': c = 'e'; break;
4155 case '\\': c = '\\'; break;
4156 case '=': c = '='; break;
4157 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004158 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004159 }
4160 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004161 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004162 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004163 out->area[out->data++] = '\\';
4164 out->area[out->data++] = 'x';
4165 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4166 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004167 }
4168 ptr++;
4169 }
4170
4171 return ptr;
4172}
4173
4174/* print a buffer in hexa.
4175 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4176 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004177int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004178{
4179 unsigned char c;
4180 int ptr = 0;
4181
4182 while (ptr < bsize) {
4183 c = buf[ptr];
4184
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004185 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004186 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004187 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4188 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004189
4190 ptr++;
4191 }
4192 return ptr;
4193}
4194
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004195/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4196 * prepending each line with prefix <pfx>. The output is *not* initialized.
4197 * The output will not wrap pas the buffer's end so it is more optimal if the
4198 * caller makes sure the buffer is aligned first. A trailing zero will always
4199 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004200 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4201 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004202 */
Willy Tarreau37101052019-05-20 16:48:20 +02004203void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004204{
4205 const unsigned char *d = buf;
4206 int i, j, start;
4207
4208 d = (const unsigned char *)(((unsigned long)buf) & -16);
4209 start = ((unsigned long)buf) & 15;
4210
4211 for (i = 0; i < start + len; i += 16) {
4212 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4213
Willy Tarreau37101052019-05-20 16:48:20 +02004214 // 0: unchecked, 1: checked safe, 2: danger
4215 unsafe = !!unsafe;
4216 if (unsafe && !may_access(d + i))
4217 unsafe = 2;
4218
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004219 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004220 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004221 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004222 else if (unsafe > 1)
4223 chunk_strcat(out, "** ");
4224 else
4225 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004226
4227 if (j == 7)
4228 chunk_strcat(out, "- ");
4229 }
4230 chunk_strcat(out, " ");
4231 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004232 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004233 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004234 else if (unsafe > 1)
4235 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004236 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004237 chunk_appendf(out, "%c", d[i + j]);
4238 else
4239 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004240 }
4241 chunk_strcat(out, "\n");
4242 }
4243}
4244
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004245/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4246 * enclosed in brackets after the address itself, formatted on 14 chars
4247 * including the "0x" prefix. This is meant to be used as a prefix for code
4248 * areas. For example:
4249 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4250 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4251 * is emitted. A NULL <pfx> will be considered empty.
4252 */
4253void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4254{
4255 int ok = 0;
4256 int i;
4257
4258 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4259
4260 for (i = 0; i < n; i++) {
4261 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4262 ok = may_access(addr + i);
4263 if (ok)
4264 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4265 else
4266 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4267 }
4268}
4269
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004270/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4271 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4272 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4273 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4274 * lines are respected within the limit of 70 output chars. Lines that are
4275 * continuation of a previous truncated line begin with "+" instead of " "
4276 * after the offset. The new pointer is returned.
4277 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004278int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004279 int *line, int ptr)
4280{
4281 int end;
4282 unsigned char c;
4283
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004284 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004285 if (end > out->size)
4286 return ptr;
4287
4288 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4289
4290 while (ptr < len && ptr < bsize) {
4291 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004292 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004293 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004294 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004295 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004296 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004297 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004298 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004299 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004300 switch (c) {
4301 case '\t': c = 't'; break;
4302 case '\n': c = 'n'; break;
4303 case '\r': c = 'r'; break;
4304 case '\e': c = 'e'; break;
4305 case '\\': c = '\\'; break;
4306 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004307 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004308 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004309 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004310 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004311 out->area[out->data++] = '\\';
4312 out->area[out->data++] = 'x';
4313 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4314 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004315 }
4316 if (buf[ptr++] == '\n') {
4317 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004318 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004319 *line = ptr;
4320 return ptr;
4321 }
4322 }
4323 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004324 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004325 return ptr;
4326}
4327
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004328/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004329 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4330 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004331 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004332void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4333 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004334{
Willy Tarreau73459792017-04-11 07:58:08 +02004335 unsigned int i;
4336 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004337
4338 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4339 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004340 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004341 for (j = 0; j < 8; j++) {
4342 if (b + j >= 0 && b + j < len)
4343 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4344 else
4345 fprintf(out, " ");
4346 }
4347
4348 if (b + j >= 0 && b + j < len)
4349 fputc('-', out);
4350 else
4351 fputc(' ', out);
4352
4353 for (j = 8; j < 16; j++) {
4354 if (b + j >= 0 && b + j < len)
4355 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4356 else
4357 fprintf(out, " ");
4358 }
4359
4360 fprintf(out, " ");
4361 for (j = 0; j < 16; j++) {
4362 if (b + j >= 0 && b + j < len) {
4363 if (isprint((unsigned char)buf[b + j]))
4364 fputc((unsigned char)buf[b + j], out);
4365 else
4366 fputc('.', out);
4367 }
4368 else
4369 fputc(' ', out);
4370 }
4371 fputc('\n', out);
4372 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004373}
4374
Willy Tarreaubb869862020-04-16 10:52:41 +02004375/* Tries to report the executable path name on platforms supporting this. If
4376 * not found or not possible, returns NULL.
4377 */
4378const char *get_exec_path()
4379{
4380 const char *ret = NULL;
4381
4382#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4383 long execfn = getauxval(AT_EXECFN);
4384
4385 if (execfn && execfn != ENOENT)
4386 ret = (const char *)execfn;
4387#endif
4388 return ret;
4389}
4390
Willy Tarreau109201f2020-03-04 10:31:58 +01004391#ifdef __ELF__
Willy Tarreau9133e482020-03-04 10:19:36 +01004392/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4393 * also returns the symbol size in <size>, otherwise returns 0 there.
4394 */
4395static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4396{
4397 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004398#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004399 const ElfW(Sym) *sym;
4400
4401 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4402 if (ret)
4403 *size = sym ? sym->st_size : 0;
4404#else
4405 ret = dladdr(addr, dli);
4406 *size = 0;
4407#endif
4408 return ret;
4409}
4410#endif
4411
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004412/* Tries to append to buffer <buf> some indications about the symbol at address
4413 * <addr> using the following form:
4414 * lib:+0xoffset (unresolvable address from lib's base)
4415 * main+0xoffset (unresolvable address from main (+/-))
4416 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4417 * name (resolved exact exec address)
4418 * lib:name (resolved exact lib address)
4419 * name+0xoffset/0xsize (resolved address within exec symbol)
4420 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4421 *
4422 * The file name (lib or executable) is limited to what lies between the last
4423 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4424 * the output if not null. The file is not dumped when it's the same as the one
Willy Tarreau109201f2020-03-04 10:31:58 +01004425 * that contains the "main" symbol, or when __ELF__ is not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004426 *
4427 * The symbol's base address is returned, or NULL when unresolved, in order to
4428 * allow the caller to match it against known ones.
4429 */
4430void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
4431{
4432 const struct {
4433 const void *func;
4434 const char *name;
4435 } fcts[] = {
4436 { .func = process_stream, .name = "process_stream" },
4437 { .func = task_run_applet, .name = "task_run_applet" },
4438 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4439 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4440 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4441 { .func = listener_accept, .name = "listener_accept" },
4442 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4443 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4444#ifdef USE_LUA
4445 { .func = hlua_process_task, .name = "hlua_process_task" },
4446#endif
4447#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4448 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4449 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4450#endif
4451 };
4452
Willy Tarreau109201f2020-03-04 10:31:58 +01004453#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004454 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004455 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004456 const char *fname, *p;
4457#endif
4458 int i;
4459
4460 if (pfx)
4461 chunk_appendf(buf, "%s", pfx);
4462
4463 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4464 if (addr == fcts[i].func) {
4465 chunk_appendf(buf, "%s", fcts[i].name);
4466 return addr;
4467 }
4468 }
4469
Willy Tarreau109201f2020-03-04 10:31:58 +01004470#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004471 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004472 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004473 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004474
4475 /* 1. prefix the library name if it's not the same object as the one
4476 * that contains the main function. The name is picked between last '/'
4477 * and first following '.'.
4478 */
4479 if (!dladdr(main, &dli_main))
4480 dli_main.dli_fbase = NULL;
4481
4482 if (dli_main.dli_fbase != dli.dli_fbase) {
4483 fname = dli.dli_fname;
4484 p = strrchr(fname, '/');
4485 if (p++)
4486 fname = p;
4487 p = strchr(fname, '.');
4488 if (!p)
4489 p = fname + strlen(fname);
4490
4491 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4492 }
4493
4494 /* 2. symbol name */
4495 if (dli.dli_sname) {
4496 /* known, dump it and return symbol's address (exact or relative) */
4497 chunk_appendf(buf, "%s", dli.dli_sname);
4498 if (addr != dli.dli_saddr) {
4499 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004500 if (size)
4501 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004502 }
4503 return dli.dli_saddr;
4504 }
4505 else if (dli_main.dli_fbase != dli.dli_fbase) {
4506 /* unresolved symbol from a known library, report relative offset */
4507 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4508 return NULL;
4509 }
Willy Tarreau109201f2020-03-04 10:31:58 +01004510#endif /* __ELF__ */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004511 unknown:
4512 /* unresolved symbol from the main file, report relative offset to main */
4513 if ((void*)addr < (void*)main)
4514 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4515 else
4516 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4517 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004518}
4519
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004520/*
4521 * Allocate an array of unsigned int with <nums> as address from <str> string
4522 * made of integer sepereated by dot characters.
4523 *
4524 * First, initializes the value with <sz> as address to 0 and initializes the
4525 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4526 * address updating <sz> pointed value to the size of this array.
4527 *
4528 * Returns 1 if succeeded, 0 if not.
4529 */
4530int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4531{
4532 unsigned int *n;
4533 const char *s, *end;
4534
4535 s = str;
4536 *sz = 0;
4537 end = str + strlen(str);
4538 *nums = n = NULL;
4539
4540 while (1) {
4541 unsigned int r;
4542
4543 if (s >= end)
4544 break;
4545
4546 r = read_uint(&s, end);
4547 /* Expected characters after having read an uint: '\0' or '.',
4548 * if '.', must not be terminal.
4549 */
4550 if (*s != '\0'&& (*s++ != '.' || s == end))
4551 return 0;
4552
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004553 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004554 if (!n)
4555 return 0;
4556
4557 n[(*sz)++] = r;
4558 }
4559 *nums = n;
4560
4561 return 1;
4562}
4563
Willy Tarreau4d589e72019-08-23 19:02:26 +02004564
4565/* returns the number of bytes needed to encode <v> as a varint. An inline
4566 * version exists for use with constants (__varint_bytes()).
4567 */
4568int varint_bytes(uint64_t v)
4569{
4570 int len = 1;
4571
4572 if (v >= 240) {
4573 v = (v - 240) >> 4;
4574 while (1) {
4575 len++;
4576 if (v < 128)
4577 break;
4578 v = (v - 128) >> 7;
4579 }
4580 }
4581 return len;
4582}
4583
Willy Tarreau52bf8392020-03-08 00:42:37 +01004584
4585/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004586static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004587
4588/* This is a thread-safe implementation of xoroshiro128** described below:
4589 * http://prng.di.unimi.it/
4590 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4591 * supports fast jumps and passes all common quality tests. It is thread-safe,
4592 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4593 * local lock on other ones.
4594 */
4595uint64_t ha_random64()
4596{
4597 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004598 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4599 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004600
4601#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4602 static HA_SPINLOCK_T rand_lock;
4603
4604 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4605#endif
4606
4607 old[0] = ha_random_state[0];
4608 old[1] = ha_random_state[1];
4609
4610#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4611 do {
4612#endif
4613 result = rotl64(old[0] * 5, 7) * 9;
4614 new[1] = old[0] ^ old[1];
4615 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4616 new[1] = rotl64(new[1], 37); // c
4617
4618#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4619 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4620#else
4621 ha_random_state[0] = new[0];
4622 ha_random_state[1] = new[1];
4623#if defined(USE_THREAD)
4624 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4625#endif
4626#endif
4627 return result;
4628}
4629
4630/* seeds the random state using up to <len> bytes from <seed>, starting with
4631 * the first non-zero byte.
4632 */
4633void ha_random_seed(const unsigned char *seed, size_t len)
4634{
4635 size_t pos;
4636
4637 /* the seed must not be all zeroes, so we pre-fill it with alternating
4638 * bits and overwrite part of them with the block starting at the first
4639 * non-zero byte from the seed.
4640 */
4641 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4642
4643 for (pos = 0; pos < len; pos++)
4644 if (seed[pos] != 0)
4645 break;
4646
4647 if (pos == len)
4648 return;
4649
4650 seed += pos;
4651 len -= pos;
4652
4653 if (len > sizeof(ha_random_state))
4654 len = sizeof(ha_random_state);
4655
4656 memcpy(ha_random_state, seed, len);
4657}
4658
4659/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4660 * and is equivalent to calling ha_random64() as many times. It is used to
4661 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4662 * different generators (i.e. different processes after a fork). The <dist>
4663 * argument is the distance to jump to and is used in a loop so it rather not
4664 * be too large if the processing time is a concern.
4665 *
4666 * BEWARE: this function is NOT thread-safe and must not be called during
4667 * concurrent accesses to ha_random64().
4668 */
4669void ha_random_jump96(uint32_t dist)
4670{
4671 while (dist--) {
4672 uint64_t s0 = 0;
4673 uint64_t s1 = 0;
4674 int b;
4675
4676 for (b = 0; b < 64; b++) {
4677 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4678 s0 ^= ha_random_state[0];
4679 s1 ^= ha_random_state[1];
4680 }
4681 ha_random64();
4682 }
4683
4684 for (b = 0; b < 64; b++) {
4685 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4686 s0 ^= ha_random_state[0];
4687 s1 ^= ha_random_state[1];
4688 }
4689 ha_random64();
4690 }
4691 ha_random_state[0] = s0;
4692 ha_random_state[1] = s1;
4693 }
4694}
4695
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004696/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4697 * bytes large.
4698 */
4699void ha_generate_uuid(struct buffer *output)
4700{
4701 uint32_t rnd[4];
4702 uint64_t last;
4703
4704 last = ha_random64();
4705 rnd[0] = last;
4706 rnd[1] = last >> 32;
4707
4708 last = ha_random64();
4709 rnd[2] = last;
4710 rnd[3] = last >> 32;
4711
4712 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4713 rnd[0],
4714 rnd[1] & 0xFFFF,
4715 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4716 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4717 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4718}
4719
4720
Willy Tarreaubaaee002006-06-26 02:48:02 +02004721/*
4722 * Local variables:
4723 * c-indent-level: 8
4724 * c-basic-offset: 8
4725 * End:
4726 */