blob: eba79101bfcba51192eded2b7742140d04e248b2 [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 Tarreau45cb4fb2009-10-26 21:10:04 +010053#include <eb32tree.h>
Willy Tarreaued3cda02017-11-15 15:04:05 +010054#include <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
1145 * is optionnal and either in the dotted or CIDR notation.
1146 * 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
1196 * is an optionnal number of bits (128 being the default).
1197 * 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.
1279 * <out> contain the code of the dectected scheme, the start and length of
1280 * 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 Tarreaubf9c2fc2011-05-31 18:06:18 +02001752 */
1753int url_decode(char *string)
1754{
1755 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001756 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001757
1758 in = string;
1759 out = string;
1760 while (*in) {
1761 switch (*in) {
1762 case '+' :
1763 *out++ = ' ';
1764 break;
1765 case '%' :
1766 if (!ishex(in[1]) || !ishex(in[2]))
1767 goto end;
1768 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1769 in += 2;
1770 break;
1771 default:
1772 *out++ = *in;
1773 break;
1774 }
1775 in++;
1776 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001777 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001778 end:
1779 *out = 0;
1780 return ret;
1781}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001782
Willy Tarreau6911fa42007-03-04 18:06:08 +01001783unsigned int str2ui(const char *s)
1784{
1785 return __str2ui(s);
1786}
1787
1788unsigned int str2uic(const char *s)
1789{
1790 return __str2uic(s);
1791}
1792
1793unsigned int strl2ui(const char *s, int len)
1794{
1795 return __strl2ui(s, len);
1796}
1797
1798unsigned int strl2uic(const char *s, int len)
1799{
1800 return __strl2uic(s, len);
1801}
1802
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001803unsigned int read_uint(const char **s, const char *end)
1804{
1805 return __read_uint(s, end);
1806}
1807
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001808/* This function reads an unsigned integer from the string pointed to by <s> and
1809 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1810 * function automatically stops at <end>. If the number overflows, the 2^64-1
1811 * value is returned.
1812 */
1813unsigned long long int read_uint64(const char **s, const char *end)
1814{
1815 const char *ptr = *s;
1816 unsigned long long int i = 0, tmp;
1817 unsigned int j;
1818
1819 while (ptr < end) {
1820
1821 /* read next char */
1822 j = *ptr - '0';
1823 if (j > 9)
1824 goto read_uint64_end;
1825
1826 /* add char to the number and check overflow. */
1827 tmp = i * 10;
1828 if (tmp / 10 != i) {
1829 i = ULLONG_MAX;
1830 goto read_uint64_eat;
1831 }
1832 if (ULLONG_MAX - tmp < j) {
1833 i = ULLONG_MAX;
1834 goto read_uint64_eat;
1835 }
1836 i = tmp + j;
1837 ptr++;
1838 }
1839read_uint64_eat:
1840 /* eat each numeric char */
1841 while (ptr < end) {
1842 if ((unsigned int)(*ptr - '0') > 9)
1843 break;
1844 ptr++;
1845 }
1846read_uint64_end:
1847 *s = ptr;
1848 return i;
1849}
1850
1851/* This function reads an integer from the string pointed to by <s> and returns
1852 * it. The <s> pointer is adjusted to point to the first unread char. The function
1853 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1854 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1855 * returned.
1856 */
1857long long int read_int64(const char **s, const char *end)
1858{
1859 unsigned long long int i = 0;
1860 int neg = 0;
1861
1862 /* Look for minus char. */
1863 if (**s == '-') {
1864 neg = 1;
1865 (*s)++;
1866 }
1867 else if (**s == '+')
1868 (*s)++;
1869
1870 /* convert as positive number. */
1871 i = read_uint64(s, end);
1872
1873 if (neg) {
1874 if (i > 0x8000000000000000ULL)
1875 return LLONG_MIN;
1876 return -i;
1877 }
1878 if (i > 0x7fffffffffffffffULL)
1879 return LLONG_MAX;
1880 return i;
1881}
1882
Willy Tarreau6911fa42007-03-04 18:06:08 +01001883/* This one is 7 times faster than strtol() on athlon with checks.
1884 * It returns the value of the number composed of all valid digits read,
1885 * and can process negative numbers too.
1886 */
1887int strl2ic(const char *s, int len)
1888{
1889 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001890 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001891
1892 if (len > 0) {
1893 if (*s != '-') {
1894 /* positive number */
1895 while (len-- > 0) {
1896 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001897 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001898 if (j > 9)
1899 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001900 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001901 }
1902 } else {
1903 /* negative number */
1904 s++;
1905 while (--len > 0) {
1906 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001907 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001908 if (j > 9)
1909 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001910 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001911 }
1912 }
1913 }
1914 return i;
1915}
1916
1917
1918/* This function reads exactly <len> chars from <s> and converts them to a
1919 * signed integer which it stores into <ret>. It accurately detects any error
1920 * (truncated string, invalid chars, overflows). It is meant to be used in
1921 * applications designed for hostile environments. It returns zero when the
1922 * number has successfully been converted, non-zero otherwise. When an error
1923 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1924 * faster than strtol().
1925 */
1926int strl2irc(const char *s, int len, int *ret)
1927{
1928 int i = 0;
1929 int j;
1930
1931 if (!len)
1932 return 1;
1933
1934 if (*s != '-') {
1935 /* positive number */
1936 while (len-- > 0) {
1937 j = (*s++) - '0';
1938 if (j > 9) return 1; /* invalid char */
1939 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1940 i = i * 10;
1941 if (i + j < i) return 1; /* check for addition overflow */
1942 i = i + j;
1943 }
1944 } else {
1945 /* negative number */
1946 s++;
1947 while (--len > 0) {
1948 j = (*s++) - '0';
1949 if (j > 9) return 1; /* invalid char */
1950 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1951 i = i * 10;
1952 if (i - j > i) return 1; /* check for subtract overflow */
1953 i = i - j;
1954 }
1955 }
1956 *ret = i;
1957 return 0;
1958}
1959
1960
1961/* This function reads exactly <len> chars from <s> and converts them to a
1962 * signed integer which it stores into <ret>. It accurately detects any error
1963 * (truncated string, invalid chars, overflows). It is meant to be used in
1964 * applications designed for hostile environments. It returns zero when the
1965 * number has successfully been converted, non-zero otherwise. When an error
1966 * is returned, the <ret> value is left untouched. It is about 3 times slower
1967 * than str2irc().
1968 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001969
1970int strl2llrc(const char *s, int len, long long *ret)
1971{
1972 long long i = 0;
1973 int j;
1974
1975 if (!len)
1976 return 1;
1977
1978 if (*s != '-') {
1979 /* positive number */
1980 while (len-- > 0) {
1981 j = (*s++) - '0';
1982 if (j > 9) return 1; /* invalid char */
1983 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1984 i = i * 10LL;
1985 if (i + j < i) return 1; /* check for addition overflow */
1986 i = i + j;
1987 }
1988 } else {
1989 /* negative number */
1990 s++;
1991 while (--len > 0) {
1992 j = (*s++) - '0';
1993 if (j > 9) return 1; /* invalid char */
1994 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1995 i = i * 10LL;
1996 if (i - j > i) return 1; /* check for subtract overflow */
1997 i = i - j;
1998 }
1999 }
2000 *ret = i;
2001 return 0;
2002}
2003
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002004/* This function is used with pat_parse_dotted_ver(). It converts a string
2005 * composed by two number separated by a dot. Each part must contain in 16 bits
2006 * because internally they will be represented as a 32-bit quantity stored in
2007 * a 64-bit integer. It returns zero when the number has successfully been
2008 * converted, non-zero otherwise. When an error is returned, the <ret> value
2009 * is left untouched.
2010 *
2011 * "1.3" -> 0x0000000000010003
2012 * "65535.65535" -> 0x00000000ffffffff
2013 */
2014int strl2llrc_dotted(const char *text, int len, long long *ret)
2015{
2016 const char *end = &text[len];
2017 const char *p;
2018 long long major, minor;
2019
2020 /* Look for dot. */
2021 for (p = text; p < end; p++)
2022 if (*p == '.')
2023 break;
2024
2025 /* Convert major. */
2026 if (strl2llrc(text, p - text, &major) != 0)
2027 return 1;
2028
2029 /* Check major. */
2030 if (major >= 65536)
2031 return 1;
2032
2033 /* Convert minor. */
2034 minor = 0;
2035 if (p < end)
2036 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2037 return 1;
2038
2039 /* Check minor. */
2040 if (minor >= 65536)
2041 return 1;
2042
2043 /* Compose value. */
2044 *ret = (major << 16) | (minor & 0xffff);
2045 return 0;
2046}
2047
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002048/* This function parses a time value optionally followed by a unit suffix among
2049 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2050 * expected by the caller. The computation does its best to avoid overflows.
2051 * The value is returned in <ret> if everything is fine, and a NULL is returned
2052 * by the function. In case of error, a pointer to the error is returned and
2053 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002054 * Values resulting in values larger than or equal to 2^31 after conversion are
2055 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2056 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002057 */
2058const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2059{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002060 unsigned long long imult, idiv;
2061 unsigned long long omult, odiv;
2062 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002063
2064 omult = odiv = 1;
2065
2066 switch (unit_flags & TIME_UNIT_MASK) {
2067 case TIME_UNIT_US: omult = 1000000; break;
2068 case TIME_UNIT_MS: omult = 1000; break;
2069 case TIME_UNIT_S: break;
2070 case TIME_UNIT_MIN: odiv = 60; break;
2071 case TIME_UNIT_HOUR: odiv = 3600; break;
2072 case TIME_UNIT_DAY: odiv = 86400; break;
2073 default: break;
2074 }
2075
2076 value = 0;
2077
2078 while (1) {
2079 unsigned int j;
2080
2081 j = *text - '0';
2082 if (j > 9)
2083 break;
2084 text++;
2085 value *= 10;
2086 value += j;
2087 }
2088
2089 imult = idiv = 1;
2090 switch (*text) {
2091 case '\0': /* no unit = default unit */
2092 imult = omult = idiv = odiv = 1;
2093 break;
2094 case 's': /* second = unscaled unit */
2095 break;
2096 case 'u': /* microsecond : "us" */
2097 if (text[1] == 's') {
2098 idiv = 1000000;
2099 text++;
2100 }
2101 break;
2102 case 'm': /* millisecond : "ms" or minute: "m" */
2103 if (text[1] == 's') {
2104 idiv = 1000;
2105 text++;
2106 } else
2107 imult = 60;
2108 break;
2109 case 'h': /* hour : "h" */
2110 imult = 3600;
2111 break;
2112 case 'd': /* day : "d" */
2113 imult = 86400;
2114 break;
2115 default:
2116 return text;
2117 break;
2118 }
2119
2120 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2121 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2122 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2123 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2124
Willy Tarreau9faebe32019-06-07 19:00:37 +02002125 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2126 if (result >= 0x80000000)
2127 return PARSE_TIME_OVER;
2128 if (!result && value)
2129 return PARSE_TIME_UNDER;
2130 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002131 return NULL;
2132}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002133
Emeric Brun39132b22010-01-04 14:57:24 +01002134/* this function converts the string starting at <text> to an unsigned int
2135 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002136 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002137 */
2138const char *parse_size_err(const char *text, unsigned *ret) {
2139 unsigned value = 0;
2140
2141 while (1) {
2142 unsigned int j;
2143
2144 j = *text - '0';
2145 if (j > 9)
2146 break;
2147 if (value > ~0U / 10)
2148 return text;
2149 value *= 10;
2150 if (value > (value + j))
2151 return text;
2152 value += j;
2153 text++;
2154 }
2155
2156 switch (*text) {
2157 case '\0':
2158 break;
2159 case 'K':
2160 case 'k':
2161 if (value > ~0U >> 10)
2162 return text;
2163 value = value << 10;
2164 break;
2165 case 'M':
2166 case 'm':
2167 if (value > ~0U >> 20)
2168 return text;
2169 value = value << 20;
2170 break;
2171 case 'G':
2172 case 'g':
2173 if (value > ~0U >> 30)
2174 return text;
2175 value = value << 30;
2176 break;
2177 default:
2178 return text;
2179 }
2180
Godbach58048a22015-01-28 17:36:16 +08002181 if (*text != '\0' && *++text != '\0')
2182 return text;
2183
Emeric Brun39132b22010-01-04 14:57:24 +01002184 *ret = value;
2185 return NULL;
2186}
2187
Willy Tarreau126d4062013-12-03 17:50:47 +01002188/*
2189 * Parse binary string written in hexadecimal (source) and store the decoded
2190 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2191 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002192 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002193 */
2194int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2195{
2196 int len;
2197 const char *p = source;
2198 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002199 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002200
2201 len = strlen(source);
2202 if (len % 2) {
2203 memprintf(err, "an even number of hex digit is expected");
2204 return 0;
2205 }
2206
2207 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002208
Willy Tarreau126d4062013-12-03 17:50:47 +01002209 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002210 *binstr = calloc(len, sizeof(char));
2211 if (!*binstr) {
2212 memprintf(err, "out of memory while loading string pattern");
2213 return 0;
2214 }
2215 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002216 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002217 else {
2218 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002219 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002220 len, *binstrlen);
2221 return 0;
2222 }
2223 alloc = 0;
2224 }
2225 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002226
2227 i = j = 0;
2228 while (j < len) {
2229 if (!ishex(p[i++]))
2230 goto bad_input;
2231 if (!ishex(p[i++]))
2232 goto bad_input;
2233 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2234 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002235 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002236
2237bad_input:
2238 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002239 if (alloc) {
2240 free(*binstr);
2241 *binstr = NULL;
2242 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002243 return 0;
2244}
2245
Willy Tarreau946ba592009-05-10 15:41:18 +02002246/* copies at most <n> characters from <src> and always terminates with '\0' */
2247char *my_strndup(const char *src, int n)
2248{
2249 int len = 0;
2250 char *ret;
2251
2252 while (len < n && src[len])
2253 len++;
2254
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002255 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002256 if (!ret)
2257 return ret;
2258 memcpy(ret, src, len);
2259 ret[len] = '\0';
2260 return ret;
2261}
2262
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002263/*
2264 * search needle in haystack
2265 * returns the pointer if found, returns NULL otherwise
2266 */
2267const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2268{
2269 const void *c = NULL;
2270 unsigned char f;
2271
2272 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2273 return NULL;
2274
2275 f = *(char *)needle;
2276 c = haystack;
2277 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2278 if ((haystacklen - (c - haystack)) < needlelen)
2279 return NULL;
2280
2281 if (memcmp(c, needle, needlelen) == 0)
2282 return c;
2283 ++c;
2284 }
2285 return NULL;
2286}
2287
Willy Tarreau482b00d2009-10-04 22:48:42 +02002288/* This function returns the first unused key greater than or equal to <key> in
2289 * ID tree <root>. Zero is returned if no place is found.
2290 */
2291unsigned int get_next_id(struct eb_root *root, unsigned int key)
2292{
2293 struct eb32_node *used;
2294
2295 do {
2296 used = eb32_lookup_ge(root, key);
2297 if (!used || used->key > key)
2298 return key; /* key is available */
2299 key++;
2300 } while (key);
2301 return key;
2302}
2303
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002304/* dump the full tree to <file> in DOT format for debugging purposes. Will
2305 * optionally highlight node <subj> if found, depending on operation <op> :
2306 * 0 : nothing
2307 * >0 : insertion, node/leaf are surrounded in red
2308 * <0 : removal, node/leaf are dashed with no background
2309 * Will optionally add "desc" as a label on the graph if set and non-null.
2310 */
2311void 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 +01002312{
2313 struct eb32sc_node *node;
2314 unsigned long scope = -1;
2315
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002316 fprintf(file, "digraph ebtree {\n");
2317
2318 if (desc && *desc) {
2319 fprintf(file,
2320 " fontname=\"fixed\";\n"
2321 " fontsize=8;\n"
2322 " label=\"%s\";\n", desc);
2323 }
2324
Willy Tarreaued3cda02017-11-15 15:04:05 +01002325 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002326 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2327 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002328 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2329 );
2330
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002331 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002332 (long)eb_root_to_node(root),
2333 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002334 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2335
2336 node = eb32sc_first(root, scope);
2337 while (node) {
2338 if (node->node.node_p) {
2339 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002340 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2341 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2342 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002343
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002344 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002345 (long)node,
2346 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002347 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002348
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002349 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002350 (long)node,
2351 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002352 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2353
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002354 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002355 (long)node,
2356 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002357 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2358 }
2359
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002360 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2361 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2362 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002363
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002364 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002365 (long)node,
2366 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002367 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002368 node = eb32sc_next(node, scope);
2369 }
2370 fprintf(file, "}\n");
2371}
2372
Willy Tarreau348238b2010-01-18 15:05:57 +01002373/* This function compares a sample word possibly followed by blanks to another
2374 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2375 * otherwise zero. This intends to be used when checking HTTP headers for some
2376 * values. Note that it validates a word followed only by blanks but does not
2377 * validate a word followed by blanks then other chars.
2378 */
2379int word_match(const char *sample, int slen, const char *word, int wlen)
2380{
2381 if (slen < wlen)
2382 return 0;
2383
2384 while (wlen) {
2385 char c = *sample ^ *word;
2386 if (c && c != ('A' ^ 'a'))
2387 return 0;
2388 sample++;
2389 word++;
2390 slen--;
2391 wlen--;
2392 }
2393
2394 while (slen) {
2395 if (*sample != ' ' && *sample != '\t')
2396 return 0;
2397 sample++;
2398 slen--;
2399 }
2400 return 1;
2401}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002402
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002403/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2404 * is particularly fast because it avoids expensive operations such as
2405 * multiplies, which are optimized away at the end. It requires a properly
2406 * formated address though (3 points).
2407 */
2408unsigned int inetaddr_host(const char *text)
2409{
2410 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2411 register unsigned int dig100, dig10, dig1;
2412 int s;
2413 const char *p, *d;
2414
2415 dig1 = dig10 = dig100 = ascii_zero;
2416 s = 24;
2417
2418 p = text;
2419 while (1) {
2420 if (((unsigned)(*p - '0')) <= 9) {
2421 p++;
2422 continue;
2423 }
2424
2425 /* here, we have a complete byte between <text> and <p> (exclusive) */
2426 if (p == text)
2427 goto end;
2428
2429 d = p - 1;
2430 dig1 |= (unsigned int)(*d << s);
2431 if (d == text)
2432 goto end;
2433
2434 d--;
2435 dig10 |= (unsigned int)(*d << s);
2436 if (d == text)
2437 goto end;
2438
2439 d--;
2440 dig100 |= (unsigned int)(*d << s);
2441 end:
2442 if (!s || *p != '.')
2443 break;
2444
2445 s -= 8;
2446 text = ++p;
2447 }
2448
2449 dig100 -= ascii_zero;
2450 dig10 -= ascii_zero;
2451 dig1 -= ascii_zero;
2452 return ((dig100 * 10) + dig10) * 10 + dig1;
2453}
2454
2455/*
2456 * Idem except the first unparsed character has to be passed in <stop>.
2457 */
2458unsigned int inetaddr_host_lim(const char *text, const char *stop)
2459{
2460 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2461 register unsigned int dig100, dig10, dig1;
2462 int s;
2463 const char *p, *d;
2464
2465 dig1 = dig10 = dig100 = ascii_zero;
2466 s = 24;
2467
2468 p = text;
2469 while (1) {
2470 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2471 p++;
2472 continue;
2473 }
2474
2475 /* here, we have a complete byte between <text> and <p> (exclusive) */
2476 if (p == text)
2477 goto end;
2478
2479 d = p - 1;
2480 dig1 |= (unsigned int)(*d << s);
2481 if (d == text)
2482 goto end;
2483
2484 d--;
2485 dig10 |= (unsigned int)(*d << s);
2486 if (d == text)
2487 goto end;
2488
2489 d--;
2490 dig100 |= (unsigned int)(*d << s);
2491 end:
2492 if (!s || p == stop || *p != '.')
2493 break;
2494
2495 s -= 8;
2496 text = ++p;
2497 }
2498
2499 dig100 -= ascii_zero;
2500 dig10 -= ascii_zero;
2501 dig1 -= ascii_zero;
2502 return ((dig100 * 10) + dig10) * 10 + dig1;
2503}
2504
2505/*
2506 * Idem except the pointer to first unparsed byte is returned into <ret> which
2507 * must not be NULL.
2508 */
Willy Tarreau74172752010-10-15 23:21:42 +02002509unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002510{
2511 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2512 register unsigned int dig100, dig10, dig1;
2513 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002514 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002515
2516 dig1 = dig10 = dig100 = ascii_zero;
2517 s = 24;
2518
2519 p = text;
2520 while (1) {
2521 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2522 p++;
2523 continue;
2524 }
2525
2526 /* here, we have a complete byte between <text> and <p> (exclusive) */
2527 if (p == text)
2528 goto end;
2529
2530 d = p - 1;
2531 dig1 |= (unsigned int)(*d << s);
2532 if (d == text)
2533 goto end;
2534
2535 d--;
2536 dig10 |= (unsigned int)(*d << s);
2537 if (d == text)
2538 goto end;
2539
2540 d--;
2541 dig100 |= (unsigned int)(*d << s);
2542 end:
2543 if (!s || p == stop || *p != '.')
2544 break;
2545
2546 s -= 8;
2547 text = ++p;
2548 }
2549
2550 *ret = p;
2551 dig100 -= ascii_zero;
2552 dig10 -= ascii_zero;
2553 dig1 -= ascii_zero;
2554 return ((dig100 * 10) + dig10) * 10 + dig1;
2555}
2556
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002557/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2558 * or the number of chars read in case of success. Maybe this could be replaced
2559 * by one of the functions above. Also, apparently this function does not support
2560 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002561 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002562 */
2563int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2564{
2565 const char *addr;
2566 int saw_digit, octets, ch;
2567 u_char tmp[4], *tp;
2568 const char *cp = buf;
2569
2570 saw_digit = 0;
2571 octets = 0;
2572 *(tp = tmp) = 0;
2573
2574 for (addr = buf; addr - buf < len; addr++) {
2575 unsigned char digit = (ch = *addr) - '0';
2576
2577 if (digit > 9 && ch != '.')
2578 break;
2579
2580 if (digit <= 9) {
2581 u_int new = *tp * 10 + digit;
2582
2583 if (new > 255)
2584 return 0;
2585
2586 *tp = new;
2587
2588 if (!saw_digit) {
2589 if (++octets > 4)
2590 return 0;
2591 saw_digit = 1;
2592 }
2593 } else if (ch == '.' && saw_digit) {
2594 if (octets == 4)
2595 return 0;
2596
2597 *++tp = 0;
2598 saw_digit = 0;
2599 } else
2600 return 0;
2601 }
2602
2603 if (octets < 4)
2604 return 0;
2605
2606 memcpy(&dst->s_addr, tmp, 4);
2607 return addr - cp;
2608}
2609
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002610/* This function converts the string in <buf> of the len <len> to
2611 * struct in6_addr <dst> which must be allocated by the caller.
2612 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002613 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002614 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002615int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2616{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002617 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002618 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002619
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002620 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002621 return 0;
2622
2623 memcpy(null_term_ip6, buf, len);
2624 null_term_ip6[len] = '\0';
2625
Willy Tarreau075415a2013-12-12 11:29:39 +01002626 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002627 return 0;
2628
Willy Tarreau075415a2013-12-12 11:29:39 +01002629 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002630 return 1;
2631}
2632
Willy Tarreauacf95772010-06-14 19:09:21 +02002633/* To be used to quote config arg positions. Returns the short string at <ptr>
2634 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2635 * if ptr is NULL or empty. The string is locally allocated.
2636 */
2637const char *quote_arg(const char *ptr)
2638{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002639 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002640 int i;
2641
2642 if (!ptr || !*ptr)
2643 return "end of line";
2644 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002645 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002646 val[i] = *ptr++;
2647 val[i++] = '\'';
2648 val[i] = '\0';
2649 return val;
2650}
2651
Willy Tarreau5b180202010-07-18 10:40:48 +02002652/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2653int get_std_op(const char *str)
2654{
2655 int ret = -1;
2656
2657 if (*str == 'e' && str[1] == 'q')
2658 ret = STD_OP_EQ;
2659 else if (*str == 'n' && str[1] == 'e')
2660 ret = STD_OP_NE;
2661 else if (*str == 'l') {
2662 if (str[1] == 'e') ret = STD_OP_LE;
2663 else if (str[1] == 't') ret = STD_OP_LT;
2664 }
2665 else if (*str == 'g') {
2666 if (str[1] == 'e') ret = STD_OP_GE;
2667 else if (str[1] == 't') ret = STD_OP_GT;
2668 }
2669
2670 if (ret == -1 || str[2] != '\0')
2671 return -1;
2672 return ret;
2673}
2674
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002675/* hash a 32-bit integer to another 32-bit integer */
2676unsigned int full_hash(unsigned int a)
2677{
2678 return __full_hash(a);
2679}
2680
Willy Tarreauf3241112019-02-26 09:56:22 +01002681/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2682 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2683 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2684 * a popcount variant and is described here :
2685 * https://graphics.stanford.edu/~seander/bithacks.html
2686 */
2687unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2688{
2689 unsigned long a, b, c, d;
2690 unsigned int s;
2691 unsigned int t;
2692
2693 a = m - ((m >> 1) & ~0UL/3);
2694 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2695 c = (b + (b >> 4)) & ~0UL/0x11;
2696 d = (c + (c >> 8)) & ~0UL/0x101;
2697
2698 r++; // make r be 1..64
2699
2700 t = 0;
2701 s = LONGBITS;
2702 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002703 unsigned long d2 = (d >> 16) >> 16;
2704 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002705 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2706 }
2707
2708 t = (d >> (s - 16)) & 0xff;
2709 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2710 t = (c >> (s - 8)) & 0xf;
2711 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2712 t = (b >> (s - 4)) & 0x7;
2713 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2714 t = (a >> (s - 2)) & 0x3;
2715 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2716 t = (m >> (s - 1)) & 0x1;
2717 s -= ((t - r) & 256) >> 8;
2718
2719 return s - 1;
2720}
2721
2722/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2723 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2724 * using mask_prep_rank_map() below.
2725 */
2726unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2727 unsigned long a, unsigned long b,
2728 unsigned long c, unsigned long d)
2729{
2730 unsigned int s;
2731 unsigned int t;
2732
2733 r++; // make r be 1..64
2734
2735 t = 0;
2736 s = LONGBITS;
2737 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002738 unsigned long d2 = (d >> 16) >> 16;
2739 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002740 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2741 }
2742
2743 t = (d >> (s - 16)) & 0xff;
2744 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2745 t = (c >> (s - 8)) & 0xf;
2746 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2747 t = (b >> (s - 4)) & 0x7;
2748 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2749 t = (a >> (s - 2)) & 0x3;
2750 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2751 t = (m >> (s - 1)) & 0x1;
2752 s -= ((t - r) & 256) >> 8;
2753
2754 return s - 1;
2755}
2756
2757/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2758 * above.
2759 */
2760void mask_prep_rank_map(unsigned long m,
2761 unsigned long *a, unsigned long *b,
2762 unsigned long *c, unsigned long *d)
2763{
2764 *a = m - ((m >> 1) & ~0UL/3);
2765 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2766 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2767 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2768}
2769
David du Colombier4f92d322011-03-24 11:09:31 +01002770/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002771 * otherwise zero. Note that <addr> may not necessarily be aligned
2772 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002773 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002774int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002775{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002776 struct in_addr addr_copy;
2777
2778 memcpy(&addr_copy, addr, sizeof(addr_copy));
2779 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002780}
2781
2782/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002783 * otherwise zero. Note that <addr> may not necessarily be aligned
2784 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002785 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002786int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002787{
2788 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002789 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002790
Willy Tarreaueec1d382016-07-13 11:59:39 +02002791 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002792 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002793 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002794 (((int *)net)[i] & ((int *)mask)[i]))
2795 return 0;
2796 return 1;
2797}
2798
2799/* RFC 4291 prefix */
2800const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2801 0x00, 0x00, 0x00, 0x00,
2802 0x00, 0x00, 0xFF, 0xFF };
2803
Joseph Herlant32b83272018-11-15 11:58:28 -08002804/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002805 * Input and output may overlap.
2806 */
David du Colombier4f92d322011-03-24 11:09:31 +01002807void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2808{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002809 struct in_addr tmp_addr;
2810
2811 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002812 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002813 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002814}
2815
Joseph Herlant32b83272018-11-15 11:58:28 -08002816/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002817 * Return true if conversion is possible and false otherwise.
2818 */
2819int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2820{
2821 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2822 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2823 sizeof(struct in_addr));
2824 return 1;
2825 }
2826
2827 return 0;
2828}
2829
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002830/* compare two struct sockaddr_storage and return:
2831 * 0 (true) if the addr is the same in both
2832 * 1 (false) if the addr is not the same in both
2833 * -1 (unable) if one of the addr is not AF_INET*
2834 */
2835int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2836{
2837 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2838 return -1;
2839
2840 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2841 return -1;
2842
2843 if (ss1->ss_family != ss2->ss_family)
2844 return 1;
2845
2846 switch (ss1->ss_family) {
2847 case AF_INET:
2848 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2849 &((struct sockaddr_in *)ss2)->sin_addr,
2850 sizeof(struct in_addr)) != 0;
2851 case AF_INET6:
2852 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2853 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2854 sizeof(struct in6_addr)) != 0;
2855 }
2856
2857 return 1;
2858}
2859
Baptiste Assmann08396c82016-01-31 00:27:17 +01002860/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002861 * The caller must allocate and clear <dest> before calling.
2862 * The source must be in either AF_INET or AF_INET6 family, or the destination
2863 * address will be undefined. If the destination address used to hold a port,
2864 * it is preserved, so that this function can be used to switch to another
2865 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002866 */
2867struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2868{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002869 int prev_port;
2870
2871 prev_port = get_net_port(dest);
2872 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002873 dest->ss_family = source->ss_family;
2874
2875 /* copy new addr and apply it */
2876 switch (source->ss_family) {
2877 case AF_INET:
2878 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002879 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002880 break;
2881 case AF_INET6:
2882 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 +01002883 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002884 break;
2885 }
2886
2887 return dest;
2888}
2889
William Lallemand421f5b52012-02-06 18:15:57 +01002890char *human_time(int t, short hz_div) {
2891 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2892 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002893 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002894 int cnt=2; // print two numbers
2895
2896 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002897 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002898 return rv;
2899 }
2900
2901 if (unlikely(hz_div > 1))
2902 t /= hz_div;
2903
2904 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002905 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002906 cnt--;
2907 }
2908
2909 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002910 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002911 cnt--;
2912 }
2913
2914 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002915 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002916 cnt--;
2917 }
2918
2919 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002920 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002921
2922 return rv;
2923}
2924
2925const char *monthname[12] = {
2926 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2927 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2928};
2929
2930/* date2str_log: write a date in the format :
2931 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2932 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2933 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2934 *
2935 * without using sprintf. return a pointer to the last char written (\0) or
2936 * NULL if there isn't enough space.
2937 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002938char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002939{
2940
2941 if (size < 25) /* the size is fixed: 24 chars + \0 */
2942 return NULL;
2943
2944 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002945 if (!dst)
2946 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002947 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002948
William Lallemand421f5b52012-02-06 18:15:57 +01002949 memcpy(dst, monthname[tm->tm_mon], 3); // month
2950 dst += 3;
2951 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002952
William Lallemand421f5b52012-02-06 18:15:57 +01002953 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002954 if (!dst)
2955 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002956 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002957
William Lallemand421f5b52012-02-06 18:15:57 +01002958 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002959 if (!dst)
2960 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002961 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002962
William Lallemand421f5b52012-02-06 18:15:57 +01002963 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002964 if (!dst)
2965 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002966 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002967
William Lallemand421f5b52012-02-06 18:15:57 +01002968 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002969 if (!dst)
2970 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002971 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002972
Willy Tarreau7d9421d2020-02-29 09:08:02 +01002973 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002974 if (!dst)
2975 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002976 *dst = '\0';
2977
2978 return dst;
2979}
2980
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002981/* Base year used to compute leap years */
2982#define TM_YEAR_BASE 1900
2983
2984/* Return the difference in seconds between two times (leap seconds are ignored).
2985 * Retrieved from glibc 2.18 source code.
2986 */
2987static int my_tm_diff(const struct tm *a, const struct tm *b)
2988{
2989 /* Compute intervening leap days correctly even if year is negative.
2990 * Take care to avoid int overflow in leap day calculations,
2991 * but it's OK to assume that A and B are close to each other.
2992 */
2993 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2994 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2995 int a100 = a4 / 25 - (a4 % 25 < 0);
2996 int b100 = b4 / 25 - (b4 % 25 < 0);
2997 int a400 = a100 >> 2;
2998 int b400 = b100 >> 2;
2999 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3000 int years = a->tm_year - b->tm_year;
3001 int days = (365 * years + intervening_leap_days
3002 + (a->tm_yday - b->tm_yday));
3003 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3004 + (a->tm_min - b->tm_min))
3005 + (a->tm_sec - b->tm_sec));
3006}
3007
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003008/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003009 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003010 * The string returned has the same format as returned by strftime(... "%z", tm).
3011 * Offsets are kept in an internal cache for better performances.
3012 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003013const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003014{
3015 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003016 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003017
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003018 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003019 struct tm tm_gmt;
3020 int diff;
3021 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003022
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003023 /* Pretend DST not active if its status is unknown */
3024 if (isdst < 0)
3025 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003026
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003027 /* Fetch the offset and initialize it if needed */
3028 gmt_offset = gmt_offsets[isdst & 0x01];
3029 if (unlikely(!*gmt_offset)) {
3030 get_gmtime(t, &tm_gmt);
3031 diff = my_tm_diff(tm, &tm_gmt);
3032 if (diff < 0) {
3033 diff = -diff;
3034 *gmt_offset = '-';
3035 } else {
3036 *gmt_offset = '+';
3037 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003038 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003039 diff /= 60; /* Convert to minutes */
3040 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3041 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003042
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003043 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003044}
3045
William Lallemand421f5b52012-02-06 18:15:57 +01003046/* gmt2str_log: write a date in the format :
3047 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3048 * return a pointer to the last char written (\0) or
3049 * NULL if there isn't enough space.
3050 */
3051char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3052{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003053 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003054 return NULL;
3055
3056 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003057 if (!dst)
3058 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003059 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003060
William Lallemand421f5b52012-02-06 18:15:57 +01003061 memcpy(dst, monthname[tm->tm_mon], 3); // month
3062 dst += 3;
3063 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003064
William Lallemand421f5b52012-02-06 18:15:57 +01003065 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003066 if (!dst)
3067 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003068 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003069
William Lallemand421f5b52012-02-06 18:15:57 +01003070 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003071 if (!dst)
3072 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003073 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003074
William Lallemand421f5b52012-02-06 18:15:57 +01003075 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003076 if (!dst)
3077 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003078 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003079
William Lallemand421f5b52012-02-06 18:15:57 +01003080 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003081 if (!dst)
3082 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003083 *dst++ = ' ';
3084 *dst++ = '+';
3085 *dst++ = '0';
3086 *dst++ = '0';
3087 *dst++ = '0';
3088 *dst++ = '0';
3089 *dst = '\0';
3090
3091 return dst;
3092}
3093
Yuxans Yao4e25b012012-10-19 10:36:09 +08003094/* localdate2str_log: write a date in the format :
3095 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003096 * Both t and tm must represent the same time.
3097 * return a pointer to the last char written (\0) or
3098 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003099 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003100char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003101{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003102 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003103 if (size < 27) /* the size is fixed: 26 chars + \0 */
3104 return NULL;
3105
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003106 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003107
Yuxans Yao4e25b012012-10-19 10:36:09 +08003108 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003109 if (!dst)
3110 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003111 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003112
Yuxans Yao4e25b012012-10-19 10:36:09 +08003113 memcpy(dst, monthname[tm->tm_mon], 3); // month
3114 dst += 3;
3115 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003116
Yuxans Yao4e25b012012-10-19 10:36:09 +08003117 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003118 if (!dst)
3119 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003120 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003121
Yuxans Yao4e25b012012-10-19 10:36:09 +08003122 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003123 if (!dst)
3124 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003125 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003126
Yuxans Yao4e25b012012-10-19 10:36:09 +08003127 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003128 if (!dst)
3129 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003130 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003131
Yuxans Yao4e25b012012-10-19 10:36:09 +08003132 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003133 if (!dst)
3134 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003135 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003136
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003137 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003138 dst += 5;
3139 *dst = '\0';
3140
3141 return dst;
3142}
3143
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003144/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3145 * It is meant as a portable replacement for timegm() for use with valid inputs.
3146 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3147 */
3148time_t my_timegm(const struct tm *tm)
3149{
3150 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3151 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3152 * sum of the extra N days for elapsed months. The sum of all these N
3153 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3154 * in a 5-bit word. This means that with 60 bits we can represent a
3155 * matrix of all these values at once, which is fast and efficient to
3156 * access. The extra February day for leap years is not counted here.
3157 *
3158 * Jan : none = 0 (0)
3159 * Feb : Jan = 3 (3)
3160 * Mar : Jan..Feb = 3 (3 + 0)
3161 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3162 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3163 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3164 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3165 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3166 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3167 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3168 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3169 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3170 */
3171 uint64_t extra =
3172 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3173 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3174 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3175 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3176
3177 unsigned int y = tm->tm_year + 1900;
3178 unsigned int m = tm->tm_mon;
3179 unsigned long days = 0;
3180
3181 /* days since 1/1/1970 for full years */
3182 days += days_since_zero(y) - days_since_zero(1970);
3183
3184 /* days for full months in the current year */
3185 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3186
3187 /* count + 1 after March for leap years. A leap year is a year multiple
3188 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3189 * is leap, 1900 isn't, 1904 is.
3190 */
3191 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3192 days++;
3193
3194 days += tm->tm_mday - 1;
3195 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3196}
3197
Thierry Fournier93127942016-01-20 18:49:45 +01003198/* This function check a char. It returns true and updates
3199 * <date> and <len> pointer to the new position if the
3200 * character is found.
3201 */
3202static inline int parse_expect_char(const char **date, int *len, char c)
3203{
3204 if (*len < 1 || **date != c)
3205 return 0;
3206 (*len)--;
3207 (*date)++;
3208 return 1;
3209}
3210
3211/* This function expects a string <str> of len <l>. It return true and updates.
3212 * <date> and <len> if the string matches, otherwise, it returns false.
3213 */
3214static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3215{
3216 if (*len < l || strncmp(*date, str, l) != 0)
3217 return 0;
3218 (*len) -= l;
3219 (*date) += l;
3220 return 1;
3221}
3222
3223/* This macro converts 3 chars name in integer. */
3224#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3225
3226/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3227 * / %x54.75.65 ; "Tue", case-sensitive
3228 * / %x57.65.64 ; "Wed", case-sensitive
3229 * / %x54.68.75 ; "Thu", case-sensitive
3230 * / %x46.72.69 ; "Fri", case-sensitive
3231 * / %x53.61.74 ; "Sat", case-sensitive
3232 * / %x53.75.6E ; "Sun", case-sensitive
3233 *
3234 * This array must be alphabetically sorted
3235 */
3236static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3237{
3238 if (*len < 3)
3239 return 0;
3240 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3241 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3242 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3243 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3244 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3245 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3246 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3247 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3248 default: return 0;
3249 }
3250 *len -= 3;
3251 *date += 3;
3252 return 1;
3253}
3254
3255/* month = %x4A.61.6E ; "Jan", case-sensitive
3256 * / %x46.65.62 ; "Feb", case-sensitive
3257 * / %x4D.61.72 ; "Mar", case-sensitive
3258 * / %x41.70.72 ; "Apr", case-sensitive
3259 * / %x4D.61.79 ; "May", case-sensitive
3260 * / %x4A.75.6E ; "Jun", case-sensitive
3261 * / %x4A.75.6C ; "Jul", case-sensitive
3262 * / %x41.75.67 ; "Aug", case-sensitive
3263 * / %x53.65.70 ; "Sep", case-sensitive
3264 * / %x4F.63.74 ; "Oct", case-sensitive
3265 * / %x4E.6F.76 ; "Nov", case-sensitive
3266 * / %x44.65.63 ; "Dec", case-sensitive
3267 *
3268 * This array must be alphabetically sorted
3269 */
3270static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3271{
3272 if (*len < 3)
3273 return 0;
3274 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3275 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3276 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3277 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3278 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3279 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3280 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3281 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3282 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3283 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3284 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3285 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3286 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3287 default: return 0;
3288 }
3289 *len -= 3;
3290 *date += 3;
3291 return 1;
3292}
3293
3294/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3295 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3296 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3297 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3298 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3299 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3300 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3301 *
3302 * This array must be alphabetically sorted
3303 */
3304static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3305{
3306 if (*len < 6) /* Minimum length. */
3307 return 0;
3308 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3309 case STR2I3('M','o','n'):
3310 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3311 tm->tm_wday = 1;
3312 return 1;
3313 case STR2I3('T','u','e'):
3314 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3315 tm->tm_wday = 2;
3316 return 1;
3317 case STR2I3('W','e','d'):
3318 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3319 tm->tm_wday = 3;
3320 return 1;
3321 case STR2I3('T','h','u'):
3322 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3323 tm->tm_wday = 4;
3324 return 1;
3325 case STR2I3('F','r','i'):
3326 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3327 tm->tm_wday = 5;
3328 return 1;
3329 case STR2I3('S','a','t'):
3330 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3331 tm->tm_wday = 6;
3332 return 1;
3333 case STR2I3('S','u','n'):
3334 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3335 tm->tm_wday = 7;
3336 return 1;
3337 }
3338 return 0;
3339}
3340
3341/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3342static inline int parse_digit(const char **date, int *len, int *digit)
3343{
3344 if (*len < 1 || **date < '0' || **date > '9')
3345 return 0;
3346 *digit = (**date - '0');
3347 (*date)++;
3348 (*len)--;
3349 return 1;
3350}
3351
3352/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3353static inline int parse_2digit(const char **date, int *len, int *digit)
3354{
3355 int value;
3356
3357 RET0_UNLESS(parse_digit(date, len, &value));
3358 (*digit) = value * 10;
3359 RET0_UNLESS(parse_digit(date, len, &value));
3360 (*digit) += value;
3361
3362 return 1;
3363}
3364
3365/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3366static inline int parse_4digit(const char **date, int *len, int *digit)
3367{
3368 int value;
3369
3370 RET0_UNLESS(parse_digit(date, len, &value));
3371 (*digit) = value * 1000;
3372
3373 RET0_UNLESS(parse_digit(date, len, &value));
3374 (*digit) += value * 100;
3375
3376 RET0_UNLESS(parse_digit(date, len, &value));
3377 (*digit) += value * 10;
3378
3379 RET0_UNLESS(parse_digit(date, len, &value));
3380 (*digit) += value;
3381
3382 return 1;
3383}
3384
3385/* time-of-day = hour ":" minute ":" second
3386 * ; 00:00:00 - 23:59:60 (leap second)
3387 *
3388 * hour = 2DIGIT
3389 * minute = 2DIGIT
3390 * second = 2DIGIT
3391 */
3392static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3393{
3394 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3395 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3396 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3397 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3398 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3399 return 1;
3400}
3401
3402/* From RFC7231
3403 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3404 *
3405 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3406 * ; fixed length/zone/capitalization subset of the format
3407 * ; see Section 3.3 of [RFC5322]
3408 *
3409 *
3410 * date1 = day SP month SP year
3411 * ; e.g., 02 Jun 1982
3412 *
3413 * day = 2DIGIT
3414 * year = 4DIGIT
3415 *
3416 * GMT = %x47.4D.54 ; "GMT", case-sensitive
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 *
3425 * DIGIT = decimal 0-9
3426 */
3427int parse_imf_date(const char *date, int len, struct tm *tm)
3428{
David Carlier327298c2016-11-20 10:42:38 +00003429 /* tm_gmtoff, if present, ought to be zero'ed */
3430 memset(tm, 0, sizeof(*tm));
3431
Thierry Fournier93127942016-01-20 18:49:45 +01003432 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3433 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3434 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3435 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3436 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3437 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3438 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3439 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3440 tm->tm_year -= 1900;
3441 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3442 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3443 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3444 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3445 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003446 return 1;
3447}
3448
3449/* From RFC7231
3450 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3451 *
3452 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3453 * date2 = day "-" month "-" 2DIGIT
3454 * ; e.g., 02-Jun-82
3455 *
3456 * day = 2DIGIT
3457 */
3458int parse_rfc850_date(const char *date, int len, struct tm *tm)
3459{
3460 int year;
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_ldayname(&date, &len, tm)); /* Read the 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 "-" */
3470 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3471 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3472
3473 /* year = 2DIGIT
3474 *
3475 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3476 * two-digit year, MUST interpret a timestamp that appears to be more
3477 * than 50 years in the future as representing the most recent year in
3478 * the past that had the same last two digits.
3479 */
3480 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3481
3482 /* expect SP */
3483 if (!parse_expect_char(&date, &len, ' ')) {
3484 /* Maybe we have the date with 4 digits. */
3485 RET0_UNLESS(parse_2digit(&date, &len, &year));
3486 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3487 /* expect SP */
3488 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3489 } else {
3490 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3491 * tm_year is the number of year since 1900, so for +1900, we
3492 * do nothing, and for +2000, we add 100.
3493 */
3494 if (tm->tm_year <= 60)
3495 tm->tm_year += 100;
3496 }
3497
3498 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3499 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3500 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3501 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003502
3503 return 1;
3504}
3505
3506/* From RFC7231
3507 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3508 *
3509 * asctime-date = day-name SP date3 SP time-of-day SP year
3510 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3511 * ; e.g., Jun 2
3512 *
3513 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3514 * whitespace in an HTTP-date beyond that specifically included as SP in
3515 * the grammar.
3516 */
3517int parse_asctime_date(const char *date, int len, struct tm *tm)
3518{
David Carlier327298c2016-11-20 10:42:38 +00003519 /* tm_gmtoff, if present, ought to be zero'ed */
3520 memset(tm, 0, sizeof(*tm));
3521
Thierry Fournier93127942016-01-20 18:49:45 +01003522 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3523 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3524 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3525 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3526
3527 /* expect SP and 1DIGIT or 2DIGIT */
3528 if (parse_expect_char(&date, &len, ' '))
3529 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3530 else
3531 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3532
3533 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3534 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3535 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3536 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3537 tm->tm_year -= 1900;
3538 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003539 return 1;
3540}
3541
3542/* From RFC7231
3543 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3544 *
3545 * HTTP-date = IMF-fixdate / obs-date
3546 * obs-date = rfc850-date / asctime-date
3547 *
3548 * parses an HTTP date in the RFC format and is accepted
3549 * alternatives. <date> is the strinf containing the date,
3550 * len is the len of the string. <tm> is filled with the
3551 * parsed time. We must considers this time as GMT.
3552 */
3553int parse_http_date(const char *date, int len, struct tm *tm)
3554{
3555 if (parse_imf_date(date, len, tm))
3556 return 1;
3557
3558 if (parse_rfc850_date(date, len, tm))
3559 return 1;
3560
3561 if (parse_asctime_date(date, len, tm))
3562 return 1;
3563
3564 return 0;
3565}
3566
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003567/* Dynamically allocates a string of the proper length to hold the formatted
3568 * output. NULL is returned on error. The caller is responsible for freeing the
3569 * memory area using free(). The resulting string is returned in <out> if the
3570 * pointer is not NULL. A previous version of <out> might be used to build the
3571 * new string, and it will be freed before returning if it is not NULL, which
3572 * makes it possible to build complex strings from iterative calls without
3573 * having to care about freeing intermediate values, as in the example below :
3574 *
3575 * memprintf(&err, "invalid argument: '%s'", arg);
3576 * ...
3577 * memprintf(&err, "parser said : <%s>\n", *err);
3578 * ...
3579 * free(*err);
3580 *
3581 * This means that <err> must be initialized to NULL before first invocation.
3582 * The return value also holds the allocated string, which eases error checking
3583 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003584 * passed instead and it will be ignored. The returned message will then also
3585 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003586 *
3587 * It is also convenient to use it without any free except the last one :
3588 * err = NULL;
3589 * if (!fct1(err)) report(*err);
3590 * if (!fct2(err)) report(*err);
3591 * if (!fct3(err)) report(*err);
3592 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003593 *
3594 * memprintf relies on memvprintf. This last version can be called from any
3595 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003596 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003597char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003598{
3599 va_list args;
3600 char *ret = NULL;
3601 int allocated = 0;
3602 int needed = 0;
3603
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003604 if (!out)
3605 return NULL;
3606
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003607 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003608 char buf1;
3609
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003610 /* vsnprintf() will return the required length even when the
3611 * target buffer is NULL. We do this in a loop just in case
3612 * intermediate evaluations get wrong.
3613 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003614 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003615 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003616 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003617 if (needed < allocated) {
3618 /* Note: on Solaris 8, the first iteration always
3619 * returns -1 if allocated is zero, so we force a
3620 * retry.
3621 */
3622 if (!allocated)
3623 needed = 0;
3624 else
3625 break;
3626 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003627
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003628 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003629 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003630 } while (ret);
3631
3632 if (needed < 0) {
3633 /* an error was encountered */
3634 free(ret);
3635 ret = NULL;
3636 }
3637
3638 if (out) {
3639 free(*out);
3640 *out = ret;
3641 }
3642
3643 return ret;
3644}
William Lallemand421f5b52012-02-06 18:15:57 +01003645
Christopher Faulet93a518f2017-10-24 11:25:33 +02003646char *memprintf(char **out, const char *format, ...)
3647{
3648 va_list args;
3649 char *ret = NULL;
3650
3651 va_start(args, format);
3652 ret = memvprintf(out, format, args);
3653 va_end(args);
3654
3655 return ret;
3656}
3657
Willy Tarreau21c705b2012-09-14 11:40:36 +02003658/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3659 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003660 * freed by the caller. It also supports being passed a NULL which results in the same
3661 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003662 * Example of use :
3663 * parse(cmd, &err); (callee: memprintf(&err, ...))
3664 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3665 * free(err);
3666 */
3667char *indent_msg(char **out, int level)
3668{
3669 char *ret, *in, *p;
3670 int needed = 0;
3671 int lf = 0;
3672 int lastlf = 0;
3673 int len;
3674
Willy Tarreau70eec382012-10-10 08:56:47 +02003675 if (!out || !*out)
3676 return NULL;
3677
Willy Tarreau21c705b2012-09-14 11:40:36 +02003678 in = *out - 1;
3679 while ((in = strchr(in + 1, '\n')) != NULL) {
3680 lastlf = in - *out;
3681 lf++;
3682 }
3683
3684 if (!lf) /* single line, no LF, return it as-is */
3685 return *out;
3686
3687 len = strlen(*out);
3688
3689 if (lf == 1 && lastlf == len - 1) {
3690 /* single line, LF at end, strip it and return as-is */
3691 (*out)[lastlf] = 0;
3692 return *out;
3693 }
3694
3695 /* OK now we have at least one LF, we need to process the whole string
3696 * as a multi-line string. What we'll do :
3697 * - prefix with an LF if there is none
3698 * - add <level> spaces before each line
3699 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3700 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3701 */
3702
3703 needed = 1 + level * (lf + 1) + len + 1;
3704 p = ret = malloc(needed);
3705 in = *out;
3706
3707 /* skip initial LFs */
3708 while (*in == '\n')
3709 in++;
3710
3711 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3712 while (*in) {
3713 *p++ = '\n';
3714 memset(p, ' ', level);
3715 p += level;
3716 do {
3717 *p++ = *in++;
3718 } while (*in && *in != '\n');
3719 if (*in)
3720 in++;
3721 }
3722 *p = 0;
3723
3724 free(*out);
3725 *out = ret;
3726
3727 return ret;
3728}
3729
Willy Tarreaua2c99112019-08-21 13:17:37 +02003730/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3731 * and end of lines replaced with <eol> if not 0. The first line to indent has
3732 * to be indicated in <first> (starts at zero), so that it is possible to skip
3733 * indenting the first line if it has to be appended after an existing message.
3734 * Empty strings are never indented, and NULL strings are considered empty both
3735 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3736 * character, non-zero otherwise.
3737 */
3738int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3739{
3740 int bol, lf;
3741 int pfxlen = pfx ? strlen(pfx) : 0;
3742
3743 if (!in)
3744 return 0;
3745
3746 bol = 1;
3747 lf = 0;
3748 while (*in) {
3749 if (bol && pfxlen) {
3750 if (first > 0)
3751 first--;
3752 else
3753 b_putblk(out, pfx, pfxlen);
3754 bol = 0;
3755 }
3756
3757 lf = (*in == '\n');
3758 bol |= lf;
3759 b_putchr(out, (lf && eol) ? eol : *in);
3760 in++;
3761 }
3762 return lf;
3763}
3764
Willy Tarreau9d22e562019-03-29 18:49:09 +01003765/* removes environment variable <name> from the environment as found in
3766 * environ. This is only provided as an alternative for systems without
3767 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
3768 * The principle is to scan environ for each occurence of variable name
3769 * <name> and to replace the matching pointers with the last pointer of
3770 * the array (since variables are not ordered).
3771 * It always returns 0 (success).
3772 */
3773int my_unsetenv(const char *name)
3774{
3775 extern char **environ;
3776 char **p = environ;
3777 int vars;
3778 int next;
3779 int len;
3780
3781 len = strlen(name);
3782 for (vars = 0; p[vars]; vars++)
3783 ;
3784 next = 0;
3785 while (next < vars) {
3786 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3787 next++;
3788 continue;
3789 }
3790 if (next < vars - 1)
3791 p[next] = p[vars - 1];
3792 p[--vars] = NULL;
3793 }
3794 return 0;
3795}
3796
Willy Tarreaudad36a32013-03-11 01:20:04 +01003797/* Convert occurrences of environment variables in the input string to their
3798 * corresponding value. A variable is identified as a series of alphanumeric
3799 * characters or underscores following a '$' sign. The <in> string must be
3800 * free()able. NULL returns NULL. The resulting string might be reallocated if
3801 * some expansion is made. Variable names may also be enclosed into braces if
3802 * needed (eg: to concatenate alphanum characters).
3803 */
3804char *env_expand(char *in)
3805{
3806 char *txt_beg;
3807 char *out;
3808 char *txt_end;
3809 char *var_beg;
3810 char *var_end;
3811 char *value;
3812 char *next;
3813 int out_len;
3814 int val_len;
3815
3816 if (!in)
3817 return in;
3818
3819 value = out = NULL;
3820 out_len = 0;
3821
3822 txt_beg = in;
3823 do {
3824 /* look for next '$' sign in <in> */
3825 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3826
3827 if (!*txt_end && !out) /* end and no expansion performed */
3828 return in;
3829
3830 val_len = 0;
3831 next = txt_end;
3832 if (*txt_end == '$') {
3833 char save;
3834
3835 var_beg = txt_end + 1;
3836 if (*var_beg == '{')
3837 var_beg++;
3838
3839 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003840 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003841 var_end++;
3842 }
3843
3844 next = var_end;
3845 if (*var_end == '}' && (var_beg > txt_end + 1))
3846 next++;
3847
3848 /* get value of the variable name at this location */
3849 save = *var_end;
3850 *var_end = '\0';
3851 value = getenv(var_beg);
3852 *var_end = save;
3853 val_len = value ? strlen(value) : 0;
3854 }
3855
Hubert Verstraete831962e2016-06-28 22:44:26 +02003856 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003857 if (txt_end > txt_beg) {
3858 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3859 out_len += txt_end - txt_beg;
3860 }
3861 if (val_len) {
3862 memcpy(out + out_len, value, val_len);
3863 out_len += val_len;
3864 }
3865 out[out_len] = 0;
3866 txt_beg = next;
3867 } while (*txt_beg);
3868
3869 /* here we know that <out> was allocated and that we don't need <in> anymore */
3870 free(in);
3871 return out;
3872}
3873
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003874
3875/* same as strstr() but case-insensitive and with limit length */
3876const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3877{
3878 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003879 unsigned int slen, plen;
3880 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003881
3882 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3883 return NULL;
3884
3885 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3886 return str1;
3887
3888 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3889 return NULL;
3890
3891 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3892 while (toupper(*start) != toupper(*str2)) {
3893 start++;
3894 slen--;
3895 tmp1++;
3896
3897 if (tmp1 >= len_str1)
3898 return NULL;
3899
3900 /* if pattern longer than string */
3901 if (slen < plen)
3902 return NULL;
3903 }
3904
3905 sptr = start;
3906 pptr = (char *)str2;
3907
3908 tmp2 = 0;
3909 while (toupper(*sptr) == toupper(*pptr)) {
3910 sptr++;
3911 pptr++;
3912 tmp2++;
3913
3914 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3915 return start;
3916 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3917 return NULL;
3918 }
3919 }
3920 return NULL;
3921}
3922
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003923/* This function read the next valid utf8 char.
3924 * <s> is the byte srray to be decode, <len> is its length.
3925 * The function returns decoded char encoded like this:
3926 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3927 * are the length read. The decoded character is stored in <c>.
3928 */
3929unsigned char utf8_next(const char *s, int len, unsigned int *c)
3930{
3931 const unsigned char *p = (unsigned char *)s;
3932 int dec;
3933 unsigned char code = UTF8_CODE_OK;
3934
3935 if (len < 1)
3936 return UTF8_CODE_OK;
3937
3938 /* Check the type of UTF8 sequence
3939 *
3940 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3941 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3942 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3943 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3944 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3945 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3946 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3947 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3948 */
3949 switch (*p) {
3950 case 0x00 ... 0x7f:
3951 *c = *p;
3952 return UTF8_CODE_OK | 1;
3953
3954 case 0x80 ... 0xbf:
3955 *c = *p;
3956 return UTF8_CODE_BADSEQ | 1;
3957
3958 case 0xc0 ... 0xdf:
3959 if (len < 2) {
3960 *c = *p;
3961 return UTF8_CODE_BADSEQ | 1;
3962 }
3963 *c = *p & 0x1f;
3964 dec = 1;
3965 break;
3966
3967 case 0xe0 ... 0xef:
3968 if (len < 3) {
3969 *c = *p;
3970 return UTF8_CODE_BADSEQ | 1;
3971 }
3972 *c = *p & 0x0f;
3973 dec = 2;
3974 break;
3975
3976 case 0xf0 ... 0xf7:
3977 if (len < 4) {
3978 *c = *p;
3979 return UTF8_CODE_BADSEQ | 1;
3980 }
3981 *c = *p & 0x07;
3982 dec = 3;
3983 break;
3984
3985 case 0xf8 ... 0xfb:
3986 if (len < 5) {
3987 *c = *p;
3988 return UTF8_CODE_BADSEQ | 1;
3989 }
3990 *c = *p & 0x03;
3991 dec = 4;
3992 break;
3993
3994 case 0xfc ... 0xfd:
3995 if (len < 6) {
3996 *c = *p;
3997 return UTF8_CODE_BADSEQ | 1;
3998 }
3999 *c = *p & 0x01;
4000 dec = 5;
4001 break;
4002
4003 case 0xfe ... 0xff:
4004 default:
4005 *c = *p;
4006 return UTF8_CODE_BADSEQ | 1;
4007 }
4008
4009 p++;
4010
4011 while (dec > 0) {
4012
4013 /* need 0x10 for the 2 first bits */
4014 if ( ( *p & 0xc0 ) != 0x80 )
4015 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4016
4017 /* add data at char */
4018 *c = ( *c << 6 ) | ( *p & 0x3f );
4019
4020 dec--;
4021 p++;
4022 }
4023
4024 /* Check ovelong encoding.
4025 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4026 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4027 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4028 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004029 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004030 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4031 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4032 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4033 code |= UTF8_CODE_OVERLONG;
4034
4035 /* Check invalid UTF8 range. */
4036 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4037 (*c >= 0xfffe && *c <= 0xffff))
4038 code |= UTF8_CODE_INVRANGE;
4039
4040 return code | ((p-(unsigned char *)s)&0x0f);
4041}
4042
Maxime de Roucydc887852016-05-13 23:52:54 +02004043/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4044 * On failure : return 0 and <err> filled with an error message.
4045 * The caller is responsible for freeing the <err> and <str> copy
4046 * memory area using free()
4047 */
4048int list_append_word(struct list *li, const char *str, char **err)
4049{
4050 struct wordlist *wl;
4051
4052 wl = calloc(1, sizeof(*wl));
4053 if (!wl) {
4054 memprintf(err, "out of memory");
4055 goto fail_wl;
4056 }
4057
4058 wl->s = strdup(str);
4059 if (!wl->s) {
4060 memprintf(err, "out of memory");
4061 goto fail_wl_s;
4062 }
4063
4064 LIST_ADDQ(li, &wl->list);
4065
4066 return 1;
4067
4068fail_wl_s:
4069 free(wl->s);
4070fail_wl:
4071 free(wl);
4072 return 0;
4073}
4074
Willy Tarreau37101052019-05-20 16:48:20 +02004075/* indicates if a memory location may safely be read or not. The trick consists
4076 * in performing a harmless syscall using this location as an input and letting
4077 * the operating system report whether it's OK or not. For this we have the
4078 * stat() syscall, which will return EFAULT when the memory location supposed
4079 * to contain the file name is not readable. If it is readable it will then
4080 * either return 0 if the area contains an existing file name, or -1 with
4081 * another code. This must not be abused, and some audit systems might detect
4082 * this as abnormal activity. It's used only for unsafe dumps.
4083 */
4084int may_access(const void *ptr)
4085{
4086 struct stat buf;
4087
4088 if (stat(ptr, &buf) == 0)
4089 return 1;
4090 if (errno == EFAULT)
4091 return 0;
4092 return 1;
4093}
4094
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004095/* print a string of text buffer to <out>. The format is :
4096 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4097 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4098 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4099 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004100int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004101{
4102 unsigned char c;
4103 int ptr = 0;
4104
4105 while (buf[ptr] && ptr < bsize) {
4106 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004107 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004108 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004109 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004110 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004111 }
4112 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004113 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004114 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004115 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004116 switch (c) {
4117 case ' ': c = ' '; break;
4118 case '\t': c = 't'; break;
4119 case '\n': c = 'n'; break;
4120 case '\r': c = 'r'; break;
4121 case '\e': c = 'e'; break;
4122 case '\\': c = '\\'; break;
4123 case '=': c = '='; break;
4124 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004125 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004126 }
4127 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004128 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004129 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004130 out->area[out->data++] = '\\';
4131 out->area[out->data++] = 'x';
4132 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4133 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004134 }
4135 ptr++;
4136 }
4137
4138 return ptr;
4139}
4140
4141/* print a buffer in hexa.
4142 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4143 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004144int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004145{
4146 unsigned char c;
4147 int ptr = 0;
4148
4149 while (ptr < bsize) {
4150 c = buf[ptr];
4151
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004152 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004153 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004154 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4155 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004156
4157 ptr++;
4158 }
4159 return ptr;
4160}
4161
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004162/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4163 * prepending each line with prefix <pfx>. The output is *not* initialized.
4164 * The output will not wrap pas the buffer's end so it is more optimal if the
4165 * caller makes sure the buffer is aligned first. A trailing zero will always
4166 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004167 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4168 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004169 */
Willy Tarreau37101052019-05-20 16:48:20 +02004170void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004171{
4172 const unsigned char *d = buf;
4173 int i, j, start;
4174
4175 d = (const unsigned char *)(((unsigned long)buf) & -16);
4176 start = ((unsigned long)buf) & 15;
4177
4178 for (i = 0; i < start + len; i += 16) {
4179 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4180
Willy Tarreau37101052019-05-20 16:48:20 +02004181 // 0: unchecked, 1: checked safe, 2: danger
4182 unsafe = !!unsafe;
4183 if (unsafe && !may_access(d + i))
4184 unsafe = 2;
4185
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004186 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004187 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004188 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004189 else if (unsafe > 1)
4190 chunk_strcat(out, "** ");
4191 else
4192 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004193
4194 if (j == 7)
4195 chunk_strcat(out, "- ");
4196 }
4197 chunk_strcat(out, " ");
4198 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004199 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004200 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004201 else if (unsafe > 1)
4202 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004203 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004204 chunk_appendf(out, "%c", d[i + j]);
4205 else
4206 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004207 }
4208 chunk_strcat(out, "\n");
4209 }
4210}
4211
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004212/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4213 * enclosed in brackets after the address itself, formatted on 14 chars
4214 * including the "0x" prefix. This is meant to be used as a prefix for code
4215 * areas. For example:
4216 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4217 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4218 * is emitted. A NULL <pfx> will be considered empty.
4219 */
4220void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4221{
4222 int ok = 0;
4223 int i;
4224
4225 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4226
4227 for (i = 0; i < n; i++) {
4228 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4229 ok = may_access(addr + i);
4230 if (ok)
4231 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4232 else
4233 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4234 }
4235}
4236
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004237/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4238 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4239 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4240 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4241 * lines are respected within the limit of 70 output chars. Lines that are
4242 * continuation of a previous truncated line begin with "+" instead of " "
4243 * after the offset. The new pointer is returned.
4244 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004245int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004246 int *line, int ptr)
4247{
4248 int end;
4249 unsigned char c;
4250
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004251 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004252 if (end > out->size)
4253 return ptr;
4254
4255 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4256
4257 while (ptr < len && ptr < bsize) {
4258 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004259 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004260 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004261 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004262 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004263 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004264 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004265 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004266 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004267 switch (c) {
4268 case '\t': c = 't'; break;
4269 case '\n': c = 'n'; break;
4270 case '\r': c = 'r'; break;
4271 case '\e': c = 'e'; break;
4272 case '\\': c = '\\'; break;
4273 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004274 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004275 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004276 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004277 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004278 out->area[out->data++] = '\\';
4279 out->area[out->data++] = 'x';
4280 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4281 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004282 }
4283 if (buf[ptr++] == '\n') {
4284 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004285 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004286 *line = ptr;
4287 return ptr;
4288 }
4289 }
4290 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004291 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004292 return ptr;
4293}
4294
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004295/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004296 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4297 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004298 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004299void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4300 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004301{
Willy Tarreau73459792017-04-11 07:58:08 +02004302 unsigned int i;
4303 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004304
4305 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4306 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004307 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004308 for (j = 0; j < 8; j++) {
4309 if (b + j >= 0 && b + j < len)
4310 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4311 else
4312 fprintf(out, " ");
4313 }
4314
4315 if (b + j >= 0 && b + j < len)
4316 fputc('-', out);
4317 else
4318 fputc(' ', out);
4319
4320 for (j = 8; j < 16; j++) {
4321 if (b + j >= 0 && b + j < len)
4322 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4323 else
4324 fprintf(out, " ");
4325 }
4326
4327 fprintf(out, " ");
4328 for (j = 0; j < 16; j++) {
4329 if (b + j >= 0 && b + j < len) {
4330 if (isprint((unsigned char)buf[b + j]))
4331 fputc((unsigned char)buf[b + j], out);
4332 else
4333 fputc('.', out);
4334 }
4335 else
4336 fputc(' ', out);
4337 }
4338 fputc('\n', out);
4339 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004340}
4341
Willy Tarreaubb869862020-04-16 10:52:41 +02004342/* Tries to report the executable path name on platforms supporting this. If
4343 * not found or not possible, returns NULL.
4344 */
4345const char *get_exec_path()
4346{
4347 const char *ret = NULL;
4348
4349#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4350 long execfn = getauxval(AT_EXECFN);
4351
4352 if (execfn && execfn != ENOENT)
4353 ret = (const char *)execfn;
4354#endif
4355 return ret;
4356}
4357
Willy Tarreau109201f2020-03-04 10:31:58 +01004358#ifdef __ELF__
Willy Tarreau9133e482020-03-04 10:19:36 +01004359/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4360 * also returns the symbol size in <size>, otherwise returns 0 there.
4361 */
4362static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4363{
4364 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004365#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004366 const ElfW(Sym) *sym;
4367
4368 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4369 if (ret)
4370 *size = sym ? sym->st_size : 0;
4371#else
4372 ret = dladdr(addr, dli);
4373 *size = 0;
4374#endif
4375 return ret;
4376}
4377#endif
4378
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004379/* Tries to append to buffer <buf> some indications about the symbol at address
4380 * <addr> using the following form:
4381 * lib:+0xoffset (unresolvable address from lib's base)
4382 * main+0xoffset (unresolvable address from main (+/-))
4383 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4384 * name (resolved exact exec address)
4385 * lib:name (resolved exact lib address)
4386 * name+0xoffset/0xsize (resolved address within exec symbol)
4387 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4388 *
4389 * The file name (lib or executable) is limited to what lies between the last
4390 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4391 * 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 +01004392 * that contains the "main" symbol, or when __ELF__ is not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004393 *
4394 * The symbol's base address is returned, or NULL when unresolved, in order to
4395 * allow the caller to match it against known ones.
4396 */
4397void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
4398{
4399 const struct {
4400 const void *func;
4401 const char *name;
4402 } fcts[] = {
4403 { .func = process_stream, .name = "process_stream" },
4404 { .func = task_run_applet, .name = "task_run_applet" },
4405 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4406 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4407 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4408 { .func = listener_accept, .name = "listener_accept" },
4409 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4410 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4411#ifdef USE_LUA
4412 { .func = hlua_process_task, .name = "hlua_process_task" },
4413#endif
4414#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4415 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4416 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4417#endif
4418 };
4419
Willy Tarreau109201f2020-03-04 10:31:58 +01004420#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004421 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004422 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004423 const char *fname, *p;
4424#endif
4425 int i;
4426
4427 if (pfx)
4428 chunk_appendf(buf, "%s", pfx);
4429
4430 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4431 if (addr == fcts[i].func) {
4432 chunk_appendf(buf, "%s", fcts[i].name);
4433 return addr;
4434 }
4435 }
4436
Willy Tarreau109201f2020-03-04 10:31:58 +01004437#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004438 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004439 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004440 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004441
4442 /* 1. prefix the library name if it's not the same object as the one
4443 * that contains the main function. The name is picked between last '/'
4444 * and first following '.'.
4445 */
4446 if (!dladdr(main, &dli_main))
4447 dli_main.dli_fbase = NULL;
4448
4449 if (dli_main.dli_fbase != dli.dli_fbase) {
4450 fname = dli.dli_fname;
4451 p = strrchr(fname, '/');
4452 if (p++)
4453 fname = p;
4454 p = strchr(fname, '.');
4455 if (!p)
4456 p = fname + strlen(fname);
4457
4458 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4459 }
4460
4461 /* 2. symbol name */
4462 if (dli.dli_sname) {
4463 /* known, dump it and return symbol's address (exact or relative) */
4464 chunk_appendf(buf, "%s", dli.dli_sname);
4465 if (addr != dli.dli_saddr) {
4466 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004467 if (size)
4468 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004469 }
4470 return dli.dli_saddr;
4471 }
4472 else if (dli_main.dli_fbase != dli.dli_fbase) {
4473 /* unresolved symbol from a known library, report relative offset */
4474 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4475 return NULL;
4476 }
Willy Tarreau109201f2020-03-04 10:31:58 +01004477#endif /* __ELF__ */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004478 unknown:
4479 /* unresolved symbol from the main file, report relative offset to main */
4480 if ((void*)addr < (void*)main)
4481 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4482 else
4483 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4484 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004485}
4486
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004487/*
4488 * Allocate an array of unsigned int with <nums> as address from <str> string
4489 * made of integer sepereated by dot characters.
4490 *
4491 * First, initializes the value with <sz> as address to 0 and initializes the
4492 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4493 * address updating <sz> pointed value to the size of this array.
4494 *
4495 * Returns 1 if succeeded, 0 if not.
4496 */
4497int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4498{
4499 unsigned int *n;
4500 const char *s, *end;
4501
4502 s = str;
4503 *sz = 0;
4504 end = str + strlen(str);
4505 *nums = n = NULL;
4506
4507 while (1) {
4508 unsigned int r;
4509
4510 if (s >= end)
4511 break;
4512
4513 r = read_uint(&s, end);
4514 /* Expected characters after having read an uint: '\0' or '.',
4515 * if '.', must not be terminal.
4516 */
4517 if (*s != '\0'&& (*s++ != '.' || s == end))
4518 return 0;
4519
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004520 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004521 if (!n)
4522 return 0;
4523
4524 n[(*sz)++] = r;
4525 }
4526 *nums = n;
4527
4528 return 1;
4529}
4530
Willy Tarreau4d589e72019-08-23 19:02:26 +02004531
4532/* returns the number of bytes needed to encode <v> as a varint. An inline
4533 * version exists for use with constants (__varint_bytes()).
4534 */
4535int varint_bytes(uint64_t v)
4536{
4537 int len = 1;
4538
4539 if (v >= 240) {
4540 v = (v - 240) >> 4;
4541 while (1) {
4542 len++;
4543 if (v < 128)
4544 break;
4545 v = (v - 128) >> 7;
4546 }
4547 }
4548 return len;
4549}
4550
Willy Tarreau52bf8392020-03-08 00:42:37 +01004551
4552/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004553static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004554
4555/* This is a thread-safe implementation of xoroshiro128** described below:
4556 * http://prng.di.unimi.it/
4557 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4558 * supports fast jumps and passes all common quality tests. It is thread-safe,
4559 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4560 * local lock on other ones.
4561 */
4562uint64_t ha_random64()
4563{
4564 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004565 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4566 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004567
4568#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4569 static HA_SPINLOCK_T rand_lock;
4570
4571 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4572#endif
4573
4574 old[0] = ha_random_state[0];
4575 old[1] = ha_random_state[1];
4576
4577#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4578 do {
4579#endif
4580 result = rotl64(old[0] * 5, 7) * 9;
4581 new[1] = old[0] ^ old[1];
4582 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4583 new[1] = rotl64(new[1], 37); // c
4584
4585#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4586 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4587#else
4588 ha_random_state[0] = new[0];
4589 ha_random_state[1] = new[1];
4590#if defined(USE_THREAD)
4591 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4592#endif
4593#endif
4594 return result;
4595}
4596
4597/* seeds the random state using up to <len> bytes from <seed>, starting with
4598 * the first non-zero byte.
4599 */
4600void ha_random_seed(const unsigned char *seed, size_t len)
4601{
4602 size_t pos;
4603
4604 /* the seed must not be all zeroes, so we pre-fill it with alternating
4605 * bits and overwrite part of them with the block starting at the first
4606 * non-zero byte from the seed.
4607 */
4608 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4609
4610 for (pos = 0; pos < len; pos++)
4611 if (seed[pos] != 0)
4612 break;
4613
4614 if (pos == len)
4615 return;
4616
4617 seed += pos;
4618 len -= pos;
4619
4620 if (len > sizeof(ha_random_state))
4621 len = sizeof(ha_random_state);
4622
4623 memcpy(ha_random_state, seed, len);
4624}
4625
4626/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4627 * and is equivalent to calling ha_random64() as many times. It is used to
4628 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4629 * different generators (i.e. different processes after a fork). The <dist>
4630 * argument is the distance to jump to and is used in a loop so it rather not
4631 * be too large if the processing time is a concern.
4632 *
4633 * BEWARE: this function is NOT thread-safe and must not be called during
4634 * concurrent accesses to ha_random64().
4635 */
4636void ha_random_jump96(uint32_t dist)
4637{
4638 while (dist--) {
4639 uint64_t s0 = 0;
4640 uint64_t s1 = 0;
4641 int b;
4642
4643 for (b = 0; b < 64; b++) {
4644 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4645 s0 ^= ha_random_state[0];
4646 s1 ^= ha_random_state[1];
4647 }
4648 ha_random64();
4649 }
4650
4651 for (b = 0; b < 64; b++) {
4652 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4653 s0 ^= ha_random_state[0];
4654 s1 ^= ha_random_state[1];
4655 }
4656 ha_random64();
4657 }
4658 ha_random_state[0] = s0;
4659 ha_random_state[1] = s1;
4660 }
4661}
4662
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004663/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4664 * bytes large.
4665 */
4666void ha_generate_uuid(struct buffer *output)
4667{
4668 uint32_t rnd[4];
4669 uint64_t last;
4670
4671 last = ha_random64();
4672 rnd[0] = last;
4673 rnd[1] = last >> 32;
4674
4675 last = ha_random64();
4676 rnd[2] = last;
4677 rnd[3] = last >> 32;
4678
4679 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4680 rnd[0],
4681 rnd[1] & 0xFFFF,
4682 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4683 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4684 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4685}
4686
4687
Willy Tarreaubaaee002006-06-26 02:48:02 +02004688/*
4689 * Local variables:
4690 * c-indent-level: 8
4691 * c-basic-offset: 8
4692 * End:
4693 */