blob: 57d0cd7db5d6cfb1b6899b61df570e7023a71156 [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/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001218 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001219 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001220int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001221{
1222 int saw_digit, octets, ch;
1223 u_char tmp[4], *tp;
1224 const char *cp = addr;
1225
1226 saw_digit = 0;
1227 octets = 0;
1228 *(tp = tmp) = 0;
1229
1230 while (*addr) {
1231 unsigned char digit = (ch = *addr++) - '0';
1232 if (digit > 9 && ch != '.')
1233 break;
1234 if (digit <= 9) {
1235 u_int new = *tp * 10 + digit;
1236 if (new > 255)
1237 return 0;
1238 *tp = new;
1239 if (!saw_digit) {
1240 if (++octets > 4)
1241 return 0;
1242 saw_digit = 1;
1243 }
1244 } else if (ch == '.' && saw_digit) {
1245 if (octets == 4)
1246 return 0;
1247 *++tp = 0;
1248 saw_digit = 0;
1249 } else
1250 return 0;
1251 }
1252
1253 if (octets < 4)
1254 return 0;
1255
1256 memcpy(&dst->s_addr, tmp, 4);
1257 return addr-cp-1;
1258}
1259
1260/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001261 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1262 * <out> contain the code of the dectected scheme, the start and length of
1263 * the hostname. Actually only http and https are supported. <out> can be NULL.
1264 * This function returns the consumed length. It is useful if you parse complete
1265 * url like http://host:port/path, because the consumed length corresponds to
1266 * the first character of the path. If the conversion fails, it returns -1.
1267 *
1268 * This function tries to resolve the DNS name if haproxy is in starting mode.
1269 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001270 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001271int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001272{
1273 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001274 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001275 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001276 unsigned long long int http_code = 0;
1277 int default_port;
1278 struct hostent *he;
1279 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001280
1281 /* Firstly, try to find :// pattern */
1282 while (curr < url+ulen && url_code != 0x3a2f2f) {
1283 url_code = ((url_code & 0xffff) << 8);
1284 url_code += (unsigned char)*curr++;
1285 }
1286
1287 /* Secondly, if :// pattern is found, verify parsed stuff
1288 * before pattern is matching our http pattern.
1289 * If so parse ip address and port in uri.
1290 *
1291 * WARNING: Current code doesn't support dynamic async dns resolver.
1292 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001293 if (url_code != 0x3a2f2f)
1294 return -1;
1295
1296 /* Copy scheme, and utrn to lower case. */
1297 while (cp < curr - 3)
1298 http_code = (http_code << 8) + *cp++;
1299 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001300
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001301 /* HTTP or HTTPS url matching */
1302 if (http_code == 0x2020202068747470ULL) {
1303 default_port = 80;
1304 if (out)
1305 out->scheme = SCH_HTTP;
1306 }
1307 else if (http_code == 0x2020206874747073ULL) {
1308 default_port = 443;
1309 if (out)
1310 out->scheme = SCH_HTTPS;
1311 }
1312 else
1313 return -1;
1314
1315 /* If the next char is '[', the host address is IPv6. */
1316 if (*curr == '[') {
1317 curr++;
1318
1319 /* Check trash size */
1320 if (trash.size < ulen)
1321 return -1;
1322
1323 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001324 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001325 for (end = curr;
1326 end < url + ulen && *end != ']';
1327 end++, p++)
1328 *p = *end;
1329 if (*end != ']')
1330 return -1;
1331 *p = '\0';
1332
1333 /* Update out. */
1334 if (out) {
1335 out->host = curr;
1336 out->host_len = end - curr;
1337 }
1338
1339 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001340 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001341 return -1;
1342 end++;
1343
1344 /* Decode port. */
1345 if (*end == ':') {
1346 end++;
1347 default_port = read_uint(&end, url + ulen);
1348 }
1349 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1350 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1351 return end - url;
1352 }
1353 else {
1354 /* We are looking for IP address. If you want to parse and
1355 * resolve hostname found in url, you can use str2sa_range(), but
1356 * be warned this can slow down global daemon performances
1357 * while handling lagging dns responses.
1358 */
1359 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1360 if (ret) {
1361 /* Update out. */
1362 if (out) {
1363 out->host = curr;
1364 out->host_len = ret;
1365 }
1366
1367 curr += ret;
1368
1369 /* Decode port. */
1370 if (*curr == ':') {
1371 curr++;
1372 default_port = read_uint(&curr, url + ulen);
1373 }
1374 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1375
1376 /* Set family. */
1377 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1378 return curr - url;
1379 }
1380 else if (global.mode & MODE_STARTING) {
1381 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1382 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001383 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001384
1385 /* look for : or / or end */
1386 for (end = curr;
1387 end < url + ulen && *end != '/' && *end != ':';
1388 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001389 memcpy(trash.area, curr, end - curr);
1390 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001391
1392 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001393 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001394 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001395 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001396
1397 /* Update out. */
1398 if (out) {
1399 out->host = curr;
1400 out->host_len = end - curr;
1401 }
1402
1403 /* Decode port. */
1404 if (*end == ':') {
1405 end++;
1406 default_port = read_uint(&end, url + ulen);
1407 }
1408
1409 /* Copy IP address, set port and family. */
1410 switch (he->h_addrtype) {
1411 case AF_INET:
1412 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1413 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1414 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1415 return end - url;
1416
1417 case AF_INET6:
1418 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1419 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1420 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1421 return end - url;
1422 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001423 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001424 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001425 return -1;
1426}
1427
Willy Tarreau631f01c2011-09-05 00:36:48 +02001428/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1429 * address family is returned so that it's easy for the caller to adapt to the
1430 * output format. Zero is returned if the address family is not supported. -1
1431 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1432 * supported.
1433 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001434int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001435{
1436
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001437 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001438
1439 if (size < 5)
1440 return 0;
1441 *str = '\0';
1442
1443 switch (addr->ss_family) {
1444 case AF_INET:
1445 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1446 break;
1447 case AF_INET6:
1448 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1449 break;
1450 case AF_UNIX:
1451 memcpy(str, "unix", 5);
1452 return addr->ss_family;
1453 default:
1454 return 0;
1455 }
1456
1457 if (inet_ntop(addr->ss_family, ptr, str, size))
1458 return addr->ss_family;
1459
1460 /* failed */
1461 return -1;
1462}
1463
Simon Horman75ab8bd2014-06-16 09:39:41 +09001464/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1465 * address family is returned so that it's easy for the caller to adapt to the
1466 * output format. Zero is returned if the address family is not supported. -1
1467 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1468 * supported.
1469 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001470int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001471{
1472
1473 uint16_t port;
1474
1475
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001476 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001477 return 0;
1478 *str = '\0';
1479
1480 switch (addr->ss_family) {
1481 case AF_INET:
1482 port = ((struct sockaddr_in *)addr)->sin_port;
1483 break;
1484 case AF_INET6:
1485 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1486 break;
1487 case AF_UNIX:
1488 memcpy(str, "unix", 5);
1489 return addr->ss_family;
1490 default:
1491 return 0;
1492 }
1493
1494 snprintf(str, size, "%u", ntohs(port));
1495 return addr->ss_family;
1496}
1497
Willy Tarreau16e01562016-08-09 16:46:18 +02001498/* check if the given address is local to the system or not. It will return
1499 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1500 * it is. We don't want to iterate over all interfaces for this (and it is not
1501 * portable). So instead we try to bind in UDP to this address on a free non
1502 * privileged port and to connect to the same address, port 0 (connect doesn't
1503 * care). If it succeeds, we own the address. Note that non-inet addresses are
1504 * considered local since they're most likely AF_UNIX.
1505 */
1506int addr_is_local(const struct netns_entry *ns,
1507 const struct sockaddr_storage *orig)
1508{
1509 struct sockaddr_storage addr;
1510 int result;
1511 int fd;
1512
1513 if (!is_inet_addr(orig))
1514 return 1;
1515
1516 memcpy(&addr, orig, sizeof(addr));
1517 set_host_port(&addr, 0);
1518
1519 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1520 if (fd < 0)
1521 return -1;
1522
1523 result = -1;
1524 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1525 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1526 result = 0; // fail, non-local address
1527 else
1528 result = 1; // success, local address
1529 }
1530 else {
1531 if (errno == EADDRNOTAVAIL)
1532 result = 0; // definitely not local :-)
1533 }
1534 close(fd);
1535
1536 return result;
1537}
1538
Willy Tarreaubaaee002006-06-26 02:48:02 +02001539/* will try to encode the string <string> replacing all characters tagged in
1540 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1541 * prefixed by <escape>, and will store the result between <start> (included)
1542 * and <stop> (excluded), and will always terminate the string with a '\0'
1543 * before <stop>. The position of the '\0' is returned if the conversion
1544 * completes. If bytes are missing between <start> and <stop>, then the
1545 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1546 * cannot even be stored so we return <start> without writing the 0.
1547 * The input string must also be zero-terminated.
1548 */
1549const char hextab[16] = "0123456789ABCDEF";
1550char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001551 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001552 const char *string)
1553{
1554 if (start < stop) {
1555 stop--; /* reserve one byte for the final '\0' */
1556 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001557 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001558 *start++ = *string;
1559 else {
1560 if (start + 3 >= stop)
1561 break;
1562 *start++ = escape;
1563 *start++ = hextab[(*string >> 4) & 15];
1564 *start++ = hextab[*string & 15];
1565 }
1566 string++;
1567 }
1568 *start = '\0';
1569 }
1570 return start;
1571}
1572
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001573/*
1574 * Same behavior as encode_string() above, except that it encodes chunk
1575 * <chunk> instead of a string.
1576 */
1577char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001578 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001579 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001580{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001581 char *str = chunk->area;
1582 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001583
1584 if (start < stop) {
1585 stop--; /* reserve one byte for the final '\0' */
1586 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001587 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001588 *start++ = *str;
1589 else {
1590 if (start + 3 >= stop)
1591 break;
1592 *start++ = escape;
1593 *start++ = hextab[(*str >> 4) & 15];
1594 *start++ = hextab[*str & 15];
1595 }
1596 str++;
1597 }
1598 *start = '\0';
1599 }
1600 return start;
1601}
1602
Dragan Dosen0edd1092016-02-12 13:23:02 +01001603/*
1604 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001605 * character. The input <string> must be zero-terminated. The result will
1606 * be stored between <start> (included) and <stop> (excluded). This
1607 * function will always try to terminate the resulting string with a '\0'
1608 * before <stop>, and will return its position if the conversion
1609 * completes.
1610 */
1611char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001612 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001613 const char *string)
1614{
1615 if (start < stop) {
1616 stop--; /* reserve one byte for the final '\0' */
1617 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001618 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001619 *start++ = *string;
1620 else {
1621 if (start + 2 >= stop)
1622 break;
1623 *start++ = escape;
1624 *start++ = *string;
1625 }
1626 string++;
1627 }
1628 *start = '\0';
1629 }
1630 return start;
1631}
1632
1633/*
1634 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001635 * character. <chunk> contains the input to be escaped. The result will be
1636 * stored between <start> (included) and <stop> (excluded). The function
1637 * will always try to terminate the resulting string with a '\0' before
1638 * <stop>, and will return its position if the conversion completes.
1639 */
1640char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001641 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001642 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001643{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001644 char *str = chunk->area;
1645 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001646
1647 if (start < stop) {
1648 stop--; /* reserve one byte for the final '\0' */
1649 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001650 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001651 *start++ = *str;
1652 else {
1653 if (start + 2 >= stop)
1654 break;
1655 *start++ = escape;
1656 *start++ = *str;
1657 }
1658 str++;
1659 }
1660 *start = '\0';
1661 }
1662 return start;
1663}
1664
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001665/* Check a string for using it in a CSV output format. If the string contains
1666 * one of the following four char <">, <,>, CR or LF, the string is
1667 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1668 * <str> is the input string to be escaped. The function assumes that
1669 * the input string is null-terminated.
1670 *
1671 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001672 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001673 * format.
1674 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001675 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001676 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001677 * If <quote> is 1, the converter puts the quotes only if any reserved character
1678 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001679 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001680 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001681 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001682 * The function returns the converted string on its output. If an error
1683 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001684 * for using the function directly as printf() argument.
1685 *
1686 * If the output buffer is too short to contain the input string, the result
1687 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001688 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001689 * This function appends the encoding to the existing output chunk, and it
1690 * guarantees that it starts immediately at the first available character of
1691 * the chunk. Please use csv_enc() instead if you want to replace the output
1692 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001693 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001694const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001695{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001696 char *end = output->area + output->size;
1697 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001698 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001699
Willy Tarreaub631c292016-01-08 10:04:08 +01001700 if (quote == 1) {
1701 /* automatic quoting: first verify if we'll have to quote the string */
1702 if (!strpbrk(str, "\n\r,\""))
1703 quote = 0;
1704 }
1705
1706 if (quote)
1707 *ptr++ = '"';
1708
Willy Tarreau898529b2016-01-06 18:07:04 +01001709 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1710 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001711 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001712 ptr++;
1713 if (ptr >= end - 2) {
1714 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001715 break;
1716 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001717 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001718 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001719 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001720 str++;
1721 }
1722
Willy Tarreaub631c292016-01-08 10:04:08 +01001723 if (quote)
1724 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001725
Willy Tarreau898529b2016-01-06 18:07:04 +01001726 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001727 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001728 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001729}
1730
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001731/* Decode an URL-encoded string in-place. The resulting string might
1732 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001733 * aborted, the string is truncated before the issue and a negative value is
1734 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001735 * If the 'in_form' argument is non-nul the string is assumed to be part of
1736 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1737 * turned to a space. If it's zero, this will only be done after a question
1738 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001739 */
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001740int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001741{
1742 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001743 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001744
1745 in = string;
1746 out = string;
1747 while (*in) {
1748 switch (*in) {
1749 case '+' :
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001750 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001751 break;
1752 case '%' :
1753 if (!ishex(in[1]) || !ishex(in[2]))
1754 goto end;
1755 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1756 in += 2;
1757 break;
Willy Tarreau7e913cb2020-04-23 17:54:47 +02001758 case '?':
1759 in_form = 1;
1760 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001761 default:
1762 *out++ = *in;
1763 break;
1764 }
1765 in++;
1766 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001767 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001768 end:
1769 *out = 0;
1770 return ret;
1771}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001772
Willy Tarreau6911fa42007-03-04 18:06:08 +01001773unsigned int str2ui(const char *s)
1774{
1775 return __str2ui(s);
1776}
1777
1778unsigned int str2uic(const char *s)
1779{
1780 return __str2uic(s);
1781}
1782
1783unsigned int strl2ui(const char *s, int len)
1784{
1785 return __strl2ui(s, len);
1786}
1787
1788unsigned int strl2uic(const char *s, int len)
1789{
1790 return __strl2uic(s, len);
1791}
1792
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001793unsigned int read_uint(const char **s, const char *end)
1794{
1795 return __read_uint(s, end);
1796}
1797
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001798/* This function reads an unsigned integer from the string pointed to by <s> and
1799 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1800 * function automatically stops at <end>. If the number overflows, the 2^64-1
1801 * value is returned.
1802 */
1803unsigned long long int read_uint64(const char **s, const char *end)
1804{
1805 const char *ptr = *s;
1806 unsigned long long int i = 0, tmp;
1807 unsigned int j;
1808
1809 while (ptr < end) {
1810
1811 /* read next char */
1812 j = *ptr - '0';
1813 if (j > 9)
1814 goto read_uint64_end;
1815
1816 /* add char to the number and check overflow. */
1817 tmp = i * 10;
1818 if (tmp / 10 != i) {
1819 i = ULLONG_MAX;
1820 goto read_uint64_eat;
1821 }
1822 if (ULLONG_MAX - tmp < j) {
1823 i = ULLONG_MAX;
1824 goto read_uint64_eat;
1825 }
1826 i = tmp + j;
1827 ptr++;
1828 }
1829read_uint64_eat:
1830 /* eat each numeric char */
1831 while (ptr < end) {
1832 if ((unsigned int)(*ptr - '0') > 9)
1833 break;
1834 ptr++;
1835 }
1836read_uint64_end:
1837 *s = ptr;
1838 return i;
1839}
1840
1841/* This function reads an integer from the string pointed to by <s> and returns
1842 * it. The <s> pointer is adjusted to point to the first unread char. The function
1843 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1844 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1845 * returned.
1846 */
1847long long int read_int64(const char **s, const char *end)
1848{
1849 unsigned long long int i = 0;
1850 int neg = 0;
1851
1852 /* Look for minus char. */
1853 if (**s == '-') {
1854 neg = 1;
1855 (*s)++;
1856 }
1857 else if (**s == '+')
1858 (*s)++;
1859
1860 /* convert as positive number. */
1861 i = read_uint64(s, end);
1862
1863 if (neg) {
1864 if (i > 0x8000000000000000ULL)
1865 return LLONG_MIN;
1866 return -i;
1867 }
1868 if (i > 0x7fffffffffffffffULL)
1869 return LLONG_MAX;
1870 return i;
1871}
1872
Willy Tarreau6911fa42007-03-04 18:06:08 +01001873/* This one is 7 times faster than strtol() on athlon with checks.
1874 * It returns the value of the number composed of all valid digits read,
1875 * and can process negative numbers too.
1876 */
1877int strl2ic(const char *s, int len)
1878{
1879 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001880 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001881
1882 if (len > 0) {
1883 if (*s != '-') {
1884 /* positive number */
1885 while (len-- > 0) {
1886 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001887 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001888 if (j > 9)
1889 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001890 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001891 }
1892 } else {
1893 /* negative number */
1894 s++;
1895 while (--len > 0) {
1896 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001897 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001898 if (j > 9)
1899 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001900 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001901 }
1902 }
1903 }
1904 return i;
1905}
1906
1907
1908/* This function reads exactly <len> chars from <s> and converts them to a
1909 * signed integer which it stores into <ret>. It accurately detects any error
1910 * (truncated string, invalid chars, overflows). It is meant to be used in
1911 * applications designed for hostile environments. It returns zero when the
1912 * number has successfully been converted, non-zero otherwise. When an error
1913 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1914 * faster than strtol().
1915 */
1916int strl2irc(const char *s, int len, int *ret)
1917{
1918 int i = 0;
1919 int j;
1920
1921 if (!len)
1922 return 1;
1923
1924 if (*s != '-') {
1925 /* positive number */
1926 while (len-- > 0) {
1927 j = (*s++) - '0';
1928 if (j > 9) return 1; /* invalid char */
1929 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1930 i = i * 10;
1931 if (i + j < i) return 1; /* check for addition overflow */
1932 i = i + j;
1933 }
1934 } else {
1935 /* negative number */
1936 s++;
1937 while (--len > 0) {
1938 j = (*s++) - '0';
1939 if (j > 9) return 1; /* invalid char */
1940 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1941 i = i * 10;
1942 if (i - j > i) return 1; /* check for subtract overflow */
1943 i = i - j;
1944 }
1945 }
1946 *ret = i;
1947 return 0;
1948}
1949
1950
1951/* This function reads exactly <len> chars from <s> and converts them to a
1952 * signed integer which it stores into <ret>. It accurately detects any error
1953 * (truncated string, invalid chars, overflows). It is meant to be used in
1954 * applications designed for hostile environments. It returns zero when the
1955 * number has successfully been converted, non-zero otherwise. When an error
1956 * is returned, the <ret> value is left untouched. It is about 3 times slower
1957 * than str2irc().
1958 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001959
1960int strl2llrc(const char *s, int len, long long *ret)
1961{
1962 long long i = 0;
1963 int j;
1964
1965 if (!len)
1966 return 1;
1967
1968 if (*s != '-') {
1969 /* positive number */
1970 while (len-- > 0) {
1971 j = (*s++) - '0';
1972 if (j > 9) return 1; /* invalid char */
1973 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1974 i = i * 10LL;
1975 if (i + j < i) return 1; /* check for addition overflow */
1976 i = i + j;
1977 }
1978 } else {
1979 /* negative number */
1980 s++;
1981 while (--len > 0) {
1982 j = (*s++) - '0';
1983 if (j > 9) return 1; /* invalid char */
1984 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1985 i = i * 10LL;
1986 if (i - j > i) return 1; /* check for subtract overflow */
1987 i = i - j;
1988 }
1989 }
1990 *ret = i;
1991 return 0;
1992}
1993
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001994/* This function is used with pat_parse_dotted_ver(). It converts a string
1995 * composed by two number separated by a dot. Each part must contain in 16 bits
1996 * because internally they will be represented as a 32-bit quantity stored in
1997 * a 64-bit integer. It returns zero when the number has successfully been
1998 * converted, non-zero otherwise. When an error is returned, the <ret> value
1999 * is left untouched.
2000 *
2001 * "1.3" -> 0x0000000000010003
2002 * "65535.65535" -> 0x00000000ffffffff
2003 */
2004int strl2llrc_dotted(const char *text, int len, long long *ret)
2005{
2006 const char *end = &text[len];
2007 const char *p;
2008 long long major, minor;
2009
2010 /* Look for dot. */
2011 for (p = text; p < end; p++)
2012 if (*p == '.')
2013 break;
2014
2015 /* Convert major. */
2016 if (strl2llrc(text, p - text, &major) != 0)
2017 return 1;
2018
2019 /* Check major. */
2020 if (major >= 65536)
2021 return 1;
2022
2023 /* Convert minor. */
2024 minor = 0;
2025 if (p < end)
2026 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2027 return 1;
2028
2029 /* Check minor. */
2030 if (minor >= 65536)
2031 return 1;
2032
2033 /* Compose value. */
2034 *ret = (major << 16) | (minor & 0xffff);
2035 return 0;
2036}
2037
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002038/* This function parses a time value optionally followed by a unit suffix among
2039 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2040 * expected by the caller. The computation does its best to avoid overflows.
2041 * The value is returned in <ret> if everything is fine, and a NULL is returned
2042 * by the function. In case of error, a pointer to the error is returned and
2043 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002044 * Values resulting in values larger than or equal to 2^31 after conversion are
2045 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2046 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002047 */
2048const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2049{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002050 unsigned long long imult, idiv;
2051 unsigned long long omult, odiv;
2052 unsigned long long value, result;
Christopher Faulet582baa52020-12-11 09:23:07 +01002053 const char *str = text;
2054
2055 if (!isdigit((unsigned char)*text))
2056 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002057
2058 omult = odiv = 1;
2059
2060 switch (unit_flags & TIME_UNIT_MASK) {
2061 case TIME_UNIT_US: omult = 1000000; break;
2062 case TIME_UNIT_MS: omult = 1000; break;
2063 case TIME_UNIT_S: break;
2064 case TIME_UNIT_MIN: odiv = 60; break;
2065 case TIME_UNIT_HOUR: odiv = 3600; break;
2066 case TIME_UNIT_DAY: odiv = 86400; break;
2067 default: break;
2068 }
2069
2070 value = 0;
2071
2072 while (1) {
2073 unsigned int j;
2074
2075 j = *text - '0';
2076 if (j > 9)
2077 break;
2078 text++;
2079 value *= 10;
2080 value += j;
2081 }
2082
2083 imult = idiv = 1;
2084 switch (*text) {
2085 case '\0': /* no unit = default unit */
2086 imult = omult = idiv = odiv = 1;
Christopher Faulet582baa52020-12-11 09:23:07 +01002087 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002088 case 's': /* second = unscaled unit */
2089 break;
2090 case 'u': /* microsecond : "us" */
2091 if (text[1] == 's') {
2092 idiv = 1000000;
2093 text++;
2094 }
Christopher Faulet582baa52020-12-11 09:23:07 +01002095 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002096 case 'm': /* millisecond : "ms" or minute: "m" */
2097 if (text[1] == 's') {
2098 idiv = 1000;
2099 text++;
2100 } else
2101 imult = 60;
2102 break;
2103 case 'h': /* hour : "h" */
2104 imult = 3600;
2105 break;
2106 case 'd': /* day : "d" */
2107 imult = 86400;
2108 break;
2109 default:
2110 return text;
2111 break;
2112 }
Christopher Faulet582baa52020-12-11 09:23:07 +01002113 if (*(++text) != '\0') {
2114 ha_warning("unexpected character '%c' after the timer value '%s', only "
2115 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2116 " This will be reported as an error in next versions.\n", *text, str);
2117 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002118
Christopher Faulet582baa52020-12-11 09:23:07 +01002119 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002120 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2121 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2122 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2123 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2124
Willy Tarreau9faebe32019-06-07 19:00:37 +02002125 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2126 if (result >= 0x80000000)
2127 return PARSE_TIME_OVER;
2128 if (!result && value)
2129 return PARSE_TIME_UNDER;
2130 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002131 return NULL;
2132}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002133
Emeric Brun39132b22010-01-04 14:57:24 +01002134/* this function converts the string starting at <text> to an unsigned int
2135 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002136 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002137 */
2138const char *parse_size_err(const char *text, unsigned *ret) {
2139 unsigned value = 0;
2140
Christopher Fauletef83dd62020-12-11 09:30:45 +01002141 if (!isdigit((unsigned char)*text))
2142 return text;
2143
Emeric Brun39132b22010-01-04 14:57:24 +01002144 while (1) {
2145 unsigned int j;
2146
2147 j = *text - '0';
2148 if (j > 9)
2149 break;
2150 if (value > ~0U / 10)
2151 return text;
2152 value *= 10;
2153 if (value > (value + j))
2154 return text;
2155 value += j;
2156 text++;
2157 }
2158
2159 switch (*text) {
2160 case '\0':
2161 break;
2162 case 'K':
2163 case 'k':
2164 if (value > ~0U >> 10)
2165 return text;
2166 value = value << 10;
2167 break;
2168 case 'M':
2169 case 'm':
2170 if (value > ~0U >> 20)
2171 return text;
2172 value = value << 20;
2173 break;
2174 case 'G':
2175 case 'g':
2176 if (value > ~0U >> 30)
2177 return text;
2178 value = value << 30;
2179 break;
2180 default:
2181 return text;
2182 }
2183
Godbach58048a22015-01-28 17:36:16 +08002184 if (*text != '\0' && *++text != '\0')
2185 return text;
2186
Emeric Brun39132b22010-01-04 14:57:24 +01002187 *ret = value;
2188 return NULL;
2189}
2190
Willy Tarreau126d4062013-12-03 17:50:47 +01002191/*
2192 * Parse binary string written in hexadecimal (source) and store the decoded
2193 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2194 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002195 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002196 */
2197int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2198{
2199 int len;
2200 const char *p = source;
2201 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002202 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002203
2204 len = strlen(source);
2205 if (len % 2) {
2206 memprintf(err, "an even number of hex digit is expected");
2207 return 0;
2208 }
2209
2210 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002211
Willy Tarreau126d4062013-12-03 17:50:47 +01002212 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002213 *binstr = calloc(len, sizeof(char));
2214 if (!*binstr) {
2215 memprintf(err, "out of memory while loading string pattern");
2216 return 0;
2217 }
2218 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002219 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002220 else {
2221 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002222 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002223 len, *binstrlen);
2224 return 0;
2225 }
2226 alloc = 0;
2227 }
2228 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002229
2230 i = j = 0;
2231 while (j < len) {
2232 if (!ishex(p[i++]))
2233 goto bad_input;
2234 if (!ishex(p[i++]))
2235 goto bad_input;
2236 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2237 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002238 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002239
2240bad_input:
2241 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002242 if (alloc) {
2243 free(*binstr);
2244 *binstr = NULL;
2245 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002246 return 0;
2247}
2248
Willy Tarreau946ba592009-05-10 15:41:18 +02002249/* copies at most <n> characters from <src> and always terminates with '\0' */
2250char *my_strndup(const char *src, int n)
2251{
2252 int len = 0;
2253 char *ret;
2254
2255 while (len < n && src[len])
2256 len++;
2257
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002258 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002259 if (!ret)
2260 return ret;
2261 memcpy(ret, src, len);
2262 ret[len] = '\0';
2263 return ret;
2264}
2265
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002266/*
2267 * search needle in haystack
2268 * returns the pointer if found, returns NULL otherwise
2269 */
2270const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2271{
2272 const void *c = NULL;
2273 unsigned char f;
2274
2275 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2276 return NULL;
2277
2278 f = *(char *)needle;
2279 c = haystack;
2280 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2281 if ((haystacklen - (c - haystack)) < needlelen)
2282 return NULL;
2283
2284 if (memcmp(c, needle, needlelen) == 0)
2285 return c;
2286 ++c;
2287 }
2288 return NULL;
2289}
2290
Willy Tarreau482b00d2009-10-04 22:48:42 +02002291/* This function returns the first unused key greater than or equal to <key> in
2292 * ID tree <root>. Zero is returned if no place is found.
2293 */
2294unsigned int get_next_id(struct eb_root *root, unsigned int key)
2295{
2296 struct eb32_node *used;
2297
2298 do {
2299 used = eb32_lookup_ge(root, key);
2300 if (!used || used->key > key)
2301 return key; /* key is available */
2302 key++;
2303 } while (key);
2304 return key;
2305}
2306
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002307/* dump the full tree to <file> in DOT format for debugging purposes. Will
2308 * optionally highlight node <subj> if found, depending on operation <op> :
2309 * 0 : nothing
2310 * >0 : insertion, node/leaf are surrounded in red
2311 * <0 : removal, node/leaf are dashed with no background
2312 * Will optionally add "desc" as a label on the graph if set and non-null.
2313 */
2314void 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 +01002315{
2316 struct eb32sc_node *node;
2317 unsigned long scope = -1;
2318
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002319 fprintf(file, "digraph ebtree {\n");
2320
2321 if (desc && *desc) {
2322 fprintf(file,
2323 " fontname=\"fixed\";\n"
2324 " fontsize=8;\n"
2325 " label=\"%s\";\n", desc);
2326 }
2327
Willy Tarreaued3cda02017-11-15 15:04:05 +01002328 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002329 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2330 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002331 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2332 );
2333
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002334 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002335 (long)eb_root_to_node(root),
2336 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002337 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2338
2339 node = eb32sc_first(root, scope);
2340 while (node) {
2341 if (node->node.node_p) {
2342 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002343 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2344 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2345 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002346
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002347 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002348 (long)node,
2349 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002350 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002351
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002352 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002353 (long)node,
2354 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002355 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2356
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002357 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002358 (long)node,
2359 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002360 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2361 }
2362
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002363 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2364 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2365 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002366
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002367 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002368 (long)node,
2369 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002370 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002371 node = eb32sc_next(node, scope);
2372 }
2373 fprintf(file, "}\n");
2374}
2375
Willy Tarreau348238b2010-01-18 15:05:57 +01002376/* This function compares a sample word possibly followed by blanks to another
2377 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2378 * otherwise zero. This intends to be used when checking HTTP headers for some
2379 * values. Note that it validates a word followed only by blanks but does not
2380 * validate a word followed by blanks then other chars.
2381 */
2382int word_match(const char *sample, int slen, const char *word, int wlen)
2383{
2384 if (slen < wlen)
2385 return 0;
2386
2387 while (wlen) {
2388 char c = *sample ^ *word;
2389 if (c && c != ('A' ^ 'a'))
2390 return 0;
2391 sample++;
2392 word++;
2393 slen--;
2394 wlen--;
2395 }
2396
2397 while (slen) {
2398 if (*sample != ' ' && *sample != '\t')
2399 return 0;
2400 sample++;
2401 slen--;
2402 }
2403 return 1;
2404}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002405
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002406/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2407 * is particularly fast because it avoids expensive operations such as
2408 * multiplies, which are optimized away at the end. It requires a properly
2409 * formated address though (3 points).
2410 */
2411unsigned int inetaddr_host(const char *text)
2412{
2413 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2414 register unsigned int dig100, dig10, dig1;
2415 int s;
2416 const char *p, *d;
2417
2418 dig1 = dig10 = dig100 = ascii_zero;
2419 s = 24;
2420
2421 p = text;
2422 while (1) {
2423 if (((unsigned)(*p - '0')) <= 9) {
2424 p++;
2425 continue;
2426 }
2427
2428 /* here, we have a complete byte between <text> and <p> (exclusive) */
2429 if (p == text)
2430 goto end;
2431
2432 d = p - 1;
2433 dig1 |= (unsigned int)(*d << s);
2434 if (d == text)
2435 goto end;
2436
2437 d--;
2438 dig10 |= (unsigned int)(*d << s);
2439 if (d == text)
2440 goto end;
2441
2442 d--;
2443 dig100 |= (unsigned int)(*d << s);
2444 end:
2445 if (!s || *p != '.')
2446 break;
2447
2448 s -= 8;
2449 text = ++p;
2450 }
2451
2452 dig100 -= ascii_zero;
2453 dig10 -= ascii_zero;
2454 dig1 -= ascii_zero;
2455 return ((dig100 * 10) + dig10) * 10 + dig1;
2456}
2457
2458/*
2459 * Idem except the first unparsed character has to be passed in <stop>.
2460 */
2461unsigned int inetaddr_host_lim(const char *text, const char *stop)
2462{
2463 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2464 register unsigned int dig100, dig10, dig1;
2465 int s;
2466 const char *p, *d;
2467
2468 dig1 = dig10 = dig100 = ascii_zero;
2469 s = 24;
2470
2471 p = text;
2472 while (1) {
2473 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2474 p++;
2475 continue;
2476 }
2477
2478 /* here, we have a complete byte between <text> and <p> (exclusive) */
2479 if (p == text)
2480 goto end;
2481
2482 d = p - 1;
2483 dig1 |= (unsigned int)(*d << s);
2484 if (d == text)
2485 goto end;
2486
2487 d--;
2488 dig10 |= (unsigned int)(*d << s);
2489 if (d == text)
2490 goto end;
2491
2492 d--;
2493 dig100 |= (unsigned int)(*d << s);
2494 end:
2495 if (!s || p == stop || *p != '.')
2496 break;
2497
2498 s -= 8;
2499 text = ++p;
2500 }
2501
2502 dig100 -= ascii_zero;
2503 dig10 -= ascii_zero;
2504 dig1 -= ascii_zero;
2505 return ((dig100 * 10) + dig10) * 10 + dig1;
2506}
2507
2508/*
2509 * Idem except the pointer to first unparsed byte is returned into <ret> which
2510 * must not be NULL.
2511 */
Willy Tarreau74172752010-10-15 23:21:42 +02002512unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002513{
2514 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2515 register unsigned int dig100, dig10, dig1;
2516 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002517 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002518
2519 dig1 = dig10 = dig100 = ascii_zero;
2520 s = 24;
2521
2522 p = text;
2523 while (1) {
2524 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2525 p++;
2526 continue;
2527 }
2528
2529 /* here, we have a complete byte between <text> and <p> (exclusive) */
2530 if (p == text)
2531 goto end;
2532
2533 d = p - 1;
2534 dig1 |= (unsigned int)(*d << s);
2535 if (d == text)
2536 goto end;
2537
2538 d--;
2539 dig10 |= (unsigned int)(*d << s);
2540 if (d == text)
2541 goto end;
2542
2543 d--;
2544 dig100 |= (unsigned int)(*d << s);
2545 end:
2546 if (!s || p == stop || *p != '.')
2547 break;
2548
2549 s -= 8;
2550 text = ++p;
2551 }
2552
2553 *ret = p;
2554 dig100 -= ascii_zero;
2555 dig10 -= ascii_zero;
2556 dig1 -= ascii_zero;
2557 return ((dig100 * 10) + dig10) * 10 + dig1;
2558}
2559
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002560/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2561 * or the number of chars read in case of success. Maybe this could be replaced
2562 * by one of the functions above. Also, apparently this function does not support
2563 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002564 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002565 */
2566int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2567{
2568 const char *addr;
2569 int saw_digit, octets, ch;
2570 u_char tmp[4], *tp;
2571 const char *cp = buf;
2572
2573 saw_digit = 0;
2574 octets = 0;
2575 *(tp = tmp) = 0;
2576
2577 for (addr = buf; addr - buf < len; addr++) {
2578 unsigned char digit = (ch = *addr) - '0';
2579
2580 if (digit > 9 && ch != '.')
2581 break;
2582
2583 if (digit <= 9) {
2584 u_int new = *tp * 10 + digit;
2585
2586 if (new > 255)
2587 return 0;
2588
2589 *tp = new;
2590
2591 if (!saw_digit) {
2592 if (++octets > 4)
2593 return 0;
2594 saw_digit = 1;
2595 }
2596 } else if (ch == '.' && saw_digit) {
2597 if (octets == 4)
2598 return 0;
2599
2600 *++tp = 0;
2601 saw_digit = 0;
2602 } else
2603 return 0;
2604 }
2605
2606 if (octets < 4)
2607 return 0;
2608
2609 memcpy(&dst->s_addr, tmp, 4);
2610 return addr - cp;
2611}
2612
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002613/* This function converts the string in <buf> of the len <len> to
2614 * struct in6_addr <dst> which must be allocated by the caller.
2615 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002616 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002617 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002618int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2619{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002620 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002621 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002622
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002623 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002624 return 0;
2625
2626 memcpy(null_term_ip6, buf, len);
2627 null_term_ip6[len] = '\0';
2628
Willy Tarreau075415a2013-12-12 11:29:39 +01002629 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002630 return 0;
2631
Willy Tarreau075415a2013-12-12 11:29:39 +01002632 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002633 return 1;
2634}
2635
Willy Tarreauacf95772010-06-14 19:09:21 +02002636/* To be used to quote config arg positions. Returns the short string at <ptr>
2637 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2638 * if ptr is NULL or empty. The string is locally allocated.
2639 */
2640const char *quote_arg(const char *ptr)
2641{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002642 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002643 int i;
2644
2645 if (!ptr || !*ptr)
2646 return "end of line";
2647 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002648 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002649 val[i] = *ptr++;
2650 val[i++] = '\'';
2651 val[i] = '\0';
2652 return val;
2653}
2654
Willy Tarreau5b180202010-07-18 10:40:48 +02002655/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2656int get_std_op(const char *str)
2657{
2658 int ret = -1;
2659
2660 if (*str == 'e' && str[1] == 'q')
2661 ret = STD_OP_EQ;
2662 else if (*str == 'n' && str[1] == 'e')
2663 ret = STD_OP_NE;
2664 else if (*str == 'l') {
2665 if (str[1] == 'e') ret = STD_OP_LE;
2666 else if (str[1] == 't') ret = STD_OP_LT;
2667 }
2668 else if (*str == 'g') {
2669 if (str[1] == 'e') ret = STD_OP_GE;
2670 else if (str[1] == 't') ret = STD_OP_GT;
2671 }
2672
2673 if (ret == -1 || str[2] != '\0')
2674 return -1;
2675 return ret;
2676}
2677
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002678/* hash a 32-bit integer to another 32-bit integer */
2679unsigned int full_hash(unsigned int a)
2680{
2681 return __full_hash(a);
2682}
2683
Willy Tarreauf3241112019-02-26 09:56:22 +01002684/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2685 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2686 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2687 * a popcount variant and is described here :
2688 * https://graphics.stanford.edu/~seander/bithacks.html
2689 */
2690unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2691{
2692 unsigned long a, b, c, d;
2693 unsigned int s;
2694 unsigned int t;
2695
2696 a = m - ((m >> 1) & ~0UL/3);
2697 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2698 c = (b + (b >> 4)) & ~0UL/0x11;
2699 d = (c + (c >> 8)) & ~0UL/0x101;
2700
2701 r++; // make r be 1..64
2702
2703 t = 0;
2704 s = LONGBITS;
2705 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002706 unsigned long d2 = (d >> 16) >> 16;
2707 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002708 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2709 }
2710
2711 t = (d >> (s - 16)) & 0xff;
2712 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2713 t = (c >> (s - 8)) & 0xf;
2714 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2715 t = (b >> (s - 4)) & 0x7;
2716 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2717 t = (a >> (s - 2)) & 0x3;
2718 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2719 t = (m >> (s - 1)) & 0x1;
2720 s -= ((t - r) & 256) >> 8;
2721
2722 return s - 1;
2723}
2724
2725/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2726 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2727 * using mask_prep_rank_map() below.
2728 */
2729unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2730 unsigned long a, unsigned long b,
2731 unsigned long c, unsigned long d)
2732{
2733 unsigned int s;
2734 unsigned int t;
2735
2736 r++; // make r be 1..64
2737
2738 t = 0;
2739 s = LONGBITS;
2740 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002741 unsigned long d2 = (d >> 16) >> 16;
2742 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002743 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2744 }
2745
2746 t = (d >> (s - 16)) & 0xff;
2747 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2748 t = (c >> (s - 8)) & 0xf;
2749 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2750 t = (b >> (s - 4)) & 0x7;
2751 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2752 t = (a >> (s - 2)) & 0x3;
2753 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2754 t = (m >> (s - 1)) & 0x1;
2755 s -= ((t - r) & 256) >> 8;
2756
2757 return s - 1;
2758}
2759
2760/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2761 * above.
2762 */
2763void mask_prep_rank_map(unsigned long m,
2764 unsigned long *a, unsigned long *b,
2765 unsigned long *c, unsigned long *d)
2766{
2767 *a = m - ((m >> 1) & ~0UL/3);
2768 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2769 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2770 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2771}
2772
David du Colombier4f92d322011-03-24 11:09:31 +01002773/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002774 * otherwise zero. Note that <addr> may not necessarily be aligned
2775 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002776 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002777int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002778{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002779 struct in_addr addr_copy;
2780
2781 memcpy(&addr_copy, addr, sizeof(addr_copy));
2782 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002783}
2784
2785/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002786 * otherwise zero. Note that <addr> may not necessarily be aligned
2787 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002788 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002789int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002790{
2791 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002792 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002793
Willy Tarreaueec1d382016-07-13 11:59:39 +02002794 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002795 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002796 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002797 (((int *)net)[i] & ((int *)mask)[i]))
2798 return 0;
2799 return 1;
2800}
2801
2802/* RFC 4291 prefix */
2803const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2804 0x00, 0x00, 0x00, 0x00,
2805 0x00, 0x00, 0xFF, 0xFF };
2806
Joseph Herlant32b83272018-11-15 11:58:28 -08002807/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002808 * Input and output may overlap.
2809 */
David du Colombier4f92d322011-03-24 11:09:31 +01002810void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2811{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002812 struct in_addr tmp_addr;
2813
2814 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002815 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002816 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002817}
2818
Joseph Herlant32b83272018-11-15 11:58:28 -08002819/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002820 * Return true if conversion is possible and false otherwise.
2821 */
2822int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2823{
2824 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2825 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2826 sizeof(struct in_addr));
2827 return 1;
2828 }
2829
2830 return 0;
2831}
2832
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002833/* compare two struct sockaddr_storage and return:
2834 * 0 (true) if the addr is the same in both
2835 * 1 (false) if the addr is not the same in both
2836 * -1 (unable) if one of the addr is not AF_INET*
2837 */
2838int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2839{
2840 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2841 return -1;
2842
2843 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2844 return -1;
2845
2846 if (ss1->ss_family != ss2->ss_family)
2847 return 1;
2848
2849 switch (ss1->ss_family) {
2850 case AF_INET:
2851 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2852 &((struct sockaddr_in *)ss2)->sin_addr,
2853 sizeof(struct in_addr)) != 0;
2854 case AF_INET6:
2855 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2856 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2857 sizeof(struct in6_addr)) != 0;
2858 }
2859
2860 return 1;
2861}
2862
Baptiste Assmann08396c82016-01-31 00:27:17 +01002863/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002864 * The caller must allocate and clear <dest> before calling.
2865 * The source must be in either AF_INET or AF_INET6 family, or the destination
2866 * address will be undefined. If the destination address used to hold a port,
2867 * it is preserved, so that this function can be used to switch to another
2868 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002869 */
2870struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2871{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002872 int prev_port;
2873
2874 prev_port = get_net_port(dest);
2875 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002876 dest->ss_family = source->ss_family;
2877
2878 /* copy new addr and apply it */
2879 switch (source->ss_family) {
2880 case AF_INET:
2881 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002882 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002883 break;
2884 case AF_INET6:
2885 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 +01002886 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002887 break;
2888 }
2889
2890 return dest;
2891}
2892
William Lallemand421f5b52012-02-06 18:15:57 +01002893char *human_time(int t, short hz_div) {
2894 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2895 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002896 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002897 int cnt=2; // print two numbers
2898
2899 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002900 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002901 return rv;
2902 }
2903
2904 if (unlikely(hz_div > 1))
2905 t /= hz_div;
2906
2907 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002908 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002909 cnt--;
2910 }
2911
2912 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002913 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002914 cnt--;
2915 }
2916
2917 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002918 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002919 cnt--;
2920 }
2921
2922 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002923 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002924
2925 return rv;
2926}
2927
2928const char *monthname[12] = {
2929 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2930 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2931};
2932
2933/* date2str_log: write a date in the format :
2934 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2935 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2936 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2937 *
2938 * without using sprintf. return a pointer to the last char written (\0) or
2939 * NULL if there isn't enough space.
2940 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002941char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002942{
2943
2944 if (size < 25) /* the size is fixed: 24 chars + \0 */
2945 return NULL;
2946
2947 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002948 if (!dst)
2949 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002950 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002951
William Lallemand421f5b52012-02-06 18:15:57 +01002952 memcpy(dst, monthname[tm->tm_mon], 3); // month
2953 dst += 3;
2954 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002955
William Lallemand421f5b52012-02-06 18:15:57 +01002956 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002957 if (!dst)
2958 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002959 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002960
William Lallemand421f5b52012-02-06 18:15:57 +01002961 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002962 if (!dst)
2963 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002964 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002965
William Lallemand421f5b52012-02-06 18:15:57 +01002966 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002967 if (!dst)
2968 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002969 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002970
William Lallemand421f5b52012-02-06 18:15:57 +01002971 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002972 if (!dst)
2973 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002974 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002975
William Lallemand421f5b52012-02-06 18:15:57 +01002976 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002977 if (!dst)
2978 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002979 dst += 3; // only the 3 first digits
2980 *dst = '\0';
2981
2982 return dst;
2983}
2984
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002985/* Base year used to compute leap years */
2986#define TM_YEAR_BASE 1900
2987
2988/* Return the difference in seconds between two times (leap seconds are ignored).
2989 * Retrieved from glibc 2.18 source code.
2990 */
2991static int my_tm_diff(const struct tm *a, const struct tm *b)
2992{
2993 /* Compute intervening leap days correctly even if year is negative.
2994 * Take care to avoid int overflow in leap day calculations,
2995 * but it's OK to assume that A and B are close to each other.
2996 */
2997 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2998 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2999 int a100 = a4 / 25 - (a4 % 25 < 0);
3000 int b100 = b4 / 25 - (b4 % 25 < 0);
3001 int a400 = a100 >> 2;
3002 int b400 = b100 >> 2;
3003 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3004 int years = a->tm_year - b->tm_year;
3005 int days = (365 * years + intervening_leap_days
3006 + (a->tm_yday - b->tm_yday));
3007 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3008 + (a->tm_min - b->tm_min))
3009 + (a->tm_sec - b->tm_sec));
3010}
3011
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003012/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003013 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003014 * The string returned has the same format as returned by strftime(... "%z", tm).
3015 * Offsets are kept in an internal cache for better performances.
3016 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003017const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003018{
3019 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003020 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003021
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003022 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003023 struct tm tm_gmt;
3024 int diff;
3025 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003026
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003027 /* Pretend DST not active if its status is unknown */
3028 if (isdst < 0)
3029 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003030
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003031 /* Fetch the offset and initialize it if needed */
3032 gmt_offset = gmt_offsets[isdst & 0x01];
3033 if (unlikely(!*gmt_offset)) {
3034 get_gmtime(t, &tm_gmt);
3035 diff = my_tm_diff(tm, &tm_gmt);
3036 if (diff < 0) {
3037 diff = -diff;
3038 *gmt_offset = '-';
3039 } else {
3040 *gmt_offset = '+';
3041 }
Willy Tarreaubf5eeb62019-10-29 10:16:11 +01003042 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003043 diff /= 60; /* Convert to minutes */
3044 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3045 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003046
Willy Tarreaubf5eeb62019-10-29 10:16:11 +01003047 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003048}
3049
William Lallemand421f5b52012-02-06 18:15:57 +01003050/* gmt2str_log: write a date in the format :
3051 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3052 * return a pointer to the last char written (\0) or
3053 * NULL if there isn't enough space.
3054 */
3055char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3056{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003057 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003058 return NULL;
3059
3060 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003061 if (!dst)
3062 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003063 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003064
William Lallemand421f5b52012-02-06 18:15:57 +01003065 memcpy(dst, monthname[tm->tm_mon], 3); // month
3066 dst += 3;
3067 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003068
William Lallemand421f5b52012-02-06 18:15:57 +01003069 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003070 if (!dst)
3071 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003072 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003073
William Lallemand421f5b52012-02-06 18:15:57 +01003074 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003075 if (!dst)
3076 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003077 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003078
William Lallemand421f5b52012-02-06 18:15:57 +01003079 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003080 if (!dst)
3081 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003082 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003083
William Lallemand421f5b52012-02-06 18:15:57 +01003084 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003085 if (!dst)
3086 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003087 *dst++ = ' ';
3088 *dst++ = '+';
3089 *dst++ = '0';
3090 *dst++ = '0';
3091 *dst++ = '0';
3092 *dst++ = '0';
3093 *dst = '\0';
3094
3095 return dst;
3096}
3097
Yuxans Yao4e25b012012-10-19 10:36:09 +08003098/* localdate2str_log: write a date in the format :
3099 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003100 * Both t and tm must represent the same time.
3101 * return a pointer to the last char written (\0) or
3102 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003103 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003104char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003105{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003106 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003107 if (size < 27) /* the size is fixed: 26 chars + \0 */
3108 return NULL;
3109
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003110 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003111
Yuxans Yao4e25b012012-10-19 10:36:09 +08003112 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003113 if (!dst)
3114 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003115 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003116
Yuxans Yao4e25b012012-10-19 10:36:09 +08003117 memcpy(dst, monthname[tm->tm_mon], 3); // month
3118 dst += 3;
3119 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003120
Yuxans Yao4e25b012012-10-19 10:36:09 +08003121 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003122 if (!dst)
3123 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003124 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003125
Yuxans Yao4e25b012012-10-19 10:36:09 +08003126 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003127 if (!dst)
3128 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003129 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003130
Yuxans Yao4e25b012012-10-19 10:36:09 +08003131 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003132 if (!dst)
3133 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003134 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003135
Yuxans Yao4e25b012012-10-19 10:36:09 +08003136 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003137 if (!dst)
3138 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003139 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003140
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003141 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003142 dst += 5;
3143 *dst = '\0';
3144
3145 return dst;
3146}
3147
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003148/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3149 * It is meant as a portable replacement for timegm() for use with valid inputs.
3150 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3151 */
3152time_t my_timegm(const struct tm *tm)
3153{
3154 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3155 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3156 * sum of the extra N days for elapsed months. The sum of all these N
3157 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3158 * in a 5-bit word. This means that with 60 bits we can represent a
3159 * matrix of all these values at once, which is fast and efficient to
3160 * access. The extra February day for leap years is not counted here.
3161 *
3162 * Jan : none = 0 (0)
3163 * Feb : Jan = 3 (3)
3164 * Mar : Jan..Feb = 3 (3 + 0)
3165 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3166 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3167 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3168 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3169 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3170 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3171 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3172 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3173 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3174 */
3175 uint64_t extra =
3176 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3177 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3178 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3179 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3180
3181 unsigned int y = tm->tm_year + 1900;
3182 unsigned int m = tm->tm_mon;
3183 unsigned long days = 0;
3184
3185 /* days since 1/1/1970 for full years */
3186 days += days_since_zero(y) - days_since_zero(1970);
3187
3188 /* days for full months in the current year */
3189 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3190
3191 /* count + 1 after March for leap years. A leap year is a year multiple
3192 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3193 * is leap, 1900 isn't, 1904 is.
3194 */
3195 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3196 days++;
3197
3198 days += tm->tm_mday - 1;
3199 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3200}
3201
Thierry Fournier93127942016-01-20 18:49:45 +01003202/* This function check a char. It returns true and updates
3203 * <date> and <len> pointer to the new position if the
3204 * character is found.
3205 */
3206static inline int parse_expect_char(const char **date, int *len, char c)
3207{
3208 if (*len < 1 || **date != c)
3209 return 0;
3210 (*len)--;
3211 (*date)++;
3212 return 1;
3213}
3214
3215/* This function expects a string <str> of len <l>. It return true and updates.
3216 * <date> and <len> if the string matches, otherwise, it returns false.
3217 */
3218static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3219{
3220 if (*len < l || strncmp(*date, str, l) != 0)
3221 return 0;
3222 (*len) -= l;
3223 (*date) += l;
3224 return 1;
3225}
3226
3227/* This macro converts 3 chars name in integer. */
3228#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3229
3230/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3231 * / %x54.75.65 ; "Tue", case-sensitive
3232 * / %x57.65.64 ; "Wed", case-sensitive
3233 * / %x54.68.75 ; "Thu", case-sensitive
3234 * / %x46.72.69 ; "Fri", case-sensitive
3235 * / %x53.61.74 ; "Sat", case-sensitive
3236 * / %x53.75.6E ; "Sun", case-sensitive
3237 *
3238 * This array must be alphabetically sorted
3239 */
3240static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3241{
3242 if (*len < 3)
3243 return 0;
3244 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3245 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3246 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3247 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3248 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3249 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3250 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3251 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3252 default: return 0;
3253 }
3254 *len -= 3;
3255 *date += 3;
3256 return 1;
3257}
3258
3259/* month = %x4A.61.6E ; "Jan", case-sensitive
3260 * / %x46.65.62 ; "Feb", case-sensitive
3261 * / %x4D.61.72 ; "Mar", case-sensitive
3262 * / %x41.70.72 ; "Apr", case-sensitive
3263 * / %x4D.61.79 ; "May", case-sensitive
3264 * / %x4A.75.6E ; "Jun", case-sensitive
3265 * / %x4A.75.6C ; "Jul", case-sensitive
3266 * / %x41.75.67 ; "Aug", case-sensitive
3267 * / %x53.65.70 ; "Sep", case-sensitive
3268 * / %x4F.63.74 ; "Oct", case-sensitive
3269 * / %x4E.6F.76 ; "Nov", case-sensitive
3270 * / %x44.65.63 ; "Dec", case-sensitive
3271 *
3272 * This array must be alphabetically sorted
3273 */
3274static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3275{
3276 if (*len < 3)
3277 return 0;
3278 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3279 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3280 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3281 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3282 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3283 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3284 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3285 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3286 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3287 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3288 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3289 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3290 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3291 default: return 0;
3292 }
3293 *len -= 3;
3294 *date += 3;
3295 return 1;
3296}
3297
3298/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3299 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3300 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3301 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3302 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3303 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3304 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3305 *
3306 * This array must be alphabetically sorted
3307 */
3308static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3309{
3310 if (*len < 6) /* Minimum length. */
3311 return 0;
3312 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3313 case STR2I3('M','o','n'):
3314 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3315 tm->tm_wday = 1;
3316 return 1;
3317 case STR2I3('T','u','e'):
3318 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3319 tm->tm_wday = 2;
3320 return 1;
3321 case STR2I3('W','e','d'):
3322 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3323 tm->tm_wday = 3;
3324 return 1;
3325 case STR2I3('T','h','u'):
3326 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3327 tm->tm_wday = 4;
3328 return 1;
3329 case STR2I3('F','r','i'):
3330 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3331 tm->tm_wday = 5;
3332 return 1;
3333 case STR2I3('S','a','t'):
3334 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3335 tm->tm_wday = 6;
3336 return 1;
3337 case STR2I3('S','u','n'):
3338 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3339 tm->tm_wday = 7;
3340 return 1;
3341 }
3342 return 0;
3343}
3344
3345/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3346static inline int parse_digit(const char **date, int *len, int *digit)
3347{
3348 if (*len < 1 || **date < '0' || **date > '9')
3349 return 0;
3350 *digit = (**date - '0');
3351 (*date)++;
3352 (*len)--;
3353 return 1;
3354}
3355
3356/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3357static inline int parse_2digit(const char **date, int *len, int *digit)
3358{
3359 int value;
3360
3361 RET0_UNLESS(parse_digit(date, len, &value));
3362 (*digit) = value * 10;
3363 RET0_UNLESS(parse_digit(date, len, &value));
3364 (*digit) += value;
3365
3366 return 1;
3367}
3368
3369/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3370static inline int parse_4digit(const char **date, int *len, int *digit)
3371{
3372 int value;
3373
3374 RET0_UNLESS(parse_digit(date, len, &value));
3375 (*digit) = value * 1000;
3376
3377 RET0_UNLESS(parse_digit(date, len, &value));
3378 (*digit) += value * 100;
3379
3380 RET0_UNLESS(parse_digit(date, len, &value));
3381 (*digit) += value * 10;
3382
3383 RET0_UNLESS(parse_digit(date, len, &value));
3384 (*digit) += value;
3385
3386 return 1;
3387}
3388
3389/* time-of-day = hour ":" minute ":" second
3390 * ; 00:00:00 - 23:59:60 (leap second)
3391 *
3392 * hour = 2DIGIT
3393 * minute = 2DIGIT
3394 * second = 2DIGIT
3395 */
3396static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3397{
3398 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3399 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3400 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3401 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3402 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3403 return 1;
3404}
3405
3406/* From RFC7231
3407 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3408 *
3409 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3410 * ; fixed length/zone/capitalization subset of the format
3411 * ; see Section 3.3 of [RFC5322]
3412 *
3413 *
3414 * date1 = day SP month SP year
3415 * ; e.g., 02 Jun 1982
3416 *
3417 * day = 2DIGIT
3418 * year = 4DIGIT
3419 *
3420 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3421 *
3422 * time-of-day = hour ":" minute ":" second
3423 * ; 00:00:00 - 23:59:60 (leap second)
3424 *
3425 * hour = 2DIGIT
3426 * minute = 2DIGIT
3427 * second = 2DIGIT
3428 *
3429 * DIGIT = decimal 0-9
3430 */
3431int parse_imf_date(const char *date, int len, struct tm *tm)
3432{
David Carlier327298c2016-11-20 10:42:38 +00003433 /* tm_gmtoff, if present, ought to be zero'ed */
3434 memset(tm, 0, sizeof(*tm));
3435
Thierry Fournier93127942016-01-20 18:49:45 +01003436 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3437 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3438 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3439 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3440 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3441 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3442 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3443 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3444 tm->tm_year -= 1900;
3445 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3446 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3447 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3448 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3449 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003450 return 1;
3451}
3452
3453/* From RFC7231
3454 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3455 *
3456 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3457 * date2 = day "-" month "-" 2DIGIT
3458 * ; e.g., 02-Jun-82
3459 *
3460 * day = 2DIGIT
3461 */
3462int parse_rfc850_date(const char *date, int len, struct tm *tm)
3463{
3464 int year;
3465
David Carlier327298c2016-11-20 10:42:38 +00003466 /* tm_gmtoff, if present, ought to be zero'ed */
3467 memset(tm, 0, sizeof(*tm));
3468
Thierry Fournier93127942016-01-20 18:49:45 +01003469 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3470 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3471 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3472 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3473 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3474 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3475 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3476
3477 /* year = 2DIGIT
3478 *
3479 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3480 * two-digit year, MUST interpret a timestamp that appears to be more
3481 * than 50 years in the future as representing the most recent year in
3482 * the past that had the same last two digits.
3483 */
3484 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3485
3486 /* expect SP */
3487 if (!parse_expect_char(&date, &len, ' ')) {
3488 /* Maybe we have the date with 4 digits. */
3489 RET0_UNLESS(parse_2digit(&date, &len, &year));
3490 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3491 /* expect SP */
3492 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3493 } else {
3494 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3495 * tm_year is the number of year since 1900, so for +1900, we
3496 * do nothing, and for +2000, we add 100.
3497 */
3498 if (tm->tm_year <= 60)
3499 tm->tm_year += 100;
3500 }
3501
3502 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3503 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3504 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3505 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003506
3507 return 1;
3508}
3509
3510/* From RFC7231
3511 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3512 *
3513 * asctime-date = day-name SP date3 SP time-of-day SP year
3514 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3515 * ; e.g., Jun 2
3516 *
3517 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3518 * whitespace in an HTTP-date beyond that specifically included as SP in
3519 * the grammar.
3520 */
3521int parse_asctime_date(const char *date, int len, struct tm *tm)
3522{
David Carlier327298c2016-11-20 10:42:38 +00003523 /* tm_gmtoff, if present, ought to be zero'ed */
3524 memset(tm, 0, sizeof(*tm));
3525
Thierry Fournier93127942016-01-20 18:49:45 +01003526 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3527 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3528 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3529 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3530
3531 /* expect SP and 1DIGIT or 2DIGIT */
3532 if (parse_expect_char(&date, &len, ' '))
3533 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3534 else
3535 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3536
3537 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3538 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3539 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3540 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3541 tm->tm_year -= 1900;
3542 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003543 return 1;
3544}
3545
3546/* From RFC7231
3547 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3548 *
3549 * HTTP-date = IMF-fixdate / obs-date
3550 * obs-date = rfc850-date / asctime-date
3551 *
3552 * parses an HTTP date in the RFC format and is accepted
3553 * alternatives. <date> is the strinf containing the date,
3554 * len is the len of the string. <tm> is filled with the
3555 * parsed time. We must considers this time as GMT.
3556 */
3557int parse_http_date(const char *date, int len, struct tm *tm)
3558{
3559 if (parse_imf_date(date, len, tm))
3560 return 1;
3561
3562 if (parse_rfc850_date(date, len, tm))
3563 return 1;
3564
3565 if (parse_asctime_date(date, len, tm))
3566 return 1;
3567
3568 return 0;
3569}
3570
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003571/* Dynamically allocates a string of the proper length to hold the formatted
3572 * output. NULL is returned on error. The caller is responsible for freeing the
3573 * memory area using free(). The resulting string is returned in <out> if the
3574 * pointer is not NULL. A previous version of <out> might be used to build the
3575 * new string, and it will be freed before returning if it is not NULL, which
3576 * makes it possible to build complex strings from iterative calls without
3577 * having to care about freeing intermediate values, as in the example below :
3578 *
3579 * memprintf(&err, "invalid argument: '%s'", arg);
3580 * ...
3581 * memprintf(&err, "parser said : <%s>\n", *err);
3582 * ...
3583 * free(*err);
3584 *
3585 * This means that <err> must be initialized to NULL before first invocation.
3586 * The return value also holds the allocated string, which eases error checking
3587 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003588 * passed instead and it will be ignored. The returned message will then also
3589 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003590 *
3591 * It is also convenient to use it without any free except the last one :
3592 * err = NULL;
3593 * if (!fct1(err)) report(*err);
3594 * if (!fct2(err)) report(*err);
3595 * if (!fct3(err)) report(*err);
3596 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003597 *
3598 * memprintf relies on memvprintf. This last version can be called from any
3599 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003600 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003601char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003602{
3603 va_list args;
3604 char *ret = NULL;
3605 int allocated = 0;
3606 int needed = 0;
3607
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003608 if (!out)
3609 return NULL;
3610
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003611 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003612 char buf1;
3613
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003614 /* vsnprintf() will return the required length even when the
3615 * target buffer is NULL. We do this in a loop just in case
3616 * intermediate evaluations get wrong.
3617 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003618 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003619 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003620 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003621 if (needed < allocated) {
3622 /* Note: on Solaris 8, the first iteration always
3623 * returns -1 if allocated is zero, so we force a
3624 * retry.
3625 */
3626 if (!allocated)
3627 needed = 0;
3628 else
3629 break;
3630 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003631
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003632 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003633 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003634 } while (ret);
3635
3636 if (needed < 0) {
3637 /* an error was encountered */
3638 free(ret);
3639 ret = NULL;
3640 }
3641
3642 if (out) {
3643 free(*out);
3644 *out = ret;
3645 }
3646
3647 return ret;
3648}
William Lallemand421f5b52012-02-06 18:15:57 +01003649
Christopher Faulet93a518f2017-10-24 11:25:33 +02003650char *memprintf(char **out, const char *format, ...)
3651{
3652 va_list args;
3653 char *ret = NULL;
3654
3655 va_start(args, format);
3656 ret = memvprintf(out, format, args);
3657 va_end(args);
3658
3659 return ret;
3660}
3661
Willy Tarreau21c705b2012-09-14 11:40:36 +02003662/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3663 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003664 * freed by the caller. It also supports being passed a NULL which results in the same
3665 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003666 * Example of use :
3667 * parse(cmd, &err); (callee: memprintf(&err, ...))
3668 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3669 * free(err);
3670 */
3671char *indent_msg(char **out, int level)
3672{
3673 char *ret, *in, *p;
3674 int needed = 0;
3675 int lf = 0;
3676 int lastlf = 0;
3677 int len;
3678
Willy Tarreau70eec382012-10-10 08:56:47 +02003679 if (!out || !*out)
3680 return NULL;
3681
Willy Tarreau21c705b2012-09-14 11:40:36 +02003682 in = *out - 1;
3683 while ((in = strchr(in + 1, '\n')) != NULL) {
3684 lastlf = in - *out;
3685 lf++;
3686 }
3687
3688 if (!lf) /* single line, no LF, return it as-is */
3689 return *out;
3690
3691 len = strlen(*out);
3692
3693 if (lf == 1 && lastlf == len - 1) {
3694 /* single line, LF at end, strip it and return as-is */
3695 (*out)[lastlf] = 0;
3696 return *out;
3697 }
3698
3699 /* OK now we have at least one LF, we need to process the whole string
3700 * as a multi-line string. What we'll do :
3701 * - prefix with an LF if there is none
3702 * - add <level> spaces before each line
3703 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3704 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3705 */
3706
3707 needed = 1 + level * (lf + 1) + len + 1;
3708 p = ret = malloc(needed);
3709 in = *out;
3710
3711 /* skip initial LFs */
3712 while (*in == '\n')
3713 in++;
3714
3715 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3716 while (*in) {
3717 *p++ = '\n';
3718 memset(p, ' ', level);
3719 p += level;
3720 do {
3721 *p++ = *in++;
3722 } while (*in && *in != '\n');
3723 if (*in)
3724 in++;
3725 }
3726 *p = 0;
3727
3728 free(*out);
3729 *out = ret;
3730
3731 return ret;
3732}
3733
Willy Tarreaufe575b52019-08-21 13:17:37 +02003734/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3735 * and end of lines replaced with <eol> if not 0. The first line to indent has
3736 * to be indicated in <first> (starts at zero), so that it is possible to skip
3737 * indenting the first line if it has to be appended after an existing message.
3738 * Empty strings are never indented, and NULL strings are considered empty both
3739 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3740 * character, non-zero otherwise.
3741 */
3742int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3743{
3744 int bol, lf;
3745 int pfxlen = pfx ? strlen(pfx) : 0;
3746
3747 if (!in)
3748 return 0;
3749
3750 bol = 1;
3751 lf = 0;
3752 while (*in) {
3753 if (bol && pfxlen) {
3754 if (first > 0)
3755 first--;
3756 else
3757 b_putblk(out, pfx, pfxlen);
3758 bol = 0;
3759 }
3760
3761 lf = (*in == '\n');
3762 bol |= lf;
3763 b_putchr(out, (lf && eol) ? eol : *in);
3764 in++;
3765 }
3766 return lf;
3767}
3768
Willy Tarreau9d22e562019-03-29 18:49:09 +01003769/* removes environment variable <name> from the environment as found in
3770 * environ. This is only provided as an alternative for systems without
3771 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
3772 * The principle is to scan environ for each occurence of variable name
3773 * <name> and to replace the matching pointers with the last pointer of
3774 * the array (since variables are not ordered).
3775 * It always returns 0 (success).
3776 */
3777int my_unsetenv(const char *name)
3778{
3779 extern char **environ;
3780 char **p = environ;
3781 int vars;
3782 int next;
3783 int len;
3784
3785 len = strlen(name);
3786 for (vars = 0; p[vars]; vars++)
3787 ;
3788 next = 0;
3789 while (next < vars) {
3790 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3791 next++;
3792 continue;
3793 }
3794 if (next < vars - 1)
3795 p[next] = p[vars - 1];
3796 p[--vars] = NULL;
3797 }
3798 return 0;
3799}
3800
Willy Tarreaudad36a32013-03-11 01:20:04 +01003801/* Convert occurrences of environment variables in the input string to their
3802 * corresponding value. A variable is identified as a series of alphanumeric
3803 * characters or underscores following a '$' sign. The <in> string must be
3804 * free()able. NULL returns NULL. The resulting string might be reallocated if
3805 * some expansion is made. Variable names may also be enclosed into braces if
3806 * needed (eg: to concatenate alphanum characters).
3807 */
3808char *env_expand(char *in)
3809{
3810 char *txt_beg;
3811 char *out;
3812 char *txt_end;
3813 char *var_beg;
3814 char *var_end;
3815 char *value;
3816 char *next;
3817 int out_len;
3818 int val_len;
3819
3820 if (!in)
3821 return in;
3822
3823 value = out = NULL;
3824 out_len = 0;
3825
3826 txt_beg = in;
3827 do {
3828 /* look for next '$' sign in <in> */
3829 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3830
3831 if (!*txt_end && !out) /* end and no expansion performed */
3832 return in;
3833
3834 val_len = 0;
3835 next = txt_end;
3836 if (*txt_end == '$') {
3837 char save;
3838
3839 var_beg = txt_end + 1;
3840 if (*var_beg == '{')
3841 var_beg++;
3842
3843 var_end = var_beg;
3844 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3845 var_end++;
3846 }
3847
3848 next = var_end;
3849 if (*var_end == '}' && (var_beg > txt_end + 1))
3850 next++;
3851
3852 /* get value of the variable name at this location */
3853 save = *var_end;
3854 *var_end = '\0';
3855 value = getenv(var_beg);
3856 *var_end = save;
3857 val_len = value ? strlen(value) : 0;
3858 }
3859
Hubert Verstraete831962e2016-06-28 22:44:26 +02003860 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003861 if (txt_end > txt_beg) {
3862 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3863 out_len += txt_end - txt_beg;
3864 }
3865 if (val_len) {
3866 memcpy(out + out_len, value, val_len);
3867 out_len += val_len;
3868 }
3869 out[out_len] = 0;
3870 txt_beg = next;
3871 } while (*txt_beg);
3872
3873 /* here we know that <out> was allocated and that we don't need <in> anymore */
3874 free(in);
3875 return out;
3876}
3877
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003878
3879/* same as strstr() but case-insensitive and with limit length */
3880const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3881{
3882 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003883 unsigned int slen, plen;
3884 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003885
3886 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3887 return NULL;
3888
3889 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3890 return str1;
3891
3892 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3893 return NULL;
3894
3895 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3896 while (toupper(*start) != toupper(*str2)) {
3897 start++;
3898 slen--;
3899 tmp1++;
3900
3901 if (tmp1 >= len_str1)
3902 return NULL;
3903
3904 /* if pattern longer than string */
3905 if (slen < plen)
3906 return NULL;
3907 }
3908
3909 sptr = start;
3910 pptr = (char *)str2;
3911
3912 tmp2 = 0;
3913 while (toupper(*sptr) == toupper(*pptr)) {
3914 sptr++;
3915 pptr++;
3916 tmp2++;
3917
3918 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3919 return start;
3920 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3921 return NULL;
3922 }
3923 }
3924 return NULL;
3925}
3926
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003927/* This function read the next valid utf8 char.
3928 * <s> is the byte srray to be decode, <len> is its length.
3929 * The function returns decoded char encoded like this:
3930 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3931 * are the length read. The decoded character is stored in <c>.
3932 */
3933unsigned char utf8_next(const char *s, int len, unsigned int *c)
3934{
3935 const unsigned char *p = (unsigned char *)s;
3936 int dec;
3937 unsigned char code = UTF8_CODE_OK;
3938
3939 if (len < 1)
3940 return UTF8_CODE_OK;
3941
3942 /* Check the type of UTF8 sequence
3943 *
3944 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3945 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3946 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3947 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3948 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3949 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3950 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3951 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3952 */
3953 switch (*p) {
3954 case 0x00 ... 0x7f:
3955 *c = *p;
3956 return UTF8_CODE_OK | 1;
3957
3958 case 0x80 ... 0xbf:
3959 *c = *p;
3960 return UTF8_CODE_BADSEQ | 1;
3961
3962 case 0xc0 ... 0xdf:
3963 if (len < 2) {
3964 *c = *p;
3965 return UTF8_CODE_BADSEQ | 1;
3966 }
3967 *c = *p & 0x1f;
3968 dec = 1;
3969 break;
3970
3971 case 0xe0 ... 0xef:
3972 if (len < 3) {
3973 *c = *p;
3974 return UTF8_CODE_BADSEQ | 1;
3975 }
3976 *c = *p & 0x0f;
3977 dec = 2;
3978 break;
3979
3980 case 0xf0 ... 0xf7:
3981 if (len < 4) {
3982 *c = *p;
3983 return UTF8_CODE_BADSEQ | 1;
3984 }
3985 *c = *p & 0x07;
3986 dec = 3;
3987 break;
3988
3989 case 0xf8 ... 0xfb:
3990 if (len < 5) {
3991 *c = *p;
3992 return UTF8_CODE_BADSEQ | 1;
3993 }
3994 *c = *p & 0x03;
3995 dec = 4;
3996 break;
3997
3998 case 0xfc ... 0xfd:
3999 if (len < 6) {
4000 *c = *p;
4001 return UTF8_CODE_BADSEQ | 1;
4002 }
4003 *c = *p & 0x01;
4004 dec = 5;
4005 break;
4006
4007 case 0xfe ... 0xff:
4008 default:
4009 *c = *p;
4010 return UTF8_CODE_BADSEQ | 1;
4011 }
4012
4013 p++;
4014
4015 while (dec > 0) {
4016
4017 /* need 0x10 for the 2 first bits */
4018 if ( ( *p & 0xc0 ) != 0x80 )
4019 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4020
4021 /* add data at char */
4022 *c = ( *c << 6 ) | ( *p & 0x3f );
4023
4024 dec--;
4025 p++;
4026 }
4027
4028 /* Check ovelong encoding.
4029 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4030 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4031 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4032 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004033 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004034 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4035 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4036 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4037 code |= UTF8_CODE_OVERLONG;
4038
4039 /* Check invalid UTF8 range. */
4040 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4041 (*c >= 0xfffe && *c <= 0xffff))
4042 code |= UTF8_CODE_INVRANGE;
4043
4044 return code | ((p-(unsigned char *)s)&0x0f);
4045}
4046
Maxime de Roucydc887852016-05-13 23:52:54 +02004047/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4048 * On failure : return 0 and <err> filled with an error message.
4049 * The caller is responsible for freeing the <err> and <str> copy
4050 * memory area using free()
4051 */
4052int list_append_word(struct list *li, const char *str, char **err)
4053{
4054 struct wordlist *wl;
4055
4056 wl = calloc(1, sizeof(*wl));
4057 if (!wl) {
4058 memprintf(err, "out of memory");
4059 goto fail_wl;
4060 }
4061
4062 wl->s = strdup(str);
4063 if (!wl->s) {
4064 memprintf(err, "out of memory");
4065 goto fail_wl_s;
4066 }
4067
4068 LIST_ADDQ(li, &wl->list);
4069
4070 return 1;
4071
4072fail_wl_s:
4073 free(wl->s);
4074fail_wl:
4075 free(wl);
4076 return 0;
4077}
4078
Willy Tarreau37101052019-05-20 16:48:20 +02004079/* indicates if a memory location may safely be read or not. The trick consists
4080 * in performing a harmless syscall using this location as an input and letting
4081 * the operating system report whether it's OK or not. For this we have the
4082 * stat() syscall, which will return EFAULT when the memory location supposed
4083 * to contain the file name is not readable. If it is readable it will then
4084 * either return 0 if the area contains an existing file name, or -1 with
4085 * another code. This must not be abused, and some audit systems might detect
4086 * this as abnormal activity. It's used only for unsafe dumps.
4087 */
4088int may_access(const void *ptr)
4089{
4090 struct stat buf;
4091
4092 if (stat(ptr, &buf) == 0)
4093 return 1;
4094 if (errno == EFAULT)
4095 return 0;
4096 return 1;
4097}
4098
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004099/* print a string of text buffer to <out>. The format is :
4100 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4101 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4102 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4103 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004104int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004105{
4106 unsigned char c;
4107 int ptr = 0;
4108
4109 while (buf[ptr] && ptr < bsize) {
4110 c = buf[ptr];
4111 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004112 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004113 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004114 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004115 }
4116 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004117 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004118 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004119 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004120 switch (c) {
4121 case ' ': c = ' '; break;
4122 case '\t': c = 't'; break;
4123 case '\n': c = 'n'; break;
4124 case '\r': c = 'r'; break;
4125 case '\e': c = 'e'; break;
4126 case '\\': c = '\\'; break;
4127 case '=': c = '='; break;
4128 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004129 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004130 }
4131 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004132 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004133 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004134 out->area[out->data++] = '\\';
4135 out->area[out->data++] = 'x';
4136 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4137 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004138 }
4139 ptr++;
4140 }
4141
4142 return ptr;
4143}
4144
4145/* print a buffer in hexa.
4146 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4147 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004148int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004149{
4150 unsigned char c;
4151 int ptr = 0;
4152
4153 while (ptr < bsize) {
4154 c = buf[ptr];
4155
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004156 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004157 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004158 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4159 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004160
4161 ptr++;
4162 }
4163 return ptr;
4164}
4165
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004166/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4167 * prepending each line with prefix <pfx>. The output is *not* initialized.
4168 * The output will not wrap pas the buffer's end so it is more optimal if the
4169 * caller makes sure the buffer is aligned first. A trailing zero will always
4170 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004171 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4172 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004173 */
Willy Tarreau37101052019-05-20 16:48:20 +02004174void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004175{
4176 const unsigned char *d = buf;
4177 int i, j, start;
4178
4179 d = (const unsigned char *)(((unsigned long)buf) & -16);
4180 start = ((unsigned long)buf) & 15;
4181
4182 for (i = 0; i < start + len; i += 16) {
4183 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4184
Willy Tarreau37101052019-05-20 16:48:20 +02004185 // 0: unchecked, 1: checked safe, 2: danger
4186 unsafe = !!unsafe;
4187 if (unsafe && !may_access(d + i))
4188 unsafe = 2;
4189
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004190 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004191 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004192 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004193 else if (unsafe > 1)
4194 chunk_strcat(out, "** ");
4195 else
4196 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004197
4198 if (j == 7)
4199 chunk_strcat(out, "- ");
4200 }
4201 chunk_strcat(out, " ");
4202 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004203 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004204 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004205 else if (unsafe > 1)
4206 chunk_strcat(out, "*");
4207 else if (isprint(d[i + j]))
4208 chunk_appendf(out, "%c", d[i + j]);
4209 else
4210 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004211 }
4212 chunk_strcat(out, "\n");
4213 }
4214}
4215
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004216/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4217 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4218 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4219 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4220 * lines are respected within the limit of 70 output chars. Lines that are
4221 * continuation of a previous truncated line begin with "+" instead of " "
4222 * after the offset. The new pointer is returned.
4223 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004224int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004225 int *line, int ptr)
4226{
4227 int end;
4228 unsigned char c;
4229
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004230 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004231 if (end > out->size)
4232 return ptr;
4233
4234 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4235
4236 while (ptr < len && ptr < bsize) {
4237 c = buf[ptr];
4238 if (isprint(c) && isascii(c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004239 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004240 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004241 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004242 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004243 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004244 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004245 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004246 switch (c) {
4247 case '\t': c = 't'; break;
4248 case '\n': c = 'n'; break;
4249 case '\r': c = 'r'; break;
4250 case '\e': c = 'e'; break;
4251 case '\\': c = '\\'; break;
4252 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004253 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004254 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004255 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004256 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004257 out->area[out->data++] = '\\';
4258 out->area[out->data++] = 'x';
4259 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4260 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004261 }
4262 if (buf[ptr++] == '\n') {
4263 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004264 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004265 *line = ptr;
4266 return ptr;
4267 }
4268 }
4269 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004270 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004271 return ptr;
4272}
4273
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004274/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004275 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4276 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004277 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004278void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4279 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004280{
Willy Tarreau73459792017-04-11 07:58:08 +02004281 unsigned int i;
4282 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004283
4284 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4285 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004286 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004287 for (j = 0; j < 8; j++) {
4288 if (b + j >= 0 && b + j < len)
4289 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4290 else
4291 fprintf(out, " ");
4292 }
4293
4294 if (b + j >= 0 && b + j < len)
4295 fputc('-', out);
4296 else
4297 fputc(' ', out);
4298
4299 for (j = 8; j < 16; j++) {
4300 if (b + j >= 0 && b + j < len)
4301 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4302 else
4303 fprintf(out, " ");
4304 }
4305
4306 fprintf(out, " ");
4307 for (j = 0; j < 16; j++) {
4308 if (b + j >= 0 && b + j < len) {
4309 if (isprint((unsigned char)buf[b + j]))
4310 fputc((unsigned char)buf[b + j], out);
4311 else
4312 fputc('.', out);
4313 }
4314 else
4315 fputc(' ', out);
4316 }
4317 fputc('\n', out);
4318 }
4319}
4320
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004321/*
4322 * Allocate an array of unsigned int with <nums> as address from <str> string
4323 * made of integer sepereated by dot characters.
4324 *
4325 * First, initializes the value with <sz> as address to 0 and initializes the
4326 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4327 * address updating <sz> pointed value to the size of this array.
4328 *
4329 * Returns 1 if succeeded, 0 if not.
4330 */
4331int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4332{
4333 unsigned int *n;
4334 const char *s, *end;
4335
4336 s = str;
4337 *sz = 0;
4338 end = str + strlen(str);
4339 *nums = n = NULL;
4340
4341 while (1) {
4342 unsigned int r;
4343
4344 if (s >= end)
4345 break;
4346
4347 r = read_uint(&s, end);
4348 /* Expected characters after having read an uint: '\0' or '.',
4349 * if '.', must not be terminal.
4350 */
Christopher Faulet21471ef2021-02-11 10:42:41 +01004351 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4352 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004353 return 0;
Christopher Faulet21471ef2021-02-11 10:42:41 +01004354 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004355
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004356 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004357 if (!n)
4358 return 0;
4359
4360 n[(*sz)++] = r;
4361 }
4362 *nums = n;
4363
4364 return 1;
4365}
4366
Willy Tarreau12963822017-10-24 10:54:08 +02004367/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
Willy Tarreau42a66212019-06-04 16:02:26 +02004368#ifndef USE_OBSOLETE_LINKER
Willy Tarreau12963822017-10-24 10:54:08 +02004369__attribute__((weak,format(printf, 1, 2)))
Willy Tarreau42a66212019-06-04 16:02:26 +02004370#endif
Willy Tarreau12963822017-10-24 10:54:08 +02004371void trace(char *msg, ...)
4372{
4373}
4374
Willy Tarreau861c4ef2020-03-08 00:42:37 +01004375
4376/* Random number generator state, see below */
Willy Tarreau11ab2e02020-03-12 00:31:18 +01004377static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau861c4ef2020-03-08 00:42:37 +01004378
4379/* This is a thread-safe implementation of xoroshiro128** described below:
4380 * http://prng.di.unimi.it/
4381 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4382 * supports fast jumps and passes all common quality tests. It is thread-safe,
4383 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4384 * local lock on other ones.
4385 */
4386uint64_t ha_random64()
4387{
4388 uint64_t result;
Willy Tarreau11ab2e02020-03-12 00:31:18 +01004389 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4390 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau861c4ef2020-03-08 00:42:37 +01004391
4392#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4393 static HA_SPINLOCK_T rand_lock;
4394
4395 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4396#endif
4397
4398 old[0] = ha_random_state[0];
4399 old[1] = ha_random_state[1];
4400
4401#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4402 do {
4403#endif
4404 result = rotl64(old[0] * 5, 7) * 9;
4405 new[1] = old[0] ^ old[1];
4406 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4407 new[1] = rotl64(new[1], 37); // c
4408
4409#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4410 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4411#else
4412 ha_random_state[0] = new[0];
4413 ha_random_state[1] = new[1];
4414#if defined(USE_THREAD)
4415 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4416#endif
4417#endif
4418 return result;
4419}
4420
4421/* seeds the random state using up to <len> bytes from <seed>, starting with
4422 * the first non-zero byte.
4423 */
4424void ha_random_seed(const unsigned char *seed, size_t len)
4425{
4426 size_t pos;
4427
4428 /* the seed must not be all zeroes, so we pre-fill it with alternating
4429 * bits and overwrite part of them with the block starting at the first
4430 * non-zero byte from the seed.
4431 */
4432 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4433
4434 for (pos = 0; pos < len; pos++)
4435 if (seed[pos] != 0)
4436 break;
4437
4438 if (pos == len)
4439 return;
4440
4441 seed += pos;
4442 len -= pos;
4443
4444 if (len > sizeof(ha_random_state))
4445 len = sizeof(ha_random_state);
4446
4447 memcpy(ha_random_state, seed, len);
4448}
4449
4450/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4451 * and is equivalent to calling ha_random64() as many times. It is used to
4452 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4453 * different generators (i.e. different processes after a fork). The <dist>
4454 * argument is the distance to jump to and is used in a loop so it rather not
4455 * be too large if the processing time is a concern.
4456 *
4457 * BEWARE: this function is NOT thread-safe and must not be called during
4458 * concurrent accesses to ha_random64().
4459 */
4460void ha_random_jump96(uint32_t dist)
4461{
4462 while (dist--) {
4463 uint64_t s0 = 0;
4464 uint64_t s1 = 0;
4465 int b;
4466
4467 for (b = 0; b < 64; b++) {
4468 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4469 s0 ^= ha_random_state[0];
4470 s1 ^= ha_random_state[1];
4471 }
4472 ha_random64();
4473 }
4474
4475 for (b = 0; b < 64; b++) {
4476 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4477 s0 ^= ha_random_state[0];
4478 s1 ^= ha_random_state[1];
4479 }
4480 ha_random64();
4481 }
4482 ha_random_state[0] = s0;
4483 ha_random_state[1] = s1;
4484 }
4485}
4486
Willy Tarreaubaaee002006-06-26 02:48:02 +02004487/*
4488 * Local variables:
4489 * c-indent-level: 8
4490 * c-basic-offset: 8
4491 * End:
4492 */