blob: 4f61ae256298e5ad5b5cab49c02a1dd1f23246dc [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 Tarreau209108d2020-06-04 20:30:20 +020050#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020051#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020052#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020053#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010054
Thierry Fournier93127942016-01-20 18:49:45 +010055/* This macro returns false if the test __x is false. Many
56 * of the following parsing function must be abort the processing
57 * if it returns 0, so this macro is useful for writing light code.
58 */
59#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
60
Willy Tarreau56adcf22012-12-23 18:00:29 +010061/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020062 * 2^64-1 = 18446744073709551615 or
63 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020064 *
65 * The HTML version needs room for adding the 25 characters
66 * '<span class="rls"></span>' around digits at positions 3N+1 in order
67 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020068 */
Christopher Faulet99bca652017-11-14 16:47:26 +010069THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
70THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020071
Willy Tarreau588297f2014-06-16 15:16:40 +020072/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
73 * to quote strings larger than a max configuration line.
74 */
Christopher Faulet99bca652017-11-14 16:47:26 +010075THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
76THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020077
Willy Tarreaubaaee002006-06-26 02:48:02 +020078/*
William Lallemande7340ec2012-01-24 11:15:39 +010079 * unsigned long long ASCII representation
80 *
81 * return the last char '\0' or NULL if no enough
82 * space in dst
83 */
84char *ulltoa(unsigned long long n, char *dst, size_t size)
85{
86 int i = 0;
87 char *res;
88
89 switch(n) {
90 case 1ULL ... 9ULL:
91 i = 0;
92 break;
93
94 case 10ULL ... 99ULL:
95 i = 1;
96 break;
97
98 case 100ULL ... 999ULL:
99 i = 2;
100 break;
101
102 case 1000ULL ... 9999ULL:
103 i = 3;
104 break;
105
106 case 10000ULL ... 99999ULL:
107 i = 4;
108 break;
109
110 case 100000ULL ... 999999ULL:
111 i = 5;
112 break;
113
114 case 1000000ULL ... 9999999ULL:
115 i = 6;
116 break;
117
118 case 10000000ULL ... 99999999ULL:
119 i = 7;
120 break;
121
122 case 100000000ULL ... 999999999ULL:
123 i = 8;
124 break;
125
126 case 1000000000ULL ... 9999999999ULL:
127 i = 9;
128 break;
129
130 case 10000000000ULL ... 99999999999ULL:
131 i = 10;
132 break;
133
134 case 100000000000ULL ... 999999999999ULL:
135 i = 11;
136 break;
137
138 case 1000000000000ULL ... 9999999999999ULL:
139 i = 12;
140 break;
141
142 case 10000000000000ULL ... 99999999999999ULL:
143 i = 13;
144 break;
145
146 case 100000000000000ULL ... 999999999999999ULL:
147 i = 14;
148 break;
149
150 case 1000000000000000ULL ... 9999999999999999ULL:
151 i = 15;
152 break;
153
154 case 10000000000000000ULL ... 99999999999999999ULL:
155 i = 16;
156 break;
157
158 case 100000000000000000ULL ... 999999999999999999ULL:
159 i = 17;
160 break;
161
162 case 1000000000000000000ULL ... 9999999999999999999ULL:
163 i = 18;
164 break;
165
166 case 10000000000000000000ULL ... ULLONG_MAX:
167 i = 19;
168 break;
169 }
170 if (i + 2 > size) // (i + 1) + '\0'
171 return NULL; // too long
172 res = dst + i + 1;
173 *res = '\0';
174 for (; i >= 0; i--) {
175 dst[i] = n % 10ULL + '0';
176 n /= 10ULL;
177 }
178 return res;
179}
180
181/*
182 * unsigned long ASCII representation
183 *
184 * return the last char '\0' or NULL if no enough
185 * space in dst
186 */
187char *ultoa_o(unsigned long n, char *dst, size_t size)
188{
189 int i = 0;
190 char *res;
191
192 switch (n) {
193 case 0U ... 9UL:
194 i = 0;
195 break;
196
197 case 10U ... 99UL:
198 i = 1;
199 break;
200
201 case 100U ... 999UL:
202 i = 2;
203 break;
204
205 case 1000U ... 9999UL:
206 i = 3;
207 break;
208
209 case 10000U ... 99999UL:
210 i = 4;
211 break;
212
213 case 100000U ... 999999UL:
214 i = 5;
215 break;
216
217 case 1000000U ... 9999999UL:
218 i = 6;
219 break;
220
221 case 10000000U ... 99999999UL:
222 i = 7;
223 break;
224
225 case 100000000U ... 999999999UL:
226 i = 8;
227 break;
228#if __WORDSIZE == 32
229
230 case 1000000000ULL ... ULONG_MAX:
231 i = 9;
232 break;
233
234#elif __WORDSIZE == 64
235
236 case 1000000000ULL ... 9999999999UL:
237 i = 9;
238 break;
239
240 case 10000000000ULL ... 99999999999UL:
241 i = 10;
242 break;
243
244 case 100000000000ULL ... 999999999999UL:
245 i = 11;
246 break;
247
248 case 1000000000000ULL ... 9999999999999UL:
249 i = 12;
250 break;
251
252 case 10000000000000ULL ... 99999999999999UL:
253 i = 13;
254 break;
255
256 case 100000000000000ULL ... 999999999999999UL:
257 i = 14;
258 break;
259
260 case 1000000000000000ULL ... 9999999999999999UL:
261 i = 15;
262 break;
263
264 case 10000000000000000ULL ... 99999999999999999UL:
265 i = 16;
266 break;
267
268 case 100000000000000000ULL ... 999999999999999999UL:
269 i = 17;
270 break;
271
272 case 1000000000000000000ULL ... 9999999999999999999UL:
273 i = 18;
274 break;
275
276 case 10000000000000000000ULL ... ULONG_MAX:
277 i = 19;
278 break;
279
280#endif
281 }
282 if (i + 2 > size) // (i + 1) + '\0'
283 return NULL; // too long
284 res = dst + i + 1;
285 *res = '\0';
286 for (; i >= 0; i--) {
287 dst[i] = n % 10U + '0';
288 n /= 10U;
289 }
290 return res;
291}
292
293/*
294 * signed long ASCII representation
295 *
296 * return the last char '\0' or NULL if no enough
297 * space in dst
298 */
299char *ltoa_o(long int n, char *dst, size_t size)
300{
301 char *pos = dst;
302
303 if (n < 0) {
304 if (size < 3)
305 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
306 *pos = '-';
307 pos++;
308 dst = ultoa_o(-n, pos, size - 1);
309 } else {
310 dst = ultoa_o(n, dst, size);
311 }
312 return dst;
313}
314
315/*
316 * signed long long ASCII representation
317 *
318 * return the last char '\0' or NULL if no enough
319 * space in dst
320 */
321char *lltoa(long long n, char *dst, size_t size)
322{
323 char *pos = dst;
324
325 if (n < 0) {
326 if (size < 3)
327 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
328 *pos = '-';
329 pos++;
330 dst = ulltoa(-n, pos, size - 1);
331 } else {
332 dst = ulltoa(n, dst, size);
333 }
334 return dst;
335}
336
337/*
338 * write a ascii representation of a unsigned into dst,
339 * return a pointer to the last character
340 * Pad the ascii representation with '0', using size.
341 */
342char *utoa_pad(unsigned int n, char *dst, size_t size)
343{
344 int i = 0;
345 char *ret;
346
347 switch(n) {
348 case 0U ... 9U:
349 i = 0;
350 break;
351
352 case 10U ... 99U:
353 i = 1;
354 break;
355
356 case 100U ... 999U:
357 i = 2;
358 break;
359
360 case 1000U ... 9999U:
361 i = 3;
362 break;
363
364 case 10000U ... 99999U:
365 i = 4;
366 break;
367
368 case 100000U ... 999999U:
369 i = 5;
370 break;
371
372 case 1000000U ... 9999999U:
373 i = 6;
374 break;
375
376 case 10000000U ... 99999999U:
377 i = 7;
378 break;
379
380 case 100000000U ... 999999999U:
381 i = 8;
382 break;
383
384 case 1000000000U ... 4294967295U:
385 i = 9;
386 break;
387 }
388 if (i + 2 > size) // (i + 1) + '\0'
389 return NULL; // too long
390 if (i < size)
391 i = size - 2; // padding - '\0'
392
393 ret = dst + i + 1;
394 *ret = '\0';
395 for (; i >= 0; i--) {
396 dst[i] = n % 10U + '0';
397 n /= 10U;
398 }
399 return ret;
400}
401
402/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200403 * copies at most <size-1> chars from <src> to <dst>. Last char is always
404 * set to 0, unless <size> is 0. The number of chars copied is returned
405 * (excluding the terminating zero).
406 * This code has been optimized for size and speed : on x86, it's 45 bytes
407 * long, uses only registers, and consumes only 4 cycles per char.
408 */
409int strlcpy2(char *dst, const char *src, int size)
410{
411 char *orig = dst;
412 if (size) {
413 while (--size && (*dst = *src)) {
414 src++; dst++;
415 }
416 *dst = 0;
417 }
418 return dst - orig;
419}
420
421/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200422 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200423 * the ascii representation for number 'n' in decimal.
424 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100425char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200426{
427 char *pos;
428
Willy Tarreau72d759c2007-10-25 12:14:10 +0200429 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200430 *pos-- = '\0';
431
432 do {
433 *pos-- = '0' + n % 10;
434 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200435 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200436 return pos + 1;
437}
438
Willy Tarreau91092e52007-10-25 16:58:42 +0200439/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200440 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200441 * the ascii representation for number 'n' in decimal.
442 */
443char *lltoa_r(long long int in, char *buffer, int size)
444{
445 char *pos;
446 int neg = 0;
447 unsigned long long int n;
448
449 pos = buffer + size - 1;
450 *pos-- = '\0';
451
452 if (in < 0) {
453 neg = 1;
454 n = -in;
455 }
456 else
457 n = in;
458
459 do {
460 *pos-- = '0' + n % 10;
461 n /= 10;
462 } while (n && pos >= buffer);
463 if (neg && pos > buffer)
464 *pos-- = '-';
465 return pos + 1;
466}
467
468/*
469 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200470 * the ascii representation for signed number 'n' in decimal.
471 */
472char *sltoa_r(long n, char *buffer, int size)
473{
474 char *pos;
475
476 if (n >= 0)
477 return ultoa_r(n, buffer, size);
478
479 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
480 *pos = '-';
481 return pos;
482}
483
484/*
485 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200486 * the ascii representation for number 'n' in decimal, formatted for
487 * HTML output with tags to create visual grouping by 3 digits. The
488 * output needs to support at least 171 characters.
489 */
490const char *ulltoh_r(unsigned long long n, char *buffer, int size)
491{
492 char *start;
493 int digit = 0;
494
495 start = buffer + size;
496 *--start = '\0';
497
498 do {
499 if (digit == 3 && start >= buffer + 7)
500 memcpy(start -= 7, "</span>", 7);
501
502 if (start >= buffer + 1) {
503 *--start = '0' + n % 10;
504 n /= 10;
505 }
506
507 if (digit == 3 && start >= buffer + 18)
508 memcpy(start -= 18, "<span class=\"rls\">", 18);
509
510 if (digit++ == 3)
511 digit = 1;
512 } while (n && start > buffer);
513 return start;
514}
515
516/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200517 * This function simply returns a locally allocated string containing the ascii
518 * representation for number 'n' in decimal, unless n is 0 in which case it
519 * returns the alternate string (or an empty string if the alternate string is
520 * NULL). It use is intended for limits reported in reports, where it's
521 * desirable not to display anything if there is no limit. Warning! it shares
522 * the same vector as ultoa_r().
523 */
524const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
525{
526 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
527}
528
Willy Tarreau588297f2014-06-16 15:16:40 +0200529/* returns a locally allocated string containing the quoted encoding of the
530 * input string. The output may be truncated to QSTR_SIZE chars, but it is
531 * guaranteed that the string will always be properly terminated. Quotes are
532 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
533 * always be at least 4 chars.
534 */
535const char *qstr(const char *str)
536{
537 char *ret = quoted_str[quoted_idx];
538 char *p, *end;
539
540 if (++quoted_idx >= NB_QSTR)
541 quoted_idx = 0;
542
543 p = ret;
544 end = ret + QSTR_SIZE;
545
546 *p++ = '"';
547
548 /* always keep 3 chars to support passing "" and the ending " */
549 while (*str && p < end - 3) {
550 if (*str == '"') {
551 *p++ = '"';
552 *p++ = '"';
553 }
554 else
555 *p++ = *str;
556 str++;
557 }
558 *p++ = '"';
559 return ret;
560}
561
Robert Tsai81ae1952007-12-05 10:47:29 +0100562/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200563 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
564 *
565 * It looks like this one would be a good candidate for inlining, but this is
566 * not interesting because it around 35 bytes long and often called multiple
567 * times within the same function.
568 */
569int ishex(char s)
570{
571 s -= '0';
572 if ((unsigned char)s <= 9)
573 return 1;
574 s -= 'A' - '0';
575 if ((unsigned char)s <= 5)
576 return 1;
577 s -= 'a' - 'A';
578 if ((unsigned char)s <= 5)
579 return 1;
580 return 0;
581}
582
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100583/* rounds <i> down to the closest value having max 2 digits */
584unsigned int round_2dig(unsigned int i)
585{
586 unsigned int mul = 1;
587
588 while (i >= 100) {
589 i /= 10;
590 mul *= 10;
591 }
592 return i * mul;
593}
594
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100595/*
596 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
597 * invalid character is found, a pointer to it is returned. If everything is
598 * fine, NULL is returned.
599 */
600const char *invalid_char(const char *name)
601{
602 if (!*name)
603 return name;
604
605 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100606 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100607 *name != '_' && *name != '-')
608 return name;
609 name++;
610 }
611 return NULL;
612}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200613
614/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200615 * Checks <name> for invalid characters. Valid chars are [_.-] and those
616 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200617 * If an invalid character is found, a pointer to it is returned.
618 * If everything is fine, NULL is returned.
619 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200620static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200621
622 if (!*name)
623 return name;
624
625 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100626 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200627 *name != '_' && *name != '-')
628 return name;
629
630 name++;
631 }
632
633 return NULL;
634}
635
636/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200637 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
638 * If an invalid character is found, a pointer to it is returned.
639 * If everything is fine, NULL is returned.
640 */
641const char *invalid_domainchar(const char *name) {
642 return __invalid_char(name, isalnum);
643}
644
645/*
646 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
647 * If an invalid character is found, a pointer to it is returned.
648 * If everything is fine, NULL is returned.
649 */
650const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200651 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200652}
653
654/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100655 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100656 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
657 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
658 * the function tries to guess the address family from the syntax. If the
659 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100660 * string is assumed to contain only an address, no port. The address can be a
661 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
662 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
663 * The return address will only have the address family and the address set,
664 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100665 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
666 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100667 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200668 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100669struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200670{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100671 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100672 /* max IPv6 length, including brackets and terminating NULL */
673 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100674 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100675
676 /* check IPv6 with square brackets */
677 if (str[0] == '[') {
678 size_t iplength = strlen(str);
679
680 if (iplength < 4) {
681 /* minimal size is 4 when using brackets "[::]" */
682 goto fail;
683 }
684 else if (iplength >= sizeof(tmpip)) {
685 /* IPv6 literal can not be larger than tmpip */
686 goto fail;
687 }
688 else {
689 if (str[iplength - 1] != ']') {
690 /* if address started with bracket, it should end with bracket */
691 goto fail;
692 }
693 else {
694 memcpy(tmpip, str + 1, iplength - 2);
695 tmpip[iplength - 2] = '\0';
696 str = tmpip;
697 }
698 }
699 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100700
Willy Tarreaufab5a432011-03-04 15:31:53 +0100701 /* Any IPv6 address */
702 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100703 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
704 sa->ss_family = AF_INET6;
705 else if (sa->ss_family != AF_INET6)
706 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100707 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100708 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100709 }
710
Willy Tarreau24709282013-03-10 21:32:12 +0100711 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100712 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100713 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
714 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100715 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100716 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100717 }
718
719 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100720 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
721 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100722 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100723 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100724 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100725 }
726
727 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100728 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
729 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100730 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100731 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100732 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100733 }
734
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100735 if (!resolve)
736 return NULL;
737
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200738 if (!dns_hostname_validation(str, NULL))
739 return NULL;
740
David du Colombierd5f43282011-03-17 10:40:16 +0100741#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200742 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100743 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100744 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100745
746 memset(&result, 0, sizeof(result));
747 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100748 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100749 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200750 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100751 hints.ai_protocol = 0;
752
753 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100754 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
755 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100756 else if (sa->ss_family != result->ai_family) {
757 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100758 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100759 }
Willy Tarreau24709282013-03-10 21:32:12 +0100760
David du Colombierd5f43282011-03-17 10:40:16 +0100761 switch (result->ai_family) {
762 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100763 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100764 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100765 success = 1;
766 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100767 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100768 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100769 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100770 success = 1;
771 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100772 }
773 }
774
Sean Carey58ea0392013-02-15 23:39:18 +0100775 if (result)
776 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100777
778 if (success)
779 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100780 }
David du Colombierd5f43282011-03-17 10:40:16 +0100781#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200782 /* try to resolve an IPv4/IPv6 hostname */
783 he = gethostbyname(str);
784 if (he) {
785 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
786 sa->ss_family = he->h_addrtype;
787 else if (sa->ss_family != he->h_addrtype)
788 goto fail;
789
790 switch (sa->ss_family) {
791 case AF_INET:
792 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100793 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200794 return sa;
795 case AF_INET6:
796 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100797 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200798 return sa;
799 }
800 }
801
David du Colombierd5f43282011-03-17 10:40:16 +0100802 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100803 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100804 return NULL;
805}
806
807/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100808 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
809 * range or offset consisting in two integers that the caller will have to
810 * check to find the relevant input format. The following format are supported :
811 *
812 * String format | address | port | low | high
813 * addr | <addr> | 0 | 0 | 0
814 * addr: | <addr> | 0 | 0 | 0
815 * addr:port | <addr> | <port> | <port> | <port>
816 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
817 * addr:+port | <addr> | <port> | 0 | <port>
818 * addr:-port | <addr> |-<port> | <port> | 0
819 *
820 * The detection of a port range or increment by the caller is made by
821 * comparing <low> and <high>. If both are equal, then port 0 means no port
822 * was specified. The caller may pass NULL for <low> and <high> if it is not
823 * interested in retrieving port ranges.
824 *
825 * Note that <addr> above may also be :
826 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
827 * - "*" => family will be AF_INET and address will be INADDR_ANY
828 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
829 * - a host name => family and address will depend on host name resolving.
830 *
Willy Tarreau24709282013-03-10 21:32:12 +0100831 * A prefix may be passed in before the address above to force the family :
832 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
833 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
834 * - "unix@" => force address to be a path to a UNIX socket even if the
835 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200836 * - 'abns@' -> force address to belong to the abstract namespace (Linux
837 * only). These sockets are just like Unix sockets but without
838 * the need for an underlying file system. The address is a
839 * string. Technically it's like a Unix socket with a zero in
840 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100841 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100842 *
mildisff5d5102015-10-26 18:50:08 +0100843 * IPv6 addresses can be declared with or without square brackets. When using
844 * square brackets for IPv6 addresses, the port separator (colon) is optional.
845 * If not using square brackets, and in order to avoid any ambiguity with
846 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
847 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
848 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100849 *
850 * If <pfx> is non-null, it is used as a string prefix before any path-based
851 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100852 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200853 * if <fqdn> is non-null, it will be filled with :
854 * - a pointer to the FQDN of the server name to resolve if there's one, and
855 * that the caller will have to free(),
856 * - NULL if there was an explicit address that doesn't require resolution.
857 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200858 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
859 * still honored so it is possible for the caller to know whether a resolution
860 * failed by clearing this flag and checking if <fqdn> was filled, indicating
861 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200862 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100863 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200864 * the address when cast to sockaddr_in and the address family is
865 * AF_CUST_EXISTING_FD.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100866 */
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200867struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100868{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100869 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100870 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100871 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100872 char *port1, *port2;
873 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200874 int abstract = 0;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200875 int is_udp = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100876
877 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200878 if (fqdn)
879 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200880
Willy Tarreaudad36a32013-03-11 01:20:04 +0100881 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100882 if (str2 == NULL) {
883 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100884 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100885 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200886
Willy Tarreau9f69f462015-09-08 16:01:25 +0200887 if (!*str2) {
888 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
889 goto out;
890 }
891
Willy Tarreau24709282013-03-10 21:32:12 +0100892 memset(&ss, 0, sizeof(ss));
893
894 if (strncmp(str2, "unix@", 5) == 0) {
895 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200896 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100897 ss.ss_family = AF_UNIX;
898 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200899 else if (strncmp(str2, "abns@", 5) == 0) {
900 str2 += 5;
901 abstract = 1;
902 ss.ss_family = AF_UNIX;
903 }
Willy Tarreau24709282013-03-10 21:32:12 +0100904 else if (strncmp(str2, "ipv4@", 5) == 0) {
905 str2 += 5;
906 ss.ss_family = AF_INET;
907 }
908 else if (strncmp(str2, "ipv6@", 5) == 0) {
909 str2 += 5;
910 ss.ss_family = AF_INET6;
911 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200912 else if (strncmp(str2, "udp4@", 5) == 0) {
913 str2 += 5;
914 ss.ss_family = AF_INET;
915 is_udp = 1;
916 }
917 else if (strncmp(str2, "udp6@", 5) == 0) {
918 str2 += 5;
919 ss.ss_family = AF_INET6;
920 is_udp = 1;
921 }
922 else if (strncmp(str2, "udp@", 4) == 0) {
923 str2 += 4;
924 ss.ss_family = AF_UNSPEC;
925 is_udp = 1;
926 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200927 else if (strncmp(str2, "fd@", 3) == 0) {
928 str2 += 3;
929 ss.ss_family = AF_CUST_EXISTING_FD;
930 }
931 else if (strncmp(str2, "sockpair@", 9) == 0) {
932 str2 += 9;
933 ss.ss_family = AF_CUST_SOCKPAIR;
934 }
Willy Tarreau24709282013-03-10 21:32:12 +0100935 else if (*str2 == '/') {
936 ss.ss_family = AF_UNIX;
937 }
938 else
939 ss.ss_family = AF_UNSPEC;
940
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200941 if (ss.ss_family == AF_CUST_SOCKPAIR) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200942 char *endptr;
943
William Lallemand2fe7dd02018-09-11 16:51:29 +0200944 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100945 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200946
947 if (!*str2 || *endptr) {
948 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
949 goto out;
950 }
William Lallemand2fe7dd02018-09-11 16:51:29 +0200951 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200952 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100953 char *endptr;
954
Willy Tarreau40aa0702013-03-10 23:51:38 +0100955 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100956 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100957
958 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100959 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100960 goto out;
961 }
Willy Tarreau40aa0702013-03-10 23:51:38 +0100962 }
963 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200964 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100965 int prefix_path_len;
966 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200967 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100968
969 /* complete unix socket path name during startup or soft-restart is
970 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
971 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200972 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +0200973 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +0100974 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +0100975
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200976 adr_len = strlen(str2);
977 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100978 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
979 goto out;
980 }
981
Willy Tarreauccfccef2014-05-10 01:49:15 +0200982 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +0200983 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200984 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +0200985 memcpy(un->sun_path, pfx, prefix_path_len);
986 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100987 }
Willy Tarreau24709282013-03-10 21:32:12 +0100988 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100989 char *end = str2 + strlen(str2);
990 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200991
mildisff5d5102015-10-26 18:50:08 +0100992 /* search for : or ] whatever comes first */
993 for (chr = end-1; chr > str2; chr--) {
994 if (*chr == ']' || *chr == ':')
995 break;
996 }
997
998 if (*chr == ':') {
999 /* Found a colon before a closing-bracket, must be a port separator.
1000 * This guarantee backward compatibility.
1001 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001002 if (!(opts & PA_O_PORT_OK)) {
1003 memprintf(err, "port specification not permitted here in '%s'", str);
1004 goto out;
1005 }
mildisff5d5102015-10-26 18:50:08 +01001006 *chr++ = '\0';
1007 port1 = chr;
1008 }
1009 else {
1010 /* Either no colon and no closing-bracket
1011 * or directly ending with a closing-bracket.
1012 * However, no port.
1013 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001014 if (opts & PA_O_PORT_MAND) {
1015 memprintf(err, "missing port specification in '%s'", str);
1016 goto out;
1017 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001018 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001019 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001020
Willy Tarreau90807112020-02-25 08:16:33 +01001021 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001022 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001023 if (port2) {
1024 if (!(opts & PA_O_PORT_RANGE)) {
1025 memprintf(err, "port range not permitted here in '%s'", str);
1026 goto out;
1027 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001028 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001029 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001030 else
1031 port2 = port1;
1032 portl = atoi(port1);
1033 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001034
1035 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1036 memprintf(err, "invalid port '%s'", port1);
1037 goto out;
1038 }
1039
1040 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1041 memprintf(err, "invalid port '%s'", port2);
1042 goto out;
1043 }
1044
1045 if (portl > porth) {
1046 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1047 goto out;
1048 }
1049
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001050 porta = portl;
1051 }
1052 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001053 if (!(opts & PA_O_PORT_OFS)) {
1054 memprintf(err, "port offset not permitted here in '%s'", str);
1055 goto out;
1056 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001057 portl = atoi(port1 + 1);
1058 porta = -portl;
1059 }
1060 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001061 if (!(opts & PA_O_PORT_OFS)) {
1062 memprintf(err, "port offset not permitted here in '%s'", str);
1063 goto out;
1064 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001065 porth = atoi(port1 + 1);
1066 porta = porth;
1067 }
1068 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001069 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001070 goto out;
1071 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001072 else if (opts & PA_O_PORT_MAND) {
1073 memprintf(err, "missing port specification in '%s'", str);
1074 goto out;
1075 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001076
1077 /* first try to parse the IP without resolving. If it fails, it
1078 * tells us we need to keep a copy of the FQDN to resolve later
1079 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001080 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001081 */
1082 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001083 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1084 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001085 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1086 goto out;
1087 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001088
Willy Tarreauceccdd72016-11-02 22:27:10 +01001089 if (fqdn) {
1090 if (str2 != back)
1091 memmove(back, str2, strlen(str2) + 1);
1092 *fqdn = back;
1093 back = NULL;
1094 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001095 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001096 set_host_port(&ss, porta);
Emeric Brun3835c0d2020-07-07 09:46:09 +02001097 if (is_udp) {
1098 if (ss.ss_family == AF_INET6)
1099 ss.ss_family = AF_CUST_UDP6;
1100 else
1101 ss.ss_family = AF_CUST_UDP4;
1102 }
1103
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001104 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001105
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001106 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001107 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001108 if (port)
1109 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001110 if (low)
1111 *low = portl;
1112 if (high)
1113 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001114 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001115 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001116}
1117
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001118/* converts <str> to a struct in_addr containing a network mask. It can be
1119 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001120 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001121 */
1122int str2mask(const char *str, struct in_addr *mask)
1123{
1124 if (strchr(str, '.') != NULL) { /* dotted notation */
1125 if (!inet_pton(AF_INET, str, mask))
1126 return 0;
1127 }
1128 else { /* mask length */
1129 char *err;
1130 unsigned long len = strtol(str, &err, 10);
1131
1132 if (!*str || (err && *err) || (unsigned)len > 32)
1133 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001134
1135 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001136 }
1137 return 1;
1138}
1139
Tim Duesterhus47185172018-01-25 16:24:49 +01001140/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001141 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001142 * if the conversion succeeds otherwise zero.
1143 */
1144int str2mask6(const char *str, struct in6_addr *mask)
1145{
1146 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1147 if (!inet_pton(AF_INET6, str, mask))
1148 return 0;
1149 }
1150 else { /* mask length */
1151 char *err;
1152 unsigned long len = strtol(str, &err, 10);
1153
1154 if (!*str || (err && *err) || (unsigned)len > 128)
1155 return 0;
1156
1157 len2mask6(len, mask);
1158 }
1159 return 1;
1160}
1161
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001162/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1163 * succeeds otherwise zero.
1164 */
1165int cidr2dotted(int cidr, struct in_addr *mask) {
1166
1167 if (cidr < 0 || cidr > 32)
1168 return 0;
1169
1170 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1171 return 1;
1172}
1173
Thierry Fournier70473a52016-02-17 17:12:14 +01001174/* Convert mask from bit length form to in_addr form.
1175 * This function never fails.
1176 */
1177void len2mask4(int len, struct in_addr *addr)
1178{
1179 if (len >= 32) {
1180 addr->s_addr = 0xffffffff;
1181 return;
1182 }
1183 if (len <= 0) {
1184 addr->s_addr = 0x00000000;
1185 return;
1186 }
1187 addr->s_addr = 0xffffffff << (32 - len);
1188 addr->s_addr = htonl(addr->s_addr);
1189}
1190
1191/* Convert mask from bit length form to in6_addr form.
1192 * This function never fails.
1193 */
1194void len2mask6(int len, struct in6_addr *addr)
1195{
1196 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1197 len -= 32;
1198 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1199 len -= 32;
1200 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1201 len -= 32;
1202 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1203}
1204
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001205/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001206 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001207 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001208 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001209 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1210 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001211int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001212{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001213 __label__ out_free, out_err;
1214 char *c, *s;
1215 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001216
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001217 s = strdup(str);
1218 if (!s)
1219 return 0;
1220
Willy Tarreaubaaee002006-06-26 02:48:02 +02001221 memset(mask, 0, sizeof(*mask));
1222 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001223
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001224 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001225 *c++ = '\0';
1226 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001227 if (!str2mask(c, mask))
1228 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001229 }
1230 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001231 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001232 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001233 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001234 struct hostent *he;
1235
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001236 if (!resolve)
1237 goto out_err;
1238
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001239 if ((he = gethostbyname(s)) == NULL) {
1240 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001241 }
1242 else
1243 *addr = *(struct in_addr *) *(he->h_addr_list);
1244 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001245
1246 ret_val = 1;
1247 out_free:
1248 free(s);
1249 return ret_val;
1250 out_err:
1251 ret_val = 0;
1252 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001253}
1254
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001255
1256/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001257 * converts <str> to two struct in6_addr* which must be pre-allocated.
1258 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001259 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001260 * Returns 1 if OK, 0 if error.
1261 */
1262int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1263{
1264 char *c, *s;
1265 int ret_val = 0;
1266 char *err;
1267 unsigned long len = 128;
1268
1269 s = strdup(str);
1270 if (!s)
1271 return 0;
1272
1273 memset(mask, 0, sizeof(*mask));
1274 memset(addr, 0, sizeof(*addr));
1275
1276 if ((c = strrchr(s, '/')) != NULL) {
1277 *c++ = '\0'; /* c points to the mask */
1278 if (!*c)
1279 goto out_free;
1280
1281 len = strtoul(c, &err, 10);
1282 if ((err && *err) || (unsigned)len > 128)
1283 goto out_free;
1284 }
1285 *mask = len; /* OK we have a valid mask in <len> */
1286
1287 if (!inet_pton(AF_INET6, s, addr))
1288 goto out_free;
1289
1290 ret_val = 1;
1291 out_free:
1292 free(s);
1293 return ret_val;
1294}
1295
1296
1297/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001298 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001299 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001300int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001301{
1302 int saw_digit, octets, ch;
1303 u_char tmp[4], *tp;
1304 const char *cp = addr;
1305
1306 saw_digit = 0;
1307 octets = 0;
1308 *(tp = tmp) = 0;
1309
1310 while (*addr) {
1311 unsigned char digit = (ch = *addr++) - '0';
1312 if (digit > 9 && ch != '.')
1313 break;
1314 if (digit <= 9) {
1315 u_int new = *tp * 10 + digit;
1316 if (new > 255)
1317 return 0;
1318 *tp = new;
1319 if (!saw_digit) {
1320 if (++octets > 4)
1321 return 0;
1322 saw_digit = 1;
1323 }
1324 } else if (ch == '.' && saw_digit) {
1325 if (octets == 4)
1326 return 0;
1327 *++tp = 0;
1328 saw_digit = 0;
1329 } else
1330 return 0;
1331 }
1332
1333 if (octets < 4)
1334 return 0;
1335
1336 memcpy(&dst->s_addr, tmp, 4);
1337 return addr-cp-1;
1338}
1339
1340/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001341 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001342 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001343 * the hostname. Actually only http and https are supported. <out> can be NULL.
1344 * This function returns the consumed length. It is useful if you parse complete
1345 * url like http://host:port/path, because the consumed length corresponds to
1346 * the first character of the path. If the conversion fails, it returns -1.
1347 *
1348 * This function tries to resolve the DNS name if haproxy is in starting mode.
1349 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001350 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001351int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001352{
1353 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001354 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001355 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001356 unsigned long long int http_code = 0;
1357 int default_port;
1358 struct hostent *he;
1359 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001360
1361 /* Firstly, try to find :// pattern */
1362 while (curr < url+ulen && url_code != 0x3a2f2f) {
1363 url_code = ((url_code & 0xffff) << 8);
1364 url_code += (unsigned char)*curr++;
1365 }
1366
1367 /* Secondly, if :// pattern is found, verify parsed stuff
1368 * before pattern is matching our http pattern.
1369 * If so parse ip address and port in uri.
1370 *
1371 * WARNING: Current code doesn't support dynamic async dns resolver.
1372 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001373 if (url_code != 0x3a2f2f)
1374 return -1;
1375
1376 /* Copy scheme, and utrn to lower case. */
1377 while (cp < curr - 3)
1378 http_code = (http_code << 8) + *cp++;
1379 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001380
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001381 /* HTTP or HTTPS url matching */
1382 if (http_code == 0x2020202068747470ULL) {
1383 default_port = 80;
1384 if (out)
1385 out->scheme = SCH_HTTP;
1386 }
1387 else if (http_code == 0x2020206874747073ULL) {
1388 default_port = 443;
1389 if (out)
1390 out->scheme = SCH_HTTPS;
1391 }
1392 else
1393 return -1;
1394
1395 /* If the next char is '[', the host address is IPv6. */
1396 if (*curr == '[') {
1397 curr++;
1398
1399 /* Check trash size */
1400 if (trash.size < ulen)
1401 return -1;
1402
1403 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001404 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001405 for (end = curr;
1406 end < url + ulen && *end != ']';
1407 end++, p++)
1408 *p = *end;
1409 if (*end != ']')
1410 return -1;
1411 *p = '\0';
1412
1413 /* Update out. */
1414 if (out) {
1415 out->host = curr;
1416 out->host_len = end - curr;
1417 }
1418
1419 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001420 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001421 return -1;
1422 end++;
1423
1424 /* Decode port. */
1425 if (*end == ':') {
1426 end++;
1427 default_port = read_uint(&end, url + ulen);
1428 }
1429 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1430 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1431 return end - url;
1432 }
1433 else {
1434 /* We are looking for IP address. If you want to parse and
1435 * resolve hostname found in url, you can use str2sa_range(), but
1436 * be warned this can slow down global daemon performances
1437 * while handling lagging dns responses.
1438 */
1439 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1440 if (ret) {
1441 /* Update out. */
1442 if (out) {
1443 out->host = curr;
1444 out->host_len = ret;
1445 }
1446
1447 curr += ret;
1448
1449 /* Decode port. */
1450 if (*curr == ':') {
1451 curr++;
1452 default_port = read_uint(&curr, url + ulen);
1453 }
1454 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1455
1456 /* Set family. */
1457 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1458 return curr - url;
1459 }
1460 else if (global.mode & MODE_STARTING) {
1461 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1462 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001463 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001464
1465 /* look for : or / or end */
1466 for (end = curr;
1467 end < url + ulen && *end != '/' && *end != ':';
1468 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001469 memcpy(trash.area, curr, end - curr);
1470 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001471
1472 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001473 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001474 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001475 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001476
1477 /* Update out. */
1478 if (out) {
1479 out->host = curr;
1480 out->host_len = end - curr;
1481 }
1482
1483 /* Decode port. */
1484 if (*end == ':') {
1485 end++;
1486 default_port = read_uint(&end, url + ulen);
1487 }
1488
1489 /* Copy IP address, set port and family. */
1490 switch (he->h_addrtype) {
1491 case AF_INET:
1492 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1493 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1494 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1495 return end - url;
1496
1497 case AF_INET6:
1498 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1499 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1500 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1501 return end - url;
1502 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001503 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001504 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001505 return -1;
1506}
1507
Willy Tarreau631f01c2011-09-05 00:36:48 +02001508/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1509 * address family is returned so that it's easy for the caller to adapt to the
1510 * output format. Zero is returned if the address family is not supported. -1
1511 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1512 * supported.
1513 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001514int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001515{
1516
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001517 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001518
1519 if (size < 5)
1520 return 0;
1521 *str = '\0';
1522
1523 switch (addr->ss_family) {
1524 case AF_INET:
1525 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1526 break;
1527 case AF_INET6:
1528 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1529 break;
1530 case AF_UNIX:
1531 memcpy(str, "unix", 5);
1532 return addr->ss_family;
1533 default:
1534 return 0;
1535 }
1536
1537 if (inet_ntop(addr->ss_family, ptr, str, size))
1538 return addr->ss_family;
1539
1540 /* failed */
1541 return -1;
1542}
1543
Simon Horman75ab8bd2014-06-16 09:39:41 +09001544/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1545 * address family is returned so that it's easy for the caller to adapt to the
1546 * output format. Zero is returned if the address family is not supported. -1
1547 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1548 * supported.
1549 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001550int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001551{
1552
1553 uint16_t port;
1554
1555
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001556 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001557 return 0;
1558 *str = '\0';
1559
1560 switch (addr->ss_family) {
1561 case AF_INET:
1562 port = ((struct sockaddr_in *)addr)->sin_port;
1563 break;
1564 case AF_INET6:
1565 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1566 break;
1567 case AF_UNIX:
1568 memcpy(str, "unix", 5);
1569 return addr->ss_family;
1570 default:
1571 return 0;
1572 }
1573
1574 snprintf(str, size, "%u", ntohs(port));
1575 return addr->ss_family;
1576}
1577
Willy Tarreau16e01562016-08-09 16:46:18 +02001578/* check if the given address is local to the system or not. It will return
1579 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1580 * it is. We don't want to iterate over all interfaces for this (and it is not
1581 * portable). So instead we try to bind in UDP to this address on a free non
1582 * privileged port and to connect to the same address, port 0 (connect doesn't
1583 * care). If it succeeds, we own the address. Note that non-inet addresses are
1584 * considered local since they're most likely AF_UNIX.
1585 */
1586int addr_is_local(const struct netns_entry *ns,
1587 const struct sockaddr_storage *orig)
1588{
1589 struct sockaddr_storage addr;
1590 int result;
1591 int fd;
1592
1593 if (!is_inet_addr(orig))
1594 return 1;
1595
1596 memcpy(&addr, orig, sizeof(addr));
1597 set_host_port(&addr, 0);
1598
1599 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1600 if (fd < 0)
1601 return -1;
1602
1603 result = -1;
1604 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1605 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1606 result = 0; // fail, non-local address
1607 else
1608 result = 1; // success, local address
1609 }
1610 else {
1611 if (errno == EADDRNOTAVAIL)
1612 result = 0; // definitely not local :-)
1613 }
1614 close(fd);
1615
1616 return result;
1617}
1618
Willy Tarreaubaaee002006-06-26 02:48:02 +02001619/* will try to encode the string <string> replacing all characters tagged in
1620 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1621 * prefixed by <escape>, and will store the result between <start> (included)
1622 * and <stop> (excluded), and will always terminate the string with a '\0'
1623 * before <stop>. The position of the '\0' is returned if the conversion
1624 * completes. If bytes are missing between <start> and <stop>, then the
1625 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1626 * cannot even be stored so we return <start> without writing the 0.
1627 * The input string must also be zero-terminated.
1628 */
1629const char hextab[16] = "0123456789ABCDEF";
1630char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001631 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001632 const char *string)
1633{
1634 if (start < stop) {
1635 stop--; /* reserve one byte for the final '\0' */
1636 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001637 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001638 *start++ = *string;
1639 else {
1640 if (start + 3 >= stop)
1641 break;
1642 *start++ = escape;
1643 *start++ = hextab[(*string >> 4) & 15];
1644 *start++ = hextab[*string & 15];
1645 }
1646 string++;
1647 }
1648 *start = '\0';
1649 }
1650 return start;
1651}
1652
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001653/*
1654 * Same behavior as encode_string() above, except that it encodes chunk
1655 * <chunk> instead of a string.
1656 */
1657char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001658 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001659 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001660{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001661 char *str = chunk->area;
1662 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001663
1664 if (start < stop) {
1665 stop--; /* reserve one byte for the final '\0' */
1666 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001667 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001668 *start++ = *str;
1669 else {
1670 if (start + 3 >= stop)
1671 break;
1672 *start++ = escape;
1673 *start++ = hextab[(*str >> 4) & 15];
1674 *start++ = hextab[*str & 15];
1675 }
1676 str++;
1677 }
1678 *start = '\0';
1679 }
1680 return start;
1681}
1682
Dragan Dosen0edd1092016-02-12 13:23:02 +01001683/*
1684 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001685 * character. The input <string> must be zero-terminated. The result will
1686 * be stored between <start> (included) and <stop> (excluded). This
1687 * function will always try to terminate the resulting string with a '\0'
1688 * before <stop>, and will return its position if the conversion
1689 * completes.
1690 */
1691char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001692 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001693 const char *string)
1694{
1695 if (start < stop) {
1696 stop--; /* reserve one byte for the final '\0' */
1697 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001698 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001699 *start++ = *string;
1700 else {
1701 if (start + 2 >= stop)
1702 break;
1703 *start++ = escape;
1704 *start++ = *string;
1705 }
1706 string++;
1707 }
1708 *start = '\0';
1709 }
1710 return start;
1711}
1712
1713/*
1714 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001715 * character. <chunk> contains the input to be escaped. The result will be
1716 * stored between <start> (included) and <stop> (excluded). The function
1717 * will always try to terminate the resulting string with a '\0' before
1718 * <stop>, and will return its position if the conversion completes.
1719 */
1720char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001721 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001722 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001723{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001724 char *str = chunk->area;
1725 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001726
1727 if (start < stop) {
1728 stop--; /* reserve one byte for the final '\0' */
1729 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001730 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001731 *start++ = *str;
1732 else {
1733 if (start + 2 >= stop)
1734 break;
1735 *start++ = escape;
1736 *start++ = *str;
1737 }
1738 str++;
1739 }
1740 *start = '\0';
1741 }
1742 return start;
1743}
1744
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001745/* Check a string for using it in a CSV output format. If the string contains
1746 * one of the following four char <">, <,>, CR or LF, the string is
1747 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1748 * <str> is the input string to be escaped. The function assumes that
1749 * the input string is null-terminated.
1750 *
1751 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001752 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001753 * format.
1754 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001755 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001756 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001757 * If <quote> is 1, the converter puts the quotes only if any reserved character
1758 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001759 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001760 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001761 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001762 * The function returns the converted string on its output. If an error
1763 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001764 * for using the function directly as printf() argument.
1765 *
1766 * If the output buffer is too short to contain the input string, the result
1767 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001768 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001769 * This function appends the encoding to the existing output chunk, and it
1770 * guarantees that it starts immediately at the first available character of
1771 * the chunk. Please use csv_enc() instead if you want to replace the output
1772 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001773 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001774const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001775{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001776 char *end = output->area + output->size;
1777 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001778 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001779
Willy Tarreaub631c292016-01-08 10:04:08 +01001780 if (quote == 1) {
1781 /* automatic quoting: first verify if we'll have to quote the string */
1782 if (!strpbrk(str, "\n\r,\""))
1783 quote = 0;
1784 }
1785
1786 if (quote)
1787 *ptr++ = '"';
1788
Willy Tarreau898529b2016-01-06 18:07:04 +01001789 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1790 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001791 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001792 ptr++;
1793 if (ptr >= end - 2) {
1794 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001795 break;
1796 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001797 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001798 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001799 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001800 str++;
1801 }
1802
Willy Tarreaub631c292016-01-08 10:04:08 +01001803 if (quote)
1804 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001805
Willy Tarreau898529b2016-01-06 18:07:04 +01001806 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001807 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001808 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001809}
1810
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001811/* Decode an URL-encoded string in-place. The resulting string might
1812 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001813 * aborted, the string is truncated before the issue and a negative value is
1814 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001815 * If the 'in_form' argument is non-nul the string is assumed to be part of
1816 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1817 * turned to a space. If it's zero, this will only be done after a question
1818 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001819 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001820int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001821{
1822 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001823 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001824
1825 in = string;
1826 out = string;
1827 while (*in) {
1828 switch (*in) {
1829 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001830 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001831 break;
1832 case '%' :
1833 if (!ishex(in[1]) || !ishex(in[2]))
1834 goto end;
1835 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1836 in += 2;
1837 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001838 case '?':
1839 in_form = 1;
1840 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001841 default:
1842 *out++ = *in;
1843 break;
1844 }
1845 in++;
1846 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001847 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001848 end:
1849 *out = 0;
1850 return ret;
1851}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001852
Willy Tarreau6911fa42007-03-04 18:06:08 +01001853unsigned int str2ui(const char *s)
1854{
1855 return __str2ui(s);
1856}
1857
1858unsigned int str2uic(const char *s)
1859{
1860 return __str2uic(s);
1861}
1862
1863unsigned int strl2ui(const char *s, int len)
1864{
1865 return __strl2ui(s, len);
1866}
1867
1868unsigned int strl2uic(const char *s, int len)
1869{
1870 return __strl2uic(s, len);
1871}
1872
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001873unsigned int read_uint(const char **s, const char *end)
1874{
1875 return __read_uint(s, end);
1876}
1877
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001878/* This function reads an unsigned integer from the string pointed to by <s> and
1879 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1880 * function automatically stops at <end>. If the number overflows, the 2^64-1
1881 * value is returned.
1882 */
1883unsigned long long int read_uint64(const char **s, const char *end)
1884{
1885 const char *ptr = *s;
1886 unsigned long long int i = 0, tmp;
1887 unsigned int j;
1888
1889 while (ptr < end) {
1890
1891 /* read next char */
1892 j = *ptr - '0';
1893 if (j > 9)
1894 goto read_uint64_end;
1895
1896 /* add char to the number and check overflow. */
1897 tmp = i * 10;
1898 if (tmp / 10 != i) {
1899 i = ULLONG_MAX;
1900 goto read_uint64_eat;
1901 }
1902 if (ULLONG_MAX - tmp < j) {
1903 i = ULLONG_MAX;
1904 goto read_uint64_eat;
1905 }
1906 i = tmp + j;
1907 ptr++;
1908 }
1909read_uint64_eat:
1910 /* eat each numeric char */
1911 while (ptr < end) {
1912 if ((unsigned int)(*ptr - '0') > 9)
1913 break;
1914 ptr++;
1915 }
1916read_uint64_end:
1917 *s = ptr;
1918 return i;
1919}
1920
1921/* This function reads an integer from the string pointed to by <s> and returns
1922 * it. The <s> pointer is adjusted to point to the first unread char. The function
1923 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1924 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1925 * returned.
1926 */
1927long long int read_int64(const char **s, const char *end)
1928{
1929 unsigned long long int i = 0;
1930 int neg = 0;
1931
1932 /* Look for minus char. */
1933 if (**s == '-') {
1934 neg = 1;
1935 (*s)++;
1936 }
1937 else if (**s == '+')
1938 (*s)++;
1939
1940 /* convert as positive number. */
1941 i = read_uint64(s, end);
1942
1943 if (neg) {
1944 if (i > 0x8000000000000000ULL)
1945 return LLONG_MIN;
1946 return -i;
1947 }
1948 if (i > 0x7fffffffffffffffULL)
1949 return LLONG_MAX;
1950 return i;
1951}
1952
Willy Tarreau6911fa42007-03-04 18:06:08 +01001953/* This one is 7 times faster than strtol() on athlon with checks.
1954 * It returns the value of the number composed of all valid digits read,
1955 * and can process negative numbers too.
1956 */
1957int strl2ic(const char *s, int len)
1958{
1959 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001960 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001961
1962 if (len > 0) {
1963 if (*s != '-') {
1964 /* positive number */
1965 while (len-- > 0) {
1966 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001967 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001968 if (j > 9)
1969 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001970 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001971 }
1972 } else {
1973 /* negative number */
1974 s++;
1975 while (--len > 0) {
1976 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001977 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001978 if (j > 9)
1979 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001980 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001981 }
1982 }
1983 }
1984 return i;
1985}
1986
1987
1988/* This function reads exactly <len> chars from <s> and converts them to a
1989 * signed integer which it stores into <ret>. It accurately detects any error
1990 * (truncated string, invalid chars, overflows). It is meant to be used in
1991 * applications designed for hostile environments. It returns zero when the
1992 * number has successfully been converted, non-zero otherwise. When an error
1993 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1994 * faster than strtol().
1995 */
1996int strl2irc(const char *s, int len, int *ret)
1997{
1998 int i = 0;
1999 int j;
2000
2001 if (!len)
2002 return 1;
2003
2004 if (*s != '-') {
2005 /* positive number */
2006 while (len-- > 0) {
2007 j = (*s++) - '0';
2008 if (j > 9) return 1; /* invalid char */
2009 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2010 i = i * 10;
2011 if (i + j < i) return 1; /* check for addition overflow */
2012 i = i + j;
2013 }
2014 } else {
2015 /* negative number */
2016 s++;
2017 while (--len > 0) {
2018 j = (*s++) - '0';
2019 if (j > 9) return 1; /* invalid char */
2020 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2021 i = i * 10;
2022 if (i - j > i) return 1; /* check for subtract overflow */
2023 i = i - j;
2024 }
2025 }
2026 *ret = i;
2027 return 0;
2028}
2029
2030
2031/* This function reads exactly <len> chars from <s> and converts them to a
2032 * signed integer which it stores into <ret>. It accurately detects any error
2033 * (truncated string, invalid chars, overflows). It is meant to be used in
2034 * applications designed for hostile environments. It returns zero when the
2035 * number has successfully been converted, non-zero otherwise. When an error
2036 * is returned, the <ret> value is left untouched. It is about 3 times slower
2037 * than str2irc().
2038 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002039
2040int strl2llrc(const char *s, int len, long long *ret)
2041{
2042 long long i = 0;
2043 int j;
2044
2045 if (!len)
2046 return 1;
2047
2048 if (*s != '-') {
2049 /* positive number */
2050 while (len-- > 0) {
2051 j = (*s++) - '0';
2052 if (j > 9) return 1; /* invalid char */
2053 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2054 i = i * 10LL;
2055 if (i + j < i) return 1; /* check for addition overflow */
2056 i = i + j;
2057 }
2058 } else {
2059 /* negative number */
2060 s++;
2061 while (--len > 0) {
2062 j = (*s++) - '0';
2063 if (j > 9) return 1; /* invalid char */
2064 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2065 i = i * 10LL;
2066 if (i - j > i) return 1; /* check for subtract overflow */
2067 i = i - j;
2068 }
2069 }
2070 *ret = i;
2071 return 0;
2072}
2073
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002074/* This function is used with pat_parse_dotted_ver(). It converts a string
2075 * composed by two number separated by a dot. Each part must contain in 16 bits
2076 * because internally they will be represented as a 32-bit quantity stored in
2077 * a 64-bit integer. It returns zero when the number has successfully been
2078 * converted, non-zero otherwise. When an error is returned, the <ret> value
2079 * is left untouched.
2080 *
2081 * "1.3" -> 0x0000000000010003
2082 * "65535.65535" -> 0x00000000ffffffff
2083 */
2084int strl2llrc_dotted(const char *text, int len, long long *ret)
2085{
2086 const char *end = &text[len];
2087 const char *p;
2088 long long major, minor;
2089
2090 /* Look for dot. */
2091 for (p = text; p < end; p++)
2092 if (*p == '.')
2093 break;
2094
2095 /* Convert major. */
2096 if (strl2llrc(text, p - text, &major) != 0)
2097 return 1;
2098
2099 /* Check major. */
2100 if (major >= 65536)
2101 return 1;
2102
2103 /* Convert minor. */
2104 minor = 0;
2105 if (p < end)
2106 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2107 return 1;
2108
2109 /* Check minor. */
2110 if (minor >= 65536)
2111 return 1;
2112
2113 /* Compose value. */
2114 *ret = (major << 16) | (minor & 0xffff);
2115 return 0;
2116}
2117
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002118/* This function parses a time value optionally followed by a unit suffix among
2119 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2120 * expected by the caller. The computation does its best to avoid overflows.
2121 * The value is returned in <ret> if everything is fine, and a NULL is returned
2122 * by the function. In case of error, a pointer to the error is returned and
2123 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002124 * Values resulting in values larger than or equal to 2^31 after conversion are
2125 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2126 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002127 */
2128const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2129{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002130 unsigned long long imult, idiv;
2131 unsigned long long omult, odiv;
2132 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002133
2134 omult = odiv = 1;
2135
2136 switch (unit_flags & TIME_UNIT_MASK) {
2137 case TIME_UNIT_US: omult = 1000000; break;
2138 case TIME_UNIT_MS: omult = 1000; break;
2139 case TIME_UNIT_S: break;
2140 case TIME_UNIT_MIN: odiv = 60; break;
2141 case TIME_UNIT_HOUR: odiv = 3600; break;
2142 case TIME_UNIT_DAY: odiv = 86400; break;
2143 default: break;
2144 }
2145
2146 value = 0;
2147
2148 while (1) {
2149 unsigned int j;
2150
2151 j = *text - '0';
2152 if (j > 9)
2153 break;
2154 text++;
2155 value *= 10;
2156 value += j;
2157 }
2158
2159 imult = idiv = 1;
2160 switch (*text) {
2161 case '\0': /* no unit = default unit */
2162 imult = omult = idiv = odiv = 1;
2163 break;
2164 case 's': /* second = unscaled unit */
2165 break;
2166 case 'u': /* microsecond : "us" */
2167 if (text[1] == 's') {
2168 idiv = 1000000;
2169 text++;
2170 }
2171 break;
2172 case 'm': /* millisecond : "ms" or minute: "m" */
2173 if (text[1] == 's') {
2174 idiv = 1000;
2175 text++;
2176 } else
2177 imult = 60;
2178 break;
2179 case 'h': /* hour : "h" */
2180 imult = 3600;
2181 break;
2182 case 'd': /* day : "d" */
2183 imult = 86400;
2184 break;
2185 default:
2186 return text;
2187 break;
2188 }
2189
2190 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2191 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2192 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2193 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2194
Willy Tarreau9faebe32019-06-07 19:00:37 +02002195 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2196 if (result >= 0x80000000)
2197 return PARSE_TIME_OVER;
2198 if (!result && value)
2199 return PARSE_TIME_UNDER;
2200 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002201 return NULL;
2202}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002203
Emeric Brun39132b22010-01-04 14:57:24 +01002204/* this function converts the string starting at <text> to an unsigned int
2205 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002206 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002207 */
2208const char *parse_size_err(const char *text, unsigned *ret) {
2209 unsigned value = 0;
2210
2211 while (1) {
2212 unsigned int j;
2213
2214 j = *text - '0';
2215 if (j > 9)
2216 break;
2217 if (value > ~0U / 10)
2218 return text;
2219 value *= 10;
2220 if (value > (value + j))
2221 return text;
2222 value += j;
2223 text++;
2224 }
2225
2226 switch (*text) {
2227 case '\0':
2228 break;
2229 case 'K':
2230 case 'k':
2231 if (value > ~0U >> 10)
2232 return text;
2233 value = value << 10;
2234 break;
2235 case 'M':
2236 case 'm':
2237 if (value > ~0U >> 20)
2238 return text;
2239 value = value << 20;
2240 break;
2241 case 'G':
2242 case 'g':
2243 if (value > ~0U >> 30)
2244 return text;
2245 value = value << 30;
2246 break;
2247 default:
2248 return text;
2249 }
2250
Godbach58048a22015-01-28 17:36:16 +08002251 if (*text != '\0' && *++text != '\0')
2252 return text;
2253
Emeric Brun39132b22010-01-04 14:57:24 +01002254 *ret = value;
2255 return NULL;
2256}
2257
Willy Tarreau126d4062013-12-03 17:50:47 +01002258/*
2259 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002260 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002261 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002262 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002263 */
2264int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2265{
2266 int len;
2267 const char *p = source;
2268 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002269 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002270
2271 len = strlen(source);
2272 if (len % 2) {
2273 memprintf(err, "an even number of hex digit is expected");
2274 return 0;
2275 }
2276
2277 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002278
Willy Tarreau126d4062013-12-03 17:50:47 +01002279 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002280 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002281 if (!*binstr) {
2282 memprintf(err, "out of memory while loading string pattern");
2283 return 0;
2284 }
2285 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002286 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002287 else {
2288 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002289 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002290 len, *binstrlen);
2291 return 0;
2292 }
2293 alloc = 0;
2294 }
2295 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002296
2297 i = j = 0;
2298 while (j < len) {
2299 if (!ishex(p[i++]))
2300 goto bad_input;
2301 if (!ishex(p[i++]))
2302 goto bad_input;
2303 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2304 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002305 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002306
2307bad_input:
2308 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002309 if (alloc) {
2310 free(*binstr);
2311 *binstr = NULL;
2312 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002313 return 0;
2314}
2315
Willy Tarreau946ba592009-05-10 15:41:18 +02002316/* copies at most <n> characters from <src> and always terminates with '\0' */
2317char *my_strndup(const char *src, int n)
2318{
2319 int len = 0;
2320 char *ret;
2321
2322 while (len < n && src[len])
2323 len++;
2324
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002325 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002326 if (!ret)
2327 return ret;
2328 memcpy(ret, src, len);
2329 ret[len] = '\0';
2330 return ret;
2331}
2332
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002333/*
2334 * search needle in haystack
2335 * returns the pointer if found, returns NULL otherwise
2336 */
2337const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2338{
2339 const void *c = NULL;
2340 unsigned char f;
2341
2342 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2343 return NULL;
2344
2345 f = *(char *)needle;
2346 c = haystack;
2347 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2348 if ((haystacklen - (c - haystack)) < needlelen)
2349 return NULL;
2350
2351 if (memcmp(c, needle, needlelen) == 0)
2352 return c;
2353 ++c;
2354 }
2355 return NULL;
2356}
2357
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002358/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002359size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2360{
2361 size_t ret = 0;
2362
2363 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2364 str++;
2365 ret++;
2366 }
2367 return ret;
2368}
2369
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002370/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002371size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2372{
2373 size_t ret = 0;
2374
2375 while (ret < len) {
2376 if(memchr(reject, *((int *)str), rejectlen))
2377 return ret;
2378 str++;
2379 ret++;
2380 }
2381 return ret;
2382}
2383
Willy Tarreau482b00d2009-10-04 22:48:42 +02002384/* This function returns the first unused key greater than or equal to <key> in
2385 * ID tree <root>. Zero is returned if no place is found.
2386 */
2387unsigned int get_next_id(struct eb_root *root, unsigned int key)
2388{
2389 struct eb32_node *used;
2390
2391 do {
2392 used = eb32_lookup_ge(root, key);
2393 if (!used || used->key > key)
2394 return key; /* key is available */
2395 key++;
2396 } while (key);
2397 return key;
2398}
2399
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002400/* dump the full tree to <file> in DOT format for debugging purposes. Will
2401 * optionally highlight node <subj> if found, depending on operation <op> :
2402 * 0 : nothing
2403 * >0 : insertion, node/leaf are surrounded in red
2404 * <0 : removal, node/leaf are dashed with no background
2405 * Will optionally add "desc" as a label on the graph if set and non-null.
2406 */
2407void 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 +01002408{
2409 struct eb32sc_node *node;
2410 unsigned long scope = -1;
2411
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002412 fprintf(file, "digraph ebtree {\n");
2413
2414 if (desc && *desc) {
2415 fprintf(file,
2416 " fontname=\"fixed\";\n"
2417 " fontsize=8;\n"
2418 " label=\"%s\";\n", desc);
2419 }
2420
Willy Tarreaued3cda02017-11-15 15:04:05 +01002421 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002422 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2423 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002424 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2425 );
2426
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002427 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002428 (long)eb_root_to_node(root),
2429 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002430 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2431
2432 node = eb32sc_first(root, scope);
2433 while (node) {
2434 if (node->node.node_p) {
2435 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002436 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2437 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2438 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002439
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002440 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002441 (long)node,
2442 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002443 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002444
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002445 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002446 (long)node,
2447 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002448 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2449
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002450 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002451 (long)node,
2452 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002453 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2454 }
2455
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002456 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2457 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2458 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002459
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002460 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002461 (long)node,
2462 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002463 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002464 node = eb32sc_next(node, scope);
2465 }
2466 fprintf(file, "}\n");
2467}
2468
Willy Tarreau348238b2010-01-18 15:05:57 +01002469/* This function compares a sample word possibly followed by blanks to another
2470 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2471 * otherwise zero. This intends to be used when checking HTTP headers for some
2472 * values. Note that it validates a word followed only by blanks but does not
2473 * validate a word followed by blanks then other chars.
2474 */
2475int word_match(const char *sample, int slen, const char *word, int wlen)
2476{
2477 if (slen < wlen)
2478 return 0;
2479
2480 while (wlen) {
2481 char c = *sample ^ *word;
2482 if (c && c != ('A' ^ 'a'))
2483 return 0;
2484 sample++;
2485 word++;
2486 slen--;
2487 wlen--;
2488 }
2489
2490 while (slen) {
2491 if (*sample != ' ' && *sample != '\t')
2492 return 0;
2493 sample++;
2494 slen--;
2495 }
2496 return 1;
2497}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002498
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002499/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2500 * is particularly fast because it avoids expensive operations such as
2501 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002502 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002503 */
2504unsigned int inetaddr_host(const char *text)
2505{
2506 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2507 register unsigned int dig100, dig10, dig1;
2508 int s;
2509 const char *p, *d;
2510
2511 dig1 = dig10 = dig100 = ascii_zero;
2512 s = 24;
2513
2514 p = text;
2515 while (1) {
2516 if (((unsigned)(*p - '0')) <= 9) {
2517 p++;
2518 continue;
2519 }
2520
2521 /* here, we have a complete byte between <text> and <p> (exclusive) */
2522 if (p == text)
2523 goto end;
2524
2525 d = p - 1;
2526 dig1 |= (unsigned int)(*d << s);
2527 if (d == text)
2528 goto end;
2529
2530 d--;
2531 dig10 |= (unsigned int)(*d << s);
2532 if (d == text)
2533 goto end;
2534
2535 d--;
2536 dig100 |= (unsigned int)(*d << s);
2537 end:
2538 if (!s || *p != '.')
2539 break;
2540
2541 s -= 8;
2542 text = ++p;
2543 }
2544
2545 dig100 -= ascii_zero;
2546 dig10 -= ascii_zero;
2547 dig1 -= ascii_zero;
2548 return ((dig100 * 10) + dig10) * 10 + dig1;
2549}
2550
2551/*
2552 * Idem except the first unparsed character has to be passed in <stop>.
2553 */
2554unsigned int inetaddr_host_lim(const char *text, const char *stop)
2555{
2556 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2557 register unsigned int dig100, dig10, dig1;
2558 int s;
2559 const char *p, *d;
2560
2561 dig1 = dig10 = dig100 = ascii_zero;
2562 s = 24;
2563
2564 p = text;
2565 while (1) {
2566 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2567 p++;
2568 continue;
2569 }
2570
2571 /* here, we have a complete byte between <text> and <p> (exclusive) */
2572 if (p == text)
2573 goto end;
2574
2575 d = p - 1;
2576 dig1 |= (unsigned int)(*d << s);
2577 if (d == text)
2578 goto end;
2579
2580 d--;
2581 dig10 |= (unsigned int)(*d << s);
2582 if (d == text)
2583 goto end;
2584
2585 d--;
2586 dig100 |= (unsigned int)(*d << s);
2587 end:
2588 if (!s || p == stop || *p != '.')
2589 break;
2590
2591 s -= 8;
2592 text = ++p;
2593 }
2594
2595 dig100 -= ascii_zero;
2596 dig10 -= ascii_zero;
2597 dig1 -= ascii_zero;
2598 return ((dig100 * 10) + dig10) * 10 + dig1;
2599}
2600
2601/*
2602 * Idem except the pointer to first unparsed byte is returned into <ret> which
2603 * must not be NULL.
2604 */
Willy Tarreau74172752010-10-15 23:21:42 +02002605unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002606{
2607 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2608 register unsigned int dig100, dig10, dig1;
2609 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002610 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002611
2612 dig1 = dig10 = dig100 = ascii_zero;
2613 s = 24;
2614
2615 p = text;
2616 while (1) {
2617 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2618 p++;
2619 continue;
2620 }
2621
2622 /* here, we have a complete byte between <text> and <p> (exclusive) */
2623 if (p == text)
2624 goto end;
2625
2626 d = p - 1;
2627 dig1 |= (unsigned int)(*d << s);
2628 if (d == text)
2629 goto end;
2630
2631 d--;
2632 dig10 |= (unsigned int)(*d << s);
2633 if (d == text)
2634 goto end;
2635
2636 d--;
2637 dig100 |= (unsigned int)(*d << s);
2638 end:
2639 if (!s || p == stop || *p != '.')
2640 break;
2641
2642 s -= 8;
2643 text = ++p;
2644 }
2645
2646 *ret = p;
2647 dig100 -= ascii_zero;
2648 dig10 -= ascii_zero;
2649 dig1 -= ascii_zero;
2650 return ((dig100 * 10) + dig10) * 10 + dig1;
2651}
2652
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002653/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2654 * or the number of chars read in case of success. Maybe this could be replaced
2655 * by one of the functions above. Also, apparently this function does not support
2656 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002657 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002658 */
2659int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2660{
2661 const char *addr;
2662 int saw_digit, octets, ch;
2663 u_char tmp[4], *tp;
2664 const char *cp = buf;
2665
2666 saw_digit = 0;
2667 octets = 0;
2668 *(tp = tmp) = 0;
2669
2670 for (addr = buf; addr - buf < len; addr++) {
2671 unsigned char digit = (ch = *addr) - '0';
2672
2673 if (digit > 9 && ch != '.')
2674 break;
2675
2676 if (digit <= 9) {
2677 u_int new = *tp * 10 + digit;
2678
2679 if (new > 255)
2680 return 0;
2681
2682 *tp = new;
2683
2684 if (!saw_digit) {
2685 if (++octets > 4)
2686 return 0;
2687 saw_digit = 1;
2688 }
2689 } else if (ch == '.' && saw_digit) {
2690 if (octets == 4)
2691 return 0;
2692
2693 *++tp = 0;
2694 saw_digit = 0;
2695 } else
2696 return 0;
2697 }
2698
2699 if (octets < 4)
2700 return 0;
2701
2702 memcpy(&dst->s_addr, tmp, 4);
2703 return addr - cp;
2704}
2705
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002706/* This function converts the string in <buf> of the len <len> to
2707 * struct in6_addr <dst> which must be allocated by the caller.
2708 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002709 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002710 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002711int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2712{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002713 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002714 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002715
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002716 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002717 return 0;
2718
2719 memcpy(null_term_ip6, buf, len);
2720 null_term_ip6[len] = '\0';
2721
Willy Tarreau075415a2013-12-12 11:29:39 +01002722 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002723 return 0;
2724
Willy Tarreau075415a2013-12-12 11:29:39 +01002725 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002726 return 1;
2727}
2728
Willy Tarreauacf95772010-06-14 19:09:21 +02002729/* To be used to quote config arg positions. Returns the short string at <ptr>
2730 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2731 * if ptr is NULL or empty. The string is locally allocated.
2732 */
2733const char *quote_arg(const char *ptr)
2734{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002735 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002736 int i;
2737
2738 if (!ptr || !*ptr)
2739 return "end of line";
2740 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002741 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002742 val[i] = *ptr++;
2743 val[i++] = '\'';
2744 val[i] = '\0';
2745 return val;
2746}
2747
Willy Tarreau5b180202010-07-18 10:40:48 +02002748/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2749int get_std_op(const char *str)
2750{
2751 int ret = -1;
2752
2753 if (*str == 'e' && str[1] == 'q')
2754 ret = STD_OP_EQ;
2755 else if (*str == 'n' && str[1] == 'e')
2756 ret = STD_OP_NE;
2757 else if (*str == 'l') {
2758 if (str[1] == 'e') ret = STD_OP_LE;
2759 else if (str[1] == 't') ret = STD_OP_LT;
2760 }
2761 else if (*str == 'g') {
2762 if (str[1] == 'e') ret = STD_OP_GE;
2763 else if (str[1] == 't') ret = STD_OP_GT;
2764 }
2765
2766 if (ret == -1 || str[2] != '\0')
2767 return -1;
2768 return ret;
2769}
2770
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002771/* hash a 32-bit integer to another 32-bit integer */
2772unsigned int full_hash(unsigned int a)
2773{
2774 return __full_hash(a);
2775}
2776
Willy Tarreauf3241112019-02-26 09:56:22 +01002777/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2778 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2779 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2780 * a popcount variant and is described here :
2781 * https://graphics.stanford.edu/~seander/bithacks.html
2782 */
2783unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2784{
2785 unsigned long a, b, c, d;
2786 unsigned int s;
2787 unsigned int t;
2788
2789 a = m - ((m >> 1) & ~0UL/3);
2790 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2791 c = (b + (b >> 4)) & ~0UL/0x11;
2792 d = (c + (c >> 8)) & ~0UL/0x101;
2793
2794 r++; // make r be 1..64
2795
2796 t = 0;
2797 s = LONGBITS;
2798 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002799 unsigned long d2 = (d >> 16) >> 16;
2800 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002801 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2802 }
2803
2804 t = (d >> (s - 16)) & 0xff;
2805 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2806 t = (c >> (s - 8)) & 0xf;
2807 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2808 t = (b >> (s - 4)) & 0x7;
2809 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2810 t = (a >> (s - 2)) & 0x3;
2811 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2812 t = (m >> (s - 1)) & 0x1;
2813 s -= ((t - r) & 256) >> 8;
2814
2815 return s - 1;
2816}
2817
2818/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2819 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2820 * using mask_prep_rank_map() below.
2821 */
2822unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2823 unsigned long a, unsigned long b,
2824 unsigned long c, unsigned long d)
2825{
2826 unsigned int s;
2827 unsigned int t;
2828
2829 r++; // make r be 1..64
2830
2831 t = 0;
2832 s = LONGBITS;
2833 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002834 unsigned long d2 = (d >> 16) >> 16;
2835 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002836 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2837 }
2838
2839 t = (d >> (s - 16)) & 0xff;
2840 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2841 t = (c >> (s - 8)) & 0xf;
2842 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2843 t = (b >> (s - 4)) & 0x7;
2844 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2845 t = (a >> (s - 2)) & 0x3;
2846 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2847 t = (m >> (s - 1)) & 0x1;
2848 s -= ((t - r) & 256) >> 8;
2849
2850 return s - 1;
2851}
2852
2853/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2854 * above.
2855 */
2856void mask_prep_rank_map(unsigned long m,
2857 unsigned long *a, unsigned long *b,
2858 unsigned long *c, unsigned long *d)
2859{
2860 *a = m - ((m >> 1) & ~0UL/3);
2861 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2862 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2863 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2864}
2865
David du Colombier4f92d322011-03-24 11:09:31 +01002866/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002867 * otherwise zero. Note that <addr> may not necessarily be aligned
2868 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002869 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002870int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002871{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002872 struct in_addr addr_copy;
2873
2874 memcpy(&addr_copy, addr, sizeof(addr_copy));
2875 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002876}
2877
2878/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002879 * otherwise zero. Note that <addr> may not necessarily be aligned
2880 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002881 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002882int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002883{
2884 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002885 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002886
Willy Tarreaueec1d382016-07-13 11:59:39 +02002887 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002888 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002889 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002890 (((int *)net)[i] & ((int *)mask)[i]))
2891 return 0;
2892 return 1;
2893}
2894
2895/* RFC 4291 prefix */
2896const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2897 0x00, 0x00, 0x00, 0x00,
2898 0x00, 0x00, 0xFF, 0xFF };
2899
Joseph Herlant32b83272018-11-15 11:58:28 -08002900/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002901 * Input and output may overlap.
2902 */
David du Colombier4f92d322011-03-24 11:09:31 +01002903void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2904{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002905 struct in_addr tmp_addr;
2906
2907 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002908 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002909 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002910}
2911
Joseph Herlant32b83272018-11-15 11:58:28 -08002912/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002913 * Return true if conversion is possible and false otherwise.
2914 */
2915int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2916{
2917 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2918 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2919 sizeof(struct in_addr));
2920 return 1;
2921 }
2922
2923 return 0;
2924}
2925
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002926/* compare two struct sockaddr_storage and return:
2927 * 0 (true) if the addr is the same in both
2928 * 1 (false) if the addr is not the same in both
2929 * -1 (unable) if one of the addr is not AF_INET*
2930 */
2931int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2932{
2933 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2934 return -1;
2935
2936 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2937 return -1;
2938
2939 if (ss1->ss_family != ss2->ss_family)
2940 return 1;
2941
2942 switch (ss1->ss_family) {
2943 case AF_INET:
2944 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2945 &((struct sockaddr_in *)ss2)->sin_addr,
2946 sizeof(struct in_addr)) != 0;
2947 case AF_INET6:
2948 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2949 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2950 sizeof(struct in6_addr)) != 0;
2951 }
2952
2953 return 1;
2954}
2955
Baptiste Assmann08396c82016-01-31 00:27:17 +01002956/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002957 * The caller must allocate and clear <dest> before calling.
2958 * The source must be in either AF_INET or AF_INET6 family, or the destination
2959 * address will be undefined. If the destination address used to hold a port,
2960 * it is preserved, so that this function can be used to switch to another
2961 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002962 */
2963struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2964{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002965 int prev_port;
2966
2967 prev_port = get_net_port(dest);
2968 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002969 dest->ss_family = source->ss_family;
2970
2971 /* copy new addr and apply it */
2972 switch (source->ss_family) {
2973 case AF_INET:
2974 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002975 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002976 break;
2977 case AF_INET6:
2978 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 +01002979 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002980 break;
2981 }
2982
2983 return dest;
2984}
2985
William Lallemand421f5b52012-02-06 18:15:57 +01002986char *human_time(int t, short hz_div) {
2987 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2988 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002989 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002990 int cnt=2; // print two numbers
2991
2992 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002993 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002994 return rv;
2995 }
2996
2997 if (unlikely(hz_div > 1))
2998 t /= hz_div;
2999
3000 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003001 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003002 cnt--;
3003 }
3004
3005 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003006 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003007 cnt--;
3008 }
3009
3010 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003011 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003012 cnt--;
3013 }
3014
3015 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003016 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003017
3018 return rv;
3019}
3020
3021const char *monthname[12] = {
3022 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3023 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3024};
3025
3026/* date2str_log: write a date in the format :
3027 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3028 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3029 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3030 *
3031 * without using sprintf. return a pointer to the last char written (\0) or
3032 * NULL if there isn't enough space.
3033 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003034char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003035{
3036
3037 if (size < 25) /* the size is fixed: 24 chars + \0 */
3038 return NULL;
3039
3040 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003041 if (!dst)
3042 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003043 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003044
William Lallemand421f5b52012-02-06 18:15:57 +01003045 memcpy(dst, monthname[tm->tm_mon], 3); // month
3046 dst += 3;
3047 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003048
William Lallemand421f5b52012-02-06 18:15:57 +01003049 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003050 if (!dst)
3051 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003052 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003053
William Lallemand421f5b52012-02-06 18:15:57 +01003054 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003055 if (!dst)
3056 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003057 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003058
William Lallemand421f5b52012-02-06 18:15:57 +01003059 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003060 if (!dst)
3061 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003062 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003063
William Lallemand421f5b52012-02-06 18:15:57 +01003064 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003065 if (!dst)
3066 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003067 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003068
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003069 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003070 if (!dst)
3071 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003072 *dst = '\0';
3073
3074 return dst;
3075}
3076
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003077/* Base year used to compute leap years */
3078#define TM_YEAR_BASE 1900
3079
3080/* Return the difference in seconds between two times (leap seconds are ignored).
3081 * Retrieved from glibc 2.18 source code.
3082 */
3083static int my_tm_diff(const struct tm *a, const struct tm *b)
3084{
3085 /* Compute intervening leap days correctly even if year is negative.
3086 * Take care to avoid int overflow in leap day calculations,
3087 * but it's OK to assume that A and B are close to each other.
3088 */
3089 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3090 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3091 int a100 = a4 / 25 - (a4 % 25 < 0);
3092 int b100 = b4 / 25 - (b4 % 25 < 0);
3093 int a400 = a100 >> 2;
3094 int b400 = b100 >> 2;
3095 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3096 int years = a->tm_year - b->tm_year;
3097 int days = (365 * years + intervening_leap_days
3098 + (a->tm_yday - b->tm_yday));
3099 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3100 + (a->tm_min - b->tm_min))
3101 + (a->tm_sec - b->tm_sec));
3102}
3103
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003104/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003105 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003106 * The string returned has the same format as returned by strftime(... "%z", tm).
3107 * Offsets are kept in an internal cache for better performances.
3108 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003109const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003110{
3111 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003112 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003113
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003114 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003115 struct tm tm_gmt;
3116 int diff;
3117 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003118
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003119 /* Pretend DST not active if its status is unknown */
3120 if (isdst < 0)
3121 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003122
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003123 /* Fetch the offset and initialize it if needed */
3124 gmt_offset = gmt_offsets[isdst & 0x01];
3125 if (unlikely(!*gmt_offset)) {
3126 get_gmtime(t, &tm_gmt);
3127 diff = my_tm_diff(tm, &tm_gmt);
3128 if (diff < 0) {
3129 diff = -diff;
3130 *gmt_offset = '-';
3131 } else {
3132 *gmt_offset = '+';
3133 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003134 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003135 diff /= 60; /* Convert to minutes */
3136 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3137 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003138
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003139 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003140}
3141
William Lallemand421f5b52012-02-06 18:15:57 +01003142/* gmt2str_log: write a date in the format :
3143 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3144 * return a pointer to the last char written (\0) or
3145 * NULL if there isn't enough space.
3146 */
3147char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3148{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003149 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003150 return NULL;
3151
3152 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003153 if (!dst)
3154 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003155 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003156
William Lallemand421f5b52012-02-06 18:15:57 +01003157 memcpy(dst, monthname[tm->tm_mon], 3); // month
3158 dst += 3;
3159 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003160
William Lallemand421f5b52012-02-06 18:15:57 +01003161 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003162 if (!dst)
3163 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003164 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003165
William Lallemand421f5b52012-02-06 18:15:57 +01003166 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003167 if (!dst)
3168 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003169 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003170
William Lallemand421f5b52012-02-06 18:15:57 +01003171 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003172 if (!dst)
3173 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003174 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003175
William Lallemand421f5b52012-02-06 18:15:57 +01003176 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003177 if (!dst)
3178 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003179 *dst++ = ' ';
3180 *dst++ = '+';
3181 *dst++ = '0';
3182 *dst++ = '0';
3183 *dst++ = '0';
3184 *dst++ = '0';
3185 *dst = '\0';
3186
3187 return dst;
3188}
3189
Yuxans Yao4e25b012012-10-19 10:36:09 +08003190/* localdate2str_log: write a date in the format :
3191 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003192 * Both t and tm must represent the same time.
3193 * return a pointer to the last char written (\0) or
3194 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003195 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003196char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003197{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003198 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003199 if (size < 27) /* the size is fixed: 26 chars + \0 */
3200 return NULL;
3201
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003202 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003203
Yuxans Yao4e25b012012-10-19 10:36:09 +08003204 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003205 if (!dst)
3206 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003207 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003208
Yuxans Yao4e25b012012-10-19 10:36:09 +08003209 memcpy(dst, monthname[tm->tm_mon], 3); // month
3210 dst += 3;
3211 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003212
Yuxans Yao4e25b012012-10-19 10:36:09 +08003213 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003214 if (!dst)
3215 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003216 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003217
Yuxans Yao4e25b012012-10-19 10:36:09 +08003218 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003219 if (!dst)
3220 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003221 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003222
Yuxans Yao4e25b012012-10-19 10:36:09 +08003223 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003224 if (!dst)
3225 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003226 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003227
Yuxans Yao4e25b012012-10-19 10:36:09 +08003228 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003229 if (!dst)
3230 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003231 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003232
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003233 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003234 dst += 5;
3235 *dst = '\0';
3236
3237 return dst;
3238}
3239
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003240/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3241 * It is meant as a portable replacement for timegm() for use with valid inputs.
3242 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3243 */
3244time_t my_timegm(const struct tm *tm)
3245{
3246 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3247 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3248 * sum of the extra N days for elapsed months. The sum of all these N
3249 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3250 * in a 5-bit word. This means that with 60 bits we can represent a
3251 * matrix of all these values at once, which is fast and efficient to
3252 * access. The extra February day for leap years is not counted here.
3253 *
3254 * Jan : none = 0 (0)
3255 * Feb : Jan = 3 (3)
3256 * Mar : Jan..Feb = 3 (3 + 0)
3257 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3258 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3259 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3260 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3261 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3262 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3263 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3264 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3265 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3266 */
3267 uint64_t extra =
3268 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3269 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3270 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3271 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3272
3273 unsigned int y = tm->tm_year + 1900;
3274 unsigned int m = tm->tm_mon;
3275 unsigned long days = 0;
3276
3277 /* days since 1/1/1970 for full years */
3278 days += days_since_zero(y) - days_since_zero(1970);
3279
3280 /* days for full months in the current year */
3281 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3282
3283 /* count + 1 after March for leap years. A leap year is a year multiple
3284 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3285 * is leap, 1900 isn't, 1904 is.
3286 */
3287 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3288 days++;
3289
3290 days += tm->tm_mday - 1;
3291 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3292}
3293
Thierry Fournier93127942016-01-20 18:49:45 +01003294/* This function check a char. It returns true and updates
3295 * <date> and <len> pointer to the new position if the
3296 * character is found.
3297 */
3298static inline int parse_expect_char(const char **date, int *len, char c)
3299{
3300 if (*len < 1 || **date != c)
3301 return 0;
3302 (*len)--;
3303 (*date)++;
3304 return 1;
3305}
3306
3307/* This function expects a string <str> of len <l>. It return true and updates.
3308 * <date> and <len> if the string matches, otherwise, it returns false.
3309 */
3310static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3311{
3312 if (*len < l || strncmp(*date, str, l) != 0)
3313 return 0;
3314 (*len) -= l;
3315 (*date) += l;
3316 return 1;
3317}
3318
3319/* This macro converts 3 chars name in integer. */
3320#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3321
3322/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3323 * / %x54.75.65 ; "Tue", case-sensitive
3324 * / %x57.65.64 ; "Wed", case-sensitive
3325 * / %x54.68.75 ; "Thu", case-sensitive
3326 * / %x46.72.69 ; "Fri", case-sensitive
3327 * / %x53.61.74 ; "Sat", case-sensitive
3328 * / %x53.75.6E ; "Sun", case-sensitive
3329 *
3330 * This array must be alphabetically sorted
3331 */
3332static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3333{
3334 if (*len < 3)
3335 return 0;
3336 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3337 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3338 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3339 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3340 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3341 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3342 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3343 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3344 default: return 0;
3345 }
3346 *len -= 3;
3347 *date += 3;
3348 return 1;
3349}
3350
3351/* month = %x4A.61.6E ; "Jan", case-sensitive
3352 * / %x46.65.62 ; "Feb", case-sensitive
3353 * / %x4D.61.72 ; "Mar", case-sensitive
3354 * / %x41.70.72 ; "Apr", case-sensitive
3355 * / %x4D.61.79 ; "May", case-sensitive
3356 * / %x4A.75.6E ; "Jun", case-sensitive
3357 * / %x4A.75.6C ; "Jul", case-sensitive
3358 * / %x41.75.67 ; "Aug", case-sensitive
3359 * / %x53.65.70 ; "Sep", case-sensitive
3360 * / %x4F.63.74 ; "Oct", case-sensitive
3361 * / %x4E.6F.76 ; "Nov", case-sensitive
3362 * / %x44.65.63 ; "Dec", case-sensitive
3363 *
3364 * This array must be alphabetically sorted
3365 */
3366static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3367{
3368 if (*len < 3)
3369 return 0;
3370 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3371 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3372 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3373 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3374 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3375 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3376 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3377 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3378 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3379 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3380 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3381 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3382 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3383 default: return 0;
3384 }
3385 *len -= 3;
3386 *date += 3;
3387 return 1;
3388}
3389
3390/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3391 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3392 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3393 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3394 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3395 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3396 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3397 *
3398 * This array must be alphabetically sorted
3399 */
3400static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3401{
3402 if (*len < 6) /* Minimum length. */
3403 return 0;
3404 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3405 case STR2I3('M','o','n'):
3406 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3407 tm->tm_wday = 1;
3408 return 1;
3409 case STR2I3('T','u','e'):
3410 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3411 tm->tm_wday = 2;
3412 return 1;
3413 case STR2I3('W','e','d'):
3414 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3415 tm->tm_wday = 3;
3416 return 1;
3417 case STR2I3('T','h','u'):
3418 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3419 tm->tm_wday = 4;
3420 return 1;
3421 case STR2I3('F','r','i'):
3422 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3423 tm->tm_wday = 5;
3424 return 1;
3425 case STR2I3('S','a','t'):
3426 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3427 tm->tm_wday = 6;
3428 return 1;
3429 case STR2I3('S','u','n'):
3430 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3431 tm->tm_wday = 7;
3432 return 1;
3433 }
3434 return 0;
3435}
3436
3437/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3438static inline int parse_digit(const char **date, int *len, int *digit)
3439{
3440 if (*len < 1 || **date < '0' || **date > '9')
3441 return 0;
3442 *digit = (**date - '0');
3443 (*date)++;
3444 (*len)--;
3445 return 1;
3446}
3447
3448/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3449static inline int parse_2digit(const char **date, int *len, int *digit)
3450{
3451 int value;
3452
3453 RET0_UNLESS(parse_digit(date, len, &value));
3454 (*digit) = value * 10;
3455 RET0_UNLESS(parse_digit(date, len, &value));
3456 (*digit) += value;
3457
3458 return 1;
3459}
3460
3461/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3462static inline int parse_4digit(const char **date, int *len, int *digit)
3463{
3464 int value;
3465
3466 RET0_UNLESS(parse_digit(date, len, &value));
3467 (*digit) = value * 1000;
3468
3469 RET0_UNLESS(parse_digit(date, len, &value));
3470 (*digit) += value * 100;
3471
3472 RET0_UNLESS(parse_digit(date, len, &value));
3473 (*digit) += value * 10;
3474
3475 RET0_UNLESS(parse_digit(date, len, &value));
3476 (*digit) += value;
3477
3478 return 1;
3479}
3480
3481/* time-of-day = hour ":" minute ":" second
3482 * ; 00:00:00 - 23:59:60 (leap second)
3483 *
3484 * hour = 2DIGIT
3485 * minute = 2DIGIT
3486 * second = 2DIGIT
3487 */
3488static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3489{
3490 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3491 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3492 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3493 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3494 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3495 return 1;
3496}
3497
3498/* From RFC7231
3499 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3500 *
3501 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3502 * ; fixed length/zone/capitalization subset of the format
3503 * ; see Section 3.3 of [RFC5322]
3504 *
3505 *
3506 * date1 = day SP month SP year
3507 * ; e.g., 02 Jun 1982
3508 *
3509 * day = 2DIGIT
3510 * year = 4DIGIT
3511 *
3512 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3513 *
3514 * time-of-day = hour ":" minute ":" second
3515 * ; 00:00:00 - 23:59:60 (leap second)
3516 *
3517 * hour = 2DIGIT
3518 * minute = 2DIGIT
3519 * second = 2DIGIT
3520 *
3521 * DIGIT = decimal 0-9
3522 */
3523int parse_imf_date(const char *date, int len, struct tm *tm)
3524{
David Carlier327298c2016-11-20 10:42:38 +00003525 /* tm_gmtoff, if present, ought to be zero'ed */
3526 memset(tm, 0, sizeof(*tm));
3527
Thierry Fournier93127942016-01-20 18:49:45 +01003528 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3529 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3530 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3531 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3532 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3533 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3534 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3535 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3536 tm->tm_year -= 1900;
3537 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3538 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3539 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3540 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3541 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003542 return 1;
3543}
3544
3545/* From RFC7231
3546 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3547 *
3548 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3549 * date2 = day "-" month "-" 2DIGIT
3550 * ; e.g., 02-Jun-82
3551 *
3552 * day = 2DIGIT
3553 */
3554int parse_rfc850_date(const char *date, int len, struct tm *tm)
3555{
3556 int year;
3557
David Carlier327298c2016-11-20 10:42:38 +00003558 /* tm_gmtoff, if present, ought to be zero'ed */
3559 memset(tm, 0, sizeof(*tm));
3560
Thierry Fournier93127942016-01-20 18:49:45 +01003561 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3562 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3563 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3564 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3565 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3566 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3567 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3568
3569 /* year = 2DIGIT
3570 *
3571 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3572 * two-digit year, MUST interpret a timestamp that appears to be more
3573 * than 50 years in the future as representing the most recent year in
3574 * the past that had the same last two digits.
3575 */
3576 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3577
3578 /* expect SP */
3579 if (!parse_expect_char(&date, &len, ' ')) {
3580 /* Maybe we have the date with 4 digits. */
3581 RET0_UNLESS(parse_2digit(&date, &len, &year));
3582 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3583 /* expect SP */
3584 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3585 } else {
3586 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3587 * tm_year is the number of year since 1900, so for +1900, we
3588 * do nothing, and for +2000, we add 100.
3589 */
3590 if (tm->tm_year <= 60)
3591 tm->tm_year += 100;
3592 }
3593
3594 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3595 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3596 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3597 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003598
3599 return 1;
3600}
3601
3602/* From RFC7231
3603 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3604 *
3605 * asctime-date = day-name SP date3 SP time-of-day SP year
3606 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3607 * ; e.g., Jun 2
3608 *
3609 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3610 * whitespace in an HTTP-date beyond that specifically included as SP in
3611 * the grammar.
3612 */
3613int parse_asctime_date(const char *date, int len, struct tm *tm)
3614{
David Carlier327298c2016-11-20 10:42:38 +00003615 /* tm_gmtoff, if present, ought to be zero'ed */
3616 memset(tm, 0, sizeof(*tm));
3617
Thierry Fournier93127942016-01-20 18:49:45 +01003618 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3619 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3620 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3621 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3622
3623 /* expect SP and 1DIGIT or 2DIGIT */
3624 if (parse_expect_char(&date, &len, ' '))
3625 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3626 else
3627 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3628
3629 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3630 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3631 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3632 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3633 tm->tm_year -= 1900;
3634 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003635 return 1;
3636}
3637
3638/* From RFC7231
3639 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3640 *
3641 * HTTP-date = IMF-fixdate / obs-date
3642 * obs-date = rfc850-date / asctime-date
3643 *
3644 * parses an HTTP date in the RFC format and is accepted
3645 * alternatives. <date> is the strinf containing the date,
3646 * len is the len of the string. <tm> is filled with the
3647 * parsed time. We must considers this time as GMT.
3648 */
3649int parse_http_date(const char *date, int len, struct tm *tm)
3650{
3651 if (parse_imf_date(date, len, tm))
3652 return 1;
3653
3654 if (parse_rfc850_date(date, len, tm))
3655 return 1;
3656
3657 if (parse_asctime_date(date, len, tm))
3658 return 1;
3659
3660 return 0;
3661}
3662
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003663/* Dynamically allocates a string of the proper length to hold the formatted
3664 * output. NULL is returned on error. The caller is responsible for freeing the
3665 * memory area using free(). The resulting string is returned in <out> if the
3666 * pointer is not NULL. A previous version of <out> might be used to build the
3667 * new string, and it will be freed before returning if it is not NULL, which
3668 * makes it possible to build complex strings from iterative calls without
3669 * having to care about freeing intermediate values, as in the example below :
3670 *
3671 * memprintf(&err, "invalid argument: '%s'", arg);
3672 * ...
3673 * memprintf(&err, "parser said : <%s>\n", *err);
3674 * ...
3675 * free(*err);
3676 *
3677 * This means that <err> must be initialized to NULL before first invocation.
3678 * The return value also holds the allocated string, which eases error checking
3679 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003680 * passed instead and it will be ignored. The returned message will then also
3681 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003682 *
3683 * It is also convenient to use it without any free except the last one :
3684 * err = NULL;
3685 * if (!fct1(err)) report(*err);
3686 * if (!fct2(err)) report(*err);
3687 * if (!fct3(err)) report(*err);
3688 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003689 *
3690 * memprintf relies on memvprintf. This last version can be called from any
3691 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003692 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003693char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003694{
3695 va_list args;
3696 char *ret = NULL;
3697 int allocated = 0;
3698 int needed = 0;
3699
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003700 if (!out)
3701 return NULL;
3702
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003703 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003704 char buf1;
3705
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003706 /* vsnprintf() will return the required length even when the
3707 * target buffer is NULL. We do this in a loop just in case
3708 * intermediate evaluations get wrong.
3709 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003710 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003711 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003712 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003713 if (needed < allocated) {
3714 /* Note: on Solaris 8, the first iteration always
3715 * returns -1 if allocated is zero, so we force a
3716 * retry.
3717 */
3718 if (!allocated)
3719 needed = 0;
3720 else
3721 break;
3722 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003723
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003724 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003725 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003726 } while (ret);
3727
3728 if (needed < 0) {
3729 /* an error was encountered */
3730 free(ret);
3731 ret = NULL;
3732 }
3733
3734 if (out) {
3735 free(*out);
3736 *out = ret;
3737 }
3738
3739 return ret;
3740}
William Lallemand421f5b52012-02-06 18:15:57 +01003741
Christopher Faulet93a518f2017-10-24 11:25:33 +02003742char *memprintf(char **out, const char *format, ...)
3743{
3744 va_list args;
3745 char *ret = NULL;
3746
3747 va_start(args, format);
3748 ret = memvprintf(out, format, args);
3749 va_end(args);
3750
3751 return ret;
3752}
3753
Willy Tarreau21c705b2012-09-14 11:40:36 +02003754/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3755 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003756 * freed by the caller. It also supports being passed a NULL which results in the same
3757 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003758 * Example of use :
3759 * parse(cmd, &err); (callee: memprintf(&err, ...))
3760 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3761 * free(err);
3762 */
3763char *indent_msg(char **out, int level)
3764{
3765 char *ret, *in, *p;
3766 int needed = 0;
3767 int lf = 0;
3768 int lastlf = 0;
3769 int len;
3770
Willy Tarreau70eec382012-10-10 08:56:47 +02003771 if (!out || !*out)
3772 return NULL;
3773
Willy Tarreau21c705b2012-09-14 11:40:36 +02003774 in = *out - 1;
3775 while ((in = strchr(in + 1, '\n')) != NULL) {
3776 lastlf = in - *out;
3777 lf++;
3778 }
3779
3780 if (!lf) /* single line, no LF, return it as-is */
3781 return *out;
3782
3783 len = strlen(*out);
3784
3785 if (lf == 1 && lastlf == len - 1) {
3786 /* single line, LF at end, strip it and return as-is */
3787 (*out)[lastlf] = 0;
3788 return *out;
3789 }
3790
3791 /* OK now we have at least one LF, we need to process the whole string
3792 * as a multi-line string. What we'll do :
3793 * - prefix with an LF if there is none
3794 * - add <level> spaces before each line
3795 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3796 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3797 */
3798
3799 needed = 1 + level * (lf + 1) + len + 1;
3800 p = ret = malloc(needed);
3801 in = *out;
3802
3803 /* skip initial LFs */
3804 while (*in == '\n')
3805 in++;
3806
3807 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3808 while (*in) {
3809 *p++ = '\n';
3810 memset(p, ' ', level);
3811 p += level;
3812 do {
3813 *p++ = *in++;
3814 } while (*in && *in != '\n');
3815 if (*in)
3816 in++;
3817 }
3818 *p = 0;
3819
3820 free(*out);
3821 *out = ret;
3822
3823 return ret;
3824}
3825
Willy Tarreaua2c99112019-08-21 13:17:37 +02003826/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3827 * and end of lines replaced with <eol> if not 0. The first line to indent has
3828 * to be indicated in <first> (starts at zero), so that it is possible to skip
3829 * indenting the first line if it has to be appended after an existing message.
3830 * Empty strings are never indented, and NULL strings are considered empty both
3831 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3832 * character, non-zero otherwise.
3833 */
3834int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3835{
3836 int bol, lf;
3837 int pfxlen = pfx ? strlen(pfx) : 0;
3838
3839 if (!in)
3840 return 0;
3841
3842 bol = 1;
3843 lf = 0;
3844 while (*in) {
3845 if (bol && pfxlen) {
3846 if (first > 0)
3847 first--;
3848 else
3849 b_putblk(out, pfx, pfxlen);
3850 bol = 0;
3851 }
3852
3853 lf = (*in == '\n');
3854 bol |= lf;
3855 b_putchr(out, (lf && eol) ? eol : *in);
3856 in++;
3857 }
3858 return lf;
3859}
3860
Willy Tarreau9d22e562019-03-29 18:49:09 +01003861/* removes environment variable <name> from the environment as found in
3862 * environ. This is only provided as an alternative for systems without
3863 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003864 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003865 * <name> and to replace the matching pointers with the last pointer of
3866 * the array (since variables are not ordered).
3867 * It always returns 0 (success).
3868 */
3869int my_unsetenv(const char *name)
3870{
3871 extern char **environ;
3872 char **p = environ;
3873 int vars;
3874 int next;
3875 int len;
3876
3877 len = strlen(name);
3878 for (vars = 0; p[vars]; vars++)
3879 ;
3880 next = 0;
3881 while (next < vars) {
3882 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3883 next++;
3884 continue;
3885 }
3886 if (next < vars - 1)
3887 p[next] = p[vars - 1];
3888 p[--vars] = NULL;
3889 }
3890 return 0;
3891}
3892
Willy Tarreaudad36a32013-03-11 01:20:04 +01003893/* Convert occurrences of environment variables in the input string to their
3894 * corresponding value. A variable is identified as a series of alphanumeric
3895 * characters or underscores following a '$' sign. The <in> string must be
3896 * free()able. NULL returns NULL. The resulting string might be reallocated if
3897 * some expansion is made. Variable names may also be enclosed into braces if
3898 * needed (eg: to concatenate alphanum characters).
3899 */
3900char *env_expand(char *in)
3901{
3902 char *txt_beg;
3903 char *out;
3904 char *txt_end;
3905 char *var_beg;
3906 char *var_end;
3907 char *value;
3908 char *next;
3909 int out_len;
3910 int val_len;
3911
3912 if (!in)
3913 return in;
3914
3915 value = out = NULL;
3916 out_len = 0;
3917
3918 txt_beg = in;
3919 do {
3920 /* look for next '$' sign in <in> */
3921 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3922
3923 if (!*txt_end && !out) /* end and no expansion performed */
3924 return in;
3925
3926 val_len = 0;
3927 next = txt_end;
3928 if (*txt_end == '$') {
3929 char save;
3930
3931 var_beg = txt_end + 1;
3932 if (*var_beg == '{')
3933 var_beg++;
3934
3935 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003936 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003937 var_end++;
3938 }
3939
3940 next = var_end;
3941 if (*var_end == '}' && (var_beg > txt_end + 1))
3942 next++;
3943
3944 /* get value of the variable name at this location */
3945 save = *var_end;
3946 *var_end = '\0';
3947 value = getenv(var_beg);
3948 *var_end = save;
3949 val_len = value ? strlen(value) : 0;
3950 }
3951
Hubert Verstraete831962e2016-06-28 22:44:26 +02003952 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003953 if (txt_end > txt_beg) {
3954 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3955 out_len += txt_end - txt_beg;
3956 }
3957 if (val_len) {
3958 memcpy(out + out_len, value, val_len);
3959 out_len += val_len;
3960 }
3961 out[out_len] = 0;
3962 txt_beg = next;
3963 } while (*txt_beg);
3964
3965 /* here we know that <out> was allocated and that we don't need <in> anymore */
3966 free(in);
3967 return out;
3968}
3969
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003970
3971/* same as strstr() but case-insensitive and with limit length */
3972const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3973{
3974 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003975 unsigned int slen, plen;
3976 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003977
3978 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3979 return NULL;
3980
3981 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3982 return str1;
3983
3984 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3985 return NULL;
3986
3987 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 +02003988 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003989 start++;
3990 slen--;
3991 tmp1++;
3992
3993 if (tmp1 >= len_str1)
3994 return NULL;
3995
3996 /* if pattern longer than string */
3997 if (slen < plen)
3998 return NULL;
3999 }
4000
4001 sptr = start;
4002 pptr = (char *)str2;
4003
4004 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004005 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004006 sptr++;
4007 pptr++;
4008 tmp2++;
4009
4010 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4011 return start;
4012 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4013 return NULL;
4014 }
4015 }
4016 return NULL;
4017}
4018
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004019/* This function read the next valid utf8 char.
4020 * <s> is the byte srray to be decode, <len> is its length.
4021 * The function returns decoded char encoded like this:
4022 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4023 * are the length read. The decoded character is stored in <c>.
4024 */
4025unsigned char utf8_next(const char *s, int len, unsigned int *c)
4026{
4027 const unsigned char *p = (unsigned char *)s;
4028 int dec;
4029 unsigned char code = UTF8_CODE_OK;
4030
4031 if (len < 1)
4032 return UTF8_CODE_OK;
4033
4034 /* Check the type of UTF8 sequence
4035 *
4036 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4037 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4038 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4039 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4040 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4041 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4042 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4043 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4044 */
4045 switch (*p) {
4046 case 0x00 ... 0x7f:
4047 *c = *p;
4048 return UTF8_CODE_OK | 1;
4049
4050 case 0x80 ... 0xbf:
4051 *c = *p;
4052 return UTF8_CODE_BADSEQ | 1;
4053
4054 case 0xc0 ... 0xdf:
4055 if (len < 2) {
4056 *c = *p;
4057 return UTF8_CODE_BADSEQ | 1;
4058 }
4059 *c = *p & 0x1f;
4060 dec = 1;
4061 break;
4062
4063 case 0xe0 ... 0xef:
4064 if (len < 3) {
4065 *c = *p;
4066 return UTF8_CODE_BADSEQ | 1;
4067 }
4068 *c = *p & 0x0f;
4069 dec = 2;
4070 break;
4071
4072 case 0xf0 ... 0xf7:
4073 if (len < 4) {
4074 *c = *p;
4075 return UTF8_CODE_BADSEQ | 1;
4076 }
4077 *c = *p & 0x07;
4078 dec = 3;
4079 break;
4080
4081 case 0xf8 ... 0xfb:
4082 if (len < 5) {
4083 *c = *p;
4084 return UTF8_CODE_BADSEQ | 1;
4085 }
4086 *c = *p & 0x03;
4087 dec = 4;
4088 break;
4089
4090 case 0xfc ... 0xfd:
4091 if (len < 6) {
4092 *c = *p;
4093 return UTF8_CODE_BADSEQ | 1;
4094 }
4095 *c = *p & 0x01;
4096 dec = 5;
4097 break;
4098
4099 case 0xfe ... 0xff:
4100 default:
4101 *c = *p;
4102 return UTF8_CODE_BADSEQ | 1;
4103 }
4104
4105 p++;
4106
4107 while (dec > 0) {
4108
4109 /* need 0x10 for the 2 first bits */
4110 if ( ( *p & 0xc0 ) != 0x80 )
4111 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4112
4113 /* add data at char */
4114 *c = ( *c << 6 ) | ( *p & 0x3f );
4115
4116 dec--;
4117 p++;
4118 }
4119
4120 /* Check ovelong encoding.
4121 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4122 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4123 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4124 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004125 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004126 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4127 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4128 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4129 code |= UTF8_CODE_OVERLONG;
4130
4131 /* Check invalid UTF8 range. */
4132 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4133 (*c >= 0xfffe && *c <= 0xffff))
4134 code |= UTF8_CODE_INVRANGE;
4135
4136 return code | ((p-(unsigned char *)s)&0x0f);
4137}
4138
Maxime de Roucydc887852016-05-13 23:52:54 +02004139/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4140 * On failure : return 0 and <err> filled with an error message.
4141 * The caller is responsible for freeing the <err> and <str> copy
4142 * memory area using free()
4143 */
4144int list_append_word(struct list *li, const char *str, char **err)
4145{
4146 struct wordlist *wl;
4147
4148 wl = calloc(1, sizeof(*wl));
4149 if (!wl) {
4150 memprintf(err, "out of memory");
4151 goto fail_wl;
4152 }
4153
4154 wl->s = strdup(str);
4155 if (!wl->s) {
4156 memprintf(err, "out of memory");
4157 goto fail_wl_s;
4158 }
4159
4160 LIST_ADDQ(li, &wl->list);
4161
4162 return 1;
4163
4164fail_wl_s:
4165 free(wl->s);
4166fail_wl:
4167 free(wl);
4168 return 0;
4169}
4170
Willy Tarreau37101052019-05-20 16:48:20 +02004171/* indicates if a memory location may safely be read or not. The trick consists
4172 * in performing a harmless syscall using this location as an input and letting
4173 * the operating system report whether it's OK or not. For this we have the
4174 * stat() syscall, which will return EFAULT when the memory location supposed
4175 * to contain the file name is not readable. If it is readable it will then
4176 * either return 0 if the area contains an existing file name, or -1 with
4177 * another code. This must not be abused, and some audit systems might detect
4178 * this as abnormal activity. It's used only for unsafe dumps.
4179 */
4180int may_access(const void *ptr)
4181{
4182 struct stat buf;
4183
4184 if (stat(ptr, &buf) == 0)
4185 return 1;
4186 if (errno == EFAULT)
4187 return 0;
4188 return 1;
4189}
4190
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004191/* print a string of text buffer to <out>. The format is :
4192 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4193 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4194 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4195 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004196int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004197{
4198 unsigned char c;
4199 int ptr = 0;
4200
4201 while (buf[ptr] && ptr < bsize) {
4202 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004203 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004204 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004205 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004206 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004207 }
4208 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004209 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004210 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004211 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004212 switch (c) {
4213 case ' ': c = ' '; break;
4214 case '\t': c = 't'; break;
4215 case '\n': c = 'n'; break;
4216 case '\r': c = 'r'; break;
4217 case '\e': c = 'e'; break;
4218 case '\\': c = '\\'; break;
4219 case '=': c = '='; break;
4220 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004221 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004222 }
4223 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004224 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004225 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004226 out->area[out->data++] = '\\';
4227 out->area[out->data++] = 'x';
4228 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4229 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004230 }
4231 ptr++;
4232 }
4233
4234 return ptr;
4235}
4236
4237/* print a buffer in hexa.
4238 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4239 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004240int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004241{
4242 unsigned char c;
4243 int ptr = 0;
4244
4245 while (ptr < bsize) {
4246 c = buf[ptr];
4247
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004248 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004249 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004250 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4251 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004252
4253 ptr++;
4254 }
4255 return ptr;
4256}
4257
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004258/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4259 * prepending each line with prefix <pfx>. The output is *not* initialized.
4260 * The output will not wrap pas the buffer's end so it is more optimal if the
4261 * caller makes sure the buffer is aligned first. A trailing zero will always
4262 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004263 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4264 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004265 */
Willy Tarreau37101052019-05-20 16:48:20 +02004266void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004267{
4268 const unsigned char *d = buf;
4269 int i, j, start;
4270
4271 d = (const unsigned char *)(((unsigned long)buf) & -16);
4272 start = ((unsigned long)buf) & 15;
4273
4274 for (i = 0; i < start + len; i += 16) {
4275 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4276
Willy Tarreau37101052019-05-20 16:48:20 +02004277 // 0: unchecked, 1: checked safe, 2: danger
4278 unsafe = !!unsafe;
4279 if (unsafe && !may_access(d + i))
4280 unsafe = 2;
4281
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004282 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004283 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004284 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004285 else if (unsafe > 1)
4286 chunk_strcat(out, "** ");
4287 else
4288 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004289
4290 if (j == 7)
4291 chunk_strcat(out, "- ");
4292 }
4293 chunk_strcat(out, " ");
4294 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004295 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004296 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004297 else if (unsafe > 1)
4298 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004299 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004300 chunk_appendf(out, "%c", d[i + j]);
4301 else
4302 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004303 }
4304 chunk_strcat(out, "\n");
4305 }
4306}
4307
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004308/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4309 * enclosed in brackets after the address itself, formatted on 14 chars
4310 * including the "0x" prefix. This is meant to be used as a prefix for code
4311 * areas. For example:
4312 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4313 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4314 * is emitted. A NULL <pfx> will be considered empty.
4315 */
4316void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4317{
4318 int ok = 0;
4319 int i;
4320
4321 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4322
4323 for (i = 0; i < n; i++) {
4324 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4325 ok = may_access(addr + i);
4326 if (ok)
4327 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4328 else
4329 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4330 }
4331}
4332
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004333/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4334 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4335 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4336 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4337 * lines are respected within the limit of 70 output chars. Lines that are
4338 * continuation of a previous truncated line begin with "+" instead of " "
4339 * after the offset. The new pointer is returned.
4340 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004341int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004342 int *line, int ptr)
4343{
4344 int end;
4345 unsigned char c;
4346
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004347 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004348 if (end > out->size)
4349 return ptr;
4350
4351 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4352
4353 while (ptr < len && ptr < bsize) {
4354 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004355 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004356 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004357 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004358 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004359 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004360 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004361 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004362 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004363 switch (c) {
4364 case '\t': c = 't'; break;
4365 case '\n': c = 'n'; break;
4366 case '\r': c = 'r'; break;
4367 case '\e': c = 'e'; break;
4368 case '\\': c = '\\'; break;
4369 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004370 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004371 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004372 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004373 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004374 out->area[out->data++] = '\\';
4375 out->area[out->data++] = 'x';
4376 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4377 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004378 }
4379 if (buf[ptr++] == '\n') {
4380 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004381 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004382 *line = ptr;
4383 return ptr;
4384 }
4385 }
4386 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004387 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004388 return ptr;
4389}
4390
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004391/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004392 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4393 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004394 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004395void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4396 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004397{
Willy Tarreau73459792017-04-11 07:58:08 +02004398 unsigned int i;
4399 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004400
4401 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4402 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004403 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004404 for (j = 0; j < 8; j++) {
4405 if (b + j >= 0 && b + j < len)
4406 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4407 else
4408 fprintf(out, " ");
4409 }
4410
4411 if (b + j >= 0 && b + j < len)
4412 fputc('-', out);
4413 else
4414 fputc(' ', out);
4415
4416 for (j = 8; j < 16; j++) {
4417 if (b + j >= 0 && b + j < len)
4418 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4419 else
4420 fprintf(out, " ");
4421 }
4422
4423 fprintf(out, " ");
4424 for (j = 0; j < 16; j++) {
4425 if (b + j >= 0 && b + j < len) {
4426 if (isprint((unsigned char)buf[b + j]))
4427 fputc((unsigned char)buf[b + j], out);
4428 else
4429 fputc('.', out);
4430 }
4431 else
4432 fputc(' ', out);
4433 }
4434 fputc('\n', out);
4435 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004436}
4437
Willy Tarreaubb869862020-04-16 10:52:41 +02004438/* Tries to report the executable path name on platforms supporting this. If
4439 * not found or not possible, returns NULL.
4440 */
4441const char *get_exec_path()
4442{
4443 const char *ret = NULL;
4444
4445#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4446 long execfn = getauxval(AT_EXECFN);
4447
4448 if (execfn && execfn != ENOENT)
4449 ret = (const char *)execfn;
4450#endif
4451 return ret;
4452}
4453
Baruch Siache1651b22020-07-24 07:52:20 +03004454#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004455/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4456 * also returns the symbol size in <size>, otherwise returns 0 there.
4457 */
4458static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4459{
4460 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004461#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004462 const ElfW(Sym) *sym;
4463
4464 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4465 if (ret)
4466 *size = sym ? sym->st_size : 0;
4467#else
4468 ret = dladdr(addr, dli);
4469 *size = 0;
4470#endif
4471 return ret;
4472}
4473#endif
4474
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004475/* Tries to append to buffer <buf> some indications about the symbol at address
4476 * <addr> using the following form:
4477 * lib:+0xoffset (unresolvable address from lib's base)
4478 * main+0xoffset (unresolvable address from main (+/-))
4479 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4480 * name (resolved exact exec address)
4481 * lib:name (resolved exact lib address)
4482 * name+0xoffset/0xsize (resolved address within exec symbol)
4483 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4484 *
4485 * The file name (lib or executable) is limited to what lies between the last
4486 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4487 * 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 +03004488 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004489 *
4490 * The symbol's base address is returned, or NULL when unresolved, in order to
4491 * allow the caller to match it against known ones.
4492 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004493const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004494{
4495 const struct {
4496 const void *func;
4497 const char *name;
4498 } fcts[] = {
4499 { .func = process_stream, .name = "process_stream" },
4500 { .func = task_run_applet, .name = "task_run_applet" },
4501 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4502 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4503 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4504 { .func = listener_accept, .name = "listener_accept" },
4505 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4506 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4507#ifdef USE_LUA
4508 { .func = hlua_process_task, .name = "hlua_process_task" },
4509#endif
4510#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4511 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4512 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4513#endif
4514 };
4515
Baruch Siache1651b22020-07-24 07:52:20 +03004516#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004517 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004518 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004519 const char *fname, *p;
4520#endif
4521 int i;
4522
4523 if (pfx)
4524 chunk_appendf(buf, "%s", pfx);
4525
4526 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4527 if (addr == fcts[i].func) {
4528 chunk_appendf(buf, "%s", fcts[i].name);
4529 return addr;
4530 }
4531 }
4532
Baruch Siache1651b22020-07-24 07:52:20 +03004533#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004534 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004535 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004536 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004537
4538 /* 1. prefix the library name if it's not the same object as the one
4539 * that contains the main function. The name is picked between last '/'
4540 * and first following '.'.
4541 */
4542 if (!dladdr(main, &dli_main))
4543 dli_main.dli_fbase = NULL;
4544
4545 if (dli_main.dli_fbase != dli.dli_fbase) {
4546 fname = dli.dli_fname;
4547 p = strrchr(fname, '/');
4548 if (p++)
4549 fname = p;
4550 p = strchr(fname, '.');
4551 if (!p)
4552 p = fname + strlen(fname);
4553
4554 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4555 }
4556
4557 /* 2. symbol name */
4558 if (dli.dli_sname) {
4559 /* known, dump it and return symbol's address (exact or relative) */
4560 chunk_appendf(buf, "%s", dli.dli_sname);
4561 if (addr != dli.dli_saddr) {
4562 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004563 if (size)
4564 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004565 }
4566 return dli.dli_saddr;
4567 }
4568 else if (dli_main.dli_fbase != dli.dli_fbase) {
4569 /* unresolved symbol from a known library, report relative offset */
4570 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4571 return NULL;
4572 }
Baruch Siache1651b22020-07-24 07:52:20 +03004573#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004574 unknown:
4575 /* unresolved symbol from the main file, report relative offset to main */
4576 if ((void*)addr < (void*)main)
4577 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4578 else
4579 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4580 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004581}
4582
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004583/*
4584 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004585 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004586 *
4587 * First, initializes the value with <sz> as address to 0 and initializes the
4588 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4589 * address updating <sz> pointed value to the size of this array.
4590 *
4591 * Returns 1 if succeeded, 0 if not.
4592 */
4593int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4594{
4595 unsigned int *n;
4596 const char *s, *end;
4597
4598 s = str;
4599 *sz = 0;
4600 end = str + strlen(str);
4601 *nums = n = NULL;
4602
4603 while (1) {
4604 unsigned int r;
4605
4606 if (s >= end)
4607 break;
4608
4609 r = read_uint(&s, end);
4610 /* Expected characters after having read an uint: '\0' or '.',
4611 * if '.', must not be terminal.
4612 */
4613 if (*s != '\0'&& (*s++ != '.' || s == end))
4614 return 0;
4615
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004616 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004617 if (!n)
4618 return 0;
4619
4620 n[(*sz)++] = r;
4621 }
4622 *nums = n;
4623
4624 return 1;
4625}
4626
Willy Tarreau4d589e72019-08-23 19:02:26 +02004627
4628/* returns the number of bytes needed to encode <v> as a varint. An inline
4629 * version exists for use with constants (__varint_bytes()).
4630 */
4631int varint_bytes(uint64_t v)
4632{
4633 int len = 1;
4634
4635 if (v >= 240) {
4636 v = (v - 240) >> 4;
4637 while (1) {
4638 len++;
4639 if (v < 128)
4640 break;
4641 v = (v - 128) >> 7;
4642 }
4643 }
4644 return len;
4645}
4646
Willy Tarreau52bf8392020-03-08 00:42:37 +01004647
4648/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004649static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004650
4651/* This is a thread-safe implementation of xoroshiro128** described below:
4652 * http://prng.di.unimi.it/
4653 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4654 * supports fast jumps and passes all common quality tests. It is thread-safe,
4655 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4656 * local lock on other ones.
4657 */
4658uint64_t ha_random64()
4659{
4660 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004661 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4662 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004663
4664#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4665 static HA_SPINLOCK_T rand_lock;
4666
4667 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4668#endif
4669
4670 old[0] = ha_random_state[0];
4671 old[1] = ha_random_state[1];
4672
4673#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4674 do {
4675#endif
4676 result = rotl64(old[0] * 5, 7) * 9;
4677 new[1] = old[0] ^ old[1];
4678 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4679 new[1] = rotl64(new[1], 37); // c
4680
4681#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4682 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4683#else
4684 ha_random_state[0] = new[0];
4685 ha_random_state[1] = new[1];
4686#if defined(USE_THREAD)
4687 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4688#endif
4689#endif
4690 return result;
4691}
4692
4693/* seeds the random state using up to <len> bytes from <seed>, starting with
4694 * the first non-zero byte.
4695 */
4696void ha_random_seed(const unsigned char *seed, size_t len)
4697{
4698 size_t pos;
4699
4700 /* the seed must not be all zeroes, so we pre-fill it with alternating
4701 * bits and overwrite part of them with the block starting at the first
4702 * non-zero byte from the seed.
4703 */
4704 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4705
4706 for (pos = 0; pos < len; pos++)
4707 if (seed[pos] != 0)
4708 break;
4709
4710 if (pos == len)
4711 return;
4712
4713 seed += pos;
4714 len -= pos;
4715
4716 if (len > sizeof(ha_random_state))
4717 len = sizeof(ha_random_state);
4718
4719 memcpy(ha_random_state, seed, len);
4720}
4721
4722/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4723 * and is equivalent to calling ha_random64() as many times. It is used to
4724 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4725 * different generators (i.e. different processes after a fork). The <dist>
4726 * argument is the distance to jump to and is used in a loop so it rather not
4727 * be too large if the processing time is a concern.
4728 *
4729 * BEWARE: this function is NOT thread-safe and must not be called during
4730 * concurrent accesses to ha_random64().
4731 */
4732void ha_random_jump96(uint32_t dist)
4733{
4734 while (dist--) {
4735 uint64_t s0 = 0;
4736 uint64_t s1 = 0;
4737 int b;
4738
4739 for (b = 0; b < 64; b++) {
4740 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4741 s0 ^= ha_random_state[0];
4742 s1 ^= ha_random_state[1];
4743 }
4744 ha_random64();
4745 }
4746
4747 for (b = 0; b < 64; b++) {
4748 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4749 s0 ^= ha_random_state[0];
4750 s1 ^= ha_random_state[1];
4751 }
4752 ha_random64();
4753 }
4754 ha_random_state[0] = s0;
4755 ha_random_state[1] = s1;
4756 }
4757}
4758
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004759/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4760 * bytes large.
4761 */
4762void ha_generate_uuid(struct buffer *output)
4763{
4764 uint32_t rnd[4];
4765 uint64_t last;
4766
4767 last = ha_random64();
4768 rnd[0] = last;
4769 rnd[1] = last >> 32;
4770
4771 last = ha_random64();
4772 rnd[2] = last;
4773 rnd[3] = last >> 32;
4774
4775 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4776 rnd[0],
4777 rnd[1] & 0xFFFF,
4778 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4779 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4780 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4781}
4782
4783
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004784/* only used by parse_line() below. It supports writing in place provided that
4785 * <in> is updated to the next location before calling it. In that case, the
4786 * char at <in> may be overwritten.
4787 */
4788#define EMIT_CHAR(x) \
4789 do { \
4790 char __c = (char)(x); \
4791 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4792 err |= PARSE_ERR_OVERLAP; \
4793 if (outpos >= outmax) \
4794 err |= PARSE_ERR_TOOLARGE; \
4795 if (!err) \
4796 out[outpos] = __c; \
4797 outpos++; \
4798 } while (0)
4799
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004800/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004801 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4802 * extraneous ones are not emitted but <outlen> is updated so that the caller
4803 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4804 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004805 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4806 * it is guaranteed that at least one arg will point to the zero. It is safe
4807 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004808 *
4809 * <out> may overlap with <in> provided that it never goes further, in which
4810 * case the parser will accept to perform in-place parsing and unquoting/
4811 * unescaping but only if environment variables do not lead to expansion that
4812 * causes overlapping, otherwise the input string being destroyed, the error
4813 * will not be recoverable. Note that even during out-of-place <in> will
4814 * experience temporary modifications in-place for variable resolution and must
4815 * be writable, and will also receive zeroes to delimit words when using
4816 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4817 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4818 * starting point of the first invalid character sequence or unmatched
4819 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4820 * error reporting might be difficult since zeroes will have been inserted into
4821 * the string. One solution for the caller may consist in replacing all args
4822 * delimiters with spaces in this case.
4823 */
4824uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4825{
4826 char *quote = NULL;
4827 char *brace = NULL;
4828 unsigned char hex1, hex2;
4829 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004830 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004831 size_t outpos = 0;
4832 int squote = 0;
4833 int dquote = 0;
4834 int arg = 0;
4835 uint32_t err = 0;
4836
4837 *nbargs = 0;
4838 *outlen = 0;
4839
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004840 /* argsmax may be -1 here, protecting args[] from any write */
4841 if (arg < argsmax)
4842 args[arg] = out;
4843
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004844 while (1) {
4845 if (*in >= '-' && *in != '\\') {
4846 /* speedup: directly send all regular chars starting
4847 * with '-', '.', '/', alnum etc...
4848 */
4849 EMIT_CHAR(*in++);
4850 continue;
4851 }
4852 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4853 /* end of line */
4854 break;
4855 }
4856 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4857 /* comment */
4858 break;
4859 }
4860 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4861 if (dquote) {
4862 dquote = 0;
4863 quote = NULL;
4864 }
4865 else {
4866 dquote = 1;
4867 quote = in;
4868 }
4869 in++;
4870 continue;
4871 }
4872 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4873 if (squote) {
4874 squote = 0;
4875 quote = NULL;
4876 }
4877 else {
4878 squote = 1;
4879 quote = in;
4880 }
4881 in++;
4882 continue;
4883 }
4884 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4885 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4886 * C equivalent value but only when they have a special meaning and within
4887 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4888 */
4889 char tosend = *in;
4890
4891 switch (in[1]) {
4892 case ' ':
4893 case '\\':
4894 tosend = in[1];
4895 in++;
4896 break;
4897
4898 case 't':
4899 tosend = '\t';
4900 in++;
4901 break;
4902
4903 case 'n':
4904 tosend = '\n';
4905 in++;
4906 break;
4907
4908 case 'r':
4909 tosend = '\r';
4910 in++;
4911 break;
4912
4913 case '#':
4914 /* escaping of "#" only if comments are supported */
4915 if (opts & PARSE_OPT_SHARP)
4916 in++;
4917 tosend = *in;
4918 break;
4919
4920 case '\'':
4921 /* escaping of "'" only outside single quotes and only if single quotes are supported */
4922 if (opts & PARSE_OPT_SQUOTE && !squote)
4923 in++;
4924 tosend = *in;
4925 break;
4926
4927 case '"':
4928 /* escaping of '"' only outside single quotes and only if double quotes are supported */
4929 if (opts & PARSE_OPT_DQUOTE && !squote)
4930 in++;
4931 tosend = *in;
4932 break;
4933
4934 case '$':
4935 /* escaping of '$' only inside double quotes and only if env supported */
4936 if (opts & PARSE_OPT_ENV && dquote)
4937 in++;
4938 tosend = *in;
4939 break;
4940
4941 case 'x':
4942 if (!ishex(in[2]) || !ishex(in[3])) {
4943 /* invalid or incomplete hex sequence */
4944 err |= PARSE_ERR_HEX;
4945 if (errptr)
4946 *errptr = in;
4947 goto leave;
4948 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02004949 hex1 = toupper((unsigned char)in[2]) - '0';
4950 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004951 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
4952 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
4953 tosend = (hex1 << 4) + hex2;
4954 in += 3;
4955 break;
4956
4957 default:
4958 /* other combinations are not escape sequences */
4959 break;
4960 }
4961
4962 in++;
4963 EMIT_CHAR(tosend);
4964 }
4965 else if (isspace((unsigned char)*in) && !squote && !dquote) {
4966 /* a non-escaped space is an argument separator */
4967 while (isspace((unsigned char)*in))
4968 in++;
4969 EMIT_CHAR(0);
4970 arg++;
4971 if (arg < argsmax)
4972 args[arg] = out + outpos;
4973 else
4974 err |= PARSE_ERR_TOOMANY;
4975 }
4976 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
4977 /* environment variables are evaluated anywhere, or only
4978 * inside double quotes if they are supported.
4979 */
4980 char *var_name;
4981 char save_char;
4982 char *value;
4983
4984 in++;
4985
4986 if (*in == '{')
4987 brace = in++;
4988
4989 if (!isalpha((unsigned char)*in) && *in != '_') {
4990 /* unacceptable character in variable name */
4991 err |= PARSE_ERR_VARNAME;
4992 if (errptr)
4993 *errptr = in;
4994 goto leave;
4995 }
4996
4997 var_name = in;
4998 while (isalnum((unsigned char)*in) || *in == '_')
4999 in++;
5000
5001 save_char = *in;
5002 *in = '\0';
5003 value = getenv(var_name);
5004 *in = save_char;
5005
5006 if (brace) {
5007 if (*in != '}') {
5008 /* unmatched brace */
5009 err |= PARSE_ERR_BRACE;
5010 if (errptr)
5011 *errptr = brace;
5012 goto leave;
5013 }
5014 in++;
5015 brace = NULL;
5016 }
5017
5018 if (value) {
5019 while (*value)
5020 EMIT_CHAR(*value++);
5021 }
5022 }
5023 else {
5024 /* any other regular char */
5025 EMIT_CHAR(*in++);
5026 }
5027 }
5028
5029 /* end of output string */
5030 EMIT_CHAR(0);
5031 arg++;
5032
5033 if (quote) {
5034 /* unmatched quote */
5035 err |= PARSE_ERR_QUOTE;
5036 if (errptr)
5037 *errptr = quote;
5038 goto leave;
5039 }
5040 leave:
5041 *nbargs = arg;
5042 *outlen = outpos;
5043
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005044 /* empty all trailing args by making them point to the trailing zero,
5045 * at least the last one in any case.
5046 */
5047 if (arg > argsmax)
5048 arg = argsmax;
5049
5050 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005051 args[arg++] = out + outpos - 1;
5052
5053 return err;
5054}
5055#undef EMIT_CHAR
5056
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005057/* This is used to sanitize an input line that's about to be used for error reporting.
5058 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5059 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5060 * If non-printable chars are present in the output. It returns the new offset <pos>
5061 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5062 * be at least 6 to support two "..." otherwise the result is undefined. The line
5063 * itself must have at least 7 chars allocated for the same reason.
5064 */
5065size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5066{
5067 size_t shift = 0;
5068 char *out = line;
5069 char *in = line;
5070 char *end = line + width;
5071
5072 if (pos >= width) {
5073 /* if we have to shift, we'll be out of context, so let's
5074 * try to put <pos> at the center of width.
5075 */
5076 shift = pos - width / 2;
5077 in += shift + 3;
5078 end = out + width - 3;
5079 out[0] = out[1] = out[2] = '.';
5080 out += 3;
5081 }
5082
5083 while (out < end && *in) {
5084 if (isspace((unsigned char)*in))
5085 *out++ = ' ';
5086 else if (isprint((unsigned char)*in))
5087 *out++ = *in;
5088 else
5089 *out++ = '?';
5090 in++;
5091 }
5092
5093 if (end < line + width) {
5094 out[0] = out[1] = out[2] = '.';
5095 out += 3;
5096 }
5097
5098 *out++ = 0;
5099 return pos - shift;
5100}
5101
Willy Tarreaubaaee002006-06-26 02:48:02 +02005102/*
5103 * Local variables:
5104 * c-indent-level: 8
5105 * c-basic-offset: 8
5106 * End:
5107 */