blob: 38723ddf3c6628483eceed0f19e7534b8d336557 [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 Tarreau2e74c3f2007-12-02 18:45:09 +010013#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020014#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020015#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020016#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020017#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020018#include <stdlib.h>
19#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010020#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020021#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010022#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020023#include <sys/stat.h>
24#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010025#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020026#include <netinet/in.h>
27#include <arpa/inet.h>
28
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010029#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020030#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020031#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010032#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010033#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020034#include <proto/dns.h>
Christopher Faulet582baa52020-12-11 09:23:07 +010035#include <proto/log.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010036#include <eb32tree.h>
Willy Tarreaued3cda02017-11-15 15:04:05 +010037#include <eb32sctree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020038
Thierry Fournier93127942016-01-20 18:49:45 +010039/* This macro returns false if the test __x is false. Many
40 * of the following parsing function must be abort the processing
41 * if it returns 0, so this macro is useful for writing light code.
42 */
43#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
44
Willy Tarreau56adcf22012-12-23 18:00:29 +010045/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020046 * 2^64-1 = 18446744073709551615 or
47 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020048 *
49 * The HTML version needs room for adding the 25 characters
50 * '<span class="rls"></span>' around digits at positions 3N+1 in order
51 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020052 */
Christopher Faulet99bca652017-11-14 16:47:26 +010053THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
54THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020055
Willy Tarreau588297f2014-06-16 15:16:40 +020056/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
57 * to quote strings larger than a max configuration line.
58 */
Christopher Faulet99bca652017-11-14 16:47:26 +010059THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
60THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020061
Willy Tarreaubaaee002006-06-26 02:48:02 +020062/*
William Lallemande7340ec2012-01-24 11:15:39 +010063 * unsigned long long ASCII representation
64 *
65 * return the last char '\0' or NULL if no enough
66 * space in dst
67 */
68char *ulltoa(unsigned long long n, char *dst, size_t size)
69{
70 int i = 0;
71 char *res;
72
73 switch(n) {
74 case 1ULL ... 9ULL:
75 i = 0;
76 break;
77
78 case 10ULL ... 99ULL:
79 i = 1;
80 break;
81
82 case 100ULL ... 999ULL:
83 i = 2;
84 break;
85
86 case 1000ULL ... 9999ULL:
87 i = 3;
88 break;
89
90 case 10000ULL ... 99999ULL:
91 i = 4;
92 break;
93
94 case 100000ULL ... 999999ULL:
95 i = 5;
96 break;
97
98 case 1000000ULL ... 9999999ULL:
99 i = 6;
100 break;
101
102 case 10000000ULL ... 99999999ULL:
103 i = 7;
104 break;
105
106 case 100000000ULL ... 999999999ULL:
107 i = 8;
108 break;
109
110 case 1000000000ULL ... 9999999999ULL:
111 i = 9;
112 break;
113
114 case 10000000000ULL ... 99999999999ULL:
115 i = 10;
116 break;
117
118 case 100000000000ULL ... 999999999999ULL:
119 i = 11;
120 break;
121
122 case 1000000000000ULL ... 9999999999999ULL:
123 i = 12;
124 break;
125
126 case 10000000000000ULL ... 99999999999999ULL:
127 i = 13;
128 break;
129
130 case 100000000000000ULL ... 999999999999999ULL:
131 i = 14;
132 break;
133
134 case 1000000000000000ULL ... 9999999999999999ULL:
135 i = 15;
136 break;
137
138 case 10000000000000000ULL ... 99999999999999999ULL:
139 i = 16;
140 break;
141
142 case 100000000000000000ULL ... 999999999999999999ULL:
143 i = 17;
144 break;
145
146 case 1000000000000000000ULL ... 9999999999999999999ULL:
147 i = 18;
148 break;
149
150 case 10000000000000000000ULL ... ULLONG_MAX:
151 i = 19;
152 break;
153 }
154 if (i + 2 > size) // (i + 1) + '\0'
155 return NULL; // too long
156 res = dst + i + 1;
157 *res = '\0';
158 for (; i >= 0; i--) {
159 dst[i] = n % 10ULL + '0';
160 n /= 10ULL;
161 }
162 return res;
163}
164
165/*
166 * unsigned long ASCII representation
167 *
168 * return the last char '\0' or NULL if no enough
169 * space in dst
170 */
171char *ultoa_o(unsigned long n, char *dst, size_t size)
172{
173 int i = 0;
174 char *res;
175
176 switch (n) {
177 case 0U ... 9UL:
178 i = 0;
179 break;
180
181 case 10U ... 99UL:
182 i = 1;
183 break;
184
185 case 100U ... 999UL:
186 i = 2;
187 break;
188
189 case 1000U ... 9999UL:
190 i = 3;
191 break;
192
193 case 10000U ... 99999UL:
194 i = 4;
195 break;
196
197 case 100000U ... 999999UL:
198 i = 5;
199 break;
200
201 case 1000000U ... 9999999UL:
202 i = 6;
203 break;
204
205 case 10000000U ... 99999999UL:
206 i = 7;
207 break;
208
209 case 100000000U ... 999999999UL:
210 i = 8;
211 break;
212#if __WORDSIZE == 32
213
214 case 1000000000ULL ... ULONG_MAX:
215 i = 9;
216 break;
217
218#elif __WORDSIZE == 64
219
220 case 1000000000ULL ... 9999999999UL:
221 i = 9;
222 break;
223
224 case 10000000000ULL ... 99999999999UL:
225 i = 10;
226 break;
227
228 case 100000000000ULL ... 999999999999UL:
229 i = 11;
230 break;
231
232 case 1000000000000ULL ... 9999999999999UL:
233 i = 12;
234 break;
235
236 case 10000000000000ULL ... 99999999999999UL:
237 i = 13;
238 break;
239
240 case 100000000000000ULL ... 999999999999999UL:
241 i = 14;
242 break;
243
244 case 1000000000000000ULL ... 9999999999999999UL:
245 i = 15;
246 break;
247
248 case 10000000000000000ULL ... 99999999999999999UL:
249 i = 16;
250 break;
251
252 case 100000000000000000ULL ... 999999999999999999UL:
253 i = 17;
254 break;
255
256 case 1000000000000000000ULL ... 9999999999999999999UL:
257 i = 18;
258 break;
259
260 case 10000000000000000000ULL ... ULONG_MAX:
261 i = 19;
262 break;
263
264#endif
265 }
266 if (i + 2 > size) // (i + 1) + '\0'
267 return NULL; // too long
268 res = dst + i + 1;
269 *res = '\0';
270 for (; i >= 0; i--) {
271 dst[i] = n % 10U + '0';
272 n /= 10U;
273 }
274 return res;
275}
276
277/*
278 * signed long ASCII representation
279 *
280 * return the last char '\0' or NULL if no enough
281 * space in dst
282 */
283char *ltoa_o(long int n, char *dst, size_t size)
284{
285 char *pos = dst;
286
287 if (n < 0) {
288 if (size < 3)
289 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
290 *pos = '-';
291 pos++;
292 dst = ultoa_o(-n, pos, size - 1);
293 } else {
294 dst = ultoa_o(n, dst, size);
295 }
296 return dst;
297}
298
299/*
300 * signed long long ASCII representation
301 *
302 * return the last char '\0' or NULL if no enough
303 * space in dst
304 */
305char *lltoa(long long n, char *dst, size_t size)
306{
307 char *pos = dst;
308
309 if (n < 0) {
310 if (size < 3)
311 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
312 *pos = '-';
313 pos++;
314 dst = ulltoa(-n, pos, size - 1);
315 } else {
316 dst = ulltoa(n, dst, size);
317 }
318 return dst;
319}
320
321/*
322 * write a ascii representation of a unsigned into dst,
323 * return a pointer to the last character
324 * Pad the ascii representation with '0', using size.
325 */
326char *utoa_pad(unsigned int n, char *dst, size_t size)
327{
328 int i = 0;
329 char *ret;
330
331 switch(n) {
332 case 0U ... 9U:
333 i = 0;
334 break;
335
336 case 10U ... 99U:
337 i = 1;
338 break;
339
340 case 100U ... 999U:
341 i = 2;
342 break;
343
344 case 1000U ... 9999U:
345 i = 3;
346 break;
347
348 case 10000U ... 99999U:
349 i = 4;
350 break;
351
352 case 100000U ... 999999U:
353 i = 5;
354 break;
355
356 case 1000000U ... 9999999U:
357 i = 6;
358 break;
359
360 case 10000000U ... 99999999U:
361 i = 7;
362 break;
363
364 case 100000000U ... 999999999U:
365 i = 8;
366 break;
367
368 case 1000000000U ... 4294967295U:
369 i = 9;
370 break;
371 }
372 if (i + 2 > size) // (i + 1) + '\0'
373 return NULL; // too long
374 if (i < size)
375 i = size - 2; // padding - '\0'
376
377 ret = dst + i + 1;
378 *ret = '\0';
379 for (; i >= 0; i--) {
380 dst[i] = n % 10U + '0';
381 n /= 10U;
382 }
383 return ret;
384}
385
386/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200387 * copies at most <size-1> chars from <src> to <dst>. Last char is always
388 * set to 0, unless <size> is 0. The number of chars copied is returned
389 * (excluding the terminating zero).
390 * This code has been optimized for size and speed : on x86, it's 45 bytes
391 * long, uses only registers, and consumes only 4 cycles per char.
392 */
393int strlcpy2(char *dst, const char *src, int size)
394{
395 char *orig = dst;
396 if (size) {
397 while (--size && (*dst = *src)) {
398 src++; dst++;
399 }
400 *dst = 0;
401 }
402 return dst - orig;
403}
404
405/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200406 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200407 * the ascii representation for number 'n' in decimal.
408 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100409char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200410{
411 char *pos;
412
Willy Tarreau72d759c2007-10-25 12:14:10 +0200413 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200414 *pos-- = '\0';
415
416 do {
417 *pos-- = '0' + n % 10;
418 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200419 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200420 return pos + 1;
421}
422
Willy Tarreau91092e52007-10-25 16:58:42 +0200423/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200424 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200425 * the ascii representation for number 'n' in decimal.
426 */
427char *lltoa_r(long long int in, char *buffer, int size)
428{
429 char *pos;
430 int neg = 0;
431 unsigned long long int n;
432
433 pos = buffer + size - 1;
434 *pos-- = '\0';
435
436 if (in < 0) {
437 neg = 1;
438 n = -in;
439 }
440 else
441 n = in;
442
443 do {
444 *pos-- = '0' + n % 10;
445 n /= 10;
446 } while (n && pos >= buffer);
447 if (neg && pos > buffer)
448 *pos-- = '-';
449 return pos + 1;
450}
451
452/*
453 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200454 * the ascii representation for signed number 'n' in decimal.
455 */
456char *sltoa_r(long n, char *buffer, int size)
457{
458 char *pos;
459
460 if (n >= 0)
461 return ultoa_r(n, buffer, size);
462
463 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
464 *pos = '-';
465 return pos;
466}
467
468/*
469 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200470 * the ascii representation for number 'n' in decimal, formatted for
471 * HTML output with tags to create visual grouping by 3 digits. The
472 * output needs to support at least 171 characters.
473 */
474const char *ulltoh_r(unsigned long long n, char *buffer, int size)
475{
476 char *start;
477 int digit = 0;
478
479 start = buffer + size;
480 *--start = '\0';
481
482 do {
483 if (digit == 3 && start >= buffer + 7)
484 memcpy(start -= 7, "</span>", 7);
485
486 if (start >= buffer + 1) {
487 *--start = '0' + n % 10;
488 n /= 10;
489 }
490
491 if (digit == 3 && start >= buffer + 18)
492 memcpy(start -= 18, "<span class=\"rls\">", 18);
493
494 if (digit++ == 3)
495 digit = 1;
496 } while (n && start > buffer);
497 return start;
498}
499
500/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200501 * This function simply returns a locally allocated string containing the ascii
502 * representation for number 'n' in decimal, unless n is 0 in which case it
503 * returns the alternate string (or an empty string if the alternate string is
504 * NULL). It use is intended for limits reported in reports, where it's
505 * desirable not to display anything if there is no limit. Warning! it shares
506 * the same vector as ultoa_r().
507 */
508const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
509{
510 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
511}
512
Willy Tarreau588297f2014-06-16 15:16:40 +0200513/* returns a locally allocated string containing the quoted encoding of the
514 * input string. The output may be truncated to QSTR_SIZE chars, but it is
515 * guaranteed that the string will always be properly terminated. Quotes are
516 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
517 * always be at least 4 chars.
518 */
519const char *qstr(const char *str)
520{
521 char *ret = quoted_str[quoted_idx];
522 char *p, *end;
523
524 if (++quoted_idx >= NB_QSTR)
525 quoted_idx = 0;
526
527 p = ret;
528 end = ret + QSTR_SIZE;
529
530 *p++ = '"';
531
532 /* always keep 3 chars to support passing "" and the ending " */
533 while (*str && p < end - 3) {
534 if (*str == '"') {
535 *p++ = '"';
536 *p++ = '"';
537 }
538 else
539 *p++ = *str;
540 str++;
541 }
542 *p++ = '"';
543 return ret;
544}
545
Robert Tsai81ae1952007-12-05 10:47:29 +0100546/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200547 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
548 *
549 * It looks like this one would be a good candidate for inlining, but this is
550 * not interesting because it around 35 bytes long and often called multiple
551 * times within the same function.
552 */
553int ishex(char s)
554{
555 s -= '0';
556 if ((unsigned char)s <= 9)
557 return 1;
558 s -= 'A' - '0';
559 if ((unsigned char)s <= 5)
560 return 1;
561 s -= 'a' - 'A';
562 if ((unsigned char)s <= 5)
563 return 1;
564 return 0;
565}
566
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100567/* rounds <i> down to the closest value having max 2 digits */
568unsigned int round_2dig(unsigned int i)
569{
570 unsigned int mul = 1;
571
572 while (i >= 100) {
573 i /= 10;
574 mul *= 10;
575 }
576 return i * mul;
577}
578
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100579/*
580 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
581 * invalid character is found, a pointer to it is returned. If everything is
582 * fine, NULL is returned.
583 */
584const char *invalid_char(const char *name)
585{
586 if (!*name)
587 return name;
588
589 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100590 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100591 *name != '_' && *name != '-')
592 return name;
593 name++;
594 }
595 return NULL;
596}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200597
598/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200599 * Checks <name> for invalid characters. Valid chars are [_.-] and those
600 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200601 * If an invalid character is found, a pointer to it is returned.
602 * If everything is fine, NULL is returned.
603 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200604static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200605
606 if (!*name)
607 return name;
608
609 while (*name) {
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200610 if (!f((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200611 *name != '_' && *name != '-')
612 return name;
613
614 name++;
615 }
616
617 return NULL;
618}
619
620/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200621 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
622 * If an invalid character is found, a pointer to it is returned.
623 * If everything is fine, NULL is returned.
624 */
625const char *invalid_domainchar(const char *name) {
626 return __invalid_char(name, isalnum);
627}
628
629/*
630 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
631 * If an invalid character is found, a pointer to it is returned.
632 * If everything is fine, NULL is returned.
633 */
634const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200635 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200636}
637
638/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100639 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100640 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
641 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
642 * the function tries to guess the address family from the syntax. If the
643 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100644 * string is assumed to contain only an address, no port. The address can be a
645 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
646 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
647 * The return address will only have the address family and the address set,
648 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100649 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
650 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100651 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200652 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100653struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200654{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100655 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100656 /* max IPv6 length, including brackets and terminating NULL */
657 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100658 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100659
660 /* check IPv6 with square brackets */
661 if (str[0] == '[') {
662 size_t iplength = strlen(str);
663
664 if (iplength < 4) {
665 /* minimal size is 4 when using brackets "[::]" */
666 goto fail;
667 }
668 else if (iplength >= sizeof(tmpip)) {
669 /* IPv6 literal can not be larger than tmpip */
670 goto fail;
671 }
672 else {
673 if (str[iplength - 1] != ']') {
674 /* if address started with bracket, it should end with bracket */
675 goto fail;
676 }
677 else {
678 memcpy(tmpip, str + 1, iplength - 2);
679 tmpip[iplength - 2] = '\0';
680 str = tmpip;
681 }
682 }
683 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100684
Willy Tarreaufab5a432011-03-04 15:31:53 +0100685 /* Any IPv6 address */
686 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100687 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
688 sa->ss_family = AF_INET6;
689 else if (sa->ss_family != AF_INET6)
690 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100691 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100692 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100693 }
694
Willy Tarreau24709282013-03-10 21:32:12 +0100695 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100696 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100697 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
698 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100699 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100700 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100701 }
702
703 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100704 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
705 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100706 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100707 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100708 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100709 }
710
711 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100712 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
713 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100714 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100715 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100716 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100717 }
718
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100719 if (!resolve)
720 return NULL;
721
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200722 if (!dns_hostname_validation(str, NULL))
723 return NULL;
724
David du Colombierd5f43282011-03-17 10:40:16 +0100725#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200726 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100727 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100728 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100729
730 memset(&result, 0, sizeof(result));
731 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100732 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100733 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200734 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100735 hints.ai_protocol = 0;
736
737 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100738 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
739 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100740 else if (sa->ss_family != result->ai_family) {
741 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100742 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100743 }
Willy Tarreau24709282013-03-10 21:32:12 +0100744
David du Colombierd5f43282011-03-17 10:40:16 +0100745 switch (result->ai_family) {
746 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100747 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100748 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100749 success = 1;
750 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100751 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100752 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100753 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100754 success = 1;
755 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100756 }
757 }
758
Sean Carey58ea0392013-02-15 23:39:18 +0100759 if (result)
760 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100761
762 if (success)
763 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100764 }
David du Colombierd5f43282011-03-17 10:40:16 +0100765#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200766 /* try to resolve an IPv4/IPv6 hostname */
767 he = gethostbyname(str);
768 if (he) {
769 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
770 sa->ss_family = he->h_addrtype;
771 else if (sa->ss_family != he->h_addrtype)
772 goto fail;
773
774 switch (sa->ss_family) {
775 case AF_INET:
776 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100777 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200778 return sa;
779 case AF_INET6:
780 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100781 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200782 return sa;
783 }
784 }
785
David du Colombierd5f43282011-03-17 10:40:16 +0100786 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100787 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100788 return NULL;
789}
790
791/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100792 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
793 * range or offset consisting in two integers that the caller will have to
794 * check to find the relevant input format. The following format are supported :
795 *
796 * String format | address | port | low | high
797 * addr | <addr> | 0 | 0 | 0
798 * addr: | <addr> | 0 | 0 | 0
799 * addr:port | <addr> | <port> | <port> | <port>
800 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
801 * addr:+port | <addr> | <port> | 0 | <port>
802 * addr:-port | <addr> |-<port> | <port> | 0
803 *
804 * The detection of a port range or increment by the caller is made by
805 * comparing <low> and <high>. If both are equal, then port 0 means no port
806 * was specified. The caller may pass NULL for <low> and <high> if it is not
807 * interested in retrieving port ranges.
808 *
809 * Note that <addr> above may also be :
810 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
811 * - "*" => family will be AF_INET and address will be INADDR_ANY
812 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
813 * - a host name => family and address will depend on host name resolving.
814 *
Willy Tarreau24709282013-03-10 21:32:12 +0100815 * A prefix may be passed in before the address above to force the family :
816 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
817 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
818 * - "unix@" => force address to be a path to a UNIX socket even if the
819 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200820 * - 'abns@' -> force address to belong to the abstract namespace (Linux
821 * only). These sockets are just like Unix sockets but without
822 * the need for an underlying file system. The address is a
823 * string. Technically it's like a Unix socket with a zero in
824 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100825 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100826 *
mildisff5d5102015-10-26 18:50:08 +0100827 * IPv6 addresses can be declared with or without square brackets. When using
828 * square brackets for IPv6 addresses, the port separator (colon) is optional.
829 * If not using square brackets, and in order to avoid any ambiguity with
830 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
831 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
832 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100833 *
834 * If <pfx> is non-null, it is used as a string prefix before any path-based
835 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100836 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200837 * if <fqdn> is non-null, it will be filled with :
838 * - a pointer to the FQDN of the server name to resolve if there's one, and
839 * that the caller will have to free(),
840 * - NULL if there was an explicit address that doesn't require resolution.
841 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100842 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
843 * is null, <fqdn> is still honnored so it is possible for the caller to know
844 * whether a resolution failed by setting <resolve> to null and checking if
845 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200846 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100847 * When a file descriptor is passed, its value is put into the s_addr part of
848 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100849 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100850struct 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 +0100851{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100852 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100853 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100854 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100855 char *port1, *port2;
856 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200857 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100858
859 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200860 if (fqdn)
861 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200862
Willy Tarreaudad36a32013-03-11 01:20:04 +0100863 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100864 if (str2 == NULL) {
865 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100866 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100867 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200868
Willy Tarreau9f69f462015-09-08 16:01:25 +0200869 if (!*str2) {
870 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
871 goto out;
872 }
873
Willy Tarreau24709282013-03-10 21:32:12 +0100874 memset(&ss, 0, sizeof(ss));
875
876 if (strncmp(str2, "unix@", 5) == 0) {
877 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200878 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100879 ss.ss_family = AF_UNIX;
880 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200881 else if (strncmp(str2, "abns@", 5) == 0) {
882 str2 += 5;
883 abstract = 1;
884 ss.ss_family = AF_UNIX;
885 }
Willy Tarreau24709282013-03-10 21:32:12 +0100886 else if (strncmp(str2, "ipv4@", 5) == 0) {
887 str2 += 5;
888 ss.ss_family = AF_INET;
889 }
890 else if (strncmp(str2, "ipv6@", 5) == 0) {
891 str2 += 5;
892 ss.ss_family = AF_INET6;
893 }
894 else if (*str2 == '/') {
895 ss.ss_family = AF_UNIX;
896 }
897 else
898 ss.ss_family = AF_UNSPEC;
899
William Lallemand2fe7dd02018-09-11 16:51:29 +0200900 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
901 char *endptr;
902
903 str2 += 9;
904
905 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100906 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200907
908 if (!*str2 || *endptr) {
909 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
910 goto out;
911 }
912
913 ss.ss_family = AF_CUST_SOCKPAIR;
914
915 }
916 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100917 char *endptr;
918
919 str2 += 3;
920 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100921 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100922
923 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100924 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100925 goto out;
926 }
927
928 /* we return AF_UNSPEC if we use a file descriptor number */
929 ss.ss_family = AF_UNSPEC;
930 }
931 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200932 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100933 int prefix_path_len;
934 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200935 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100936
937 /* complete unix socket path name during startup or soft-restart is
938 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
939 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200940 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +0200941 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau5d1c9482020-02-11 06:43:37 +0100942 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +0100943
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200944 adr_len = strlen(str2);
945 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100946 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
947 goto out;
948 }
949
Willy Tarreauccfccef2014-05-10 01:49:15 +0200950 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +0200951 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200952 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +0200953 memcpy(un->sun_path, pfx, prefix_path_len);
954 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100955 }
Willy Tarreau24709282013-03-10 21:32:12 +0100956 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100957 char *end = str2 + strlen(str2);
958 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200959
mildisff5d5102015-10-26 18:50:08 +0100960 /* search for : or ] whatever comes first */
961 for (chr = end-1; chr > str2; chr--) {
962 if (*chr == ']' || *chr == ':')
963 break;
964 }
965
966 if (*chr == ':') {
967 /* Found a colon before a closing-bracket, must be a port separator.
968 * This guarantee backward compatibility.
969 */
970 *chr++ = '\0';
971 port1 = chr;
972 }
973 else {
974 /* Either no colon and no closing-bracket
975 * or directly ending with a closing-bracket.
976 * However, no port.
977 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100978 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100979 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200980
Willy Tarreaua39d1992013-04-01 20:37:42 +0200981 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100982 port2 = strchr(port1, '-');
983 if (port2)
984 *port2++ = '\0';
985 else
986 port2 = port1;
987 portl = atoi(port1);
988 porth = atoi(port2);
989 porta = portl;
990 }
991 else if (*port1 == '-') { /* negative offset */
992 portl = atoi(port1 + 1);
993 porta = -portl;
994 }
995 else if (*port1 == '+') { /* positive offset */
996 porth = atoi(port1 + 1);
997 porta = porth;
998 }
999 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001000 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001001 goto out;
1002 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001003
1004 /* first try to parse the IP without resolving. If it fails, it
1005 * tells us we need to keep a copy of the FQDN to resolve later
1006 * and to enable DNS. In this case we can proceed if <fqdn> is
1007 * set or if resolve is set, otherwise it's an error.
1008 */
1009 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001010 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001011 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1012 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1013 goto out;
1014 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001015
Willy Tarreauceccdd72016-11-02 22:27:10 +01001016 if (fqdn) {
1017 if (str2 != back)
1018 memmove(back, str2, strlen(str2) + 1);
1019 *fqdn = back;
1020 back = NULL;
1021 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001022 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001023 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001024 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001025
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001026 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001027 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001028 if (port)
1029 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001030 if (low)
1031 *low = portl;
1032 if (high)
1033 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001034 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001035 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001036}
1037
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001038/* converts <str> to a struct in_addr containing a network mask. It can be
1039 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001040 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001041 */
1042int str2mask(const char *str, struct in_addr *mask)
1043{
1044 if (strchr(str, '.') != NULL) { /* dotted notation */
1045 if (!inet_pton(AF_INET, str, mask))
1046 return 0;
1047 }
1048 else { /* mask length */
1049 char *err;
1050 unsigned long len = strtol(str, &err, 10);
1051
1052 if (!*str || (err && *err) || (unsigned)len > 32)
1053 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001054
1055 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001056 }
1057 return 1;
1058}
1059
Tim Duesterhus47185172018-01-25 16:24:49 +01001060/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001061 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001062 * if the conversion succeeds otherwise zero.
1063 */
1064int str2mask6(const char *str, struct in6_addr *mask)
1065{
1066 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1067 if (!inet_pton(AF_INET6, str, mask))
1068 return 0;
1069 }
1070 else { /* mask length */
1071 char *err;
1072 unsigned long len = strtol(str, &err, 10);
1073
1074 if (!*str || (err && *err) || (unsigned)len > 128)
1075 return 0;
1076
1077 len2mask6(len, mask);
1078 }
1079 return 1;
1080}
1081
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001082/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1083 * succeeds otherwise zero.
1084 */
1085int cidr2dotted(int cidr, struct in_addr *mask) {
1086
1087 if (cidr < 0 || cidr > 32)
1088 return 0;
1089
1090 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1091 return 1;
1092}
1093
Thierry Fournier70473a52016-02-17 17:12:14 +01001094/* Convert mask from bit length form to in_addr form.
1095 * This function never fails.
1096 */
1097void len2mask4(int len, struct in_addr *addr)
1098{
1099 if (len >= 32) {
1100 addr->s_addr = 0xffffffff;
1101 return;
1102 }
1103 if (len <= 0) {
1104 addr->s_addr = 0x00000000;
1105 return;
1106 }
1107 addr->s_addr = 0xffffffff << (32 - len);
1108 addr->s_addr = htonl(addr->s_addr);
1109}
1110
1111/* Convert mask from bit length form to in6_addr form.
1112 * This function never fails.
1113 */
1114void len2mask6(int len, struct in6_addr *addr)
1115{
1116 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1117 len -= 32;
1118 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1119 len -= 32;
1120 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1121 len -= 32;
1122 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1123}
1124
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001125/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001126 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001127 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1128 * is optionnal and either in the dotted or CIDR notation.
1129 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1130 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001131int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001132{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001133 __label__ out_free, out_err;
1134 char *c, *s;
1135 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001136
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001137 s = strdup(str);
1138 if (!s)
1139 return 0;
1140
Willy Tarreaubaaee002006-06-26 02:48:02 +02001141 memset(mask, 0, sizeof(*mask));
1142 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001143
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001144 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001145 *c++ = '\0';
1146 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001147 if (!str2mask(c, mask))
1148 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001149 }
1150 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001151 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001152 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001153 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001154 struct hostent *he;
1155
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001156 if (!resolve)
1157 goto out_err;
1158
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001159 if ((he = gethostbyname(s)) == NULL) {
1160 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001161 }
1162 else
1163 *addr = *(struct in_addr *) *(he->h_addr_list);
1164 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001165
1166 ret_val = 1;
1167 out_free:
1168 free(s);
1169 return ret_val;
1170 out_err:
1171 ret_val = 0;
1172 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001173}
1174
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001175
1176/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001177 * converts <str> to two struct in6_addr* which must be pre-allocated.
1178 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1179 * is an optionnal number of bits (128 being the default).
1180 * Returns 1 if OK, 0 if error.
1181 */
1182int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1183{
1184 char *c, *s;
1185 int ret_val = 0;
1186 char *err;
1187 unsigned long len = 128;
1188
1189 s = strdup(str);
1190 if (!s)
1191 return 0;
1192
1193 memset(mask, 0, sizeof(*mask));
1194 memset(addr, 0, sizeof(*addr));
1195
1196 if ((c = strrchr(s, '/')) != NULL) {
1197 *c++ = '\0'; /* c points to the mask */
1198 if (!*c)
1199 goto out_free;
1200
1201 len = strtoul(c, &err, 10);
1202 if ((err && *err) || (unsigned)len > 128)
1203 goto out_free;
1204 }
1205 *mask = len; /* OK we have a valid mask in <len> */
1206
1207 if (!inet_pton(AF_INET6, s, addr))
1208 goto out_free;
1209
1210 ret_val = 1;
1211 out_free:
1212 free(s);
1213 return ret_val;
1214}
1215
1216
1217/*
Willy Tarreau57b22352021-03-25 11:34:40 +01001218 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1219 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1220 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001221 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001222int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001223{
1224 int saw_digit, octets, ch;
1225 u_char tmp[4], *tp;
1226 const char *cp = addr;
1227
1228 saw_digit = 0;
1229 octets = 0;
1230 *(tp = tmp) = 0;
1231
1232 while (*addr) {
Willy Tarreau57b22352021-03-25 11:34:40 +01001233 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001234 if (digit > 9 && ch != '.')
1235 break;
Willy Tarreau57b22352021-03-25 11:34:40 +01001236 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001237 if (digit <= 9) {
1238 u_int new = *tp * 10 + digit;
1239 if (new > 255)
1240 return 0;
1241 *tp = new;
1242 if (!saw_digit) {
1243 if (++octets > 4)
1244 return 0;
1245 saw_digit = 1;
1246 }
1247 } else if (ch == '.' && saw_digit) {
1248 if (octets == 4)
1249 return 0;
1250 *++tp = 0;
1251 saw_digit = 0;
1252 } else
1253 return 0;
1254 }
1255
1256 if (octets < 4)
1257 return 0;
1258
1259 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau57b22352021-03-25 11:34:40 +01001260 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001261}
1262
1263/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001264 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1265 * <out> contain the code of the dectected scheme, the start and length of
1266 * the hostname. Actually only http and https are supported. <out> can be NULL.
1267 * This function returns the consumed length. It is useful if you parse complete
1268 * url like http://host:port/path, because the consumed length corresponds to
1269 * the first character of the path. If the conversion fails, it returns -1.
1270 *
1271 * This function tries to resolve the DNS name if haproxy is in starting mode.
1272 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001273 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001274int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001275{
1276 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001277 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001278 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001279 unsigned long long int http_code = 0;
1280 int default_port;
1281 struct hostent *he;
1282 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001283
1284 /* Firstly, try to find :// pattern */
1285 while (curr < url+ulen && url_code != 0x3a2f2f) {
1286 url_code = ((url_code & 0xffff) << 8);
1287 url_code += (unsigned char)*curr++;
1288 }
1289
1290 /* Secondly, if :// pattern is found, verify parsed stuff
1291 * before pattern is matching our http pattern.
1292 * If so parse ip address and port in uri.
1293 *
1294 * WARNING: Current code doesn't support dynamic async dns resolver.
1295 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001296 if (url_code != 0x3a2f2f)
1297 return -1;
1298
1299 /* Copy scheme, and utrn to lower case. */
1300 while (cp < curr - 3)
1301 http_code = (http_code << 8) + *cp++;
1302 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001303
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001304 /* HTTP or HTTPS url matching */
1305 if (http_code == 0x2020202068747470ULL) {
1306 default_port = 80;
1307 if (out)
1308 out->scheme = SCH_HTTP;
1309 }
1310 else if (http_code == 0x2020206874747073ULL) {
1311 default_port = 443;
1312 if (out)
1313 out->scheme = SCH_HTTPS;
1314 }
1315 else
1316 return -1;
1317
1318 /* If the next char is '[', the host address is IPv6. */
1319 if (*curr == '[') {
1320 curr++;
1321
1322 /* Check trash size */
1323 if (trash.size < ulen)
1324 return -1;
1325
1326 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001327 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001328 for (end = curr;
1329 end < url + ulen && *end != ']';
1330 end++, p++)
1331 *p = *end;
1332 if (*end != ']')
1333 return -1;
1334 *p = '\0';
1335
1336 /* Update out. */
1337 if (out) {
1338 out->host = curr;
1339 out->host_len = end - curr;
1340 }
1341
1342 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001343 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001344 return -1;
1345 end++;
1346
1347 /* Decode port. */
1348 if (*end == ':') {
1349 end++;
1350 default_port = read_uint(&end, url + ulen);
1351 }
1352 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1353 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1354 return end - url;
1355 }
1356 else {
1357 /* We are looking for IP address. If you want to parse and
1358 * resolve hostname found in url, you can use str2sa_range(), but
1359 * be warned this can slow down global daemon performances
1360 * while handling lagging dns responses.
1361 */
1362 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1363 if (ret) {
1364 /* Update out. */
1365 if (out) {
1366 out->host = curr;
1367 out->host_len = ret;
1368 }
1369
1370 curr += ret;
1371
1372 /* Decode port. */
1373 if (*curr == ':') {
1374 curr++;
1375 default_port = read_uint(&curr, url + ulen);
1376 }
1377 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1378
1379 /* Set family. */
1380 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1381 return curr - url;
1382 }
1383 else if (global.mode & MODE_STARTING) {
1384 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1385 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001386 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001387
1388 /* look for : or / or end */
1389 for (end = curr;
1390 end < url + ulen && *end != '/' && *end != ':';
1391 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001392 memcpy(trash.area, curr, end - curr);
1393 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001394
1395 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001396 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001397 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001398 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001399
1400 /* Update out. */
1401 if (out) {
1402 out->host = curr;
1403 out->host_len = end - curr;
1404 }
1405
1406 /* Decode port. */
1407 if (*end == ':') {
1408 end++;
1409 default_port = read_uint(&end, url + ulen);
1410 }
1411
1412 /* Copy IP address, set port and family. */
1413 switch (he->h_addrtype) {
1414 case AF_INET:
1415 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1416 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1417 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1418 return end - url;
1419
1420 case AF_INET6:
1421 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1422 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1423 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1424 return end - url;
1425 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001426 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001427 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001428 return -1;
1429}
1430
Willy Tarreau631f01c2011-09-05 00:36:48 +02001431/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1432 * address family is returned so that it's easy for the caller to adapt to the
1433 * output format. Zero is returned if the address family is not supported. -1
1434 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1435 * supported.
1436 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001437int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001438{
1439
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001440 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001441
1442 if (size < 5)
1443 return 0;
1444 *str = '\0';
1445
1446 switch (addr->ss_family) {
1447 case AF_INET:
1448 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1449 break;
1450 case AF_INET6:
1451 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1452 break;
1453 case AF_UNIX:
1454 memcpy(str, "unix", 5);
1455 return addr->ss_family;
1456 default:
1457 return 0;
1458 }
1459
1460 if (inet_ntop(addr->ss_family, ptr, str, size))
1461 return addr->ss_family;
1462
1463 /* failed */
1464 return -1;
1465}
1466
Simon Horman75ab8bd2014-06-16 09:39:41 +09001467/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1468 * address family is returned so that it's easy for the caller to adapt to the
1469 * output format. Zero is returned if the address family is not supported. -1
1470 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1471 * supported.
1472 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001473int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001474{
1475
1476 uint16_t port;
1477
1478
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001479 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001480 return 0;
1481 *str = '\0';
1482
1483 switch (addr->ss_family) {
1484 case AF_INET:
1485 port = ((struct sockaddr_in *)addr)->sin_port;
1486 break;
1487 case AF_INET6:
1488 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1489 break;
1490 case AF_UNIX:
1491 memcpy(str, "unix", 5);
1492 return addr->ss_family;
1493 default:
1494 return 0;
1495 }
1496
1497 snprintf(str, size, "%u", ntohs(port));
1498 return addr->ss_family;
1499}
1500
Willy Tarreau16e01562016-08-09 16:46:18 +02001501/* check if the given address is local to the system or not. It will return
1502 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1503 * it is. We don't want to iterate over all interfaces for this (and it is not
1504 * portable). So instead we try to bind in UDP to this address on a free non
1505 * privileged port and to connect to the same address, port 0 (connect doesn't
1506 * care). If it succeeds, we own the address. Note that non-inet addresses are
1507 * considered local since they're most likely AF_UNIX.
1508 */
1509int addr_is_local(const struct netns_entry *ns,
1510 const struct sockaddr_storage *orig)
1511{
1512 struct sockaddr_storage addr;
1513 int result;
1514 int fd;
1515
1516 if (!is_inet_addr(orig))
1517 return 1;
1518
1519 memcpy(&addr, orig, sizeof(addr));
1520 set_host_port(&addr, 0);
1521
1522 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1523 if (fd < 0)
1524 return -1;
1525
1526 result = -1;
1527 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1528 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1529 result = 0; // fail, non-local address
1530 else
1531 result = 1; // success, local address
1532 }
1533 else {
1534 if (errno == EADDRNOTAVAIL)
1535 result = 0; // definitely not local :-)
1536 }
1537 close(fd);
1538
1539 return result;
1540}
1541
Willy Tarreaubaaee002006-06-26 02:48:02 +02001542/* will try to encode the string <string> replacing all characters tagged in
1543 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1544 * prefixed by <escape>, and will store the result between <start> (included)
1545 * and <stop> (excluded), and will always terminate the string with a '\0'
1546 * before <stop>. The position of the '\0' is returned if the conversion
1547 * completes. If bytes are missing between <start> and <stop>, then the
1548 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1549 * cannot even be stored so we return <start> without writing the 0.
1550 * The input string must also be zero-terminated.
1551 */
1552const char hextab[16] = "0123456789ABCDEF";
1553char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001554 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001555 const char *string)
1556{
1557 if (start < stop) {
1558 stop--; /* reserve one byte for the final '\0' */
1559 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001560 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001561 *start++ = *string;
1562 else {
1563 if (start + 3 >= stop)
1564 break;
1565 *start++ = escape;
1566 *start++ = hextab[(*string >> 4) & 15];
1567 *start++ = hextab[*string & 15];
1568 }
1569 string++;
1570 }
1571 *start = '\0';
1572 }
1573 return start;
1574}
1575
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001576/*
1577 * Same behavior as encode_string() above, except that it encodes chunk
1578 * <chunk> instead of a string.
1579 */
1580char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001581 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001582 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001583{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001584 char *str = chunk->area;
1585 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001586
1587 if (start < stop) {
1588 stop--; /* reserve one byte for the final '\0' */
1589 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001590 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001591 *start++ = *str;
1592 else {
1593 if (start + 3 >= stop)
1594 break;
1595 *start++ = escape;
1596 *start++ = hextab[(*str >> 4) & 15];
1597 *start++ = hextab[*str & 15];
1598 }
1599 str++;
1600 }
1601 *start = '\0';
1602 }
1603 return start;
1604}
1605
Dragan Dosen0edd1092016-02-12 13:23:02 +01001606/*
1607 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001608 * character. The input <string> must be zero-terminated. The result will
1609 * be stored between <start> (included) and <stop> (excluded). This
1610 * function will always try to terminate the resulting string with a '\0'
1611 * before <stop>, and will return its position if the conversion
1612 * completes.
1613 */
1614char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001615 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001616 const char *string)
1617{
1618 if (start < stop) {
1619 stop--; /* reserve one byte for the final '\0' */
1620 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001621 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001622 *start++ = *string;
1623 else {
1624 if (start + 2 >= stop)
1625 break;
1626 *start++ = escape;
1627 *start++ = *string;
1628 }
1629 string++;
1630 }
1631 *start = '\0';
1632 }
1633 return start;
1634}
1635
1636/*
1637 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001638 * character. <chunk> contains the input to be escaped. The result will be
1639 * stored between <start> (included) and <stop> (excluded). The function
1640 * will always try to terminate the resulting string with a '\0' before
1641 * <stop>, and will return its position if the conversion completes.
1642 */
1643char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001644 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001645 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001646{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001647 char *str = chunk->area;
1648 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001649
1650 if (start < stop) {
1651 stop--; /* reserve one byte for the final '\0' */
1652 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001653 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001654 *start++ = *str;
1655 else {
1656 if (start + 2 >= stop)
1657 break;
1658 *start++ = escape;
1659 *start++ = *str;
1660 }
1661 str++;
1662 }
1663 *start = '\0';
1664 }
1665 return start;
1666}
1667
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001668/* Check a string for using it in a CSV output format. If the string contains
1669 * one of the following four char <">, <,>, CR or LF, the string is
1670 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1671 * <str> is the input string to be escaped. The function assumes that
1672 * the input string is null-terminated.
1673 *
1674 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001675 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001676 * format.
1677 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001678 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001679 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001680 * If <quote> is 1, the converter puts the quotes only if any reserved character
1681 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001682 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001683 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001684 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001685 * The function returns the converted string on its output. If an error
1686 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001687 * for using the function directly as printf() argument.
1688 *
1689 * If the output buffer is too short to contain the input string, the result
1690 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001691 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001692 * This function appends the encoding to the existing output chunk, and it
1693 * guarantees that it starts immediately at the first available character of
1694 * the chunk. Please use csv_enc() instead if you want to replace the output
1695 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001696 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001697const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001698{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001699 char *end = output->area + output->size;
1700 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001701 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001702
Willy Tarreaub631c292016-01-08 10:04:08 +01001703 if (quote == 1) {
1704 /* automatic quoting: first verify if we'll have to quote the string */
1705 if (!strpbrk(str, "\n\r,\""))
1706 quote = 0;
1707 }
1708
1709 if (quote)
1710 *ptr++ = '"';
1711
Willy Tarreau898529b2016-01-06 18:07:04 +01001712 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1713 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001714 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001715 ptr++;
1716 if (ptr >= end - 2) {
1717 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001718 break;
1719 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001720 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001721 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001722 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001723 str++;
1724 }
1725
Willy Tarreaub631c292016-01-08 10:04:08 +01001726 if (quote)
1727 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001728
Willy Tarreau898529b2016-01-06 18:07:04 +01001729 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001730 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001731 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001732}
1733
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001734/* Decode an URL-encoded string in-place. The resulting string might
1735 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001736 * aborted, the string is truncated before the issue and a negative value is
1737 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001738 * If the 'in_form' argument is non-nul the string is assumed to be part of
1739 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1740 * turned to a space. If it's zero, this will only be done after a question
1741 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001742 */
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001743int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001744{
1745 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001746 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001747
1748 in = string;
1749 out = string;
1750 while (*in) {
1751 switch (*in) {
1752 case '+' :
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001753 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001754 break;
1755 case '%' :
1756 if (!ishex(in[1]) || !ishex(in[2]))
1757 goto end;
1758 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1759 in += 2;
1760 break;
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001761 case '?':
1762 in_form = 1;
1763 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001764 default:
1765 *out++ = *in;
1766 break;
1767 }
1768 in++;
1769 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001770 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001771 end:
1772 *out = 0;
1773 return ret;
1774}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001775
Willy Tarreau6911fa42007-03-04 18:06:08 +01001776unsigned int str2ui(const char *s)
1777{
1778 return __str2ui(s);
1779}
1780
1781unsigned int str2uic(const char *s)
1782{
1783 return __str2uic(s);
1784}
1785
1786unsigned int strl2ui(const char *s, int len)
1787{
1788 return __strl2ui(s, len);
1789}
1790
1791unsigned int strl2uic(const char *s, int len)
1792{
1793 return __strl2uic(s, len);
1794}
1795
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001796unsigned int read_uint(const char **s, const char *end)
1797{
1798 return __read_uint(s, end);
1799}
1800
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001801/* This function reads an unsigned integer from the string pointed to by <s> and
1802 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1803 * function automatically stops at <end>. If the number overflows, the 2^64-1
1804 * value is returned.
1805 */
1806unsigned long long int read_uint64(const char **s, const char *end)
1807{
1808 const char *ptr = *s;
1809 unsigned long long int i = 0, tmp;
1810 unsigned int j;
1811
1812 while (ptr < end) {
1813
1814 /* read next char */
1815 j = *ptr - '0';
1816 if (j > 9)
1817 goto read_uint64_end;
1818
1819 /* add char to the number and check overflow. */
1820 tmp = i * 10;
1821 if (tmp / 10 != i) {
1822 i = ULLONG_MAX;
1823 goto read_uint64_eat;
1824 }
1825 if (ULLONG_MAX - tmp < j) {
1826 i = ULLONG_MAX;
1827 goto read_uint64_eat;
1828 }
1829 i = tmp + j;
1830 ptr++;
1831 }
1832read_uint64_eat:
1833 /* eat each numeric char */
1834 while (ptr < end) {
1835 if ((unsigned int)(*ptr - '0') > 9)
1836 break;
1837 ptr++;
1838 }
1839read_uint64_end:
1840 *s = ptr;
1841 return i;
1842}
1843
1844/* This function reads an integer from the string pointed to by <s> and returns
1845 * it. The <s> pointer is adjusted to point to the first unread char. The function
1846 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1847 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1848 * returned.
1849 */
1850long long int read_int64(const char **s, const char *end)
1851{
1852 unsigned long long int i = 0;
1853 int neg = 0;
1854
1855 /* Look for minus char. */
1856 if (**s == '-') {
1857 neg = 1;
1858 (*s)++;
1859 }
1860 else if (**s == '+')
1861 (*s)++;
1862
1863 /* convert as positive number. */
1864 i = read_uint64(s, end);
1865
1866 if (neg) {
1867 if (i > 0x8000000000000000ULL)
1868 return LLONG_MIN;
1869 return -i;
1870 }
1871 if (i > 0x7fffffffffffffffULL)
1872 return LLONG_MAX;
1873 return i;
1874}
1875
Willy Tarreau6911fa42007-03-04 18:06:08 +01001876/* This one is 7 times faster than strtol() on athlon with checks.
1877 * It returns the value of the number composed of all valid digits read,
1878 * and can process negative numbers too.
1879 */
1880int strl2ic(const char *s, int len)
1881{
1882 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001883 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001884
1885 if (len > 0) {
1886 if (*s != '-') {
1887 /* positive number */
1888 while (len-- > 0) {
1889 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001890 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001891 if (j > 9)
1892 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001893 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001894 }
1895 } else {
1896 /* negative number */
1897 s++;
1898 while (--len > 0) {
1899 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001900 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001901 if (j > 9)
1902 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001903 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001904 }
1905 }
1906 }
1907 return i;
1908}
1909
1910
1911/* This function reads exactly <len> chars from <s> and converts them to a
1912 * signed integer which it stores into <ret>. It accurately detects any error
1913 * (truncated string, invalid chars, overflows). It is meant to be used in
1914 * applications designed for hostile environments. It returns zero when the
1915 * number has successfully been converted, non-zero otherwise. When an error
1916 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1917 * faster than strtol().
1918 */
1919int strl2irc(const char *s, int len, int *ret)
1920{
1921 int i = 0;
1922 int j;
1923
1924 if (!len)
1925 return 1;
1926
1927 if (*s != '-') {
1928 /* positive number */
1929 while (len-- > 0) {
1930 j = (*s++) - '0';
1931 if (j > 9) return 1; /* invalid char */
1932 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1933 i = i * 10;
1934 if (i + j < i) return 1; /* check for addition overflow */
1935 i = i + j;
1936 }
1937 } else {
1938 /* negative number */
1939 s++;
1940 while (--len > 0) {
1941 j = (*s++) - '0';
1942 if (j > 9) return 1; /* invalid char */
1943 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1944 i = i * 10;
1945 if (i - j > i) return 1; /* check for subtract overflow */
1946 i = i - j;
1947 }
1948 }
1949 *ret = i;
1950 return 0;
1951}
1952
1953
1954/* This function reads exactly <len> chars from <s> and converts them to a
1955 * signed integer which it stores into <ret>. It accurately detects any error
1956 * (truncated string, invalid chars, overflows). It is meant to be used in
1957 * applications designed for hostile environments. It returns zero when the
1958 * number has successfully been converted, non-zero otherwise. When an error
1959 * is returned, the <ret> value is left untouched. It is about 3 times slower
1960 * than str2irc().
1961 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001962
1963int strl2llrc(const char *s, int len, long long *ret)
1964{
1965 long long i = 0;
1966 int j;
1967
1968 if (!len)
1969 return 1;
1970
1971 if (*s != '-') {
1972 /* positive number */
1973 while (len-- > 0) {
1974 j = (*s++) - '0';
1975 if (j > 9) return 1; /* invalid char */
1976 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1977 i = i * 10LL;
1978 if (i + j < i) return 1; /* check for addition overflow */
1979 i = i + j;
1980 }
1981 } else {
1982 /* negative number */
1983 s++;
1984 while (--len > 0) {
1985 j = (*s++) - '0';
1986 if (j > 9) return 1; /* invalid char */
1987 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1988 i = i * 10LL;
1989 if (i - j > i) return 1; /* check for subtract overflow */
1990 i = i - j;
1991 }
1992 }
1993 *ret = i;
1994 return 0;
1995}
1996
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001997/* This function is used with pat_parse_dotted_ver(). It converts a string
1998 * composed by two number separated by a dot. Each part must contain in 16 bits
1999 * because internally they will be represented as a 32-bit quantity stored in
2000 * a 64-bit integer. It returns zero when the number has successfully been
2001 * converted, non-zero otherwise. When an error is returned, the <ret> value
2002 * is left untouched.
2003 *
2004 * "1.3" -> 0x0000000000010003
2005 * "65535.65535" -> 0x00000000ffffffff
2006 */
2007int strl2llrc_dotted(const char *text, int len, long long *ret)
2008{
2009 const char *end = &text[len];
2010 const char *p;
2011 long long major, minor;
2012
2013 /* Look for dot. */
2014 for (p = text; p < end; p++)
2015 if (*p == '.')
2016 break;
2017
2018 /* Convert major. */
2019 if (strl2llrc(text, p - text, &major) != 0)
2020 return 1;
2021
2022 /* Check major. */
2023 if (major >= 65536)
2024 return 1;
2025
2026 /* Convert minor. */
2027 minor = 0;
2028 if (p < end)
2029 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2030 return 1;
2031
2032 /* Check minor. */
2033 if (minor >= 65536)
2034 return 1;
2035
2036 /* Compose value. */
2037 *ret = (major << 16) | (minor & 0xffff);
2038 return 0;
2039}
2040
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002041/* This function parses a time value optionally followed by a unit suffix among
2042 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2043 * expected by the caller. The computation does its best to avoid overflows.
2044 * The value is returned in <ret> if everything is fine, and a NULL is returned
2045 * by the function. In case of error, a pointer to the error is returned and
2046 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002047 * Values resulting in values larger than or equal to 2^31 after conversion are
2048 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2049 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002050 */
2051const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2052{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002053 unsigned long long imult, idiv;
2054 unsigned long long omult, odiv;
2055 unsigned long long value, result;
Christopher Faulet582baa52020-12-11 09:23:07 +01002056 const char *str = text;
2057
2058 if (!isdigit((unsigned char)*text))
2059 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002060
2061 omult = odiv = 1;
2062
2063 switch (unit_flags & TIME_UNIT_MASK) {
2064 case TIME_UNIT_US: omult = 1000000; break;
2065 case TIME_UNIT_MS: omult = 1000; break;
2066 case TIME_UNIT_S: break;
2067 case TIME_UNIT_MIN: odiv = 60; break;
2068 case TIME_UNIT_HOUR: odiv = 3600; break;
2069 case TIME_UNIT_DAY: odiv = 86400; break;
2070 default: break;
2071 }
2072
2073 value = 0;
2074
2075 while (1) {
2076 unsigned int j;
2077
2078 j = *text - '0';
2079 if (j > 9)
2080 break;
2081 text++;
2082 value *= 10;
2083 value += j;
2084 }
2085
2086 imult = idiv = 1;
2087 switch (*text) {
2088 case '\0': /* no unit = default unit */
2089 imult = omult = idiv = odiv = 1;
Christopher Faulet582baa52020-12-11 09:23:07 +01002090 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002091 case 's': /* second = unscaled unit */
2092 break;
2093 case 'u': /* microsecond : "us" */
2094 if (text[1] == 's') {
2095 idiv = 1000000;
2096 text++;
Thayne McCombsd0ce7372021-04-02 14:12:43 -06002097 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002098 }
Christopher Faulet582baa52020-12-11 09:23:07 +01002099 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002100 case 'm': /* millisecond : "ms" or minute: "m" */
2101 if (text[1] == 's') {
2102 idiv = 1000;
2103 text++;
2104 } else
2105 imult = 60;
2106 break;
2107 case 'h': /* hour : "h" */
2108 imult = 3600;
2109 break;
2110 case 'd': /* day : "d" */
2111 imult = 86400;
2112 break;
2113 default:
2114 return text;
2115 break;
2116 }
Christopher Faulet582baa52020-12-11 09:23:07 +01002117 if (*(++text) != '\0') {
2118 ha_warning("unexpected character '%c' after the timer value '%s', only "
2119 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2120 " This will be reported as an error in next versions.\n", *text, str);
2121 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002122
Christopher Faulet582baa52020-12-11 09:23:07 +01002123 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002124 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2125 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2126 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2127 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2128
Willy Tarreau9faebe32019-06-07 19:00:37 +02002129 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2130 if (result >= 0x80000000)
2131 return PARSE_TIME_OVER;
2132 if (!result && value)
2133 return PARSE_TIME_UNDER;
2134 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002135 return NULL;
2136}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002137
Emeric Brun39132b22010-01-04 14:57:24 +01002138/* this function converts the string starting at <text> to an unsigned int
2139 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002140 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002141 */
2142const char *parse_size_err(const char *text, unsigned *ret) {
2143 unsigned value = 0;
2144
Christopher Fauletef83dd62020-12-11 09:30:45 +01002145 if (!isdigit((unsigned char)*text))
2146 return text;
2147
Emeric Brun39132b22010-01-04 14:57:24 +01002148 while (1) {
2149 unsigned int j;
2150
2151 j = *text - '0';
2152 if (j > 9)
2153 break;
2154 if (value > ~0U / 10)
2155 return text;
2156 value *= 10;
2157 if (value > (value + j))
2158 return text;
2159 value += j;
2160 text++;
2161 }
2162
2163 switch (*text) {
2164 case '\0':
2165 break;
2166 case 'K':
2167 case 'k':
2168 if (value > ~0U >> 10)
2169 return text;
2170 value = value << 10;
2171 break;
2172 case 'M':
2173 case 'm':
2174 if (value > ~0U >> 20)
2175 return text;
2176 value = value << 20;
2177 break;
2178 case 'G':
2179 case 'g':
2180 if (value > ~0U >> 30)
2181 return text;
2182 value = value << 30;
2183 break;
2184 default:
2185 return text;
2186 }
2187
Godbach58048a22015-01-28 17:36:16 +08002188 if (*text != '\0' && *++text != '\0')
2189 return text;
2190
Emeric Brun39132b22010-01-04 14:57:24 +01002191 *ret = value;
2192 return NULL;
2193}
2194
Willy Tarreau126d4062013-12-03 17:50:47 +01002195/*
2196 * Parse binary string written in hexadecimal (source) and store the decoded
2197 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2198 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002199 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002200 */
2201int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2202{
2203 int len;
2204 const char *p = source;
2205 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002206 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002207
2208 len = strlen(source);
2209 if (len % 2) {
2210 memprintf(err, "an even number of hex digit is expected");
2211 return 0;
2212 }
2213
2214 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002215
Willy Tarreau126d4062013-12-03 17:50:47 +01002216 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002217 *binstr = calloc(len, sizeof(char));
2218 if (!*binstr) {
2219 memprintf(err, "out of memory while loading string pattern");
2220 return 0;
2221 }
2222 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002223 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002224 else {
2225 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002226 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002227 len, *binstrlen);
2228 return 0;
2229 }
2230 alloc = 0;
2231 }
2232 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002233
2234 i = j = 0;
2235 while (j < len) {
2236 if (!ishex(p[i++]))
2237 goto bad_input;
2238 if (!ishex(p[i++]))
2239 goto bad_input;
2240 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2241 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002242 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002243
2244bad_input:
2245 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002246 if (alloc) {
2247 free(*binstr);
2248 *binstr = NULL;
2249 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002250 return 0;
2251}
2252
Willy Tarreau946ba592009-05-10 15:41:18 +02002253/* copies at most <n> characters from <src> and always terminates with '\0' */
2254char *my_strndup(const char *src, int n)
2255{
2256 int len = 0;
2257 char *ret;
2258
2259 while (len < n && src[len])
2260 len++;
2261
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002262 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002263 if (!ret)
2264 return ret;
2265 memcpy(ret, src, len);
2266 ret[len] = '\0';
2267 return ret;
2268}
2269
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002270/*
2271 * search needle in haystack
2272 * returns the pointer if found, returns NULL otherwise
2273 */
2274const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2275{
2276 const void *c = NULL;
2277 unsigned char f;
2278
2279 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2280 return NULL;
2281
2282 f = *(char *)needle;
2283 c = haystack;
2284 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2285 if ((haystacklen - (c - haystack)) < needlelen)
2286 return NULL;
2287
2288 if (memcmp(c, needle, needlelen) == 0)
2289 return c;
2290 ++c;
2291 }
2292 return NULL;
2293}
2294
Willy Tarreau482b00d2009-10-04 22:48:42 +02002295/* This function returns the first unused key greater than or equal to <key> in
2296 * ID tree <root>. Zero is returned if no place is found.
2297 */
2298unsigned int get_next_id(struct eb_root *root, unsigned int key)
2299{
2300 struct eb32_node *used;
2301
2302 do {
2303 used = eb32_lookup_ge(root, key);
2304 if (!used || used->key > key)
2305 return key; /* key is available */
2306 key++;
2307 } while (key);
2308 return key;
2309}
2310
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002311/* dump the full tree to <file> in DOT format for debugging purposes. Will
2312 * optionally highlight node <subj> if found, depending on operation <op> :
2313 * 0 : nothing
2314 * >0 : insertion, node/leaf are surrounded in red
2315 * <0 : removal, node/leaf are dashed with no background
2316 * Will optionally add "desc" as a label on the graph if set and non-null.
2317 */
2318void 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 +01002319{
2320 struct eb32sc_node *node;
2321 unsigned long scope = -1;
2322
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002323 fprintf(file, "digraph ebtree {\n");
2324
2325 if (desc && *desc) {
2326 fprintf(file,
2327 " fontname=\"fixed\";\n"
2328 " fontsize=8;\n"
2329 " label=\"%s\";\n", desc);
2330 }
2331
Willy Tarreaued3cda02017-11-15 15:04:05 +01002332 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002333 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2334 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002335 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2336 );
2337
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002338 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002339 (long)eb_root_to_node(root),
2340 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002341 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2342
2343 node = eb32sc_first(root, scope);
2344 while (node) {
2345 if (node->node.node_p) {
2346 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002347 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2348 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2349 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002350
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002351 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002352 (long)node,
2353 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002354 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002355
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002356 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002357 (long)node,
2358 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002359 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2360
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002361 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002362 (long)node,
2363 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002364 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2365 }
2366
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002367 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2368 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2369 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002370
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002371 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002372 (long)node,
2373 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002374 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002375 node = eb32sc_next(node, scope);
2376 }
2377 fprintf(file, "}\n");
2378}
2379
Willy Tarreau348238b2010-01-18 15:05:57 +01002380/* This function compares a sample word possibly followed by blanks to another
2381 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2382 * otherwise zero. This intends to be used when checking HTTP headers for some
2383 * values. Note that it validates a word followed only by blanks but does not
2384 * validate a word followed by blanks then other chars.
2385 */
2386int word_match(const char *sample, int slen, const char *word, int wlen)
2387{
2388 if (slen < wlen)
2389 return 0;
2390
2391 while (wlen) {
2392 char c = *sample ^ *word;
2393 if (c && c != ('A' ^ 'a'))
2394 return 0;
2395 sample++;
2396 word++;
2397 slen--;
2398 wlen--;
2399 }
2400
2401 while (slen) {
2402 if (*sample != ' ' && *sample != '\t')
2403 return 0;
2404 sample++;
2405 slen--;
2406 }
2407 return 1;
2408}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002409
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002410/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2411 * is particularly fast because it avoids expensive operations such as
2412 * multiplies, which are optimized away at the end. It requires a properly
2413 * formated address though (3 points).
2414 */
2415unsigned int inetaddr_host(const char *text)
2416{
2417 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2418 register unsigned int dig100, dig10, dig1;
2419 int s;
2420 const char *p, *d;
2421
2422 dig1 = dig10 = dig100 = ascii_zero;
2423 s = 24;
2424
2425 p = text;
2426 while (1) {
2427 if (((unsigned)(*p - '0')) <= 9) {
2428 p++;
2429 continue;
2430 }
2431
2432 /* here, we have a complete byte between <text> and <p> (exclusive) */
2433 if (p == text)
2434 goto end;
2435
2436 d = p - 1;
2437 dig1 |= (unsigned int)(*d << s);
2438 if (d == text)
2439 goto end;
2440
2441 d--;
2442 dig10 |= (unsigned int)(*d << s);
2443 if (d == text)
2444 goto end;
2445
2446 d--;
2447 dig100 |= (unsigned int)(*d << s);
2448 end:
2449 if (!s || *p != '.')
2450 break;
2451
2452 s -= 8;
2453 text = ++p;
2454 }
2455
2456 dig100 -= ascii_zero;
2457 dig10 -= ascii_zero;
2458 dig1 -= ascii_zero;
2459 return ((dig100 * 10) + dig10) * 10 + dig1;
2460}
2461
2462/*
2463 * Idem except the first unparsed character has to be passed in <stop>.
2464 */
2465unsigned int inetaddr_host_lim(const char *text, const char *stop)
2466{
2467 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2468 register unsigned int dig100, dig10, dig1;
2469 int s;
2470 const char *p, *d;
2471
2472 dig1 = dig10 = dig100 = ascii_zero;
2473 s = 24;
2474
2475 p = text;
2476 while (1) {
2477 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2478 p++;
2479 continue;
2480 }
2481
2482 /* here, we have a complete byte between <text> and <p> (exclusive) */
2483 if (p == text)
2484 goto end;
2485
2486 d = p - 1;
2487 dig1 |= (unsigned int)(*d << s);
2488 if (d == text)
2489 goto end;
2490
2491 d--;
2492 dig10 |= (unsigned int)(*d << s);
2493 if (d == text)
2494 goto end;
2495
2496 d--;
2497 dig100 |= (unsigned int)(*d << s);
2498 end:
2499 if (!s || p == stop || *p != '.')
2500 break;
2501
2502 s -= 8;
2503 text = ++p;
2504 }
2505
2506 dig100 -= ascii_zero;
2507 dig10 -= ascii_zero;
2508 dig1 -= ascii_zero;
2509 return ((dig100 * 10) + dig10) * 10 + dig1;
2510}
2511
2512/*
2513 * Idem except the pointer to first unparsed byte is returned into <ret> which
2514 * must not be NULL.
2515 */
Willy Tarreau74172752010-10-15 23:21:42 +02002516unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002517{
2518 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2519 register unsigned int dig100, dig10, dig1;
2520 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002521 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002522
2523 dig1 = dig10 = dig100 = ascii_zero;
2524 s = 24;
2525
2526 p = text;
2527 while (1) {
2528 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2529 p++;
2530 continue;
2531 }
2532
2533 /* here, we have a complete byte between <text> and <p> (exclusive) */
2534 if (p == text)
2535 goto end;
2536
2537 d = p - 1;
2538 dig1 |= (unsigned int)(*d << s);
2539 if (d == text)
2540 goto end;
2541
2542 d--;
2543 dig10 |= (unsigned int)(*d << s);
2544 if (d == text)
2545 goto end;
2546
2547 d--;
2548 dig100 |= (unsigned int)(*d << s);
2549 end:
2550 if (!s || p == stop || *p != '.')
2551 break;
2552
2553 s -= 8;
2554 text = ++p;
2555 }
2556
2557 *ret = p;
2558 dig100 -= ascii_zero;
2559 dig10 -= ascii_zero;
2560 dig1 -= ascii_zero;
2561 return ((dig100 * 10) + dig10) * 10 + dig1;
2562}
2563
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002564/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2565 * or the number of chars read in case of success. Maybe this could be replaced
2566 * by one of the functions above. Also, apparently this function does not support
2567 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002568 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002569 */
2570int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2571{
2572 const char *addr;
2573 int saw_digit, octets, ch;
2574 u_char tmp[4], *tp;
2575 const char *cp = buf;
2576
2577 saw_digit = 0;
2578 octets = 0;
2579 *(tp = tmp) = 0;
2580
2581 for (addr = buf; addr - buf < len; addr++) {
2582 unsigned char digit = (ch = *addr) - '0';
2583
2584 if (digit > 9 && ch != '.')
2585 break;
2586
2587 if (digit <= 9) {
2588 u_int new = *tp * 10 + digit;
2589
2590 if (new > 255)
2591 return 0;
2592
2593 *tp = new;
2594
2595 if (!saw_digit) {
2596 if (++octets > 4)
2597 return 0;
2598 saw_digit = 1;
2599 }
2600 } else if (ch == '.' && saw_digit) {
2601 if (octets == 4)
2602 return 0;
2603
2604 *++tp = 0;
2605 saw_digit = 0;
2606 } else
2607 return 0;
2608 }
2609
2610 if (octets < 4)
2611 return 0;
2612
2613 memcpy(&dst->s_addr, tmp, 4);
2614 return addr - cp;
2615}
2616
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002617/* This function converts the string in <buf> of the len <len> to
2618 * struct in6_addr <dst> which must be allocated by the caller.
2619 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002620 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002621 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002622int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2623{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002624 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002625 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002626
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002627 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002628 return 0;
2629
2630 memcpy(null_term_ip6, buf, len);
2631 null_term_ip6[len] = '\0';
2632
Willy Tarreau075415a2013-12-12 11:29:39 +01002633 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002634 return 0;
2635
Willy Tarreau075415a2013-12-12 11:29:39 +01002636 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002637 return 1;
2638}
2639
Willy Tarreauacf95772010-06-14 19:09:21 +02002640/* To be used to quote config arg positions. Returns the short string at <ptr>
2641 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2642 * if ptr is NULL or empty. The string is locally allocated.
2643 */
2644const char *quote_arg(const char *ptr)
2645{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002646 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002647 int i;
2648
2649 if (!ptr || !*ptr)
2650 return "end of line";
2651 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002652 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002653 val[i] = *ptr++;
2654 val[i++] = '\'';
2655 val[i] = '\0';
2656 return val;
2657}
2658
Willy Tarreau5b180202010-07-18 10:40:48 +02002659/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2660int get_std_op(const char *str)
2661{
2662 int ret = -1;
2663
2664 if (*str == 'e' && str[1] == 'q')
2665 ret = STD_OP_EQ;
2666 else if (*str == 'n' && str[1] == 'e')
2667 ret = STD_OP_NE;
2668 else if (*str == 'l') {
2669 if (str[1] == 'e') ret = STD_OP_LE;
2670 else if (str[1] == 't') ret = STD_OP_LT;
2671 }
2672 else if (*str == 'g') {
2673 if (str[1] == 'e') ret = STD_OP_GE;
2674 else if (str[1] == 't') ret = STD_OP_GT;
2675 }
2676
2677 if (ret == -1 || str[2] != '\0')
2678 return -1;
2679 return ret;
2680}
2681
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002682/* hash a 32-bit integer to another 32-bit integer */
2683unsigned int full_hash(unsigned int a)
2684{
2685 return __full_hash(a);
2686}
2687
Willy Tarreauf3241112019-02-26 09:56:22 +01002688/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2689 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2690 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2691 * a popcount variant and is described here :
2692 * https://graphics.stanford.edu/~seander/bithacks.html
2693 */
2694unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2695{
2696 unsigned long a, b, c, d;
2697 unsigned int s;
2698 unsigned int t;
2699
2700 a = m - ((m >> 1) & ~0UL/3);
2701 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2702 c = (b + (b >> 4)) & ~0UL/0x11;
2703 d = (c + (c >> 8)) & ~0UL/0x101;
2704
2705 r++; // make r be 1..64
2706
2707 t = 0;
2708 s = LONGBITS;
2709 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002710 unsigned long d2 = (d >> 16) >> 16;
2711 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002712 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2713 }
2714
2715 t = (d >> (s - 16)) & 0xff;
2716 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2717 t = (c >> (s - 8)) & 0xf;
2718 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2719 t = (b >> (s - 4)) & 0x7;
2720 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2721 t = (a >> (s - 2)) & 0x3;
2722 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2723 t = (m >> (s - 1)) & 0x1;
2724 s -= ((t - r) & 256) >> 8;
2725
2726 return s - 1;
2727}
2728
2729/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2730 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2731 * using mask_prep_rank_map() below.
2732 */
2733unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2734 unsigned long a, unsigned long b,
2735 unsigned long c, unsigned long d)
2736{
2737 unsigned int s;
2738 unsigned int t;
2739
2740 r++; // make r be 1..64
2741
2742 t = 0;
2743 s = LONGBITS;
2744 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002745 unsigned long d2 = (d >> 16) >> 16;
2746 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002747 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2748 }
2749
2750 t = (d >> (s - 16)) & 0xff;
2751 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2752 t = (c >> (s - 8)) & 0xf;
2753 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2754 t = (b >> (s - 4)) & 0x7;
2755 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2756 t = (a >> (s - 2)) & 0x3;
2757 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2758 t = (m >> (s - 1)) & 0x1;
2759 s -= ((t - r) & 256) >> 8;
2760
2761 return s - 1;
2762}
2763
2764/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2765 * above.
2766 */
2767void mask_prep_rank_map(unsigned long m,
2768 unsigned long *a, unsigned long *b,
2769 unsigned long *c, unsigned long *d)
2770{
2771 *a = m - ((m >> 1) & ~0UL/3);
2772 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2773 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2774 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2775}
2776
David du Colombier4f92d322011-03-24 11:09:31 +01002777/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002778 * otherwise zero. Note that <addr> may not necessarily be aligned
2779 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002780 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002781int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002782{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002783 struct in_addr addr_copy;
2784
2785 memcpy(&addr_copy, addr, sizeof(addr_copy));
2786 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002787}
2788
2789/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002790 * otherwise zero. Note that <addr> may not necessarily be aligned
2791 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002792 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002793int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002794{
2795 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002796 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002797
Willy Tarreaueec1d382016-07-13 11:59:39 +02002798 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002799 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002800 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002801 (((int *)net)[i] & ((int *)mask)[i]))
2802 return 0;
2803 return 1;
2804}
2805
2806/* RFC 4291 prefix */
2807const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2808 0x00, 0x00, 0x00, 0x00,
2809 0x00, 0x00, 0xFF, 0xFF };
2810
Joseph Herlant32b83272018-11-15 11:58:28 -08002811/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002812 * Input and output may overlap.
2813 */
David du Colombier4f92d322011-03-24 11:09:31 +01002814void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2815{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002816 struct in_addr tmp_addr;
2817
2818 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002819 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002820 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002821}
2822
Joseph Herlant32b83272018-11-15 11:58:28 -08002823/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002824 * Return true if conversion is possible and false otherwise.
2825 */
2826int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2827{
2828 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2829 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2830 sizeof(struct in_addr));
2831 return 1;
2832 }
2833
2834 return 0;
2835}
2836
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002837/* compare two struct sockaddr_storage and return:
2838 * 0 (true) if the addr is the same in both
2839 * 1 (false) if the addr is not the same in both
2840 * -1 (unable) if one of the addr is not AF_INET*
2841 */
2842int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2843{
2844 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2845 return -1;
2846
2847 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2848 return -1;
2849
2850 if (ss1->ss_family != ss2->ss_family)
2851 return 1;
2852
2853 switch (ss1->ss_family) {
2854 case AF_INET:
2855 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2856 &((struct sockaddr_in *)ss2)->sin_addr,
2857 sizeof(struct in_addr)) != 0;
2858 case AF_INET6:
2859 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2860 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2861 sizeof(struct in6_addr)) != 0;
2862 }
2863
2864 return 1;
2865}
2866
Baptiste Assmann08396c82016-01-31 00:27:17 +01002867/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002868 * The caller must allocate and clear <dest> before calling.
2869 * The source must be in either AF_INET or AF_INET6 family, or the destination
2870 * address will be undefined. If the destination address used to hold a port,
2871 * it is preserved, so that this function can be used to switch to another
2872 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002873 */
2874struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2875{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002876 int prev_port;
2877
2878 prev_port = get_net_port(dest);
2879 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002880 dest->ss_family = source->ss_family;
2881
2882 /* copy new addr and apply it */
2883 switch (source->ss_family) {
2884 case AF_INET:
2885 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002886 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002887 break;
2888 case AF_INET6:
2889 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 +01002890 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002891 break;
2892 }
2893
2894 return dest;
2895}
2896
William Lallemand421f5b52012-02-06 18:15:57 +01002897char *human_time(int t, short hz_div) {
2898 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2899 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002900 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002901 int cnt=2; // print two numbers
2902
2903 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002904 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002905 return rv;
2906 }
2907
2908 if (unlikely(hz_div > 1))
2909 t /= hz_div;
2910
2911 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002912 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002913 cnt--;
2914 }
2915
2916 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002917 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002918 cnt--;
2919 }
2920
2921 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002922 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002923 cnt--;
2924 }
2925
2926 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002927 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002928
2929 return rv;
2930}
2931
2932const char *monthname[12] = {
2933 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2934 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2935};
2936
2937/* date2str_log: write a date in the format :
2938 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2939 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2940 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2941 *
2942 * without using sprintf. return a pointer to the last char written (\0) or
2943 * NULL if there isn't enough space.
2944 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002945char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002946{
2947
2948 if (size < 25) /* the size is fixed: 24 chars + \0 */
2949 return NULL;
2950
2951 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002952 if (!dst)
2953 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002954 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002955
William Lallemand421f5b52012-02-06 18:15:57 +01002956 memcpy(dst, monthname[tm->tm_mon], 3); // month
2957 dst += 3;
2958 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002959
William Lallemand421f5b52012-02-06 18:15:57 +01002960 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002961 if (!dst)
2962 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002963 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002964
William Lallemand421f5b52012-02-06 18:15:57 +01002965 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002966 if (!dst)
2967 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002968 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002969
William Lallemand421f5b52012-02-06 18:15:57 +01002970 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002971 if (!dst)
2972 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002973 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002974
William Lallemand421f5b52012-02-06 18:15:57 +01002975 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002976 if (!dst)
2977 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002978 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002979
William Lallemand421f5b52012-02-06 18:15:57 +01002980 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002981 if (!dst)
2982 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002983 dst += 3; // only the 3 first digits
2984 *dst = '\0';
2985
2986 return dst;
2987}
2988
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002989/* Base year used to compute leap years */
2990#define TM_YEAR_BASE 1900
2991
2992/* Return the difference in seconds between two times (leap seconds are ignored).
2993 * Retrieved from glibc 2.18 source code.
2994 */
2995static int my_tm_diff(const struct tm *a, const struct tm *b)
2996{
2997 /* Compute intervening leap days correctly even if year is negative.
2998 * Take care to avoid int overflow in leap day calculations,
2999 * but it's OK to assume that A and B are close to each other.
3000 */
3001 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3002 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3003 int a100 = a4 / 25 - (a4 % 25 < 0);
3004 int b100 = b4 / 25 - (b4 % 25 < 0);
3005 int a400 = a100 >> 2;
3006 int b400 = b100 >> 2;
3007 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3008 int years = a->tm_year - b->tm_year;
3009 int days = (365 * years + intervening_leap_days
3010 + (a->tm_yday - b->tm_yday));
3011 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3012 + (a->tm_min - b->tm_min))
3013 + (a->tm_sec - b->tm_sec));
3014}
3015
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003016/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003017 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003018 * The string returned has the same format as returned by strftime(... "%z", tm).
3019 * Offsets are kept in an internal cache for better performances.
3020 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003021const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003022{
3023 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003024 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003025
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003026 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003027 struct tm tm_gmt;
3028 int diff;
3029 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003030
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003031 /* Pretend DST not active if its status is unknown */
3032 if (isdst < 0)
3033 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003034
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003035 /* Fetch the offset and initialize it if needed */
3036 gmt_offset = gmt_offsets[isdst & 0x01];
3037 if (unlikely(!*gmt_offset)) {
3038 get_gmtime(t, &tm_gmt);
3039 diff = my_tm_diff(tm, &tm_gmt);
3040 if (diff < 0) {
3041 diff = -diff;
3042 *gmt_offset = '-';
3043 } else {
3044 *gmt_offset = '+';
3045 }
Willy Tarreaubf5eeb62019-10-29 10:16:11 +01003046 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003047 diff /= 60; /* Convert to minutes */
3048 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3049 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003050
Willy Tarreaubf5eeb62019-10-29 10:16:11 +01003051 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003052}
3053
William Lallemand421f5b52012-02-06 18:15:57 +01003054/* gmt2str_log: write a date in the format :
3055 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3056 * return a pointer to the last char written (\0) or
3057 * NULL if there isn't enough space.
3058 */
3059char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3060{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003061 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003062 return NULL;
3063
3064 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003065 if (!dst)
3066 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003067 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003068
William Lallemand421f5b52012-02-06 18:15:57 +01003069 memcpy(dst, monthname[tm->tm_mon], 3); // month
3070 dst += 3;
3071 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003072
William Lallemand421f5b52012-02-06 18:15:57 +01003073 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003074 if (!dst)
3075 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003076 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003077
William Lallemand421f5b52012-02-06 18:15:57 +01003078 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003079 if (!dst)
3080 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003081 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003082
William Lallemand421f5b52012-02-06 18:15:57 +01003083 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003084 if (!dst)
3085 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003086 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003087
William Lallemand421f5b52012-02-06 18:15:57 +01003088 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003089 if (!dst)
3090 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003091 *dst++ = ' ';
3092 *dst++ = '+';
3093 *dst++ = '0';
3094 *dst++ = '0';
3095 *dst++ = '0';
3096 *dst++ = '0';
3097 *dst = '\0';
3098
3099 return dst;
3100}
3101
Yuxans Yao4e25b012012-10-19 10:36:09 +08003102/* localdate2str_log: write a date in the format :
3103 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003104 * Both t and tm must represent the same time.
3105 * return a pointer to the last char written (\0) or
3106 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003107 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003108char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003109{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003110 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003111 if (size < 27) /* the size is fixed: 26 chars + \0 */
3112 return NULL;
3113
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003114 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003115
Yuxans Yao4e25b012012-10-19 10:36:09 +08003116 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003117 if (!dst)
3118 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003119 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003120
Yuxans Yao4e25b012012-10-19 10:36:09 +08003121 memcpy(dst, monthname[tm->tm_mon], 3); // month
3122 dst += 3;
3123 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003124
Yuxans Yao4e25b012012-10-19 10:36:09 +08003125 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003126 if (!dst)
3127 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003128 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003129
Yuxans Yao4e25b012012-10-19 10:36:09 +08003130 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003131 if (!dst)
3132 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003133 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003134
Yuxans Yao4e25b012012-10-19 10:36:09 +08003135 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003136 if (!dst)
3137 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003138 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003139
Yuxans Yao4e25b012012-10-19 10:36:09 +08003140 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003141 if (!dst)
3142 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003143 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003144
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003145 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003146 dst += 5;
3147 *dst = '\0';
3148
3149 return dst;
3150}
3151
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003152/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3153 * It is meant as a portable replacement for timegm() for use with valid inputs.
3154 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3155 */
3156time_t my_timegm(const struct tm *tm)
3157{
3158 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3159 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3160 * sum of the extra N days for elapsed months. The sum of all these N
3161 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3162 * in a 5-bit word. This means that with 60 bits we can represent a
3163 * matrix of all these values at once, which is fast and efficient to
3164 * access. The extra February day for leap years is not counted here.
3165 *
3166 * Jan : none = 0 (0)
3167 * Feb : Jan = 3 (3)
3168 * Mar : Jan..Feb = 3 (3 + 0)
3169 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3170 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3171 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3172 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3173 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3174 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3175 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3176 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3177 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3178 */
3179 uint64_t extra =
3180 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3181 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3182 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3183 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3184
3185 unsigned int y = tm->tm_year + 1900;
3186 unsigned int m = tm->tm_mon;
3187 unsigned long days = 0;
3188
3189 /* days since 1/1/1970 for full years */
3190 days += days_since_zero(y) - days_since_zero(1970);
3191
3192 /* days for full months in the current year */
3193 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3194
3195 /* count + 1 after March for leap years. A leap year is a year multiple
3196 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3197 * is leap, 1900 isn't, 1904 is.
3198 */
3199 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3200 days++;
3201
3202 days += tm->tm_mday - 1;
3203 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3204}
3205
Thierry Fournier93127942016-01-20 18:49:45 +01003206/* This function check a char. It returns true and updates
3207 * <date> and <len> pointer to the new position if the
3208 * character is found.
3209 */
3210static inline int parse_expect_char(const char **date, int *len, char c)
3211{
3212 if (*len < 1 || **date != c)
3213 return 0;
3214 (*len)--;
3215 (*date)++;
3216 return 1;
3217}
3218
3219/* This function expects a string <str> of len <l>. It return true and updates.
3220 * <date> and <len> if the string matches, otherwise, it returns false.
3221 */
3222static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3223{
3224 if (*len < l || strncmp(*date, str, l) != 0)
3225 return 0;
3226 (*len) -= l;
3227 (*date) += l;
3228 return 1;
3229}
3230
3231/* This macro converts 3 chars name in integer. */
3232#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3233
3234/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3235 * / %x54.75.65 ; "Tue", case-sensitive
3236 * / %x57.65.64 ; "Wed", case-sensitive
3237 * / %x54.68.75 ; "Thu", case-sensitive
3238 * / %x46.72.69 ; "Fri", case-sensitive
3239 * / %x53.61.74 ; "Sat", case-sensitive
3240 * / %x53.75.6E ; "Sun", case-sensitive
3241 *
3242 * This array must be alphabetically sorted
3243 */
3244static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3245{
3246 if (*len < 3)
3247 return 0;
3248 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3249 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3250 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3251 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3252 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3253 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3254 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3255 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3256 default: return 0;
3257 }
3258 *len -= 3;
3259 *date += 3;
3260 return 1;
3261}
3262
3263/* month = %x4A.61.6E ; "Jan", case-sensitive
3264 * / %x46.65.62 ; "Feb", case-sensitive
3265 * / %x4D.61.72 ; "Mar", case-sensitive
3266 * / %x41.70.72 ; "Apr", case-sensitive
3267 * / %x4D.61.79 ; "May", case-sensitive
3268 * / %x4A.75.6E ; "Jun", case-sensitive
3269 * / %x4A.75.6C ; "Jul", case-sensitive
3270 * / %x41.75.67 ; "Aug", case-sensitive
3271 * / %x53.65.70 ; "Sep", case-sensitive
3272 * / %x4F.63.74 ; "Oct", case-sensitive
3273 * / %x4E.6F.76 ; "Nov", case-sensitive
3274 * / %x44.65.63 ; "Dec", case-sensitive
3275 *
3276 * This array must be alphabetically sorted
3277 */
3278static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3279{
3280 if (*len < 3)
3281 return 0;
3282 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3283 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3284 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3285 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3286 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3287 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3288 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3289 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3290 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3291 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3292 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3293 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3294 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3295 default: return 0;
3296 }
3297 *len -= 3;
3298 *date += 3;
3299 return 1;
3300}
3301
3302/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3303 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3304 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3305 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3306 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3307 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3308 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3309 *
3310 * This array must be alphabetically sorted
3311 */
3312static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3313{
3314 if (*len < 6) /* Minimum length. */
3315 return 0;
3316 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3317 case STR2I3('M','o','n'):
3318 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3319 tm->tm_wday = 1;
3320 return 1;
3321 case STR2I3('T','u','e'):
3322 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3323 tm->tm_wday = 2;
3324 return 1;
3325 case STR2I3('W','e','d'):
3326 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3327 tm->tm_wday = 3;
3328 return 1;
3329 case STR2I3('T','h','u'):
3330 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3331 tm->tm_wday = 4;
3332 return 1;
3333 case STR2I3('F','r','i'):
3334 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3335 tm->tm_wday = 5;
3336 return 1;
3337 case STR2I3('S','a','t'):
3338 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3339 tm->tm_wday = 6;
3340 return 1;
3341 case STR2I3('S','u','n'):
3342 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3343 tm->tm_wday = 7;
3344 return 1;
3345 }
3346 return 0;
3347}
3348
3349/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3350static inline int parse_digit(const char **date, int *len, int *digit)
3351{
3352 if (*len < 1 || **date < '0' || **date > '9')
3353 return 0;
3354 *digit = (**date - '0');
3355 (*date)++;
3356 (*len)--;
3357 return 1;
3358}
3359
3360/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3361static inline int parse_2digit(const char **date, int *len, int *digit)
3362{
3363 int value;
3364
3365 RET0_UNLESS(parse_digit(date, len, &value));
3366 (*digit) = value * 10;
3367 RET0_UNLESS(parse_digit(date, len, &value));
3368 (*digit) += value;
3369
3370 return 1;
3371}
3372
3373/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3374static inline int parse_4digit(const char **date, int *len, int *digit)
3375{
3376 int value;
3377
3378 RET0_UNLESS(parse_digit(date, len, &value));
3379 (*digit) = value * 1000;
3380
3381 RET0_UNLESS(parse_digit(date, len, &value));
3382 (*digit) += value * 100;
3383
3384 RET0_UNLESS(parse_digit(date, len, &value));
3385 (*digit) += value * 10;
3386
3387 RET0_UNLESS(parse_digit(date, len, &value));
3388 (*digit) += value;
3389
3390 return 1;
3391}
3392
3393/* time-of-day = hour ":" minute ":" second
3394 * ; 00:00:00 - 23:59:60 (leap second)
3395 *
3396 * hour = 2DIGIT
3397 * minute = 2DIGIT
3398 * second = 2DIGIT
3399 */
3400static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3401{
3402 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3403 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3404 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3405 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3406 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3407 return 1;
3408}
3409
3410/* From RFC7231
3411 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3412 *
3413 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3414 * ; fixed length/zone/capitalization subset of the format
3415 * ; see Section 3.3 of [RFC5322]
3416 *
3417 *
3418 * date1 = day SP month SP year
3419 * ; e.g., 02 Jun 1982
3420 *
3421 * day = 2DIGIT
3422 * year = 4DIGIT
3423 *
3424 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3425 *
3426 * time-of-day = hour ":" minute ":" second
3427 * ; 00:00:00 - 23:59:60 (leap second)
3428 *
3429 * hour = 2DIGIT
3430 * minute = 2DIGIT
3431 * second = 2DIGIT
3432 *
3433 * DIGIT = decimal 0-9
3434 */
3435int parse_imf_date(const char *date, int len, struct tm *tm)
3436{
David Carlier327298c2016-11-20 10:42:38 +00003437 /* tm_gmtoff, if present, ought to be zero'ed */
3438 memset(tm, 0, sizeof(*tm));
3439
Thierry Fournier93127942016-01-20 18:49:45 +01003440 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3441 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3442 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3443 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3444 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3445 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3446 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3447 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3448 tm->tm_year -= 1900;
3449 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3450 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3451 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3452 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3453 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003454 return 1;
3455}
3456
3457/* From RFC7231
3458 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3459 *
3460 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3461 * date2 = day "-" month "-" 2DIGIT
3462 * ; e.g., 02-Jun-82
3463 *
3464 * day = 2DIGIT
3465 */
3466int parse_rfc850_date(const char *date, int len, struct tm *tm)
3467{
3468 int year;
3469
David Carlier327298c2016-11-20 10:42:38 +00003470 /* tm_gmtoff, if present, ought to be zero'ed */
3471 memset(tm, 0, sizeof(*tm));
3472
Thierry Fournier93127942016-01-20 18:49:45 +01003473 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3474 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3475 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3476 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3477 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3478 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3479 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3480
3481 /* year = 2DIGIT
3482 *
3483 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3484 * two-digit year, MUST interpret a timestamp that appears to be more
3485 * than 50 years in the future as representing the most recent year in
3486 * the past that had the same last two digits.
3487 */
3488 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3489
3490 /* expect SP */
3491 if (!parse_expect_char(&date, &len, ' ')) {
3492 /* Maybe we have the date with 4 digits. */
3493 RET0_UNLESS(parse_2digit(&date, &len, &year));
3494 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3495 /* expect SP */
3496 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3497 } else {
3498 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3499 * tm_year is the number of year since 1900, so for +1900, we
3500 * do nothing, and for +2000, we add 100.
3501 */
3502 if (tm->tm_year <= 60)
3503 tm->tm_year += 100;
3504 }
3505
3506 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3507 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3508 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3509 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003510
3511 return 1;
3512}
3513
3514/* From RFC7231
3515 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3516 *
3517 * asctime-date = day-name SP date3 SP time-of-day SP year
3518 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3519 * ; e.g., Jun 2
3520 *
3521 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3522 * whitespace in an HTTP-date beyond that specifically included as SP in
3523 * the grammar.
3524 */
3525int parse_asctime_date(const char *date, int len, struct tm *tm)
3526{
David Carlier327298c2016-11-20 10:42:38 +00003527 /* tm_gmtoff, if present, ought to be zero'ed */
3528 memset(tm, 0, sizeof(*tm));
3529
Thierry Fournier93127942016-01-20 18:49:45 +01003530 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3531 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3532 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3533 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3534
3535 /* expect SP and 1DIGIT or 2DIGIT */
3536 if (parse_expect_char(&date, &len, ' '))
3537 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3538 else
3539 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3540
3541 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3542 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3543 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3544 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3545 tm->tm_year -= 1900;
3546 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003547 return 1;
3548}
3549
3550/* From RFC7231
3551 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3552 *
3553 * HTTP-date = IMF-fixdate / obs-date
3554 * obs-date = rfc850-date / asctime-date
3555 *
3556 * parses an HTTP date in the RFC format and is accepted
3557 * alternatives. <date> is the strinf containing the date,
3558 * len is the len of the string. <tm> is filled with the
3559 * parsed time. We must considers this time as GMT.
3560 */
3561int parse_http_date(const char *date, int len, struct tm *tm)
3562{
3563 if (parse_imf_date(date, len, tm))
3564 return 1;
3565
3566 if (parse_rfc850_date(date, len, tm))
3567 return 1;
3568
3569 if (parse_asctime_date(date, len, tm))
3570 return 1;
3571
3572 return 0;
3573}
3574
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003575/* Dynamically allocates a string of the proper length to hold the formatted
3576 * output. NULL is returned on error. The caller is responsible for freeing the
3577 * memory area using free(). The resulting string is returned in <out> if the
3578 * pointer is not NULL. A previous version of <out> might be used to build the
3579 * new string, and it will be freed before returning if it is not NULL, which
3580 * makes it possible to build complex strings from iterative calls without
3581 * having to care about freeing intermediate values, as in the example below :
3582 *
3583 * memprintf(&err, "invalid argument: '%s'", arg);
3584 * ...
3585 * memprintf(&err, "parser said : <%s>\n", *err);
3586 * ...
3587 * free(*err);
3588 *
3589 * This means that <err> must be initialized to NULL before first invocation.
3590 * The return value also holds the allocated string, which eases error checking
3591 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003592 * passed instead and it will be ignored. The returned message will then also
3593 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003594 *
3595 * It is also convenient to use it without any free except the last one :
3596 * err = NULL;
3597 * if (!fct1(err)) report(*err);
3598 * if (!fct2(err)) report(*err);
3599 * if (!fct3(err)) report(*err);
3600 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003601 *
3602 * memprintf relies on memvprintf. This last version can be called from any
3603 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003604 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003605char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003606{
3607 va_list args;
3608 char *ret = NULL;
3609 int allocated = 0;
3610 int needed = 0;
3611
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003612 if (!out)
3613 return NULL;
3614
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003615 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003616 char buf1;
3617
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003618 /* vsnprintf() will return the required length even when the
3619 * target buffer is NULL. We do this in a loop just in case
3620 * intermediate evaluations get wrong.
3621 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003622 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003623 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003624 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003625 if (needed < allocated) {
3626 /* Note: on Solaris 8, the first iteration always
3627 * returns -1 if allocated is zero, so we force a
3628 * retry.
3629 */
3630 if (!allocated)
3631 needed = 0;
3632 else
3633 break;
3634 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003635
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003636 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003637 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003638 } while (ret);
3639
3640 if (needed < 0) {
3641 /* an error was encountered */
3642 free(ret);
3643 ret = NULL;
3644 }
3645
3646 if (out) {
3647 free(*out);
3648 *out = ret;
3649 }
3650
3651 return ret;
3652}
William Lallemand421f5b52012-02-06 18:15:57 +01003653
Christopher Faulet93a518f2017-10-24 11:25:33 +02003654char *memprintf(char **out, const char *format, ...)
3655{
3656 va_list args;
3657 char *ret = NULL;
3658
3659 va_start(args, format);
3660 ret = memvprintf(out, format, args);
3661 va_end(args);
3662
3663 return ret;
3664}
3665
Willy Tarreau21c705b2012-09-14 11:40:36 +02003666/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3667 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003668 * freed by the caller. It also supports being passed a NULL which results in the same
3669 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003670 * Example of use :
3671 * parse(cmd, &err); (callee: memprintf(&err, ...))
3672 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3673 * free(err);
3674 */
3675char *indent_msg(char **out, int level)
3676{
3677 char *ret, *in, *p;
3678 int needed = 0;
3679 int lf = 0;
3680 int lastlf = 0;
3681 int len;
3682
Willy Tarreau70eec382012-10-10 08:56:47 +02003683 if (!out || !*out)
3684 return NULL;
3685
Willy Tarreau21c705b2012-09-14 11:40:36 +02003686 in = *out - 1;
3687 while ((in = strchr(in + 1, '\n')) != NULL) {
3688 lastlf = in - *out;
3689 lf++;
3690 }
3691
3692 if (!lf) /* single line, no LF, return it as-is */
3693 return *out;
3694
3695 len = strlen(*out);
3696
3697 if (lf == 1 && lastlf == len - 1) {
3698 /* single line, LF at end, strip it and return as-is */
3699 (*out)[lastlf] = 0;
3700 return *out;
3701 }
3702
3703 /* OK now we have at least one LF, we need to process the whole string
3704 * as a multi-line string. What we'll do :
3705 * - prefix with an LF if there is none
3706 * - add <level> spaces before each line
3707 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3708 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3709 */
3710
3711 needed = 1 + level * (lf + 1) + len + 1;
3712 p = ret = malloc(needed);
3713 in = *out;
3714
3715 /* skip initial LFs */
3716 while (*in == '\n')
3717 in++;
3718
3719 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3720 while (*in) {
3721 *p++ = '\n';
3722 memset(p, ' ', level);
3723 p += level;
3724 do {
3725 *p++ = *in++;
3726 } while (*in && *in != '\n');
3727 if (*in)
3728 in++;
3729 }
3730 *p = 0;
3731
3732 free(*out);
3733 *out = ret;
3734
3735 return ret;
3736}
3737
Willy Tarreaufe575b52019-08-21 13:17:37 +02003738/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3739 * and end of lines replaced with <eol> if not 0. The first line to indent has
3740 * to be indicated in <first> (starts at zero), so that it is possible to skip
3741 * indenting the first line if it has to be appended after an existing message.
3742 * Empty strings are never indented, and NULL strings are considered empty both
3743 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3744 * character, non-zero otherwise.
3745 */
3746int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3747{
3748 int bol, lf;
3749 int pfxlen = pfx ? strlen(pfx) : 0;
3750
3751 if (!in)
3752 return 0;
3753
3754 bol = 1;
3755 lf = 0;
3756 while (*in) {
3757 if (bol && pfxlen) {
3758 if (first > 0)
3759 first--;
3760 else
3761 b_putblk(out, pfx, pfxlen);
3762 bol = 0;
3763 }
3764
3765 lf = (*in == '\n');
3766 bol |= lf;
3767 b_putchr(out, (lf && eol) ? eol : *in);
3768 in++;
3769 }
3770 return lf;
3771}
3772
Willy Tarreau9d22e562019-03-29 18:49:09 +01003773/* removes environment variable <name> from the environment as found in
3774 * environ. This is only provided as an alternative for systems without
3775 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
3776 * The principle is to scan environ for each occurence of variable name
3777 * <name> and to replace the matching pointers with the last pointer of
3778 * the array (since variables are not ordered).
3779 * It always returns 0 (success).
3780 */
3781int my_unsetenv(const char *name)
3782{
3783 extern char **environ;
3784 char **p = environ;
3785 int vars;
3786 int next;
3787 int len;
3788
3789 len = strlen(name);
3790 for (vars = 0; p[vars]; vars++)
3791 ;
3792 next = 0;
3793 while (next < vars) {
3794 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3795 next++;
3796 continue;
3797 }
3798 if (next < vars - 1)
3799 p[next] = p[vars - 1];
3800 p[--vars] = NULL;
3801 }
3802 return 0;
3803}
3804
Willy Tarreaudad36a32013-03-11 01:20:04 +01003805/* Convert occurrences of environment variables in the input string to their
3806 * corresponding value. A variable is identified as a series of alphanumeric
3807 * characters or underscores following a '$' sign. The <in> string must be
3808 * free()able. NULL returns NULL. The resulting string might be reallocated if
3809 * some expansion is made. Variable names may also be enclosed into braces if
3810 * needed (eg: to concatenate alphanum characters).
3811 */
3812char *env_expand(char *in)
3813{
3814 char *txt_beg;
3815 char *out;
3816 char *txt_end;
3817 char *var_beg;
3818 char *var_end;
3819 char *value;
3820 char *next;
3821 int out_len;
3822 int val_len;
3823
3824 if (!in)
3825 return in;
3826
3827 value = out = NULL;
3828 out_len = 0;
3829
3830 txt_beg = in;
3831 do {
3832 /* look for next '$' sign in <in> */
3833 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3834
3835 if (!*txt_end && !out) /* end and no expansion performed */
3836 return in;
3837
3838 val_len = 0;
3839 next = txt_end;
3840 if (*txt_end == '$') {
3841 char save;
3842
3843 var_beg = txt_end + 1;
3844 if (*var_beg == '{')
3845 var_beg++;
3846
3847 var_end = var_beg;
3848 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3849 var_end++;
3850 }
3851
3852 next = var_end;
3853 if (*var_end == '}' && (var_beg > txt_end + 1))
3854 next++;
3855
3856 /* get value of the variable name at this location */
3857 save = *var_end;
3858 *var_end = '\0';
3859 value = getenv(var_beg);
3860 *var_end = save;
3861 val_len = value ? strlen(value) : 0;
3862 }
3863
Hubert Verstraete831962e2016-06-28 22:44:26 +02003864 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003865 if (txt_end > txt_beg) {
3866 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3867 out_len += txt_end - txt_beg;
3868 }
3869 if (val_len) {
3870 memcpy(out + out_len, value, val_len);
3871 out_len += val_len;
3872 }
3873 out[out_len] = 0;
3874 txt_beg = next;
3875 } while (*txt_beg);
3876
3877 /* here we know that <out> was allocated and that we don't need <in> anymore */
3878 free(in);
3879 return out;
3880}
3881
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003882
3883/* same as strstr() but case-insensitive and with limit length */
3884const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3885{
3886 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003887 unsigned int slen, plen;
3888 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003889
3890 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3891 return NULL;
3892
3893 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3894 return str1;
3895
3896 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3897 return NULL;
3898
3899 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3900 while (toupper(*start) != toupper(*str2)) {
3901 start++;
3902 slen--;
3903 tmp1++;
3904
3905 if (tmp1 >= len_str1)
3906 return NULL;
3907
3908 /* if pattern longer than string */
3909 if (slen < plen)
3910 return NULL;
3911 }
3912
3913 sptr = start;
3914 pptr = (char *)str2;
3915
3916 tmp2 = 0;
3917 while (toupper(*sptr) == toupper(*pptr)) {
3918 sptr++;
3919 pptr++;
3920 tmp2++;
3921
3922 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3923 return start;
3924 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3925 return NULL;
3926 }
3927 }
3928 return NULL;
3929}
3930
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003931/* This function read the next valid utf8 char.
3932 * <s> is the byte srray to be decode, <len> is its length.
3933 * The function returns decoded char encoded like this:
3934 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3935 * are the length read. The decoded character is stored in <c>.
3936 */
3937unsigned char utf8_next(const char *s, int len, unsigned int *c)
3938{
3939 const unsigned char *p = (unsigned char *)s;
3940 int dec;
3941 unsigned char code = UTF8_CODE_OK;
3942
3943 if (len < 1)
3944 return UTF8_CODE_OK;
3945
3946 /* Check the type of UTF8 sequence
3947 *
3948 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3949 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3950 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3951 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3952 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3953 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3954 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3955 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3956 */
3957 switch (*p) {
3958 case 0x00 ... 0x7f:
3959 *c = *p;
3960 return UTF8_CODE_OK | 1;
3961
3962 case 0x80 ... 0xbf:
3963 *c = *p;
3964 return UTF8_CODE_BADSEQ | 1;
3965
3966 case 0xc0 ... 0xdf:
3967 if (len < 2) {
3968 *c = *p;
3969 return UTF8_CODE_BADSEQ | 1;
3970 }
3971 *c = *p & 0x1f;
3972 dec = 1;
3973 break;
3974
3975 case 0xe0 ... 0xef:
3976 if (len < 3) {
3977 *c = *p;
3978 return UTF8_CODE_BADSEQ | 1;
3979 }
3980 *c = *p & 0x0f;
3981 dec = 2;
3982 break;
3983
3984 case 0xf0 ... 0xf7:
3985 if (len < 4) {
3986 *c = *p;
3987 return UTF8_CODE_BADSEQ | 1;
3988 }
3989 *c = *p & 0x07;
3990 dec = 3;
3991 break;
3992
3993 case 0xf8 ... 0xfb:
3994 if (len < 5) {
3995 *c = *p;
3996 return UTF8_CODE_BADSEQ | 1;
3997 }
3998 *c = *p & 0x03;
3999 dec = 4;
4000 break;
4001
4002 case 0xfc ... 0xfd:
4003 if (len < 6) {
4004 *c = *p;
4005 return UTF8_CODE_BADSEQ | 1;
4006 }
4007 *c = *p & 0x01;
4008 dec = 5;
4009 break;
4010
4011 case 0xfe ... 0xff:
4012 default:
4013 *c = *p;
4014 return UTF8_CODE_BADSEQ | 1;
4015 }
4016
4017 p++;
4018
4019 while (dec > 0) {
4020
4021 /* need 0x10 for the 2 first bits */
4022 if ( ( *p & 0xc0 ) != 0x80 )
4023 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4024
4025 /* add data at char */
4026 *c = ( *c << 6 ) | ( *p & 0x3f );
4027
4028 dec--;
4029 p++;
4030 }
4031
4032 /* Check ovelong encoding.
4033 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4034 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4035 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4036 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004037 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004038 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4039 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4040 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4041 code |= UTF8_CODE_OVERLONG;
4042
4043 /* Check invalid UTF8 range. */
4044 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4045 (*c >= 0xfffe && *c <= 0xffff))
4046 code |= UTF8_CODE_INVRANGE;
4047
4048 return code | ((p-(unsigned char *)s)&0x0f);
4049}
4050
Maxime de Roucydc887852016-05-13 23:52:54 +02004051/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4052 * On failure : return 0 and <err> filled with an error message.
4053 * The caller is responsible for freeing the <err> and <str> copy
4054 * memory area using free()
4055 */
4056int list_append_word(struct list *li, const char *str, char **err)
4057{
4058 struct wordlist *wl;
4059
4060 wl = calloc(1, sizeof(*wl));
4061 if (!wl) {
4062 memprintf(err, "out of memory");
4063 goto fail_wl;
4064 }
4065
4066 wl->s = strdup(str);
4067 if (!wl->s) {
4068 memprintf(err, "out of memory");
4069 goto fail_wl_s;
4070 }
4071
4072 LIST_ADDQ(li, &wl->list);
4073
4074 return 1;
4075
4076fail_wl_s:
4077 free(wl->s);
4078fail_wl:
4079 free(wl);
4080 return 0;
4081}
4082
Willy Tarreau37101052019-05-20 16:48:20 +02004083/* indicates if a memory location may safely be read or not. The trick consists
4084 * in performing a harmless syscall using this location as an input and letting
4085 * the operating system report whether it's OK or not. For this we have the
4086 * stat() syscall, which will return EFAULT when the memory location supposed
4087 * to contain the file name is not readable. If it is readable it will then
4088 * either return 0 if the area contains an existing file name, or -1 with
4089 * another code. This must not be abused, and some audit systems might detect
4090 * this as abnormal activity. It's used only for unsafe dumps.
4091 */
4092int may_access(const void *ptr)
4093{
4094 struct stat buf;
4095
4096 if (stat(ptr, &buf) == 0)
4097 return 1;
4098 if (errno == EFAULT)
4099 return 0;
4100 return 1;
4101}
4102
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004103/* print a string of text buffer to <out>. The format is :
4104 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4105 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4106 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4107 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004108int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004109{
4110 unsigned char c;
4111 int ptr = 0;
4112
4113 while (buf[ptr] && ptr < bsize) {
4114 c = buf[ptr];
4115 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004116 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004117 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004118 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004119 }
4120 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004121 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004122 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004123 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004124 switch (c) {
4125 case ' ': c = ' '; break;
4126 case '\t': c = 't'; break;
4127 case '\n': c = 'n'; break;
4128 case '\r': c = 'r'; break;
4129 case '\e': c = 'e'; break;
4130 case '\\': c = '\\'; break;
4131 case '=': c = '='; break;
4132 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004133 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004134 }
4135 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004136 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004137 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004138 out->area[out->data++] = '\\';
4139 out->area[out->data++] = 'x';
4140 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4141 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004142 }
4143 ptr++;
4144 }
4145
4146 return ptr;
4147}
4148
4149/* print a buffer in hexa.
4150 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4151 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004152int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004153{
4154 unsigned char c;
4155 int ptr = 0;
4156
4157 while (ptr < bsize) {
4158 c = buf[ptr];
4159
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004160 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004161 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004162 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4163 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004164
4165 ptr++;
4166 }
4167 return ptr;
4168}
4169
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004170/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4171 * prepending each line with prefix <pfx>. The output is *not* initialized.
4172 * The output will not wrap pas the buffer's end so it is more optimal if the
4173 * caller makes sure the buffer is aligned first. A trailing zero will always
4174 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004175 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4176 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004177 */
Willy Tarreau37101052019-05-20 16:48:20 +02004178void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004179{
4180 const unsigned char *d = buf;
4181 int i, j, start;
4182
4183 d = (const unsigned char *)(((unsigned long)buf) & -16);
4184 start = ((unsigned long)buf) & 15;
4185
4186 for (i = 0; i < start + len; i += 16) {
4187 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4188
Willy Tarreau37101052019-05-20 16:48:20 +02004189 // 0: unchecked, 1: checked safe, 2: danger
4190 unsafe = !!unsafe;
4191 if (unsafe && !may_access(d + i))
4192 unsafe = 2;
4193
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004194 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004195 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004196 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004197 else if (unsafe > 1)
4198 chunk_strcat(out, "** ");
4199 else
4200 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004201
4202 if (j == 7)
4203 chunk_strcat(out, "- ");
4204 }
4205 chunk_strcat(out, " ");
4206 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004207 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004208 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004209 else if (unsafe > 1)
4210 chunk_strcat(out, "*");
4211 else if (isprint(d[i + j]))
4212 chunk_appendf(out, "%c", d[i + j]);
4213 else
4214 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004215 }
4216 chunk_strcat(out, "\n");
4217 }
4218}
4219
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004220/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4221 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4222 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4223 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4224 * lines are respected within the limit of 70 output chars. Lines that are
4225 * continuation of a previous truncated line begin with "+" instead of " "
4226 * after the offset. The new pointer is returned.
4227 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004228int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004229 int *line, int ptr)
4230{
4231 int end;
4232 unsigned char c;
4233
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004234 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004235 if (end > out->size)
4236 return ptr;
4237
4238 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4239
4240 while (ptr < len && ptr < bsize) {
4241 c = buf[ptr];
4242 if (isprint(c) && isascii(c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004243 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004244 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004245 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004246 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004247 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004248 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004249 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004250 switch (c) {
4251 case '\t': c = 't'; break;
4252 case '\n': c = 'n'; break;
4253 case '\r': c = 'r'; break;
4254 case '\e': c = 'e'; break;
4255 case '\\': c = '\\'; break;
4256 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004257 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004258 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004259 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004260 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004261 out->area[out->data++] = '\\';
4262 out->area[out->data++] = 'x';
4263 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4264 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004265 }
4266 if (buf[ptr++] == '\n') {
4267 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004268 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004269 *line = ptr;
4270 return ptr;
4271 }
4272 }
4273 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004274 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004275 return ptr;
4276}
4277
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004278/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004279 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4280 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004281 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004282void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4283 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004284{
Willy Tarreau73459792017-04-11 07:58:08 +02004285 unsigned int i;
4286 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004287
4288 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4289 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004290 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004291 for (j = 0; j < 8; j++) {
4292 if (b + j >= 0 && b + j < len)
4293 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4294 else
4295 fprintf(out, " ");
4296 }
4297
4298 if (b + j >= 0 && b + j < len)
4299 fputc('-', out);
4300 else
4301 fputc(' ', out);
4302
4303 for (j = 8; j < 16; j++) {
4304 if (b + j >= 0 && b + j < len)
4305 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4306 else
4307 fprintf(out, " ");
4308 }
4309
4310 fprintf(out, " ");
4311 for (j = 0; j < 16; j++) {
4312 if (b + j >= 0 && b + j < len) {
4313 if (isprint((unsigned char)buf[b + j]))
4314 fputc((unsigned char)buf[b + j], out);
4315 else
4316 fputc('.', out);
4317 }
4318 else
4319 fputc(' ', out);
4320 }
4321 fputc('\n', out);
4322 }
4323}
4324
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004325/*
4326 * Allocate an array of unsigned int with <nums> as address from <str> string
4327 * made of integer sepereated by dot characters.
4328 *
4329 * First, initializes the value with <sz> as address to 0 and initializes the
4330 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4331 * address updating <sz> pointed value to the size of this array.
4332 *
4333 * Returns 1 if succeeded, 0 if not.
4334 */
4335int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4336{
4337 unsigned int *n;
4338 const char *s, *end;
4339
4340 s = str;
4341 *sz = 0;
4342 end = str + strlen(str);
4343 *nums = n = NULL;
4344
4345 while (1) {
4346 unsigned int r;
4347
4348 if (s >= end)
4349 break;
4350
4351 r = read_uint(&s, end);
4352 /* Expected characters after having read an uint: '\0' or '.',
4353 * if '.', must not be terminal.
4354 */
Christopher Faulet21471ef2021-02-11 10:42:41 +01004355 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4356 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004357 return 0;
Christopher Faulet21471ef2021-02-11 10:42:41 +01004358 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004359
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004360 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004361 if (!n)
4362 return 0;
4363
4364 n[(*sz)++] = r;
4365 }
4366 *nums = n;
4367
4368 return 1;
4369}
4370
Willy Tarreau12963822017-10-24 10:54:08 +02004371/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
Willy Tarreau42a66212019-06-04 16:02:26 +02004372#ifndef USE_OBSOLETE_LINKER
Willy Tarreau12963822017-10-24 10:54:08 +02004373__attribute__((weak,format(printf, 1, 2)))
Willy Tarreau42a66212019-06-04 16:02:26 +02004374#endif
Willy Tarreau12963822017-10-24 10:54:08 +02004375void trace(char *msg, ...)
4376{
4377}
4378
Willy Tarreau861c4ef2020-03-08 00:42:37 +01004379
4380/* Random number generator state, see below */
Willy Tarreau11ab2e02020-03-12 00:31:18 +01004381static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau861c4ef2020-03-08 00:42:37 +01004382
4383/* This is a thread-safe implementation of xoroshiro128** described below:
4384 * http://prng.di.unimi.it/
4385 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4386 * supports fast jumps and passes all common quality tests. It is thread-safe,
4387 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4388 * local lock on other ones.
4389 */
4390uint64_t ha_random64()
4391{
4392 uint64_t result;
Willy Tarreau11ab2e02020-03-12 00:31:18 +01004393 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4394 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau861c4ef2020-03-08 00:42:37 +01004395
4396#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4397 static HA_SPINLOCK_T rand_lock;
4398
4399 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4400#endif
4401
4402 old[0] = ha_random_state[0];
4403 old[1] = ha_random_state[1];
4404
4405#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4406 do {
4407#endif
4408 result = rotl64(old[0] * 5, 7) * 9;
4409 new[1] = old[0] ^ old[1];
4410 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4411 new[1] = rotl64(new[1], 37); // c
4412
4413#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4414 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4415#else
4416 ha_random_state[0] = new[0];
4417 ha_random_state[1] = new[1];
4418#if defined(USE_THREAD)
4419 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4420#endif
4421#endif
4422 return result;
4423}
4424
4425/* seeds the random state using up to <len> bytes from <seed>, starting with
4426 * the first non-zero byte.
4427 */
4428void ha_random_seed(const unsigned char *seed, size_t len)
4429{
4430 size_t pos;
4431
4432 /* the seed must not be all zeroes, so we pre-fill it with alternating
4433 * bits and overwrite part of them with the block starting at the first
4434 * non-zero byte from the seed.
4435 */
4436 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4437
4438 for (pos = 0; pos < len; pos++)
4439 if (seed[pos] != 0)
4440 break;
4441
4442 if (pos == len)
4443 return;
4444
4445 seed += pos;
4446 len -= pos;
4447
4448 if (len > sizeof(ha_random_state))
4449 len = sizeof(ha_random_state);
4450
4451 memcpy(ha_random_state, seed, len);
4452}
4453
4454/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4455 * and is equivalent to calling ha_random64() as many times. It is used to
4456 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4457 * different generators (i.e. different processes after a fork). The <dist>
4458 * argument is the distance to jump to and is used in a loop so it rather not
4459 * be too large if the processing time is a concern.
4460 *
4461 * BEWARE: this function is NOT thread-safe and must not be called during
4462 * concurrent accesses to ha_random64().
4463 */
4464void ha_random_jump96(uint32_t dist)
4465{
4466 while (dist--) {
4467 uint64_t s0 = 0;
4468 uint64_t s1 = 0;
4469 int b;
4470
4471 for (b = 0; b < 64; b++) {
4472 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4473 s0 ^= ha_random_state[0];
4474 s1 ^= ha_random_state[1];
4475 }
4476 ha_random64();
4477 }
4478
4479 for (b = 0; b < 64; b++) {
4480 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4481 s0 ^= ha_random_state[0];
4482 s1 ^= ha_random_state[1];
4483 }
4484 ha_random64();
4485 }
4486 ha_random_state[0] = s0;
4487 ha_random_state[1] = s1;
4488 }
4489}
4490
Willy Tarreaubaaee002006-06-26 02:48:02 +02004491/*
4492 * Local variables:
4493 * c-indent-level: 8
4494 * c-basic-offset: 8
4495 * End:
4496 */