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