blob: c4bc821fabeed9ca53627077015c685fd93e93e3 [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
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010019#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020020#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020022#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020023#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <stdlib.h>
25#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010026#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020027#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010028#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020029#include <sys/stat.h>
30#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010031#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netinet/in.h>
33#include <arpa/inet.h>
34
Willy Tarreau30053062020-08-20 16:39:14 +020035#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
36#include <sys/auxv.h>
37#endif
38
Willy Tarreau48fbcae2020-06-03 18:09:46 +020039#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020040#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020041
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020042#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020043#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020044#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020045#include <haproxy/dns.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020046#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020047#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020048#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020049#include <haproxy/namespace.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020050#include <haproxy/protocol.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020051#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020052#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020053#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020054#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010055
Thierry Fournier93127942016-01-20 18:49:45 +010056/* This macro returns false if the test __x is false. Many
57 * of the following parsing function must be abort the processing
58 * if it returns 0, so this macro is useful for writing light code.
59 */
60#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
61
Willy Tarreau56adcf22012-12-23 18:00:29 +010062/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020063 * 2^64-1 = 18446744073709551615 or
64 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020065 *
66 * The HTML version needs room for adding the 25 characters
67 * '<span class="rls"></span>' around digits at positions 3N+1 in order
68 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020069 */
Christopher Faulet99bca652017-11-14 16:47:26 +010070THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
71THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020072
Willy Tarreau588297f2014-06-16 15:16:40 +020073/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
74 * to quote strings larger than a max configuration line.
75 */
Christopher Faulet99bca652017-11-14 16:47:26 +010076THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
77THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020078
Willy Tarreaubaaee002006-06-26 02:48:02 +020079/*
William Lallemande7340ec2012-01-24 11:15:39 +010080 * unsigned long long ASCII representation
81 *
82 * return the last char '\0' or NULL if no enough
83 * space in dst
84 */
85char *ulltoa(unsigned long long n, char *dst, size_t size)
86{
87 int i = 0;
88 char *res;
89
90 switch(n) {
91 case 1ULL ... 9ULL:
92 i = 0;
93 break;
94
95 case 10ULL ... 99ULL:
96 i = 1;
97 break;
98
99 case 100ULL ... 999ULL:
100 i = 2;
101 break;
102
103 case 1000ULL ... 9999ULL:
104 i = 3;
105 break;
106
107 case 10000ULL ... 99999ULL:
108 i = 4;
109 break;
110
111 case 100000ULL ... 999999ULL:
112 i = 5;
113 break;
114
115 case 1000000ULL ... 9999999ULL:
116 i = 6;
117 break;
118
119 case 10000000ULL ... 99999999ULL:
120 i = 7;
121 break;
122
123 case 100000000ULL ... 999999999ULL:
124 i = 8;
125 break;
126
127 case 1000000000ULL ... 9999999999ULL:
128 i = 9;
129 break;
130
131 case 10000000000ULL ... 99999999999ULL:
132 i = 10;
133 break;
134
135 case 100000000000ULL ... 999999999999ULL:
136 i = 11;
137 break;
138
139 case 1000000000000ULL ... 9999999999999ULL:
140 i = 12;
141 break;
142
143 case 10000000000000ULL ... 99999999999999ULL:
144 i = 13;
145 break;
146
147 case 100000000000000ULL ... 999999999999999ULL:
148 i = 14;
149 break;
150
151 case 1000000000000000ULL ... 9999999999999999ULL:
152 i = 15;
153 break;
154
155 case 10000000000000000ULL ... 99999999999999999ULL:
156 i = 16;
157 break;
158
159 case 100000000000000000ULL ... 999999999999999999ULL:
160 i = 17;
161 break;
162
163 case 1000000000000000000ULL ... 9999999999999999999ULL:
164 i = 18;
165 break;
166
167 case 10000000000000000000ULL ... ULLONG_MAX:
168 i = 19;
169 break;
170 }
171 if (i + 2 > size) // (i + 1) + '\0'
172 return NULL; // too long
173 res = dst + i + 1;
174 *res = '\0';
175 for (; i >= 0; i--) {
176 dst[i] = n % 10ULL + '0';
177 n /= 10ULL;
178 }
179 return res;
180}
181
182/*
183 * unsigned long ASCII representation
184 *
185 * return the last char '\0' or NULL if no enough
186 * space in dst
187 */
188char *ultoa_o(unsigned long n, char *dst, size_t size)
189{
190 int i = 0;
191 char *res;
192
193 switch (n) {
194 case 0U ... 9UL:
195 i = 0;
196 break;
197
198 case 10U ... 99UL:
199 i = 1;
200 break;
201
202 case 100U ... 999UL:
203 i = 2;
204 break;
205
206 case 1000U ... 9999UL:
207 i = 3;
208 break;
209
210 case 10000U ... 99999UL:
211 i = 4;
212 break;
213
214 case 100000U ... 999999UL:
215 i = 5;
216 break;
217
218 case 1000000U ... 9999999UL:
219 i = 6;
220 break;
221
222 case 10000000U ... 99999999UL:
223 i = 7;
224 break;
225
226 case 100000000U ... 999999999UL:
227 i = 8;
228 break;
229#if __WORDSIZE == 32
230
231 case 1000000000ULL ... ULONG_MAX:
232 i = 9;
233 break;
234
235#elif __WORDSIZE == 64
236
237 case 1000000000ULL ... 9999999999UL:
238 i = 9;
239 break;
240
241 case 10000000000ULL ... 99999999999UL:
242 i = 10;
243 break;
244
245 case 100000000000ULL ... 999999999999UL:
246 i = 11;
247 break;
248
249 case 1000000000000ULL ... 9999999999999UL:
250 i = 12;
251 break;
252
253 case 10000000000000ULL ... 99999999999999UL:
254 i = 13;
255 break;
256
257 case 100000000000000ULL ... 999999999999999UL:
258 i = 14;
259 break;
260
261 case 1000000000000000ULL ... 9999999999999999UL:
262 i = 15;
263 break;
264
265 case 10000000000000000ULL ... 99999999999999999UL:
266 i = 16;
267 break;
268
269 case 100000000000000000ULL ... 999999999999999999UL:
270 i = 17;
271 break;
272
273 case 1000000000000000000ULL ... 9999999999999999999UL:
274 i = 18;
275 break;
276
277 case 10000000000000000000ULL ... ULONG_MAX:
278 i = 19;
279 break;
280
281#endif
282 }
283 if (i + 2 > size) // (i + 1) + '\0'
284 return NULL; // too long
285 res = dst + i + 1;
286 *res = '\0';
287 for (; i >= 0; i--) {
288 dst[i] = n % 10U + '0';
289 n /= 10U;
290 }
291 return res;
292}
293
294/*
295 * signed long ASCII representation
296 *
297 * return the last char '\0' or NULL if no enough
298 * space in dst
299 */
300char *ltoa_o(long int n, char *dst, size_t size)
301{
302 char *pos = dst;
303
304 if (n < 0) {
305 if (size < 3)
306 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
307 *pos = '-';
308 pos++;
309 dst = ultoa_o(-n, pos, size - 1);
310 } else {
311 dst = ultoa_o(n, dst, size);
312 }
313 return dst;
314}
315
316/*
317 * signed long long ASCII representation
318 *
319 * return the last char '\0' or NULL if no enough
320 * space in dst
321 */
322char *lltoa(long long n, char *dst, size_t size)
323{
324 char *pos = dst;
325
326 if (n < 0) {
327 if (size < 3)
328 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
329 *pos = '-';
330 pos++;
331 dst = ulltoa(-n, pos, size - 1);
332 } else {
333 dst = ulltoa(n, dst, size);
334 }
335 return dst;
336}
337
338/*
339 * write a ascii representation of a unsigned into dst,
340 * return a pointer to the last character
341 * Pad the ascii representation with '0', using size.
342 */
343char *utoa_pad(unsigned int n, char *dst, size_t size)
344{
345 int i = 0;
346 char *ret;
347
348 switch(n) {
349 case 0U ... 9U:
350 i = 0;
351 break;
352
353 case 10U ... 99U:
354 i = 1;
355 break;
356
357 case 100U ... 999U:
358 i = 2;
359 break;
360
361 case 1000U ... 9999U:
362 i = 3;
363 break;
364
365 case 10000U ... 99999U:
366 i = 4;
367 break;
368
369 case 100000U ... 999999U:
370 i = 5;
371 break;
372
373 case 1000000U ... 9999999U:
374 i = 6;
375 break;
376
377 case 10000000U ... 99999999U:
378 i = 7;
379 break;
380
381 case 100000000U ... 999999999U:
382 i = 8;
383 break;
384
385 case 1000000000U ... 4294967295U:
386 i = 9;
387 break;
388 }
389 if (i + 2 > size) // (i + 1) + '\0'
390 return NULL; // too long
391 if (i < size)
392 i = size - 2; // padding - '\0'
393
394 ret = dst + i + 1;
395 *ret = '\0';
396 for (; i >= 0; i--) {
397 dst[i] = n % 10U + '0';
398 n /= 10U;
399 }
400 return ret;
401}
402
403/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404 * copies at most <size-1> chars from <src> to <dst>. Last char is always
405 * set to 0, unless <size> is 0. The number of chars copied is returned
406 * (excluding the terminating zero).
407 * This code has been optimized for size and speed : on x86, it's 45 bytes
408 * long, uses only registers, and consumes only 4 cycles per char.
409 */
410int strlcpy2(char *dst, const char *src, int size)
411{
412 char *orig = dst;
413 if (size) {
414 while (--size && (*dst = *src)) {
415 src++; dst++;
416 }
417 *dst = 0;
418 }
419 return dst - orig;
420}
421
422/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200423 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200424 * the ascii representation for number 'n' in decimal.
425 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100426char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200427{
428 char *pos;
429
Willy Tarreau72d759c2007-10-25 12:14:10 +0200430 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200431 *pos-- = '\0';
432
433 do {
434 *pos-- = '0' + n % 10;
435 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200436 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200437 return pos + 1;
438}
439
Willy Tarreau91092e52007-10-25 16:58:42 +0200440/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200441 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200442 * the ascii representation for number 'n' in decimal.
443 */
444char *lltoa_r(long long int in, char *buffer, int size)
445{
446 char *pos;
447 int neg = 0;
448 unsigned long long int n;
449
450 pos = buffer + size - 1;
451 *pos-- = '\0';
452
453 if (in < 0) {
454 neg = 1;
455 n = -in;
456 }
457 else
458 n = in;
459
460 do {
461 *pos-- = '0' + n % 10;
462 n /= 10;
463 } while (n && pos >= buffer);
464 if (neg && pos > buffer)
465 *pos-- = '-';
466 return pos + 1;
467}
468
469/*
470 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200471 * the ascii representation for signed number 'n' in decimal.
472 */
473char *sltoa_r(long n, char *buffer, int size)
474{
475 char *pos;
476
477 if (n >= 0)
478 return ultoa_r(n, buffer, size);
479
480 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
481 *pos = '-';
482 return pos;
483}
484
485/*
486 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200487 * the ascii representation for number 'n' in decimal, formatted for
488 * HTML output with tags to create visual grouping by 3 digits. The
489 * output needs to support at least 171 characters.
490 */
491const char *ulltoh_r(unsigned long long n, char *buffer, int size)
492{
493 char *start;
494 int digit = 0;
495
496 start = buffer + size;
497 *--start = '\0';
498
499 do {
500 if (digit == 3 && start >= buffer + 7)
501 memcpy(start -= 7, "</span>", 7);
502
503 if (start >= buffer + 1) {
504 *--start = '0' + n % 10;
505 n /= 10;
506 }
507
508 if (digit == 3 && start >= buffer + 18)
509 memcpy(start -= 18, "<span class=\"rls\">", 18);
510
511 if (digit++ == 3)
512 digit = 1;
513 } while (n && start > buffer);
514 return start;
515}
516
517/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200518 * This function simply returns a locally allocated string containing the ascii
519 * representation for number 'n' in decimal, unless n is 0 in which case it
520 * returns the alternate string (or an empty string if the alternate string is
521 * NULL). It use is intended for limits reported in reports, where it's
522 * desirable not to display anything if there is no limit. Warning! it shares
523 * the same vector as ultoa_r().
524 */
525const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
526{
527 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
528}
529
Willy Tarreau588297f2014-06-16 15:16:40 +0200530/* returns a locally allocated string containing the quoted encoding of the
531 * input string. The output may be truncated to QSTR_SIZE chars, but it is
532 * guaranteed that the string will always be properly terminated. Quotes are
533 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
534 * always be at least 4 chars.
535 */
536const char *qstr(const char *str)
537{
538 char *ret = quoted_str[quoted_idx];
539 char *p, *end;
540
541 if (++quoted_idx >= NB_QSTR)
542 quoted_idx = 0;
543
544 p = ret;
545 end = ret + QSTR_SIZE;
546
547 *p++ = '"';
548
549 /* always keep 3 chars to support passing "" and the ending " */
550 while (*str && p < end - 3) {
551 if (*str == '"') {
552 *p++ = '"';
553 *p++ = '"';
554 }
555 else
556 *p++ = *str;
557 str++;
558 }
559 *p++ = '"';
560 return ret;
561}
562
Robert Tsai81ae1952007-12-05 10:47:29 +0100563/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200564 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
565 *
566 * It looks like this one would be a good candidate for inlining, but this is
567 * not interesting because it around 35 bytes long and often called multiple
568 * times within the same function.
569 */
570int ishex(char s)
571{
572 s -= '0';
573 if ((unsigned char)s <= 9)
574 return 1;
575 s -= 'A' - '0';
576 if ((unsigned char)s <= 5)
577 return 1;
578 s -= 'a' - 'A';
579 if ((unsigned char)s <= 5)
580 return 1;
581 return 0;
582}
583
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100584/* rounds <i> down to the closest value having max 2 digits */
585unsigned int round_2dig(unsigned int i)
586{
587 unsigned int mul = 1;
588
589 while (i >= 100) {
590 i /= 10;
591 mul *= 10;
592 }
593 return i * mul;
594}
595
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100596/*
597 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
598 * invalid character is found, a pointer to it is returned. If everything is
599 * fine, NULL is returned.
600 */
601const char *invalid_char(const char *name)
602{
603 if (!*name)
604 return name;
605
606 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100607 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100608 *name != '_' && *name != '-')
609 return name;
610 name++;
611 }
612 return NULL;
613}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200614
615/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200616 * Checks <name> for invalid characters. Valid chars are [_.-] and those
617 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200618 * If an invalid character is found, a pointer to it is returned.
619 * If everything is fine, NULL is returned.
620 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200621static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200622
623 if (!*name)
624 return name;
625
626 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100627 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200628 *name != '_' && *name != '-')
629 return name;
630
631 name++;
632 }
633
634 return NULL;
635}
636
637/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200638 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
639 * If an invalid character is found, a pointer to it is returned.
640 * If everything is fine, NULL is returned.
641 */
642const char *invalid_domainchar(const char *name) {
643 return __invalid_char(name, isalnum);
644}
645
646/*
647 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
648 * If an invalid character is found, a pointer to it is returned.
649 * If everything is fine, NULL is returned.
650 */
651const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200652 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200653}
654
655/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100656 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100657 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
658 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
659 * the function tries to guess the address family from the syntax. If the
660 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100661 * string is assumed to contain only an address, no port. The address can be a
662 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
663 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
664 * The return address will only have the address family and the address set,
665 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100666 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
667 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100668 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200669 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100670struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200671{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100672 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100673 /* max IPv6 length, including brackets and terminating NULL */
674 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100675 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100676
677 /* check IPv6 with square brackets */
678 if (str[0] == '[') {
679 size_t iplength = strlen(str);
680
681 if (iplength < 4) {
682 /* minimal size is 4 when using brackets "[::]" */
683 goto fail;
684 }
685 else if (iplength >= sizeof(tmpip)) {
686 /* IPv6 literal can not be larger than tmpip */
687 goto fail;
688 }
689 else {
690 if (str[iplength - 1] != ']') {
691 /* if address started with bracket, it should end with bracket */
692 goto fail;
693 }
694 else {
695 memcpy(tmpip, str + 1, iplength - 2);
696 tmpip[iplength - 2] = '\0';
697 str = tmpip;
698 }
699 }
700 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100701
Willy Tarreaufab5a432011-03-04 15:31:53 +0100702 /* Any IPv6 address */
703 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100704 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
705 sa->ss_family = AF_INET6;
706 else if (sa->ss_family != AF_INET6)
707 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100708 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100709 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100710 }
711
Willy Tarreau24709282013-03-10 21:32:12 +0100712 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100713 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100714 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
715 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100716 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100717 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100718 }
719
720 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100721 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
722 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100723 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100724 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100726 }
727
728 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100729 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
730 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100731 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100732 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100733 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100734 }
735
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100736 if (!resolve)
737 return NULL;
738
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200739 if (!dns_hostname_validation(str, NULL))
740 return NULL;
741
David du Colombierd5f43282011-03-17 10:40:16 +0100742#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200743 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100744 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100745 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100746
747 memset(&result, 0, sizeof(result));
748 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100749 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100750 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200751 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100752 hints.ai_protocol = 0;
753
754 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100755 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
756 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100757 else if (sa->ss_family != result->ai_family) {
758 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100759 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100760 }
Willy Tarreau24709282013-03-10 21:32:12 +0100761
David du Colombierd5f43282011-03-17 10:40:16 +0100762 switch (result->ai_family) {
763 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100764 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100765 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100766 success = 1;
767 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100768 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100769 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100770 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100771 success = 1;
772 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100773 }
774 }
775
Sean Carey58ea0392013-02-15 23:39:18 +0100776 if (result)
777 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100778
779 if (success)
780 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100781 }
David du Colombierd5f43282011-03-17 10:40:16 +0100782#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200783 /* try to resolve an IPv4/IPv6 hostname */
784 he = gethostbyname(str);
785 if (he) {
786 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
787 sa->ss_family = he->h_addrtype;
788 else if (sa->ss_family != he->h_addrtype)
789 goto fail;
790
791 switch (sa->ss_family) {
792 case AF_INET:
793 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100794 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200795 return sa;
796 case AF_INET6:
797 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100798 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200799 return sa;
800 }
801 }
802
David du Colombierd5f43282011-03-17 10:40:16 +0100803 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100804 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100805 return NULL;
806}
807
808/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100809 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
810 * range or offset consisting in two integers that the caller will have to
811 * check to find the relevant input format. The following format are supported :
812 *
813 * String format | address | port | low | high
814 * addr | <addr> | 0 | 0 | 0
815 * addr: | <addr> | 0 | 0 | 0
816 * addr:port | <addr> | <port> | <port> | <port>
817 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
818 * addr:+port | <addr> | <port> | 0 | <port>
819 * addr:-port | <addr> |-<port> | <port> | 0
820 *
821 * The detection of a port range or increment by the caller is made by
822 * comparing <low> and <high>. If both are equal, then port 0 means no port
823 * was specified. The caller may pass NULL for <low> and <high> if it is not
824 * interested in retrieving port ranges.
825 *
826 * Note that <addr> above may also be :
827 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
828 * - "*" => family will be AF_INET and address will be INADDR_ANY
829 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
830 * - a host name => family and address will depend on host name resolving.
831 *
Willy Tarreau24709282013-03-10 21:32:12 +0100832 * A prefix may be passed in before the address above to force the family :
833 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
834 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
835 * - "unix@" => force address to be a path to a UNIX socket even if the
836 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200837 * - 'abns@' -> force address to belong to the abstract namespace (Linux
838 * only). These sockets are just like Unix sockets but without
839 * the need for an underlying file system. The address is a
840 * string. Technically it's like a Unix socket with a zero in
841 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100842 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100843 *
mildisff5d5102015-10-26 18:50:08 +0100844 * IPv6 addresses can be declared with or without square brackets. When using
845 * square brackets for IPv6 addresses, the port separator (colon) is optional.
846 * If not using square brackets, and in order to avoid any ambiguity with
847 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
848 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
849 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100850 *
851 * If <pfx> is non-null, it is used as a string prefix before any path-based
852 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100853 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200854 * if <fqdn> is non-null, it will be filled with :
855 * - a pointer to the FQDN of the server name to resolve if there's one, and
856 * that the caller will have to free(),
857 * - NULL if there was an explicit address that doesn't require resolution.
858 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200859 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
860 * still honored so it is possible for the caller to know whether a resolution
861 * failed by clearing this flag and checking if <fqdn> was filled, indicating
862 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200863 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100864 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200865 * the address when cast to sockaddr_in and the address family is
866 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200867 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200868 * The matching protocol will be set into <proto> if non-null.
869 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200870 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
871 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100872 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200873struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
874 struct protocol **proto, char **err,
875 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100876{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100877 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100878 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200879 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100880 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100881 char *port1, *port2;
882 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200883 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200884 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200885 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100886
887 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200888 if (fqdn)
889 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200890
Willy Tarreaudad36a32013-03-11 01:20:04 +0100891 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100892 if (str2 == NULL) {
893 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100894 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100895 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200896
Willy Tarreau9f69f462015-09-08 16:01:25 +0200897 if (!*str2) {
898 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
899 goto out;
900 }
901
Willy Tarreau24709282013-03-10 21:32:12 +0100902 memset(&ss, 0, sizeof(ss));
903
Willy Tarreaue835bd82020-09-16 11:35:47 +0200904 /* prepare the default socket types */
905 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM)
906 sock_type = ctrl_type = SOCK_DGRAM;
907 else
908 sock_type = ctrl_type = SOCK_STREAM;
909
910 if (strncmp(str2, "stream+", 7) == 0) {
911 str2 += 7;
912 sock_type = ctrl_type = SOCK_STREAM;
913 }
914 else if (strncmp(str2, "dgram+", 6) == 0) {
915 str2 += 6;
916 sock_type = ctrl_type = SOCK_DGRAM;
917 }
918
Willy Tarreau24709282013-03-10 21:32:12 +0100919 if (strncmp(str2, "unix@", 5) == 0) {
920 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200921 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100922 ss.ss_family = AF_UNIX;
923 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200924 else if (strncmp(str2, "abns@", 5) == 0) {
925 str2 += 5;
926 abstract = 1;
927 ss.ss_family = AF_UNIX;
928 }
Willy Tarreau24709282013-03-10 21:32:12 +0100929 else if (strncmp(str2, "ipv4@", 5) == 0) {
930 str2 += 5;
931 ss.ss_family = AF_INET;
932 }
933 else if (strncmp(str2, "ipv6@", 5) == 0) {
934 str2 += 5;
935 ss.ss_family = AF_INET6;
936 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200937 else if (strncmp(str2, "udp4@", 5) == 0) {
938 str2 += 5;
939 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200940 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200941 }
942 else if (strncmp(str2, "udp6@", 5) == 0) {
943 str2 += 5;
944 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200945 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200946 }
947 else if (strncmp(str2, "udp@", 4) == 0) {
948 str2 += 4;
949 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200950 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200951 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200952 else if (strncmp(str2, "fd@", 3) == 0) {
953 str2 += 3;
954 ss.ss_family = AF_CUST_EXISTING_FD;
955 }
956 else if (strncmp(str2, "sockpair@", 9) == 0) {
957 str2 += 9;
958 ss.ss_family = AF_CUST_SOCKPAIR;
959 }
Willy Tarreau24709282013-03-10 21:32:12 +0100960 else if (*str2 == '/') {
961 ss.ss_family = AF_UNIX;
962 }
963 else
964 ss.ss_family = AF_UNSPEC;
965
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200966 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200967 struct sockaddr_storage ss2;
968 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200969 char *endptr;
970
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200971 new_fd = strtol(str2, &endptr, 10);
972 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200973 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
974 goto out;
975 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200976
Willy Tarreaua215be22020-09-16 10:14:16 +0200977 /* just verify that it's a socket */
978 addr_len = sizeof(ss2);
979 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
980 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
981 goto out;
982 }
983
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200984 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
985 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200986 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200987 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100988 char *endptr;
989
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200990 new_fd = strtol(str2, &endptr, 10);
991 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100992 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100993 goto out;
994 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200995
Willy Tarreau6edc7222020-09-15 17:41:56 +0200996 if (opts & PA_O_SOCKET_FD) {
997 socklen_t addr_len;
998 int type;
999
1000 addr_len = sizeof(ss);
1001 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1002 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1003 goto out;
1004 }
1005
1006 addr_len = sizeof(type);
1007 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001008 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001009 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1010 goto out;
1011 }
1012
1013 porta = portl = porth = get_host_port(&ss);
1014 } else if (opts & PA_O_RAW_FD) {
1015 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1016 ((struct sockaddr_in *)&ss)->sin_port = 0;
1017 } else {
1018 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1019 goto out;
1020 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001021 }
1022 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001023 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001024 int prefix_path_len;
1025 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001026 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001027
1028 /* complete unix socket path name during startup or soft-restart is
1029 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1030 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001031 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001032 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001033 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001034
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001035 adr_len = strlen(str2);
1036 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001037 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1038 goto out;
1039 }
1040
Willy Tarreauccfccef2014-05-10 01:49:15 +02001041 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001042 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001043 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001044 memcpy(un->sun_path, pfx, prefix_path_len);
1045 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001046 }
Willy Tarreau24709282013-03-10 21:32:12 +01001047 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001048 char *end = str2 + strlen(str2);
1049 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001050
mildisff5d5102015-10-26 18:50:08 +01001051 /* search for : or ] whatever comes first */
1052 for (chr = end-1; chr > str2; chr--) {
1053 if (*chr == ']' || *chr == ':')
1054 break;
1055 }
1056
1057 if (*chr == ':') {
1058 /* Found a colon before a closing-bracket, must be a port separator.
1059 * This guarantee backward compatibility.
1060 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001061 if (!(opts & PA_O_PORT_OK)) {
1062 memprintf(err, "port specification not permitted here in '%s'", str);
1063 goto out;
1064 }
mildisff5d5102015-10-26 18:50:08 +01001065 *chr++ = '\0';
1066 port1 = chr;
1067 }
1068 else {
1069 /* Either no colon and no closing-bracket
1070 * or directly ending with a closing-bracket.
1071 * However, no port.
1072 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001073 if (opts & PA_O_PORT_MAND) {
1074 memprintf(err, "missing port specification in '%s'", str);
1075 goto out;
1076 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001077 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001078 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001079
Willy Tarreau90807112020-02-25 08:16:33 +01001080 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001081 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001082 if (port2) {
1083 if (!(opts & PA_O_PORT_RANGE)) {
1084 memprintf(err, "port range not permitted here in '%s'", str);
1085 goto out;
1086 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001087 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001088 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001089 else
1090 port2 = port1;
1091 portl = atoi(port1);
1092 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001093
1094 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1095 memprintf(err, "invalid port '%s'", port1);
1096 goto out;
1097 }
1098
1099 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1100 memprintf(err, "invalid port '%s'", port2);
1101 goto out;
1102 }
1103
1104 if (portl > porth) {
1105 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1106 goto out;
1107 }
1108
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001109 porta = portl;
1110 }
1111 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001112 if (!(opts & PA_O_PORT_OFS)) {
1113 memprintf(err, "port offset not permitted here in '%s'", str);
1114 goto out;
1115 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001116 portl = atoi(port1 + 1);
1117 porta = -portl;
1118 }
1119 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001120 if (!(opts & PA_O_PORT_OFS)) {
1121 memprintf(err, "port offset not permitted here in '%s'", str);
1122 goto out;
1123 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001124 porth = atoi(port1 + 1);
1125 porta = porth;
1126 }
1127 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001128 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001129 goto out;
1130 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001131 else if (opts & PA_O_PORT_MAND) {
1132 memprintf(err, "missing port specification in '%s'", str);
1133 goto out;
1134 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001135
1136 /* first try to parse the IP without resolving. If it fails, it
1137 * tells us we need to keep a copy of the FQDN to resolve later
1138 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001139 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001140 */
1141 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001142 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1143 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001144 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1145 goto out;
1146 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001147
Willy Tarreauceccdd72016-11-02 22:27:10 +01001148 if (fqdn) {
1149 if (str2 != back)
1150 memmove(back, str2, strlen(str2) + 1);
1151 *fqdn = back;
1152 back = NULL;
1153 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001154 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001155 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001156 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001157
Willy Tarreaue835bd82020-09-16 11:35:47 +02001158 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1159 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1160 goto out;
1161 }
1162 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1163 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1164 goto out;
1165 }
1166
Willy Tarreau62a976c2020-09-16 15:20:59 +02001167 if (opts & PA_O_SOCKET_FD && sock_type == SOCK_DGRAM && ctrl_type == SOCK_DGRAM) {
1168 /* FIXME: for now UDP is still its own family. However some UDP clients
1169 * (logs, dns) use AF_INET and are not aware of AF_CUST_UDP*. Since we
1170 * only want this mapping for listeners and they are the only ones
1171 * setting PA_O_SOCKET_FD, for now we condition this mapping to this.
1172 */
1173 if (ss.ss_family == AF_INET6)
1174 ss.ss_family = AF_CUST_UDP6;
1175 else if (ss.ss_family == AF_INET)
1176 ss.ss_family = AF_CUST_UDP4;
1177 }
1178
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001179 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001180 /* Note: if the caller asks for a proto, we must find one,
1181 * except if we return with an fqdn that will resolve later,
1182 * in which case the address is not known yet (this is only
1183 * for servers actually).
1184 */
1185 new_proto = protocol_by_family(ss.ss_family);
1186 if (!new_proto && (!fqdn || !*fqdn)) {
1187 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1188 goto out;
1189 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001190
1191 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1192 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1193 goto out;
1194 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001195 }
1196
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001197 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001198 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001199 if (port)
1200 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001201 if (low)
1202 *low = portl;
1203 if (high)
1204 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001205 if (fd)
1206 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001207 if (proto)
1208 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001209 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001210 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001211}
1212
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001213/* converts <str> to a struct in_addr containing a network mask. It can be
1214 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001215 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001216 */
1217int str2mask(const char *str, struct in_addr *mask)
1218{
1219 if (strchr(str, '.') != NULL) { /* dotted notation */
1220 if (!inet_pton(AF_INET, str, mask))
1221 return 0;
1222 }
1223 else { /* mask length */
1224 char *err;
1225 unsigned long len = strtol(str, &err, 10);
1226
1227 if (!*str || (err && *err) || (unsigned)len > 32)
1228 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001229
1230 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001231 }
1232 return 1;
1233}
1234
Tim Duesterhus47185172018-01-25 16:24:49 +01001235/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001236 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001237 * if the conversion succeeds otherwise zero.
1238 */
1239int str2mask6(const char *str, struct in6_addr *mask)
1240{
1241 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1242 if (!inet_pton(AF_INET6, str, mask))
1243 return 0;
1244 }
1245 else { /* mask length */
1246 char *err;
1247 unsigned long len = strtol(str, &err, 10);
1248
1249 if (!*str || (err && *err) || (unsigned)len > 128)
1250 return 0;
1251
1252 len2mask6(len, mask);
1253 }
1254 return 1;
1255}
1256
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001257/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1258 * succeeds otherwise zero.
1259 */
1260int cidr2dotted(int cidr, struct in_addr *mask) {
1261
1262 if (cidr < 0 || cidr > 32)
1263 return 0;
1264
1265 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1266 return 1;
1267}
1268
Thierry Fournier70473a52016-02-17 17:12:14 +01001269/* Convert mask from bit length form to in_addr form.
1270 * This function never fails.
1271 */
1272void len2mask4(int len, struct in_addr *addr)
1273{
1274 if (len >= 32) {
1275 addr->s_addr = 0xffffffff;
1276 return;
1277 }
1278 if (len <= 0) {
1279 addr->s_addr = 0x00000000;
1280 return;
1281 }
1282 addr->s_addr = 0xffffffff << (32 - len);
1283 addr->s_addr = htonl(addr->s_addr);
1284}
1285
1286/* Convert mask from bit length form to in6_addr form.
1287 * This function never fails.
1288 */
1289void len2mask6(int len, struct in6_addr *addr)
1290{
1291 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1292 len -= 32;
1293 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1294 len -= 32;
1295 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1296 len -= 32;
1297 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1298}
1299
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001300/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001301 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001302 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001303 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001304 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1305 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001306int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001307{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001308 __label__ out_free, out_err;
1309 char *c, *s;
1310 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001311
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001312 s = strdup(str);
1313 if (!s)
1314 return 0;
1315
Willy Tarreaubaaee002006-06-26 02:48:02 +02001316 memset(mask, 0, sizeof(*mask));
1317 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001318
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001319 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001320 *c++ = '\0';
1321 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001322 if (!str2mask(c, mask))
1323 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001324 }
1325 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001326 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001327 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001328 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001329 struct hostent *he;
1330
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001331 if (!resolve)
1332 goto out_err;
1333
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001334 if ((he = gethostbyname(s)) == NULL) {
1335 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001336 }
1337 else
1338 *addr = *(struct in_addr *) *(he->h_addr_list);
1339 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001340
1341 ret_val = 1;
1342 out_free:
1343 free(s);
1344 return ret_val;
1345 out_err:
1346 ret_val = 0;
1347 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001348}
1349
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001350
1351/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001352 * converts <str> to two struct in6_addr* which must be pre-allocated.
1353 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001354 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001355 * Returns 1 if OK, 0 if error.
1356 */
1357int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1358{
1359 char *c, *s;
1360 int ret_val = 0;
1361 char *err;
1362 unsigned long len = 128;
1363
1364 s = strdup(str);
1365 if (!s)
1366 return 0;
1367
1368 memset(mask, 0, sizeof(*mask));
1369 memset(addr, 0, sizeof(*addr));
1370
1371 if ((c = strrchr(s, '/')) != NULL) {
1372 *c++ = '\0'; /* c points to the mask */
1373 if (!*c)
1374 goto out_free;
1375
1376 len = strtoul(c, &err, 10);
1377 if ((err && *err) || (unsigned)len > 128)
1378 goto out_free;
1379 }
1380 *mask = len; /* OK we have a valid mask in <len> */
1381
1382 if (!inet_pton(AF_INET6, s, addr))
1383 goto out_free;
1384
1385 ret_val = 1;
1386 out_free:
1387 free(s);
1388 return ret_val;
1389}
1390
1391
1392/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001393 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001394 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001395int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001396{
1397 int saw_digit, octets, ch;
1398 u_char tmp[4], *tp;
1399 const char *cp = addr;
1400
1401 saw_digit = 0;
1402 octets = 0;
1403 *(tp = tmp) = 0;
1404
1405 while (*addr) {
1406 unsigned char digit = (ch = *addr++) - '0';
1407 if (digit > 9 && ch != '.')
1408 break;
1409 if (digit <= 9) {
1410 u_int new = *tp * 10 + digit;
1411 if (new > 255)
1412 return 0;
1413 *tp = new;
1414 if (!saw_digit) {
1415 if (++octets > 4)
1416 return 0;
1417 saw_digit = 1;
1418 }
1419 } else if (ch == '.' && saw_digit) {
1420 if (octets == 4)
1421 return 0;
1422 *++tp = 0;
1423 saw_digit = 0;
1424 } else
1425 return 0;
1426 }
1427
1428 if (octets < 4)
1429 return 0;
1430
1431 memcpy(&dst->s_addr, tmp, 4);
1432 return addr-cp-1;
1433}
1434
1435/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001436 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001437 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001438 * the hostname. Actually only http and https are supported. <out> can be NULL.
1439 * This function returns the consumed length. It is useful if you parse complete
1440 * url like http://host:port/path, because the consumed length corresponds to
1441 * the first character of the path. If the conversion fails, it returns -1.
1442 *
1443 * This function tries to resolve the DNS name if haproxy is in starting mode.
1444 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001445 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001446int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001447{
1448 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001449 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001450 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001451 unsigned long long int http_code = 0;
1452 int default_port;
1453 struct hostent *he;
1454 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001455
1456 /* Firstly, try to find :// pattern */
1457 while (curr < url+ulen && url_code != 0x3a2f2f) {
1458 url_code = ((url_code & 0xffff) << 8);
1459 url_code += (unsigned char)*curr++;
1460 }
1461
1462 /* Secondly, if :// pattern is found, verify parsed stuff
1463 * before pattern is matching our http pattern.
1464 * If so parse ip address and port in uri.
1465 *
1466 * WARNING: Current code doesn't support dynamic async dns resolver.
1467 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001468 if (url_code != 0x3a2f2f)
1469 return -1;
1470
1471 /* Copy scheme, and utrn to lower case. */
1472 while (cp < curr - 3)
1473 http_code = (http_code << 8) + *cp++;
1474 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001475
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001476 /* HTTP or HTTPS url matching */
1477 if (http_code == 0x2020202068747470ULL) {
1478 default_port = 80;
1479 if (out)
1480 out->scheme = SCH_HTTP;
1481 }
1482 else if (http_code == 0x2020206874747073ULL) {
1483 default_port = 443;
1484 if (out)
1485 out->scheme = SCH_HTTPS;
1486 }
1487 else
1488 return -1;
1489
1490 /* If the next char is '[', the host address is IPv6. */
1491 if (*curr == '[') {
1492 curr++;
1493
1494 /* Check trash size */
1495 if (trash.size < ulen)
1496 return -1;
1497
1498 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001499 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001500 for (end = curr;
1501 end < url + ulen && *end != ']';
1502 end++, p++)
1503 *p = *end;
1504 if (*end != ']')
1505 return -1;
1506 *p = '\0';
1507
1508 /* Update out. */
1509 if (out) {
1510 out->host = curr;
1511 out->host_len = end - curr;
1512 }
1513
1514 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001515 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001516 return -1;
1517 end++;
1518
1519 /* Decode port. */
1520 if (*end == ':') {
1521 end++;
1522 default_port = read_uint(&end, url + ulen);
1523 }
1524 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1525 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1526 return end - url;
1527 }
1528 else {
1529 /* We are looking for IP address. If you want to parse and
1530 * resolve hostname found in url, you can use str2sa_range(), but
1531 * be warned this can slow down global daemon performances
1532 * while handling lagging dns responses.
1533 */
1534 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1535 if (ret) {
1536 /* Update out. */
1537 if (out) {
1538 out->host = curr;
1539 out->host_len = ret;
1540 }
1541
1542 curr += ret;
1543
1544 /* Decode port. */
1545 if (*curr == ':') {
1546 curr++;
1547 default_port = read_uint(&curr, url + ulen);
1548 }
1549 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1550
1551 /* Set family. */
1552 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1553 return curr - url;
1554 }
1555 else if (global.mode & MODE_STARTING) {
1556 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1557 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001558 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001559
1560 /* look for : or / or end */
1561 for (end = curr;
1562 end < url + ulen && *end != '/' && *end != ':';
1563 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001564 memcpy(trash.area, curr, end - curr);
1565 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001566
1567 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001568 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001569 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001570 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001571
1572 /* Update out. */
1573 if (out) {
1574 out->host = curr;
1575 out->host_len = end - curr;
1576 }
1577
1578 /* Decode port. */
1579 if (*end == ':') {
1580 end++;
1581 default_port = read_uint(&end, url + ulen);
1582 }
1583
1584 /* Copy IP address, set port and family. */
1585 switch (he->h_addrtype) {
1586 case AF_INET:
1587 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1588 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1589 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1590 return end - url;
1591
1592 case AF_INET6:
1593 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1594 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1595 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1596 return end - url;
1597 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001598 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001599 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001600 return -1;
1601}
1602
Willy Tarreau631f01c2011-09-05 00:36:48 +02001603/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1604 * address family is returned so that it's easy for the caller to adapt to the
1605 * output format. Zero is returned if the address family is not supported. -1
1606 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1607 * supported.
1608 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001609int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001610{
1611
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001612 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001613
1614 if (size < 5)
1615 return 0;
1616 *str = '\0';
1617
1618 switch (addr->ss_family) {
1619 case AF_INET:
1620 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1621 break;
1622 case AF_INET6:
1623 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1624 break;
1625 case AF_UNIX:
1626 memcpy(str, "unix", 5);
1627 return addr->ss_family;
1628 default:
1629 return 0;
1630 }
1631
1632 if (inet_ntop(addr->ss_family, ptr, str, size))
1633 return addr->ss_family;
1634
1635 /* failed */
1636 return -1;
1637}
1638
Simon Horman75ab8bd2014-06-16 09:39:41 +09001639/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1640 * address family is returned so that it's easy for the caller to adapt to the
1641 * output format. Zero is returned if the address family is not supported. -1
1642 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1643 * supported.
1644 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001645int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001646{
1647
1648 uint16_t port;
1649
1650
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001651 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001652 return 0;
1653 *str = '\0';
1654
1655 switch (addr->ss_family) {
1656 case AF_INET:
1657 port = ((struct sockaddr_in *)addr)->sin_port;
1658 break;
1659 case AF_INET6:
1660 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1661 break;
1662 case AF_UNIX:
1663 memcpy(str, "unix", 5);
1664 return addr->ss_family;
1665 default:
1666 return 0;
1667 }
1668
1669 snprintf(str, size, "%u", ntohs(port));
1670 return addr->ss_family;
1671}
1672
Willy Tarreau16e01562016-08-09 16:46:18 +02001673/* check if the given address is local to the system or not. It will return
1674 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1675 * it is. We don't want to iterate over all interfaces for this (and it is not
1676 * portable). So instead we try to bind in UDP to this address on a free non
1677 * privileged port and to connect to the same address, port 0 (connect doesn't
1678 * care). If it succeeds, we own the address. Note that non-inet addresses are
1679 * considered local since they're most likely AF_UNIX.
1680 */
1681int addr_is_local(const struct netns_entry *ns,
1682 const struct sockaddr_storage *orig)
1683{
1684 struct sockaddr_storage addr;
1685 int result;
1686 int fd;
1687
1688 if (!is_inet_addr(orig))
1689 return 1;
1690
1691 memcpy(&addr, orig, sizeof(addr));
1692 set_host_port(&addr, 0);
1693
1694 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1695 if (fd < 0)
1696 return -1;
1697
1698 result = -1;
1699 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1700 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1701 result = 0; // fail, non-local address
1702 else
1703 result = 1; // success, local address
1704 }
1705 else {
1706 if (errno == EADDRNOTAVAIL)
1707 result = 0; // definitely not local :-)
1708 }
1709 close(fd);
1710
1711 return result;
1712}
1713
Willy Tarreaubaaee002006-06-26 02:48:02 +02001714/* will try to encode the string <string> replacing all characters tagged in
1715 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1716 * prefixed by <escape>, and will store the result between <start> (included)
1717 * and <stop> (excluded), and will always terminate the string with a '\0'
1718 * before <stop>. The position of the '\0' is returned if the conversion
1719 * completes. If bytes are missing between <start> and <stop>, then the
1720 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1721 * cannot even be stored so we return <start> without writing the 0.
1722 * The input string must also be zero-terminated.
1723 */
1724const char hextab[16] = "0123456789ABCDEF";
1725char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001726 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001727 const char *string)
1728{
1729 if (start < stop) {
1730 stop--; /* reserve one byte for the final '\0' */
1731 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001732 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001733 *start++ = *string;
1734 else {
1735 if (start + 3 >= stop)
1736 break;
1737 *start++ = escape;
1738 *start++ = hextab[(*string >> 4) & 15];
1739 *start++ = hextab[*string & 15];
1740 }
1741 string++;
1742 }
1743 *start = '\0';
1744 }
1745 return start;
1746}
1747
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001748/*
1749 * Same behavior as encode_string() above, except that it encodes chunk
1750 * <chunk> instead of a string.
1751 */
1752char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001753 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001754 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001755{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001756 char *str = chunk->area;
1757 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001758
1759 if (start < stop) {
1760 stop--; /* reserve one byte for the final '\0' */
1761 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001762 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001763 *start++ = *str;
1764 else {
1765 if (start + 3 >= stop)
1766 break;
1767 *start++ = escape;
1768 *start++ = hextab[(*str >> 4) & 15];
1769 *start++ = hextab[*str & 15];
1770 }
1771 str++;
1772 }
1773 *start = '\0';
1774 }
1775 return start;
1776}
1777
Dragan Dosen0edd1092016-02-12 13:23:02 +01001778/*
1779 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001780 * character. The input <string> must be zero-terminated. The result will
1781 * be stored between <start> (included) and <stop> (excluded). This
1782 * function will always try to terminate the resulting string with a '\0'
1783 * before <stop>, and will return its position if the conversion
1784 * completes.
1785 */
1786char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001787 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001788 const char *string)
1789{
1790 if (start < stop) {
1791 stop--; /* reserve one byte for the final '\0' */
1792 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001793 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001794 *start++ = *string;
1795 else {
1796 if (start + 2 >= stop)
1797 break;
1798 *start++ = escape;
1799 *start++ = *string;
1800 }
1801 string++;
1802 }
1803 *start = '\0';
1804 }
1805 return start;
1806}
1807
1808/*
1809 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001810 * character. <chunk> contains the input to be escaped. The result will be
1811 * stored between <start> (included) and <stop> (excluded). The function
1812 * will always try to terminate the resulting string with a '\0' before
1813 * <stop>, and will return its position if the conversion completes.
1814 */
1815char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001816 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001817 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001818{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001819 char *str = chunk->area;
1820 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001821
1822 if (start < stop) {
1823 stop--; /* reserve one byte for the final '\0' */
1824 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001825 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001826 *start++ = *str;
1827 else {
1828 if (start + 2 >= stop)
1829 break;
1830 *start++ = escape;
1831 *start++ = *str;
1832 }
1833 str++;
1834 }
1835 *start = '\0';
1836 }
1837 return start;
1838}
1839
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001840/* Check a string for using it in a CSV output format. If the string contains
1841 * one of the following four char <">, <,>, CR or LF, the string is
1842 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1843 * <str> is the input string to be escaped. The function assumes that
1844 * the input string is null-terminated.
1845 *
1846 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001847 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001848 * format.
1849 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001850 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001851 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001852 * If <quote> is 1, the converter puts the quotes only if any reserved character
1853 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001854 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001855 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001856 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001857 * The function returns the converted string on its output. If an error
1858 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001859 * for using the function directly as printf() argument.
1860 *
1861 * If the output buffer is too short to contain the input string, the result
1862 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001863 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001864 * This function appends the encoding to the existing output chunk, and it
1865 * guarantees that it starts immediately at the first available character of
1866 * the chunk. Please use csv_enc() instead if you want to replace the output
1867 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001868 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001869const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001870{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001871 char *end = output->area + output->size;
1872 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001873 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001874
Willy Tarreaub631c292016-01-08 10:04:08 +01001875 if (quote == 1) {
1876 /* automatic quoting: first verify if we'll have to quote the string */
1877 if (!strpbrk(str, "\n\r,\""))
1878 quote = 0;
1879 }
1880
1881 if (quote)
1882 *ptr++ = '"';
1883
Willy Tarreau898529b2016-01-06 18:07:04 +01001884 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1885 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001886 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001887 ptr++;
1888 if (ptr >= end - 2) {
1889 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001890 break;
1891 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001892 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001893 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001894 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001895 str++;
1896 }
1897
Willy Tarreaub631c292016-01-08 10:04:08 +01001898 if (quote)
1899 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001900
Willy Tarreau898529b2016-01-06 18:07:04 +01001901 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001902 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001903 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001904}
1905
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001906/* Decode an URL-encoded string in-place. The resulting string might
1907 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001908 * aborted, the string is truncated before the issue and a negative value is
1909 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001910 * If the 'in_form' argument is non-nul the string is assumed to be part of
1911 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1912 * turned to a space. If it's zero, this will only be done after a question
1913 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001914 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001915int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001916{
1917 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001918 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001919
1920 in = string;
1921 out = string;
1922 while (*in) {
1923 switch (*in) {
1924 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001925 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001926 break;
1927 case '%' :
1928 if (!ishex(in[1]) || !ishex(in[2]))
1929 goto end;
1930 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1931 in += 2;
1932 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001933 case '?':
1934 in_form = 1;
1935 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001936 default:
1937 *out++ = *in;
1938 break;
1939 }
1940 in++;
1941 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001942 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001943 end:
1944 *out = 0;
1945 return ret;
1946}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001947
Willy Tarreau6911fa42007-03-04 18:06:08 +01001948unsigned int str2ui(const char *s)
1949{
1950 return __str2ui(s);
1951}
1952
1953unsigned int str2uic(const char *s)
1954{
1955 return __str2uic(s);
1956}
1957
1958unsigned int strl2ui(const char *s, int len)
1959{
1960 return __strl2ui(s, len);
1961}
1962
1963unsigned int strl2uic(const char *s, int len)
1964{
1965 return __strl2uic(s, len);
1966}
1967
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001968unsigned int read_uint(const char **s, const char *end)
1969{
1970 return __read_uint(s, end);
1971}
1972
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001973/* This function reads an unsigned integer from the string pointed to by <s> and
1974 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1975 * function automatically stops at <end>. If the number overflows, the 2^64-1
1976 * value is returned.
1977 */
1978unsigned long long int read_uint64(const char **s, const char *end)
1979{
1980 const char *ptr = *s;
1981 unsigned long long int i = 0, tmp;
1982 unsigned int j;
1983
1984 while (ptr < end) {
1985
1986 /* read next char */
1987 j = *ptr - '0';
1988 if (j > 9)
1989 goto read_uint64_end;
1990
1991 /* add char to the number and check overflow. */
1992 tmp = i * 10;
1993 if (tmp / 10 != i) {
1994 i = ULLONG_MAX;
1995 goto read_uint64_eat;
1996 }
1997 if (ULLONG_MAX - tmp < j) {
1998 i = ULLONG_MAX;
1999 goto read_uint64_eat;
2000 }
2001 i = tmp + j;
2002 ptr++;
2003 }
2004read_uint64_eat:
2005 /* eat each numeric char */
2006 while (ptr < end) {
2007 if ((unsigned int)(*ptr - '0') > 9)
2008 break;
2009 ptr++;
2010 }
2011read_uint64_end:
2012 *s = ptr;
2013 return i;
2014}
2015
2016/* This function reads an integer from the string pointed to by <s> and returns
2017 * it. The <s> pointer is adjusted to point to the first unread char. The function
2018 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2019 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2020 * returned.
2021 */
2022long long int read_int64(const char **s, const char *end)
2023{
2024 unsigned long long int i = 0;
2025 int neg = 0;
2026
2027 /* Look for minus char. */
2028 if (**s == '-') {
2029 neg = 1;
2030 (*s)++;
2031 }
2032 else if (**s == '+')
2033 (*s)++;
2034
2035 /* convert as positive number. */
2036 i = read_uint64(s, end);
2037
2038 if (neg) {
2039 if (i > 0x8000000000000000ULL)
2040 return LLONG_MIN;
2041 return -i;
2042 }
2043 if (i > 0x7fffffffffffffffULL)
2044 return LLONG_MAX;
2045 return i;
2046}
2047
Willy Tarreau6911fa42007-03-04 18:06:08 +01002048/* This one is 7 times faster than strtol() on athlon with checks.
2049 * It returns the value of the number composed of all valid digits read,
2050 * and can process negative numbers too.
2051 */
2052int strl2ic(const char *s, int len)
2053{
2054 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002055 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002056
2057 if (len > 0) {
2058 if (*s != '-') {
2059 /* positive number */
2060 while (len-- > 0) {
2061 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002062 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002063 if (j > 9)
2064 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002065 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002066 }
2067 } else {
2068 /* negative number */
2069 s++;
2070 while (--len > 0) {
2071 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002072 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002073 if (j > 9)
2074 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002075 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002076 }
2077 }
2078 }
2079 return i;
2080}
2081
2082
2083/* This function reads exactly <len> chars from <s> and converts them to a
2084 * signed integer which it stores into <ret>. It accurately detects any error
2085 * (truncated string, invalid chars, overflows). It is meant to be used in
2086 * applications designed for hostile environments. It returns zero when the
2087 * number has successfully been converted, non-zero otherwise. When an error
2088 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2089 * faster than strtol().
2090 */
2091int strl2irc(const char *s, int len, int *ret)
2092{
2093 int i = 0;
2094 int j;
2095
2096 if (!len)
2097 return 1;
2098
2099 if (*s != '-') {
2100 /* positive number */
2101 while (len-- > 0) {
2102 j = (*s++) - '0';
2103 if (j > 9) return 1; /* invalid char */
2104 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2105 i = i * 10;
2106 if (i + j < i) return 1; /* check for addition overflow */
2107 i = i + j;
2108 }
2109 } else {
2110 /* negative number */
2111 s++;
2112 while (--len > 0) {
2113 j = (*s++) - '0';
2114 if (j > 9) return 1; /* invalid char */
2115 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2116 i = i * 10;
2117 if (i - j > i) return 1; /* check for subtract overflow */
2118 i = i - j;
2119 }
2120 }
2121 *ret = i;
2122 return 0;
2123}
2124
2125
2126/* This function reads exactly <len> chars from <s> and converts them to a
2127 * signed integer which it stores into <ret>. It accurately detects any error
2128 * (truncated string, invalid chars, overflows). It is meant to be used in
2129 * applications designed for hostile environments. It returns zero when the
2130 * number has successfully been converted, non-zero otherwise. When an error
2131 * is returned, the <ret> value is left untouched. It is about 3 times slower
2132 * than str2irc().
2133 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002134
2135int strl2llrc(const char *s, int len, long long *ret)
2136{
2137 long long i = 0;
2138 int j;
2139
2140 if (!len)
2141 return 1;
2142
2143 if (*s != '-') {
2144 /* positive number */
2145 while (len-- > 0) {
2146 j = (*s++) - '0';
2147 if (j > 9) return 1; /* invalid char */
2148 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2149 i = i * 10LL;
2150 if (i + j < i) return 1; /* check for addition overflow */
2151 i = i + j;
2152 }
2153 } else {
2154 /* negative number */
2155 s++;
2156 while (--len > 0) {
2157 j = (*s++) - '0';
2158 if (j > 9) return 1; /* invalid char */
2159 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2160 i = i * 10LL;
2161 if (i - j > i) return 1; /* check for subtract overflow */
2162 i = i - j;
2163 }
2164 }
2165 *ret = i;
2166 return 0;
2167}
2168
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002169/* This function is used with pat_parse_dotted_ver(). It converts a string
2170 * composed by two number separated by a dot. Each part must contain in 16 bits
2171 * because internally they will be represented as a 32-bit quantity stored in
2172 * a 64-bit integer. It returns zero when the number has successfully been
2173 * converted, non-zero otherwise. When an error is returned, the <ret> value
2174 * is left untouched.
2175 *
2176 * "1.3" -> 0x0000000000010003
2177 * "65535.65535" -> 0x00000000ffffffff
2178 */
2179int strl2llrc_dotted(const char *text, int len, long long *ret)
2180{
2181 const char *end = &text[len];
2182 const char *p;
2183 long long major, minor;
2184
2185 /* Look for dot. */
2186 for (p = text; p < end; p++)
2187 if (*p == '.')
2188 break;
2189
2190 /* Convert major. */
2191 if (strl2llrc(text, p - text, &major) != 0)
2192 return 1;
2193
2194 /* Check major. */
2195 if (major >= 65536)
2196 return 1;
2197
2198 /* Convert minor. */
2199 minor = 0;
2200 if (p < end)
2201 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2202 return 1;
2203
2204 /* Check minor. */
2205 if (minor >= 65536)
2206 return 1;
2207
2208 /* Compose value. */
2209 *ret = (major << 16) | (minor & 0xffff);
2210 return 0;
2211}
2212
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002213/* This function parses a time value optionally followed by a unit suffix among
2214 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2215 * expected by the caller. The computation does its best to avoid overflows.
2216 * The value is returned in <ret> if everything is fine, and a NULL is returned
2217 * by the function. In case of error, a pointer to the error is returned and
2218 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002219 * Values resulting in values larger than or equal to 2^31 after conversion are
2220 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2221 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002222 */
2223const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2224{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002225 unsigned long long imult, idiv;
2226 unsigned long long omult, odiv;
2227 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002228
2229 omult = odiv = 1;
2230
2231 switch (unit_flags & TIME_UNIT_MASK) {
2232 case TIME_UNIT_US: omult = 1000000; break;
2233 case TIME_UNIT_MS: omult = 1000; break;
2234 case TIME_UNIT_S: break;
2235 case TIME_UNIT_MIN: odiv = 60; break;
2236 case TIME_UNIT_HOUR: odiv = 3600; break;
2237 case TIME_UNIT_DAY: odiv = 86400; break;
2238 default: break;
2239 }
2240
2241 value = 0;
2242
2243 while (1) {
2244 unsigned int j;
2245
2246 j = *text - '0';
2247 if (j > 9)
2248 break;
2249 text++;
2250 value *= 10;
2251 value += j;
2252 }
2253
2254 imult = idiv = 1;
2255 switch (*text) {
2256 case '\0': /* no unit = default unit */
2257 imult = omult = idiv = odiv = 1;
2258 break;
2259 case 's': /* second = unscaled unit */
2260 break;
2261 case 'u': /* microsecond : "us" */
2262 if (text[1] == 's') {
2263 idiv = 1000000;
2264 text++;
2265 }
2266 break;
2267 case 'm': /* millisecond : "ms" or minute: "m" */
2268 if (text[1] == 's') {
2269 idiv = 1000;
2270 text++;
2271 } else
2272 imult = 60;
2273 break;
2274 case 'h': /* hour : "h" */
2275 imult = 3600;
2276 break;
2277 case 'd': /* day : "d" */
2278 imult = 86400;
2279 break;
2280 default:
2281 return text;
2282 break;
2283 }
2284
2285 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2286 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2287 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2288 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2289
Willy Tarreau9faebe32019-06-07 19:00:37 +02002290 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2291 if (result >= 0x80000000)
2292 return PARSE_TIME_OVER;
2293 if (!result && value)
2294 return PARSE_TIME_UNDER;
2295 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002296 return NULL;
2297}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002298
Emeric Brun39132b22010-01-04 14:57:24 +01002299/* this function converts the string starting at <text> to an unsigned int
2300 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002301 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002302 */
2303const char *parse_size_err(const char *text, unsigned *ret) {
2304 unsigned value = 0;
2305
2306 while (1) {
2307 unsigned int j;
2308
2309 j = *text - '0';
2310 if (j > 9)
2311 break;
2312 if (value > ~0U / 10)
2313 return text;
2314 value *= 10;
2315 if (value > (value + j))
2316 return text;
2317 value += j;
2318 text++;
2319 }
2320
2321 switch (*text) {
2322 case '\0':
2323 break;
2324 case 'K':
2325 case 'k':
2326 if (value > ~0U >> 10)
2327 return text;
2328 value = value << 10;
2329 break;
2330 case 'M':
2331 case 'm':
2332 if (value > ~0U >> 20)
2333 return text;
2334 value = value << 20;
2335 break;
2336 case 'G':
2337 case 'g':
2338 if (value > ~0U >> 30)
2339 return text;
2340 value = value << 30;
2341 break;
2342 default:
2343 return text;
2344 }
2345
Godbach58048a22015-01-28 17:36:16 +08002346 if (*text != '\0' && *++text != '\0')
2347 return text;
2348
Emeric Brun39132b22010-01-04 14:57:24 +01002349 *ret = value;
2350 return NULL;
2351}
2352
Willy Tarreau126d4062013-12-03 17:50:47 +01002353/*
2354 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002355 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002356 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002357 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002358 */
2359int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2360{
2361 int len;
2362 const char *p = source;
2363 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002364 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002365
2366 len = strlen(source);
2367 if (len % 2) {
2368 memprintf(err, "an even number of hex digit is expected");
2369 return 0;
2370 }
2371
2372 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002373
Willy Tarreau126d4062013-12-03 17:50:47 +01002374 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002375 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002376 if (!*binstr) {
2377 memprintf(err, "out of memory while loading string pattern");
2378 return 0;
2379 }
2380 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002381 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002382 else {
2383 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002384 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002385 len, *binstrlen);
2386 return 0;
2387 }
2388 alloc = 0;
2389 }
2390 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002391
2392 i = j = 0;
2393 while (j < len) {
2394 if (!ishex(p[i++]))
2395 goto bad_input;
2396 if (!ishex(p[i++]))
2397 goto bad_input;
2398 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2399 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002400 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002401
2402bad_input:
2403 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002404 if (alloc) {
2405 free(*binstr);
2406 *binstr = NULL;
2407 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002408 return 0;
2409}
2410
Willy Tarreau946ba592009-05-10 15:41:18 +02002411/* copies at most <n> characters from <src> and always terminates with '\0' */
2412char *my_strndup(const char *src, int n)
2413{
2414 int len = 0;
2415 char *ret;
2416
2417 while (len < n && src[len])
2418 len++;
2419
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002420 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002421 if (!ret)
2422 return ret;
2423 memcpy(ret, src, len);
2424 ret[len] = '\0';
2425 return ret;
2426}
2427
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002428/*
2429 * search needle in haystack
2430 * returns the pointer if found, returns NULL otherwise
2431 */
2432const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2433{
2434 const void *c = NULL;
2435 unsigned char f;
2436
2437 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2438 return NULL;
2439
2440 f = *(char *)needle;
2441 c = haystack;
2442 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2443 if ((haystacklen - (c - haystack)) < needlelen)
2444 return NULL;
2445
2446 if (memcmp(c, needle, needlelen) == 0)
2447 return c;
2448 ++c;
2449 }
2450 return NULL;
2451}
2452
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002453/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002454size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2455{
2456 size_t ret = 0;
2457
2458 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2459 str++;
2460 ret++;
2461 }
2462 return ret;
2463}
2464
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002465/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002466size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2467{
2468 size_t ret = 0;
2469
2470 while (ret < len) {
2471 if(memchr(reject, *((int *)str), rejectlen))
2472 return ret;
2473 str++;
2474 ret++;
2475 }
2476 return ret;
2477}
2478
Willy Tarreau482b00d2009-10-04 22:48:42 +02002479/* This function returns the first unused key greater than or equal to <key> in
2480 * ID tree <root>. Zero is returned if no place is found.
2481 */
2482unsigned int get_next_id(struct eb_root *root, unsigned int key)
2483{
2484 struct eb32_node *used;
2485
2486 do {
2487 used = eb32_lookup_ge(root, key);
2488 if (!used || used->key > key)
2489 return key; /* key is available */
2490 key++;
2491 } while (key);
2492 return key;
2493}
2494
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002495/* dump the full tree to <file> in DOT format for debugging purposes. Will
2496 * optionally highlight node <subj> if found, depending on operation <op> :
2497 * 0 : nothing
2498 * >0 : insertion, node/leaf are surrounded in red
2499 * <0 : removal, node/leaf are dashed with no background
2500 * Will optionally add "desc" as a label on the graph if set and non-null.
2501 */
2502void 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 +01002503{
2504 struct eb32sc_node *node;
2505 unsigned long scope = -1;
2506
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002507 fprintf(file, "digraph ebtree {\n");
2508
2509 if (desc && *desc) {
2510 fprintf(file,
2511 " fontname=\"fixed\";\n"
2512 " fontsize=8;\n"
2513 " label=\"%s\";\n", desc);
2514 }
2515
Willy Tarreaued3cda02017-11-15 15:04:05 +01002516 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002517 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2518 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002519 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2520 );
2521
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002522 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002523 (long)eb_root_to_node(root),
2524 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002525 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2526
2527 node = eb32sc_first(root, scope);
2528 while (node) {
2529 if (node->node.node_p) {
2530 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002531 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2532 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2533 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002534
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002535 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002536 (long)node,
2537 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002538 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002539
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002540 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002541 (long)node,
2542 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002543 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2544
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002545 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002546 (long)node,
2547 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002548 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2549 }
2550
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002551 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2552 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2553 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002554
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002555 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002556 (long)node,
2557 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002558 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002559 node = eb32sc_next(node, scope);
2560 }
2561 fprintf(file, "}\n");
2562}
2563
Willy Tarreau348238b2010-01-18 15:05:57 +01002564/* This function compares a sample word possibly followed by blanks to another
2565 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2566 * otherwise zero. This intends to be used when checking HTTP headers for some
2567 * values. Note that it validates a word followed only by blanks but does not
2568 * validate a word followed by blanks then other chars.
2569 */
2570int word_match(const char *sample, int slen, const char *word, int wlen)
2571{
2572 if (slen < wlen)
2573 return 0;
2574
2575 while (wlen) {
2576 char c = *sample ^ *word;
2577 if (c && c != ('A' ^ 'a'))
2578 return 0;
2579 sample++;
2580 word++;
2581 slen--;
2582 wlen--;
2583 }
2584
2585 while (slen) {
2586 if (*sample != ' ' && *sample != '\t')
2587 return 0;
2588 sample++;
2589 slen--;
2590 }
2591 return 1;
2592}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002593
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002594/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2595 * is particularly fast because it avoids expensive operations such as
2596 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002597 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002598 */
2599unsigned int inetaddr_host(const char *text)
2600{
2601 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2602 register unsigned int dig100, dig10, dig1;
2603 int s;
2604 const char *p, *d;
2605
2606 dig1 = dig10 = dig100 = ascii_zero;
2607 s = 24;
2608
2609 p = text;
2610 while (1) {
2611 if (((unsigned)(*p - '0')) <= 9) {
2612 p++;
2613 continue;
2614 }
2615
2616 /* here, we have a complete byte between <text> and <p> (exclusive) */
2617 if (p == text)
2618 goto end;
2619
2620 d = p - 1;
2621 dig1 |= (unsigned int)(*d << s);
2622 if (d == text)
2623 goto end;
2624
2625 d--;
2626 dig10 |= (unsigned int)(*d << s);
2627 if (d == text)
2628 goto end;
2629
2630 d--;
2631 dig100 |= (unsigned int)(*d << s);
2632 end:
2633 if (!s || *p != '.')
2634 break;
2635
2636 s -= 8;
2637 text = ++p;
2638 }
2639
2640 dig100 -= ascii_zero;
2641 dig10 -= ascii_zero;
2642 dig1 -= ascii_zero;
2643 return ((dig100 * 10) + dig10) * 10 + dig1;
2644}
2645
2646/*
2647 * Idem except the first unparsed character has to be passed in <stop>.
2648 */
2649unsigned int inetaddr_host_lim(const char *text, const char *stop)
2650{
2651 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2652 register unsigned int dig100, dig10, dig1;
2653 int s;
2654 const char *p, *d;
2655
2656 dig1 = dig10 = dig100 = ascii_zero;
2657 s = 24;
2658
2659 p = text;
2660 while (1) {
2661 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2662 p++;
2663 continue;
2664 }
2665
2666 /* here, we have a complete byte between <text> and <p> (exclusive) */
2667 if (p == text)
2668 goto end;
2669
2670 d = p - 1;
2671 dig1 |= (unsigned int)(*d << s);
2672 if (d == text)
2673 goto end;
2674
2675 d--;
2676 dig10 |= (unsigned int)(*d << s);
2677 if (d == text)
2678 goto end;
2679
2680 d--;
2681 dig100 |= (unsigned int)(*d << s);
2682 end:
2683 if (!s || p == stop || *p != '.')
2684 break;
2685
2686 s -= 8;
2687 text = ++p;
2688 }
2689
2690 dig100 -= ascii_zero;
2691 dig10 -= ascii_zero;
2692 dig1 -= ascii_zero;
2693 return ((dig100 * 10) + dig10) * 10 + dig1;
2694}
2695
2696/*
2697 * Idem except the pointer to first unparsed byte is returned into <ret> which
2698 * must not be NULL.
2699 */
Willy Tarreau74172752010-10-15 23:21:42 +02002700unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002701{
2702 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2703 register unsigned int dig100, dig10, dig1;
2704 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002705 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002706
2707 dig1 = dig10 = dig100 = ascii_zero;
2708 s = 24;
2709
2710 p = text;
2711 while (1) {
2712 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2713 p++;
2714 continue;
2715 }
2716
2717 /* here, we have a complete byte between <text> and <p> (exclusive) */
2718 if (p == text)
2719 goto end;
2720
2721 d = p - 1;
2722 dig1 |= (unsigned int)(*d << s);
2723 if (d == text)
2724 goto end;
2725
2726 d--;
2727 dig10 |= (unsigned int)(*d << s);
2728 if (d == text)
2729 goto end;
2730
2731 d--;
2732 dig100 |= (unsigned int)(*d << s);
2733 end:
2734 if (!s || p == stop || *p != '.')
2735 break;
2736
2737 s -= 8;
2738 text = ++p;
2739 }
2740
2741 *ret = p;
2742 dig100 -= ascii_zero;
2743 dig10 -= ascii_zero;
2744 dig1 -= ascii_zero;
2745 return ((dig100 * 10) + dig10) * 10 + dig1;
2746}
2747
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002748/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2749 * or the number of chars read in case of success. Maybe this could be replaced
2750 * by one of the functions above. Also, apparently this function does not support
2751 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002752 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002753 */
2754int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2755{
2756 const char *addr;
2757 int saw_digit, octets, ch;
2758 u_char tmp[4], *tp;
2759 const char *cp = buf;
2760
2761 saw_digit = 0;
2762 octets = 0;
2763 *(tp = tmp) = 0;
2764
2765 for (addr = buf; addr - buf < len; addr++) {
2766 unsigned char digit = (ch = *addr) - '0';
2767
2768 if (digit > 9 && ch != '.')
2769 break;
2770
2771 if (digit <= 9) {
2772 u_int new = *tp * 10 + digit;
2773
2774 if (new > 255)
2775 return 0;
2776
2777 *tp = new;
2778
2779 if (!saw_digit) {
2780 if (++octets > 4)
2781 return 0;
2782 saw_digit = 1;
2783 }
2784 } else if (ch == '.' && saw_digit) {
2785 if (octets == 4)
2786 return 0;
2787
2788 *++tp = 0;
2789 saw_digit = 0;
2790 } else
2791 return 0;
2792 }
2793
2794 if (octets < 4)
2795 return 0;
2796
2797 memcpy(&dst->s_addr, tmp, 4);
2798 return addr - cp;
2799}
2800
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002801/* This function converts the string in <buf> of the len <len> to
2802 * struct in6_addr <dst> which must be allocated by the caller.
2803 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002804 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002805 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002806int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2807{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002808 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002809 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002810
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002811 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002812 return 0;
2813
2814 memcpy(null_term_ip6, buf, len);
2815 null_term_ip6[len] = '\0';
2816
Willy Tarreau075415a2013-12-12 11:29:39 +01002817 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002818 return 0;
2819
Willy Tarreau075415a2013-12-12 11:29:39 +01002820 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002821 return 1;
2822}
2823
Willy Tarreauacf95772010-06-14 19:09:21 +02002824/* To be used to quote config arg positions. Returns the short string at <ptr>
2825 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2826 * if ptr is NULL or empty. The string is locally allocated.
2827 */
2828const char *quote_arg(const char *ptr)
2829{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002830 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002831 int i;
2832
2833 if (!ptr || !*ptr)
2834 return "end of line";
2835 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002836 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002837 val[i] = *ptr++;
2838 val[i++] = '\'';
2839 val[i] = '\0';
2840 return val;
2841}
2842
Willy Tarreau5b180202010-07-18 10:40:48 +02002843/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2844int get_std_op(const char *str)
2845{
2846 int ret = -1;
2847
2848 if (*str == 'e' && str[1] == 'q')
2849 ret = STD_OP_EQ;
2850 else if (*str == 'n' && str[1] == 'e')
2851 ret = STD_OP_NE;
2852 else if (*str == 'l') {
2853 if (str[1] == 'e') ret = STD_OP_LE;
2854 else if (str[1] == 't') ret = STD_OP_LT;
2855 }
2856 else if (*str == 'g') {
2857 if (str[1] == 'e') ret = STD_OP_GE;
2858 else if (str[1] == 't') ret = STD_OP_GT;
2859 }
2860
2861 if (ret == -1 || str[2] != '\0')
2862 return -1;
2863 return ret;
2864}
2865
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002866/* hash a 32-bit integer to another 32-bit integer */
2867unsigned int full_hash(unsigned int a)
2868{
2869 return __full_hash(a);
2870}
2871
Willy Tarreauf3241112019-02-26 09:56:22 +01002872/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2873 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2874 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2875 * a popcount variant and is described here :
2876 * https://graphics.stanford.edu/~seander/bithacks.html
2877 */
2878unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2879{
2880 unsigned long a, b, c, d;
2881 unsigned int s;
2882 unsigned int t;
2883
2884 a = m - ((m >> 1) & ~0UL/3);
2885 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2886 c = (b + (b >> 4)) & ~0UL/0x11;
2887 d = (c + (c >> 8)) & ~0UL/0x101;
2888
2889 r++; // make r be 1..64
2890
2891 t = 0;
2892 s = LONGBITS;
2893 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002894 unsigned long d2 = (d >> 16) >> 16;
2895 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002896 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2897 }
2898
2899 t = (d >> (s - 16)) & 0xff;
2900 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2901 t = (c >> (s - 8)) & 0xf;
2902 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2903 t = (b >> (s - 4)) & 0x7;
2904 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2905 t = (a >> (s - 2)) & 0x3;
2906 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2907 t = (m >> (s - 1)) & 0x1;
2908 s -= ((t - r) & 256) >> 8;
2909
2910 return s - 1;
2911}
2912
2913/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2914 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2915 * using mask_prep_rank_map() below.
2916 */
2917unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2918 unsigned long a, unsigned long b,
2919 unsigned long c, unsigned long d)
2920{
2921 unsigned int s;
2922 unsigned int t;
2923
2924 r++; // make r be 1..64
2925
2926 t = 0;
2927 s = LONGBITS;
2928 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002929 unsigned long d2 = (d >> 16) >> 16;
2930 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002931 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2932 }
2933
2934 t = (d >> (s - 16)) & 0xff;
2935 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2936 t = (c >> (s - 8)) & 0xf;
2937 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2938 t = (b >> (s - 4)) & 0x7;
2939 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2940 t = (a >> (s - 2)) & 0x3;
2941 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2942 t = (m >> (s - 1)) & 0x1;
2943 s -= ((t - r) & 256) >> 8;
2944
2945 return s - 1;
2946}
2947
2948/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2949 * above.
2950 */
2951void mask_prep_rank_map(unsigned long m,
2952 unsigned long *a, unsigned long *b,
2953 unsigned long *c, unsigned long *d)
2954{
2955 *a = m - ((m >> 1) & ~0UL/3);
2956 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2957 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2958 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2959}
2960
David du Colombier4f92d322011-03-24 11:09:31 +01002961/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002962 * otherwise zero. Note that <addr> may not necessarily be aligned
2963 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002964 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002965int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002966{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002967 struct in_addr addr_copy;
2968
2969 memcpy(&addr_copy, addr, sizeof(addr_copy));
2970 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002971}
2972
2973/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002974 * otherwise zero. Note that <addr> may not necessarily be aligned
2975 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002976 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002977int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002978{
2979 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002980 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002981
Willy Tarreaueec1d382016-07-13 11:59:39 +02002982 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002983 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002984 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002985 (((int *)net)[i] & ((int *)mask)[i]))
2986 return 0;
2987 return 1;
2988}
2989
2990/* RFC 4291 prefix */
2991const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2992 0x00, 0x00, 0x00, 0x00,
2993 0x00, 0x00, 0xFF, 0xFF };
2994
Joseph Herlant32b83272018-11-15 11:58:28 -08002995/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002996 * Input and output may overlap.
2997 */
David du Colombier4f92d322011-03-24 11:09:31 +01002998void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2999{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003000 struct in_addr tmp_addr;
3001
3002 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003003 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003004 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003005}
3006
Joseph Herlant32b83272018-11-15 11:58:28 -08003007/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003008 * Return true if conversion is possible and false otherwise.
3009 */
3010int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3011{
3012 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3013 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3014 sizeof(struct in_addr));
3015 return 1;
3016 }
3017
3018 return 0;
3019}
3020
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003021/* compare two struct sockaddr_storage and return:
3022 * 0 (true) if the addr is the same in both
3023 * 1 (false) if the addr is not the same in both
3024 * -1 (unable) if one of the addr is not AF_INET*
3025 */
3026int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3027{
3028 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3029 return -1;
3030
3031 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3032 return -1;
3033
3034 if (ss1->ss_family != ss2->ss_family)
3035 return 1;
3036
3037 switch (ss1->ss_family) {
3038 case AF_INET:
3039 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3040 &((struct sockaddr_in *)ss2)->sin_addr,
3041 sizeof(struct in_addr)) != 0;
3042 case AF_INET6:
3043 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3044 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3045 sizeof(struct in6_addr)) != 0;
3046 }
3047
3048 return 1;
3049}
3050
Baptiste Assmann08396c82016-01-31 00:27:17 +01003051/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003052 * The caller must allocate and clear <dest> before calling.
3053 * The source must be in either AF_INET or AF_INET6 family, or the destination
3054 * address will be undefined. If the destination address used to hold a port,
3055 * it is preserved, so that this function can be used to switch to another
3056 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003057 */
3058struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3059{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003060 int prev_port;
3061
3062 prev_port = get_net_port(dest);
3063 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003064 dest->ss_family = source->ss_family;
3065
3066 /* copy new addr and apply it */
3067 switch (source->ss_family) {
3068 case AF_INET:
3069 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003070 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003071 break;
3072 case AF_INET6:
3073 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 +01003074 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003075 break;
3076 }
3077
3078 return dest;
3079}
3080
William Lallemand421f5b52012-02-06 18:15:57 +01003081char *human_time(int t, short hz_div) {
3082 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3083 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003084 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003085 int cnt=2; // print two numbers
3086
3087 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003088 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003089 return rv;
3090 }
3091
3092 if (unlikely(hz_div > 1))
3093 t /= hz_div;
3094
3095 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003096 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003097 cnt--;
3098 }
3099
3100 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003101 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003102 cnt--;
3103 }
3104
3105 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003106 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003107 cnt--;
3108 }
3109
3110 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003111 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003112
3113 return rv;
3114}
3115
3116const char *monthname[12] = {
3117 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3118 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3119};
3120
3121/* date2str_log: write a date in the format :
3122 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3123 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3124 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3125 *
3126 * without using sprintf. return a pointer to the last char written (\0) or
3127 * NULL if there isn't enough space.
3128 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003129char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003130{
3131
3132 if (size < 25) /* the size is fixed: 24 chars + \0 */
3133 return NULL;
3134
3135 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003136 if (!dst)
3137 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003138 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003139
William Lallemand421f5b52012-02-06 18:15:57 +01003140 memcpy(dst, monthname[tm->tm_mon], 3); // month
3141 dst += 3;
3142 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003143
William Lallemand421f5b52012-02-06 18:15:57 +01003144 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003145 if (!dst)
3146 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003147 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003148
William Lallemand421f5b52012-02-06 18:15:57 +01003149 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003150 if (!dst)
3151 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003152 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003153
William Lallemand421f5b52012-02-06 18:15:57 +01003154 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003155 if (!dst)
3156 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003157 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003158
William Lallemand421f5b52012-02-06 18:15:57 +01003159 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003160 if (!dst)
3161 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003162 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003163
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003164 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003165 if (!dst)
3166 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003167 *dst = '\0';
3168
3169 return dst;
3170}
3171
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003172/* Base year used to compute leap years */
3173#define TM_YEAR_BASE 1900
3174
3175/* Return the difference in seconds between two times (leap seconds are ignored).
3176 * Retrieved from glibc 2.18 source code.
3177 */
3178static int my_tm_diff(const struct tm *a, const struct tm *b)
3179{
3180 /* Compute intervening leap days correctly even if year is negative.
3181 * Take care to avoid int overflow in leap day calculations,
3182 * but it's OK to assume that A and B are close to each other.
3183 */
3184 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3185 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3186 int a100 = a4 / 25 - (a4 % 25 < 0);
3187 int b100 = b4 / 25 - (b4 % 25 < 0);
3188 int a400 = a100 >> 2;
3189 int b400 = b100 >> 2;
3190 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3191 int years = a->tm_year - b->tm_year;
3192 int days = (365 * years + intervening_leap_days
3193 + (a->tm_yday - b->tm_yday));
3194 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3195 + (a->tm_min - b->tm_min))
3196 + (a->tm_sec - b->tm_sec));
3197}
3198
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003199/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003200 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003201 * The string returned has the same format as returned by strftime(... "%z", tm).
3202 * Offsets are kept in an internal cache for better performances.
3203 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003204const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003205{
3206 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003207 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003208
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003209 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003210 struct tm tm_gmt;
3211 int diff;
3212 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003213
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003214 /* Pretend DST not active if its status is unknown */
3215 if (isdst < 0)
3216 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003217
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003218 /* Fetch the offset and initialize it if needed */
3219 gmt_offset = gmt_offsets[isdst & 0x01];
3220 if (unlikely(!*gmt_offset)) {
3221 get_gmtime(t, &tm_gmt);
3222 diff = my_tm_diff(tm, &tm_gmt);
3223 if (diff < 0) {
3224 diff = -diff;
3225 *gmt_offset = '-';
3226 } else {
3227 *gmt_offset = '+';
3228 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003229 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003230 diff /= 60; /* Convert to minutes */
3231 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3232 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003233
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003234 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003235}
3236
William Lallemand421f5b52012-02-06 18:15:57 +01003237/* gmt2str_log: write a date in the format :
3238 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3239 * return a pointer to the last char written (\0) or
3240 * NULL if there isn't enough space.
3241 */
3242char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3243{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003244 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003245 return NULL;
3246
3247 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003248 if (!dst)
3249 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003250 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003251
William Lallemand421f5b52012-02-06 18:15:57 +01003252 memcpy(dst, monthname[tm->tm_mon], 3); // month
3253 dst += 3;
3254 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003255
William Lallemand421f5b52012-02-06 18:15:57 +01003256 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003257 if (!dst)
3258 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003259 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003260
William Lallemand421f5b52012-02-06 18:15:57 +01003261 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003262 if (!dst)
3263 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003264 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003265
William Lallemand421f5b52012-02-06 18:15:57 +01003266 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003267 if (!dst)
3268 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003269 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003270
William Lallemand421f5b52012-02-06 18:15:57 +01003271 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003272 if (!dst)
3273 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003274 *dst++ = ' ';
3275 *dst++ = '+';
3276 *dst++ = '0';
3277 *dst++ = '0';
3278 *dst++ = '0';
3279 *dst++ = '0';
3280 *dst = '\0';
3281
3282 return dst;
3283}
3284
Yuxans Yao4e25b012012-10-19 10:36:09 +08003285/* localdate2str_log: write a date in the format :
3286 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003287 * Both t and tm must represent the same time.
3288 * return a pointer to the last char written (\0) or
3289 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003290 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003291char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003292{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003293 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003294 if (size < 27) /* the size is fixed: 26 chars + \0 */
3295 return NULL;
3296
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003297 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003298
Yuxans Yao4e25b012012-10-19 10:36:09 +08003299 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003300 if (!dst)
3301 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003302 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003303
Yuxans Yao4e25b012012-10-19 10:36:09 +08003304 memcpy(dst, monthname[tm->tm_mon], 3); // month
3305 dst += 3;
3306 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003307
Yuxans Yao4e25b012012-10-19 10:36:09 +08003308 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003309 if (!dst)
3310 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003311 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003312
Yuxans Yao4e25b012012-10-19 10:36:09 +08003313 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003314 if (!dst)
3315 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003316 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003317
Yuxans Yao4e25b012012-10-19 10:36:09 +08003318 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003319 if (!dst)
3320 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003321 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003322
Yuxans Yao4e25b012012-10-19 10:36:09 +08003323 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003324 if (!dst)
3325 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003326 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003327
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003328 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003329 dst += 5;
3330 *dst = '\0';
3331
3332 return dst;
3333}
3334
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003335/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3336 * It is meant as a portable replacement for timegm() for use with valid inputs.
3337 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3338 */
3339time_t my_timegm(const struct tm *tm)
3340{
3341 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3342 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3343 * sum of the extra N days for elapsed months. The sum of all these N
3344 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3345 * in a 5-bit word. This means that with 60 bits we can represent a
3346 * matrix of all these values at once, which is fast and efficient to
3347 * access. The extra February day for leap years is not counted here.
3348 *
3349 * Jan : none = 0 (0)
3350 * Feb : Jan = 3 (3)
3351 * Mar : Jan..Feb = 3 (3 + 0)
3352 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3353 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3354 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3355 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3356 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3357 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3358 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3359 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3360 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3361 */
3362 uint64_t extra =
3363 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3364 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3365 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3366 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3367
3368 unsigned int y = tm->tm_year + 1900;
3369 unsigned int m = tm->tm_mon;
3370 unsigned long days = 0;
3371
3372 /* days since 1/1/1970 for full years */
3373 days += days_since_zero(y) - days_since_zero(1970);
3374
3375 /* days for full months in the current year */
3376 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3377
3378 /* count + 1 after March for leap years. A leap year is a year multiple
3379 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3380 * is leap, 1900 isn't, 1904 is.
3381 */
3382 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3383 days++;
3384
3385 days += tm->tm_mday - 1;
3386 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3387}
3388
Thierry Fournier93127942016-01-20 18:49:45 +01003389/* This function check a char. It returns true and updates
3390 * <date> and <len> pointer to the new position if the
3391 * character is found.
3392 */
3393static inline int parse_expect_char(const char **date, int *len, char c)
3394{
3395 if (*len < 1 || **date != c)
3396 return 0;
3397 (*len)--;
3398 (*date)++;
3399 return 1;
3400}
3401
3402/* This function expects a string <str> of len <l>. It return true and updates.
3403 * <date> and <len> if the string matches, otherwise, it returns false.
3404 */
3405static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3406{
3407 if (*len < l || strncmp(*date, str, l) != 0)
3408 return 0;
3409 (*len) -= l;
3410 (*date) += l;
3411 return 1;
3412}
3413
3414/* This macro converts 3 chars name in integer. */
3415#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3416
3417/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3418 * / %x54.75.65 ; "Tue", case-sensitive
3419 * / %x57.65.64 ; "Wed", case-sensitive
3420 * / %x54.68.75 ; "Thu", case-sensitive
3421 * / %x46.72.69 ; "Fri", case-sensitive
3422 * / %x53.61.74 ; "Sat", case-sensitive
3423 * / %x53.75.6E ; "Sun", case-sensitive
3424 *
3425 * This array must be alphabetically sorted
3426 */
3427static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3428{
3429 if (*len < 3)
3430 return 0;
3431 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3432 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3433 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3434 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3435 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3436 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3437 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3438 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3439 default: return 0;
3440 }
3441 *len -= 3;
3442 *date += 3;
3443 return 1;
3444}
3445
3446/* month = %x4A.61.6E ; "Jan", case-sensitive
3447 * / %x46.65.62 ; "Feb", case-sensitive
3448 * / %x4D.61.72 ; "Mar", case-sensitive
3449 * / %x41.70.72 ; "Apr", case-sensitive
3450 * / %x4D.61.79 ; "May", case-sensitive
3451 * / %x4A.75.6E ; "Jun", case-sensitive
3452 * / %x4A.75.6C ; "Jul", case-sensitive
3453 * / %x41.75.67 ; "Aug", case-sensitive
3454 * / %x53.65.70 ; "Sep", case-sensitive
3455 * / %x4F.63.74 ; "Oct", case-sensitive
3456 * / %x4E.6F.76 ; "Nov", case-sensitive
3457 * / %x44.65.63 ; "Dec", case-sensitive
3458 *
3459 * This array must be alphabetically sorted
3460 */
3461static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3462{
3463 if (*len < 3)
3464 return 0;
3465 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3466 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3467 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3468 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3469 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3470 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3471 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3472 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3473 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3474 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3475 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3476 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3477 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3478 default: return 0;
3479 }
3480 *len -= 3;
3481 *date += 3;
3482 return 1;
3483}
3484
3485/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3486 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3487 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3488 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3489 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3490 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3491 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3492 *
3493 * This array must be alphabetically sorted
3494 */
3495static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3496{
3497 if (*len < 6) /* Minimum length. */
3498 return 0;
3499 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3500 case STR2I3('M','o','n'):
3501 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3502 tm->tm_wday = 1;
3503 return 1;
3504 case STR2I3('T','u','e'):
3505 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3506 tm->tm_wday = 2;
3507 return 1;
3508 case STR2I3('W','e','d'):
3509 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3510 tm->tm_wday = 3;
3511 return 1;
3512 case STR2I3('T','h','u'):
3513 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3514 tm->tm_wday = 4;
3515 return 1;
3516 case STR2I3('F','r','i'):
3517 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3518 tm->tm_wday = 5;
3519 return 1;
3520 case STR2I3('S','a','t'):
3521 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3522 tm->tm_wday = 6;
3523 return 1;
3524 case STR2I3('S','u','n'):
3525 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3526 tm->tm_wday = 7;
3527 return 1;
3528 }
3529 return 0;
3530}
3531
3532/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3533static inline int parse_digit(const char **date, int *len, int *digit)
3534{
3535 if (*len < 1 || **date < '0' || **date > '9')
3536 return 0;
3537 *digit = (**date - '0');
3538 (*date)++;
3539 (*len)--;
3540 return 1;
3541}
3542
3543/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3544static inline int parse_2digit(const char **date, int *len, int *digit)
3545{
3546 int value;
3547
3548 RET0_UNLESS(parse_digit(date, len, &value));
3549 (*digit) = value * 10;
3550 RET0_UNLESS(parse_digit(date, len, &value));
3551 (*digit) += value;
3552
3553 return 1;
3554}
3555
3556/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3557static inline int parse_4digit(const char **date, int *len, int *digit)
3558{
3559 int value;
3560
3561 RET0_UNLESS(parse_digit(date, len, &value));
3562 (*digit) = value * 1000;
3563
3564 RET0_UNLESS(parse_digit(date, len, &value));
3565 (*digit) += value * 100;
3566
3567 RET0_UNLESS(parse_digit(date, len, &value));
3568 (*digit) += value * 10;
3569
3570 RET0_UNLESS(parse_digit(date, len, &value));
3571 (*digit) += value;
3572
3573 return 1;
3574}
3575
3576/* time-of-day = hour ":" minute ":" second
3577 * ; 00:00:00 - 23:59:60 (leap second)
3578 *
3579 * hour = 2DIGIT
3580 * minute = 2DIGIT
3581 * second = 2DIGIT
3582 */
3583static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3584{
3585 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3586 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3587 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3588 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3589 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3590 return 1;
3591}
3592
3593/* From RFC7231
3594 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3595 *
3596 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3597 * ; fixed length/zone/capitalization subset of the format
3598 * ; see Section 3.3 of [RFC5322]
3599 *
3600 *
3601 * date1 = day SP month SP year
3602 * ; e.g., 02 Jun 1982
3603 *
3604 * day = 2DIGIT
3605 * year = 4DIGIT
3606 *
3607 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3608 *
3609 * time-of-day = hour ":" minute ":" second
3610 * ; 00:00:00 - 23:59:60 (leap second)
3611 *
3612 * hour = 2DIGIT
3613 * minute = 2DIGIT
3614 * second = 2DIGIT
3615 *
3616 * DIGIT = decimal 0-9
3617 */
3618int parse_imf_date(const char *date, int len, struct tm *tm)
3619{
David Carlier327298c2016-11-20 10:42:38 +00003620 /* tm_gmtoff, if present, ought to be zero'ed */
3621 memset(tm, 0, sizeof(*tm));
3622
Thierry Fournier93127942016-01-20 18:49:45 +01003623 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3624 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3625 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3626 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3627 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3628 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3629 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3630 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3631 tm->tm_year -= 1900;
3632 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3633 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3634 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3635 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3636 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003637 return 1;
3638}
3639
3640/* From RFC7231
3641 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3642 *
3643 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3644 * date2 = day "-" month "-" 2DIGIT
3645 * ; e.g., 02-Jun-82
3646 *
3647 * day = 2DIGIT
3648 */
3649int parse_rfc850_date(const char *date, int len, struct tm *tm)
3650{
3651 int year;
3652
David Carlier327298c2016-11-20 10:42:38 +00003653 /* tm_gmtoff, if present, ought to be zero'ed */
3654 memset(tm, 0, sizeof(*tm));
3655
Thierry Fournier93127942016-01-20 18:49:45 +01003656 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3657 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3658 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3659 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3660 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3661 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3662 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3663
3664 /* year = 2DIGIT
3665 *
3666 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3667 * two-digit year, MUST interpret a timestamp that appears to be more
3668 * than 50 years in the future as representing the most recent year in
3669 * the past that had the same last two digits.
3670 */
3671 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3672
3673 /* expect SP */
3674 if (!parse_expect_char(&date, &len, ' ')) {
3675 /* Maybe we have the date with 4 digits. */
3676 RET0_UNLESS(parse_2digit(&date, &len, &year));
3677 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3678 /* expect SP */
3679 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3680 } else {
3681 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3682 * tm_year is the number of year since 1900, so for +1900, we
3683 * do nothing, and for +2000, we add 100.
3684 */
3685 if (tm->tm_year <= 60)
3686 tm->tm_year += 100;
3687 }
3688
3689 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3690 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3691 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3692 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003693
3694 return 1;
3695}
3696
3697/* From RFC7231
3698 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3699 *
3700 * asctime-date = day-name SP date3 SP time-of-day SP year
3701 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3702 * ; e.g., Jun 2
3703 *
3704 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3705 * whitespace in an HTTP-date beyond that specifically included as SP in
3706 * the grammar.
3707 */
3708int parse_asctime_date(const char *date, int len, struct tm *tm)
3709{
David Carlier327298c2016-11-20 10:42:38 +00003710 /* tm_gmtoff, if present, ought to be zero'ed */
3711 memset(tm, 0, sizeof(*tm));
3712
Thierry Fournier93127942016-01-20 18:49:45 +01003713 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3714 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3715 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3716 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3717
3718 /* expect SP and 1DIGIT or 2DIGIT */
3719 if (parse_expect_char(&date, &len, ' '))
3720 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3721 else
3722 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3723
3724 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3725 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3726 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3727 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3728 tm->tm_year -= 1900;
3729 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003730 return 1;
3731}
3732
3733/* From RFC7231
3734 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3735 *
3736 * HTTP-date = IMF-fixdate / obs-date
3737 * obs-date = rfc850-date / asctime-date
3738 *
3739 * parses an HTTP date in the RFC format and is accepted
3740 * alternatives. <date> is the strinf containing the date,
3741 * len is the len of the string. <tm> is filled with the
3742 * parsed time. We must considers this time as GMT.
3743 */
3744int parse_http_date(const char *date, int len, struct tm *tm)
3745{
3746 if (parse_imf_date(date, len, tm))
3747 return 1;
3748
3749 if (parse_rfc850_date(date, len, tm))
3750 return 1;
3751
3752 if (parse_asctime_date(date, len, tm))
3753 return 1;
3754
3755 return 0;
3756}
3757
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003758/* Dynamically allocates a string of the proper length to hold the formatted
3759 * output. NULL is returned on error. The caller is responsible for freeing the
3760 * memory area using free(). The resulting string is returned in <out> if the
3761 * pointer is not NULL. A previous version of <out> might be used to build the
3762 * new string, and it will be freed before returning if it is not NULL, which
3763 * makes it possible to build complex strings from iterative calls without
3764 * having to care about freeing intermediate values, as in the example below :
3765 *
3766 * memprintf(&err, "invalid argument: '%s'", arg);
3767 * ...
3768 * memprintf(&err, "parser said : <%s>\n", *err);
3769 * ...
3770 * free(*err);
3771 *
3772 * This means that <err> must be initialized to NULL before first invocation.
3773 * The return value also holds the allocated string, which eases error checking
3774 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003775 * passed instead and it will be ignored. The returned message will then also
3776 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003777 *
3778 * It is also convenient to use it without any free except the last one :
3779 * err = NULL;
3780 * if (!fct1(err)) report(*err);
3781 * if (!fct2(err)) report(*err);
3782 * if (!fct3(err)) report(*err);
3783 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003784 *
3785 * memprintf relies on memvprintf. This last version can be called from any
3786 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003787 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003788char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003789{
3790 va_list args;
3791 char *ret = NULL;
3792 int allocated = 0;
3793 int needed = 0;
3794
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003795 if (!out)
3796 return NULL;
3797
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003798 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003799 char buf1;
3800
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003801 /* vsnprintf() will return the required length even when the
3802 * target buffer is NULL. We do this in a loop just in case
3803 * intermediate evaluations get wrong.
3804 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003805 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003806 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003807 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003808 if (needed < allocated) {
3809 /* Note: on Solaris 8, the first iteration always
3810 * returns -1 if allocated is zero, so we force a
3811 * retry.
3812 */
3813 if (!allocated)
3814 needed = 0;
3815 else
3816 break;
3817 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003818
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003819 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003820 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003821 } while (ret);
3822
3823 if (needed < 0) {
3824 /* an error was encountered */
3825 free(ret);
3826 ret = NULL;
3827 }
3828
3829 if (out) {
3830 free(*out);
3831 *out = ret;
3832 }
3833
3834 return ret;
3835}
William Lallemand421f5b52012-02-06 18:15:57 +01003836
Christopher Faulet93a518f2017-10-24 11:25:33 +02003837char *memprintf(char **out, const char *format, ...)
3838{
3839 va_list args;
3840 char *ret = NULL;
3841
3842 va_start(args, format);
3843 ret = memvprintf(out, format, args);
3844 va_end(args);
3845
3846 return ret;
3847}
3848
Willy Tarreau21c705b2012-09-14 11:40:36 +02003849/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3850 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003851 * freed by the caller. It also supports being passed a NULL which results in the same
3852 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003853 * Example of use :
3854 * parse(cmd, &err); (callee: memprintf(&err, ...))
3855 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3856 * free(err);
3857 */
3858char *indent_msg(char **out, int level)
3859{
3860 char *ret, *in, *p;
3861 int needed = 0;
3862 int lf = 0;
3863 int lastlf = 0;
3864 int len;
3865
Willy Tarreau70eec382012-10-10 08:56:47 +02003866 if (!out || !*out)
3867 return NULL;
3868
Willy Tarreau21c705b2012-09-14 11:40:36 +02003869 in = *out - 1;
3870 while ((in = strchr(in + 1, '\n')) != NULL) {
3871 lastlf = in - *out;
3872 lf++;
3873 }
3874
3875 if (!lf) /* single line, no LF, return it as-is */
3876 return *out;
3877
3878 len = strlen(*out);
3879
3880 if (lf == 1 && lastlf == len - 1) {
3881 /* single line, LF at end, strip it and return as-is */
3882 (*out)[lastlf] = 0;
3883 return *out;
3884 }
3885
3886 /* OK now we have at least one LF, we need to process the whole string
3887 * as a multi-line string. What we'll do :
3888 * - prefix with an LF if there is none
3889 * - add <level> spaces before each line
3890 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3891 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3892 */
3893
3894 needed = 1 + level * (lf + 1) + len + 1;
3895 p = ret = malloc(needed);
3896 in = *out;
3897
3898 /* skip initial LFs */
3899 while (*in == '\n')
3900 in++;
3901
3902 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3903 while (*in) {
3904 *p++ = '\n';
3905 memset(p, ' ', level);
3906 p += level;
3907 do {
3908 *p++ = *in++;
3909 } while (*in && *in != '\n');
3910 if (*in)
3911 in++;
3912 }
3913 *p = 0;
3914
3915 free(*out);
3916 *out = ret;
3917
3918 return ret;
3919}
3920
Willy Tarreaua2c99112019-08-21 13:17:37 +02003921/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3922 * and end of lines replaced with <eol> if not 0. The first line to indent has
3923 * to be indicated in <first> (starts at zero), so that it is possible to skip
3924 * indenting the first line if it has to be appended after an existing message.
3925 * Empty strings are never indented, and NULL strings are considered empty both
3926 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3927 * character, non-zero otherwise.
3928 */
3929int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3930{
3931 int bol, lf;
3932 int pfxlen = pfx ? strlen(pfx) : 0;
3933
3934 if (!in)
3935 return 0;
3936
3937 bol = 1;
3938 lf = 0;
3939 while (*in) {
3940 if (bol && pfxlen) {
3941 if (first > 0)
3942 first--;
3943 else
3944 b_putblk(out, pfx, pfxlen);
3945 bol = 0;
3946 }
3947
3948 lf = (*in == '\n');
3949 bol |= lf;
3950 b_putchr(out, (lf && eol) ? eol : *in);
3951 in++;
3952 }
3953 return lf;
3954}
3955
Willy Tarreau9d22e562019-03-29 18:49:09 +01003956/* removes environment variable <name> from the environment as found in
3957 * environ. This is only provided as an alternative for systems without
3958 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003959 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003960 * <name> and to replace the matching pointers with the last pointer of
3961 * the array (since variables are not ordered).
3962 * It always returns 0 (success).
3963 */
3964int my_unsetenv(const char *name)
3965{
3966 extern char **environ;
3967 char **p = environ;
3968 int vars;
3969 int next;
3970 int len;
3971
3972 len = strlen(name);
3973 for (vars = 0; p[vars]; vars++)
3974 ;
3975 next = 0;
3976 while (next < vars) {
3977 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3978 next++;
3979 continue;
3980 }
3981 if (next < vars - 1)
3982 p[next] = p[vars - 1];
3983 p[--vars] = NULL;
3984 }
3985 return 0;
3986}
3987
Willy Tarreaudad36a32013-03-11 01:20:04 +01003988/* Convert occurrences of environment variables in the input string to their
3989 * corresponding value. A variable is identified as a series of alphanumeric
3990 * characters or underscores following a '$' sign. The <in> string must be
3991 * free()able. NULL returns NULL. The resulting string might be reallocated if
3992 * some expansion is made. Variable names may also be enclosed into braces if
3993 * needed (eg: to concatenate alphanum characters).
3994 */
3995char *env_expand(char *in)
3996{
3997 char *txt_beg;
3998 char *out;
3999 char *txt_end;
4000 char *var_beg;
4001 char *var_end;
4002 char *value;
4003 char *next;
4004 int out_len;
4005 int val_len;
4006
4007 if (!in)
4008 return in;
4009
4010 value = out = NULL;
4011 out_len = 0;
4012
4013 txt_beg = in;
4014 do {
4015 /* look for next '$' sign in <in> */
4016 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4017
4018 if (!*txt_end && !out) /* end and no expansion performed */
4019 return in;
4020
4021 val_len = 0;
4022 next = txt_end;
4023 if (*txt_end == '$') {
4024 char save;
4025
4026 var_beg = txt_end + 1;
4027 if (*var_beg == '{')
4028 var_beg++;
4029
4030 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004031 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004032 var_end++;
4033 }
4034
4035 next = var_end;
4036 if (*var_end == '}' && (var_beg > txt_end + 1))
4037 next++;
4038
4039 /* get value of the variable name at this location */
4040 save = *var_end;
4041 *var_end = '\0';
4042 value = getenv(var_beg);
4043 *var_end = save;
4044 val_len = value ? strlen(value) : 0;
4045 }
4046
Hubert Verstraete831962e2016-06-28 22:44:26 +02004047 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004048 if (txt_end > txt_beg) {
4049 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4050 out_len += txt_end - txt_beg;
4051 }
4052 if (val_len) {
4053 memcpy(out + out_len, value, val_len);
4054 out_len += val_len;
4055 }
4056 out[out_len] = 0;
4057 txt_beg = next;
4058 } while (*txt_beg);
4059
4060 /* here we know that <out> was allocated and that we don't need <in> anymore */
4061 free(in);
4062 return out;
4063}
4064
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004065
4066/* same as strstr() but case-insensitive and with limit length */
4067const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4068{
4069 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004070 unsigned int slen, plen;
4071 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004072
4073 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4074 return NULL;
4075
4076 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4077 return str1;
4078
4079 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4080 return NULL;
4081
4082 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
Willy Tarreauf278eec2020-07-05 21:46:32 +02004083 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004084 start++;
4085 slen--;
4086 tmp1++;
4087
4088 if (tmp1 >= len_str1)
4089 return NULL;
4090
4091 /* if pattern longer than string */
4092 if (slen < plen)
4093 return NULL;
4094 }
4095
4096 sptr = start;
4097 pptr = (char *)str2;
4098
4099 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004100 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004101 sptr++;
4102 pptr++;
4103 tmp2++;
4104
4105 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4106 return start;
4107 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4108 return NULL;
4109 }
4110 }
4111 return NULL;
4112}
4113
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004114/* This function read the next valid utf8 char.
4115 * <s> is the byte srray to be decode, <len> is its length.
4116 * The function returns decoded char encoded like this:
4117 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4118 * are the length read. The decoded character is stored in <c>.
4119 */
4120unsigned char utf8_next(const char *s, int len, unsigned int *c)
4121{
4122 const unsigned char *p = (unsigned char *)s;
4123 int dec;
4124 unsigned char code = UTF8_CODE_OK;
4125
4126 if (len < 1)
4127 return UTF8_CODE_OK;
4128
4129 /* Check the type of UTF8 sequence
4130 *
4131 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4132 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4133 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4134 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4135 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4136 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4137 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4138 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4139 */
4140 switch (*p) {
4141 case 0x00 ... 0x7f:
4142 *c = *p;
4143 return UTF8_CODE_OK | 1;
4144
4145 case 0x80 ... 0xbf:
4146 *c = *p;
4147 return UTF8_CODE_BADSEQ | 1;
4148
4149 case 0xc0 ... 0xdf:
4150 if (len < 2) {
4151 *c = *p;
4152 return UTF8_CODE_BADSEQ | 1;
4153 }
4154 *c = *p & 0x1f;
4155 dec = 1;
4156 break;
4157
4158 case 0xe0 ... 0xef:
4159 if (len < 3) {
4160 *c = *p;
4161 return UTF8_CODE_BADSEQ | 1;
4162 }
4163 *c = *p & 0x0f;
4164 dec = 2;
4165 break;
4166
4167 case 0xf0 ... 0xf7:
4168 if (len < 4) {
4169 *c = *p;
4170 return UTF8_CODE_BADSEQ | 1;
4171 }
4172 *c = *p & 0x07;
4173 dec = 3;
4174 break;
4175
4176 case 0xf8 ... 0xfb:
4177 if (len < 5) {
4178 *c = *p;
4179 return UTF8_CODE_BADSEQ | 1;
4180 }
4181 *c = *p & 0x03;
4182 dec = 4;
4183 break;
4184
4185 case 0xfc ... 0xfd:
4186 if (len < 6) {
4187 *c = *p;
4188 return UTF8_CODE_BADSEQ | 1;
4189 }
4190 *c = *p & 0x01;
4191 dec = 5;
4192 break;
4193
4194 case 0xfe ... 0xff:
4195 default:
4196 *c = *p;
4197 return UTF8_CODE_BADSEQ | 1;
4198 }
4199
4200 p++;
4201
4202 while (dec > 0) {
4203
4204 /* need 0x10 for the 2 first bits */
4205 if ( ( *p & 0xc0 ) != 0x80 )
4206 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4207
4208 /* add data at char */
4209 *c = ( *c << 6 ) | ( *p & 0x3f );
4210
4211 dec--;
4212 p++;
4213 }
4214
4215 /* Check ovelong encoding.
4216 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4217 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4218 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4219 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004220 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004221 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4222 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4223 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4224 code |= UTF8_CODE_OVERLONG;
4225
4226 /* Check invalid UTF8 range. */
4227 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4228 (*c >= 0xfffe && *c <= 0xffff))
4229 code |= UTF8_CODE_INVRANGE;
4230
4231 return code | ((p-(unsigned char *)s)&0x0f);
4232}
4233
Maxime de Roucydc887852016-05-13 23:52:54 +02004234/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4235 * On failure : return 0 and <err> filled with an error message.
4236 * The caller is responsible for freeing the <err> and <str> copy
4237 * memory area using free()
4238 */
4239int list_append_word(struct list *li, const char *str, char **err)
4240{
4241 struct wordlist *wl;
4242
4243 wl = calloc(1, sizeof(*wl));
4244 if (!wl) {
4245 memprintf(err, "out of memory");
4246 goto fail_wl;
4247 }
4248
4249 wl->s = strdup(str);
4250 if (!wl->s) {
4251 memprintf(err, "out of memory");
4252 goto fail_wl_s;
4253 }
4254
4255 LIST_ADDQ(li, &wl->list);
4256
4257 return 1;
4258
4259fail_wl_s:
4260 free(wl->s);
4261fail_wl:
4262 free(wl);
4263 return 0;
4264}
4265
Willy Tarreau37101052019-05-20 16:48:20 +02004266/* indicates if a memory location may safely be read or not. The trick consists
4267 * in performing a harmless syscall using this location as an input and letting
4268 * the operating system report whether it's OK or not. For this we have the
4269 * stat() syscall, which will return EFAULT when the memory location supposed
4270 * to contain the file name is not readable. If it is readable it will then
4271 * either return 0 if the area contains an existing file name, or -1 with
4272 * another code. This must not be abused, and some audit systems might detect
4273 * this as abnormal activity. It's used only for unsafe dumps.
4274 */
4275int may_access(const void *ptr)
4276{
4277 struct stat buf;
4278
4279 if (stat(ptr, &buf) == 0)
4280 return 1;
4281 if (errno == EFAULT)
4282 return 0;
4283 return 1;
4284}
4285
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004286/* print a string of text buffer to <out>. The format is :
4287 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4288 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4289 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4290 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004291int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004292{
4293 unsigned char c;
4294 int ptr = 0;
4295
4296 while (buf[ptr] && ptr < bsize) {
4297 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004298 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004299 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004300 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004301 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004302 }
4303 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004304 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004305 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004306 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004307 switch (c) {
4308 case ' ': c = ' '; break;
4309 case '\t': c = 't'; break;
4310 case '\n': c = 'n'; break;
4311 case '\r': c = 'r'; break;
4312 case '\e': c = 'e'; break;
4313 case '\\': c = '\\'; break;
4314 case '=': c = '='; break;
4315 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004316 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004317 }
4318 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004319 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004320 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004321 out->area[out->data++] = '\\';
4322 out->area[out->data++] = 'x';
4323 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4324 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004325 }
4326 ptr++;
4327 }
4328
4329 return ptr;
4330}
4331
4332/* print a buffer in hexa.
4333 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4334 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004335int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004336{
4337 unsigned char c;
4338 int ptr = 0;
4339
4340 while (ptr < bsize) {
4341 c = buf[ptr];
4342
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004343 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004344 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004345 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4346 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004347
4348 ptr++;
4349 }
4350 return ptr;
4351}
4352
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004353/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4354 * prepending each line with prefix <pfx>. The output is *not* initialized.
4355 * The output will not wrap pas the buffer's end so it is more optimal if the
4356 * caller makes sure the buffer is aligned first. A trailing zero will always
4357 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004358 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4359 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004360 */
Willy Tarreau37101052019-05-20 16:48:20 +02004361void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004362{
4363 const unsigned char *d = buf;
4364 int i, j, start;
4365
4366 d = (const unsigned char *)(((unsigned long)buf) & -16);
4367 start = ((unsigned long)buf) & 15;
4368
4369 for (i = 0; i < start + len; i += 16) {
4370 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4371
Willy Tarreau37101052019-05-20 16:48:20 +02004372 // 0: unchecked, 1: checked safe, 2: danger
4373 unsafe = !!unsafe;
4374 if (unsafe && !may_access(d + i))
4375 unsafe = 2;
4376
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004377 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004378 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004379 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004380 else if (unsafe > 1)
4381 chunk_strcat(out, "** ");
4382 else
4383 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004384
4385 if (j == 7)
4386 chunk_strcat(out, "- ");
4387 }
4388 chunk_strcat(out, " ");
4389 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004390 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004391 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004392 else if (unsafe > 1)
4393 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004394 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004395 chunk_appendf(out, "%c", d[i + j]);
4396 else
4397 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004398 }
4399 chunk_strcat(out, "\n");
4400 }
4401}
4402
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004403/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4404 * enclosed in brackets after the address itself, formatted on 14 chars
4405 * including the "0x" prefix. This is meant to be used as a prefix for code
4406 * areas. For example:
4407 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4408 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4409 * is emitted. A NULL <pfx> will be considered empty.
4410 */
4411void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4412{
4413 int ok = 0;
4414 int i;
4415
4416 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4417
4418 for (i = 0; i < n; i++) {
4419 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4420 ok = may_access(addr + i);
4421 if (ok)
4422 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4423 else
4424 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4425 }
4426}
4427
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004428/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4429 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4430 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4431 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4432 * lines are respected within the limit of 70 output chars. Lines that are
4433 * continuation of a previous truncated line begin with "+" instead of " "
4434 * after the offset. The new pointer is returned.
4435 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004436int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004437 int *line, int ptr)
4438{
4439 int end;
4440 unsigned char c;
4441
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004442 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004443 if (end > out->size)
4444 return ptr;
4445
4446 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4447
4448 while (ptr < len && ptr < bsize) {
4449 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004450 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004451 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004452 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004453 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004454 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004455 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004456 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004457 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004458 switch (c) {
4459 case '\t': c = 't'; break;
4460 case '\n': c = 'n'; break;
4461 case '\r': c = 'r'; break;
4462 case '\e': c = 'e'; break;
4463 case '\\': c = '\\'; break;
4464 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004465 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004466 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004467 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004468 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004469 out->area[out->data++] = '\\';
4470 out->area[out->data++] = 'x';
4471 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4472 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004473 }
4474 if (buf[ptr++] == '\n') {
4475 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004476 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004477 *line = ptr;
4478 return ptr;
4479 }
4480 }
4481 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004482 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004483 return ptr;
4484}
4485
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004486/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004487 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4488 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004489 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004490void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4491 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004492{
Willy Tarreau73459792017-04-11 07:58:08 +02004493 unsigned int i;
4494 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004495
4496 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4497 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004498 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004499 for (j = 0; j < 8; j++) {
4500 if (b + j >= 0 && b + j < len)
4501 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4502 else
4503 fprintf(out, " ");
4504 }
4505
4506 if (b + j >= 0 && b + j < len)
4507 fputc('-', out);
4508 else
4509 fputc(' ', out);
4510
4511 for (j = 8; j < 16; j++) {
4512 if (b + j >= 0 && b + j < len)
4513 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4514 else
4515 fprintf(out, " ");
4516 }
4517
4518 fprintf(out, " ");
4519 for (j = 0; j < 16; j++) {
4520 if (b + j >= 0 && b + j < len) {
4521 if (isprint((unsigned char)buf[b + j]))
4522 fputc((unsigned char)buf[b + j], out);
4523 else
4524 fputc('.', out);
4525 }
4526 else
4527 fputc(' ', out);
4528 }
4529 fputc('\n', out);
4530 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004531}
4532
Willy Tarreaubb869862020-04-16 10:52:41 +02004533/* Tries to report the executable path name on platforms supporting this. If
4534 * not found or not possible, returns NULL.
4535 */
4536const char *get_exec_path()
4537{
4538 const char *ret = NULL;
4539
4540#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4541 long execfn = getauxval(AT_EXECFN);
4542
4543 if (execfn && execfn != ENOENT)
4544 ret = (const char *)execfn;
4545#endif
4546 return ret;
4547}
4548
Baruch Siache1651b22020-07-24 07:52:20 +03004549#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004550/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4551 * also returns the symbol size in <size>, otherwise returns 0 there.
4552 */
4553static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4554{
4555 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004556#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004557 const ElfW(Sym) *sym;
4558
4559 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4560 if (ret)
4561 *size = sym ? sym->st_size : 0;
4562#else
4563 ret = dladdr(addr, dli);
4564 *size = 0;
4565#endif
4566 return ret;
4567}
4568#endif
4569
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004570/* Tries to append to buffer <buf> some indications about the symbol at address
4571 * <addr> using the following form:
4572 * lib:+0xoffset (unresolvable address from lib's base)
4573 * main+0xoffset (unresolvable address from main (+/-))
4574 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4575 * name (resolved exact exec address)
4576 * lib:name (resolved exact lib address)
4577 * name+0xoffset/0xsize (resolved address within exec symbol)
4578 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4579 *
4580 * The file name (lib or executable) is limited to what lies between the last
4581 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4582 * the output if not null. The file is not dumped when it's the same as the one
Baruch Siache1651b22020-07-24 07:52:20 +03004583 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004584 *
4585 * The symbol's base address is returned, or NULL when unresolved, in order to
4586 * allow the caller to match it against known ones.
4587 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004588const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004589{
4590 const struct {
4591 const void *func;
4592 const char *name;
4593 } fcts[] = {
4594 { .func = process_stream, .name = "process_stream" },
4595 { .func = task_run_applet, .name = "task_run_applet" },
4596 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4597 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4598 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4599 { .func = listener_accept, .name = "listener_accept" },
4600 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4601 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4602#ifdef USE_LUA
4603 { .func = hlua_process_task, .name = "hlua_process_task" },
4604#endif
4605#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4606 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4607 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4608#endif
4609 };
4610
Baruch Siache1651b22020-07-24 07:52:20 +03004611#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004612 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004613 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004614 const char *fname, *p;
4615#endif
4616 int i;
4617
4618 if (pfx)
4619 chunk_appendf(buf, "%s", pfx);
4620
4621 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4622 if (addr == fcts[i].func) {
4623 chunk_appendf(buf, "%s", fcts[i].name);
4624 return addr;
4625 }
4626 }
4627
Baruch Siache1651b22020-07-24 07:52:20 +03004628#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004629 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004630 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004631 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004632
4633 /* 1. prefix the library name if it's not the same object as the one
4634 * that contains the main function. The name is picked between last '/'
4635 * and first following '.'.
4636 */
4637 if (!dladdr(main, &dli_main))
4638 dli_main.dli_fbase = NULL;
4639
4640 if (dli_main.dli_fbase != dli.dli_fbase) {
4641 fname = dli.dli_fname;
4642 p = strrchr(fname, '/');
4643 if (p++)
4644 fname = p;
4645 p = strchr(fname, '.');
4646 if (!p)
4647 p = fname + strlen(fname);
4648
4649 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4650 }
4651
4652 /* 2. symbol name */
4653 if (dli.dli_sname) {
4654 /* known, dump it and return symbol's address (exact or relative) */
4655 chunk_appendf(buf, "%s", dli.dli_sname);
4656 if (addr != dli.dli_saddr) {
4657 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004658 if (size)
4659 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004660 }
4661 return dli.dli_saddr;
4662 }
4663 else if (dli_main.dli_fbase != dli.dli_fbase) {
4664 /* unresolved symbol from a known library, report relative offset */
4665 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4666 return NULL;
4667 }
Baruch Siache1651b22020-07-24 07:52:20 +03004668#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004669 unknown:
4670 /* unresolved symbol from the main file, report relative offset to main */
4671 if ((void*)addr < (void*)main)
4672 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4673 else
4674 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4675 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004676}
4677
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004678/*
4679 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004680 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004681 *
4682 * First, initializes the value with <sz> as address to 0 and initializes the
4683 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4684 * address updating <sz> pointed value to the size of this array.
4685 *
4686 * Returns 1 if succeeded, 0 if not.
4687 */
4688int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4689{
4690 unsigned int *n;
4691 const char *s, *end;
4692
4693 s = str;
4694 *sz = 0;
4695 end = str + strlen(str);
4696 *nums = n = NULL;
4697
4698 while (1) {
4699 unsigned int r;
4700
4701 if (s >= end)
4702 break;
4703
4704 r = read_uint(&s, end);
4705 /* Expected characters after having read an uint: '\0' or '.',
4706 * if '.', must not be terminal.
4707 */
4708 if (*s != '\0'&& (*s++ != '.' || s == end))
4709 return 0;
4710
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004711 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004712 if (!n)
4713 return 0;
4714
4715 n[(*sz)++] = r;
4716 }
4717 *nums = n;
4718
4719 return 1;
4720}
4721
Willy Tarreau4d589e72019-08-23 19:02:26 +02004722
4723/* returns the number of bytes needed to encode <v> as a varint. An inline
4724 * version exists for use with constants (__varint_bytes()).
4725 */
4726int varint_bytes(uint64_t v)
4727{
4728 int len = 1;
4729
4730 if (v >= 240) {
4731 v = (v - 240) >> 4;
4732 while (1) {
4733 len++;
4734 if (v < 128)
4735 break;
4736 v = (v - 128) >> 7;
4737 }
4738 }
4739 return len;
4740}
4741
Willy Tarreau52bf8392020-03-08 00:42:37 +01004742
4743/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004744static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004745
4746/* This is a thread-safe implementation of xoroshiro128** described below:
4747 * http://prng.di.unimi.it/
4748 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4749 * supports fast jumps and passes all common quality tests. It is thread-safe,
4750 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4751 * local lock on other ones.
4752 */
4753uint64_t ha_random64()
4754{
4755 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004756 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4757 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004758
4759#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4760 static HA_SPINLOCK_T rand_lock;
4761
4762 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4763#endif
4764
4765 old[0] = ha_random_state[0];
4766 old[1] = ha_random_state[1];
4767
4768#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4769 do {
4770#endif
4771 result = rotl64(old[0] * 5, 7) * 9;
4772 new[1] = old[0] ^ old[1];
4773 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4774 new[1] = rotl64(new[1], 37); // c
4775
4776#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4777 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4778#else
4779 ha_random_state[0] = new[0];
4780 ha_random_state[1] = new[1];
4781#if defined(USE_THREAD)
4782 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4783#endif
4784#endif
4785 return result;
4786}
4787
4788/* seeds the random state using up to <len> bytes from <seed>, starting with
4789 * the first non-zero byte.
4790 */
4791void ha_random_seed(const unsigned char *seed, size_t len)
4792{
4793 size_t pos;
4794
4795 /* the seed must not be all zeroes, so we pre-fill it with alternating
4796 * bits and overwrite part of them with the block starting at the first
4797 * non-zero byte from the seed.
4798 */
4799 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4800
4801 for (pos = 0; pos < len; pos++)
4802 if (seed[pos] != 0)
4803 break;
4804
4805 if (pos == len)
4806 return;
4807
4808 seed += pos;
4809 len -= pos;
4810
4811 if (len > sizeof(ha_random_state))
4812 len = sizeof(ha_random_state);
4813
4814 memcpy(ha_random_state, seed, len);
4815}
4816
4817/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4818 * and is equivalent to calling ha_random64() as many times. It is used to
4819 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4820 * different generators (i.e. different processes after a fork). The <dist>
4821 * argument is the distance to jump to and is used in a loop so it rather not
4822 * be too large if the processing time is a concern.
4823 *
4824 * BEWARE: this function is NOT thread-safe and must not be called during
4825 * concurrent accesses to ha_random64().
4826 */
4827void ha_random_jump96(uint32_t dist)
4828{
4829 while (dist--) {
4830 uint64_t s0 = 0;
4831 uint64_t s1 = 0;
4832 int b;
4833
4834 for (b = 0; b < 64; b++) {
4835 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4836 s0 ^= ha_random_state[0];
4837 s1 ^= ha_random_state[1];
4838 }
4839 ha_random64();
4840 }
4841
4842 for (b = 0; b < 64; b++) {
4843 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4844 s0 ^= ha_random_state[0];
4845 s1 ^= ha_random_state[1];
4846 }
4847 ha_random64();
4848 }
4849 ha_random_state[0] = s0;
4850 ha_random_state[1] = s1;
4851 }
4852}
4853
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004854/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4855 * bytes large.
4856 */
4857void ha_generate_uuid(struct buffer *output)
4858{
4859 uint32_t rnd[4];
4860 uint64_t last;
4861
4862 last = ha_random64();
4863 rnd[0] = last;
4864 rnd[1] = last >> 32;
4865
4866 last = ha_random64();
4867 rnd[2] = last;
4868 rnd[3] = last >> 32;
4869
4870 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4871 rnd[0],
4872 rnd[1] & 0xFFFF,
4873 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4874 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4875 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4876}
4877
4878
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004879/* only used by parse_line() below. It supports writing in place provided that
4880 * <in> is updated to the next location before calling it. In that case, the
4881 * char at <in> may be overwritten.
4882 */
4883#define EMIT_CHAR(x) \
4884 do { \
4885 char __c = (char)(x); \
4886 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4887 err |= PARSE_ERR_OVERLAP; \
4888 if (outpos >= outmax) \
4889 err |= PARSE_ERR_TOOLARGE; \
4890 if (!err) \
4891 out[outpos] = __c; \
4892 outpos++; \
4893 } while (0)
4894
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004895/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004896 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4897 * extraneous ones are not emitted but <outlen> is updated so that the caller
4898 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4899 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004900 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4901 * it is guaranteed that at least one arg will point to the zero. It is safe
4902 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004903 *
4904 * <out> may overlap with <in> provided that it never goes further, in which
4905 * case the parser will accept to perform in-place parsing and unquoting/
4906 * unescaping but only if environment variables do not lead to expansion that
4907 * causes overlapping, otherwise the input string being destroyed, the error
4908 * will not be recoverable. Note that even during out-of-place <in> will
4909 * experience temporary modifications in-place for variable resolution and must
4910 * be writable, and will also receive zeroes to delimit words when using
4911 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4912 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4913 * starting point of the first invalid character sequence or unmatched
4914 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4915 * error reporting might be difficult since zeroes will have been inserted into
4916 * the string. One solution for the caller may consist in replacing all args
4917 * delimiters with spaces in this case.
4918 */
4919uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4920{
4921 char *quote = NULL;
4922 char *brace = NULL;
4923 unsigned char hex1, hex2;
4924 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004925 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004926 size_t outpos = 0;
4927 int squote = 0;
4928 int dquote = 0;
4929 int arg = 0;
4930 uint32_t err = 0;
4931
4932 *nbargs = 0;
4933 *outlen = 0;
4934
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004935 /* argsmax may be -1 here, protecting args[] from any write */
4936 if (arg < argsmax)
4937 args[arg] = out;
4938
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004939 while (1) {
4940 if (*in >= '-' && *in != '\\') {
4941 /* speedup: directly send all regular chars starting
4942 * with '-', '.', '/', alnum etc...
4943 */
4944 EMIT_CHAR(*in++);
4945 continue;
4946 }
4947 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4948 /* end of line */
4949 break;
4950 }
4951 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4952 /* comment */
4953 break;
4954 }
4955 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4956 if (dquote) {
4957 dquote = 0;
4958 quote = NULL;
4959 }
4960 else {
4961 dquote = 1;
4962 quote = in;
4963 }
4964 in++;
4965 continue;
4966 }
4967 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4968 if (squote) {
4969 squote = 0;
4970 quote = NULL;
4971 }
4972 else {
4973 squote = 1;
4974 quote = in;
4975 }
4976 in++;
4977 continue;
4978 }
4979 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4980 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4981 * C equivalent value but only when they have a special meaning and within
4982 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4983 */
4984 char tosend = *in;
4985
4986 switch (in[1]) {
4987 case ' ':
4988 case '\\':
4989 tosend = in[1];
4990 in++;
4991 break;
4992
4993 case 't':
4994 tosend = '\t';
4995 in++;
4996 break;
4997
4998 case 'n':
4999 tosend = '\n';
5000 in++;
5001 break;
5002
5003 case 'r':
5004 tosend = '\r';
5005 in++;
5006 break;
5007
5008 case '#':
5009 /* escaping of "#" only if comments are supported */
5010 if (opts & PARSE_OPT_SHARP)
5011 in++;
5012 tosend = *in;
5013 break;
5014
5015 case '\'':
5016 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5017 if (opts & PARSE_OPT_SQUOTE && !squote)
5018 in++;
5019 tosend = *in;
5020 break;
5021
5022 case '"':
5023 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5024 if (opts & PARSE_OPT_DQUOTE && !squote)
5025 in++;
5026 tosend = *in;
5027 break;
5028
5029 case '$':
5030 /* escaping of '$' only inside double quotes and only if env supported */
5031 if (opts & PARSE_OPT_ENV && dquote)
5032 in++;
5033 tosend = *in;
5034 break;
5035
5036 case 'x':
5037 if (!ishex(in[2]) || !ishex(in[3])) {
5038 /* invalid or incomplete hex sequence */
5039 err |= PARSE_ERR_HEX;
5040 if (errptr)
5041 *errptr = in;
5042 goto leave;
5043 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005044 hex1 = toupper((unsigned char)in[2]) - '0';
5045 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005046 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5047 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5048 tosend = (hex1 << 4) + hex2;
5049 in += 3;
5050 break;
5051
5052 default:
5053 /* other combinations are not escape sequences */
5054 break;
5055 }
5056
5057 in++;
5058 EMIT_CHAR(tosend);
5059 }
5060 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5061 /* a non-escaped space is an argument separator */
5062 while (isspace((unsigned char)*in))
5063 in++;
5064 EMIT_CHAR(0);
5065 arg++;
5066 if (arg < argsmax)
5067 args[arg] = out + outpos;
5068 else
5069 err |= PARSE_ERR_TOOMANY;
5070 }
5071 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5072 /* environment variables are evaluated anywhere, or only
5073 * inside double quotes if they are supported.
5074 */
5075 char *var_name;
5076 char save_char;
5077 char *value;
5078
5079 in++;
5080
5081 if (*in == '{')
5082 brace = in++;
5083
5084 if (!isalpha((unsigned char)*in) && *in != '_') {
5085 /* unacceptable character in variable name */
5086 err |= PARSE_ERR_VARNAME;
5087 if (errptr)
5088 *errptr = in;
5089 goto leave;
5090 }
5091
5092 var_name = in;
5093 while (isalnum((unsigned char)*in) || *in == '_')
5094 in++;
5095
5096 save_char = *in;
5097 *in = '\0';
5098 value = getenv(var_name);
5099 *in = save_char;
5100
5101 if (brace) {
5102 if (*in != '}') {
5103 /* unmatched brace */
5104 err |= PARSE_ERR_BRACE;
5105 if (errptr)
5106 *errptr = brace;
5107 goto leave;
5108 }
5109 in++;
5110 brace = NULL;
5111 }
5112
5113 if (value) {
5114 while (*value)
5115 EMIT_CHAR(*value++);
5116 }
5117 }
5118 else {
5119 /* any other regular char */
5120 EMIT_CHAR(*in++);
5121 }
5122 }
5123
5124 /* end of output string */
5125 EMIT_CHAR(0);
5126 arg++;
5127
5128 if (quote) {
5129 /* unmatched quote */
5130 err |= PARSE_ERR_QUOTE;
5131 if (errptr)
5132 *errptr = quote;
5133 goto leave;
5134 }
5135 leave:
5136 *nbargs = arg;
5137 *outlen = outpos;
5138
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005139 /* empty all trailing args by making them point to the trailing zero,
5140 * at least the last one in any case.
5141 */
5142 if (arg > argsmax)
5143 arg = argsmax;
5144
5145 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005146 args[arg++] = out + outpos - 1;
5147
5148 return err;
5149}
5150#undef EMIT_CHAR
5151
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005152/* This is used to sanitize an input line that's about to be used for error reporting.
5153 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5154 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5155 * If non-printable chars are present in the output. It returns the new offset <pos>
5156 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5157 * be at least 6 to support two "..." otherwise the result is undefined. The line
5158 * itself must have at least 7 chars allocated for the same reason.
5159 */
5160size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5161{
5162 size_t shift = 0;
5163 char *out = line;
5164 char *in = line;
5165 char *end = line + width;
5166
5167 if (pos >= width) {
5168 /* if we have to shift, we'll be out of context, so let's
5169 * try to put <pos> at the center of width.
5170 */
5171 shift = pos - width / 2;
5172 in += shift + 3;
5173 end = out + width - 3;
5174 out[0] = out[1] = out[2] = '.';
5175 out += 3;
5176 }
5177
5178 while (out < end && *in) {
5179 if (isspace((unsigned char)*in))
5180 *out++ = ' ';
5181 else if (isprint((unsigned char)*in))
5182 *out++ = *in;
5183 else
5184 *out++ = '?';
5185 in++;
5186 }
5187
5188 if (end < line + width) {
5189 out[0] = out[1] = out[2] = '.';
5190 out += 3;
5191 }
5192
5193 *out++ = 0;
5194 return pos - shift;
5195}
5196
Willy Tarreaubaaee002006-06-26 02:48:02 +02005197/*
5198 * Local variables:
5199 * c-indent-level: 8
5200 * c-basic-offset: 8
5201 * End:
5202 */