blob: 9fffc702998521739f1755c2b36982a8cbbcbda4 [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 Tarreaua93e5c72020-09-15 14:01:16 +0200866 *
867 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
868 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100869 */
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200870struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd, char **err, const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100871{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100872 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100873 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100874 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100875 char *port1, *port2;
876 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200877 int abstract = 0;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200878 int is_udp = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200879 int new_fd = -1;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100880
881 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200882 if (fqdn)
883 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200884
Willy Tarreaudad36a32013-03-11 01:20:04 +0100885 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100886 if (str2 == NULL) {
887 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100888 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100889 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200890
Willy Tarreau9f69f462015-09-08 16:01:25 +0200891 if (!*str2) {
892 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
893 goto out;
894 }
895
Willy Tarreau24709282013-03-10 21:32:12 +0100896 memset(&ss, 0, sizeof(ss));
897
898 if (strncmp(str2, "unix@", 5) == 0) {
899 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200900 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100901 ss.ss_family = AF_UNIX;
902 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200903 else if (strncmp(str2, "abns@", 5) == 0) {
904 str2 += 5;
905 abstract = 1;
906 ss.ss_family = AF_UNIX;
907 }
Willy Tarreau24709282013-03-10 21:32:12 +0100908 else if (strncmp(str2, "ipv4@", 5) == 0) {
909 str2 += 5;
910 ss.ss_family = AF_INET;
911 }
912 else if (strncmp(str2, "ipv6@", 5) == 0) {
913 str2 += 5;
914 ss.ss_family = AF_INET6;
915 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200916 else if (strncmp(str2, "udp4@", 5) == 0) {
917 str2 += 5;
918 ss.ss_family = AF_INET;
919 is_udp = 1;
920 }
921 else if (strncmp(str2, "udp6@", 5) == 0) {
922 str2 += 5;
923 ss.ss_family = AF_INET6;
924 is_udp = 1;
925 }
926 else if (strncmp(str2, "udp@", 4) == 0) {
927 str2 += 4;
928 ss.ss_family = AF_UNSPEC;
929 is_udp = 1;
930 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200931 else if (strncmp(str2, "fd@", 3) == 0) {
932 str2 += 3;
933 ss.ss_family = AF_CUST_EXISTING_FD;
934 }
935 else if (strncmp(str2, "sockpair@", 9) == 0) {
936 str2 += 9;
937 ss.ss_family = AF_CUST_SOCKPAIR;
938 }
Willy Tarreau24709282013-03-10 21:32:12 +0100939 else if (*str2 == '/') {
940 ss.ss_family = AF_UNIX;
941 }
942 else
943 ss.ss_family = AF_UNSPEC;
944
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200945 if (ss.ss_family == AF_CUST_SOCKPAIR) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200946 char *endptr;
947
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200948 new_fd = strtol(str2, &endptr, 10);
949 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200950 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
951 goto out;
952 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200953
954 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
955 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200956 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200957 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100958 char *endptr;
959
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200960 new_fd = strtol(str2, &endptr, 10);
961 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100962 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100963 goto out;
964 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200965
966 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
967 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100968 }
969 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200970 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100971 int prefix_path_len;
972 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200973 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100974
975 /* complete unix socket path name during startup or soft-restart is
976 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
977 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200978 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +0200979 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +0100980 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +0100981
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200982 adr_len = strlen(str2);
983 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100984 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
985 goto out;
986 }
987
Willy Tarreauccfccef2014-05-10 01:49:15 +0200988 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +0200989 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200990 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +0200991 memcpy(un->sun_path, pfx, prefix_path_len);
992 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100993 }
Willy Tarreau24709282013-03-10 21:32:12 +0100994 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100995 char *end = str2 + strlen(str2);
996 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200997
mildisff5d5102015-10-26 18:50:08 +0100998 /* search for : or ] whatever comes first */
999 for (chr = end-1; chr > str2; chr--) {
1000 if (*chr == ']' || *chr == ':')
1001 break;
1002 }
1003
1004 if (*chr == ':') {
1005 /* Found a colon before a closing-bracket, must be a port separator.
1006 * This guarantee backward compatibility.
1007 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001008 if (!(opts & PA_O_PORT_OK)) {
1009 memprintf(err, "port specification not permitted here in '%s'", str);
1010 goto out;
1011 }
mildisff5d5102015-10-26 18:50:08 +01001012 *chr++ = '\0';
1013 port1 = chr;
1014 }
1015 else {
1016 /* Either no colon and no closing-bracket
1017 * or directly ending with a closing-bracket.
1018 * However, no port.
1019 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001020 if (opts & PA_O_PORT_MAND) {
1021 memprintf(err, "missing port specification in '%s'", str);
1022 goto out;
1023 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001024 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001025 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001026
Willy Tarreau90807112020-02-25 08:16:33 +01001027 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001028 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001029 if (port2) {
1030 if (!(opts & PA_O_PORT_RANGE)) {
1031 memprintf(err, "port range not permitted here in '%s'", str);
1032 goto out;
1033 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001034 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001035 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001036 else
1037 port2 = port1;
1038 portl = atoi(port1);
1039 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001040
1041 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1042 memprintf(err, "invalid port '%s'", port1);
1043 goto out;
1044 }
1045
1046 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1047 memprintf(err, "invalid port '%s'", port2);
1048 goto out;
1049 }
1050
1051 if (portl > porth) {
1052 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1053 goto out;
1054 }
1055
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001056 porta = portl;
1057 }
1058 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001059 if (!(opts & PA_O_PORT_OFS)) {
1060 memprintf(err, "port offset not permitted here in '%s'", str);
1061 goto out;
1062 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001063 portl = atoi(port1 + 1);
1064 porta = -portl;
1065 }
1066 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001067 if (!(opts & PA_O_PORT_OFS)) {
1068 memprintf(err, "port offset not permitted here in '%s'", str);
1069 goto out;
1070 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001071 porth = atoi(port1 + 1);
1072 porta = porth;
1073 }
1074 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001075 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001076 goto out;
1077 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001078 else if (opts & PA_O_PORT_MAND) {
1079 memprintf(err, "missing port specification in '%s'", str);
1080 goto out;
1081 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001082
1083 /* first try to parse the IP without resolving. If it fails, it
1084 * tells us we need to keep a copy of the FQDN to resolve later
1085 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001086 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001087 */
1088 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001089 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1090 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001091 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1092 goto out;
1093 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001094
Willy Tarreauceccdd72016-11-02 22:27:10 +01001095 if (fqdn) {
1096 if (str2 != back)
1097 memmove(back, str2, strlen(str2) + 1);
1098 *fqdn = back;
1099 back = NULL;
1100 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001101 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001102 set_host_port(&ss, porta);
Emeric Brun3835c0d2020-07-07 09:46:09 +02001103 if (is_udp) {
1104 if (ss.ss_family == AF_INET6)
1105 ss.ss_family = AF_CUST_UDP6;
1106 else
1107 ss.ss_family = AF_CUST_UDP4;
1108 }
1109
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001110 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001111
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001112 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001113 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001114 if (port)
1115 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001116 if (low)
1117 *low = portl;
1118 if (high)
1119 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001120 if (fd)
1121 *fd = new_fd;
Willy Tarreau24709282013-03-10 21:32:12 +01001122 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001123 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001124}
1125
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001126/* converts <str> to a struct in_addr containing a network mask. It can be
1127 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001128 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001129 */
1130int str2mask(const char *str, struct in_addr *mask)
1131{
1132 if (strchr(str, '.') != NULL) { /* dotted notation */
1133 if (!inet_pton(AF_INET, str, mask))
1134 return 0;
1135 }
1136 else { /* mask length */
1137 char *err;
1138 unsigned long len = strtol(str, &err, 10);
1139
1140 if (!*str || (err && *err) || (unsigned)len > 32)
1141 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001142
1143 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001144 }
1145 return 1;
1146}
1147
Tim Duesterhus47185172018-01-25 16:24:49 +01001148/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001149 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001150 * if the conversion succeeds otherwise zero.
1151 */
1152int str2mask6(const char *str, struct in6_addr *mask)
1153{
1154 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1155 if (!inet_pton(AF_INET6, str, mask))
1156 return 0;
1157 }
1158 else { /* mask length */
1159 char *err;
1160 unsigned long len = strtol(str, &err, 10);
1161
1162 if (!*str || (err && *err) || (unsigned)len > 128)
1163 return 0;
1164
1165 len2mask6(len, mask);
1166 }
1167 return 1;
1168}
1169
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001170/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1171 * succeeds otherwise zero.
1172 */
1173int cidr2dotted(int cidr, struct in_addr *mask) {
1174
1175 if (cidr < 0 || cidr > 32)
1176 return 0;
1177
1178 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1179 return 1;
1180}
1181
Thierry Fournier70473a52016-02-17 17:12:14 +01001182/* Convert mask from bit length form to in_addr form.
1183 * This function never fails.
1184 */
1185void len2mask4(int len, struct in_addr *addr)
1186{
1187 if (len >= 32) {
1188 addr->s_addr = 0xffffffff;
1189 return;
1190 }
1191 if (len <= 0) {
1192 addr->s_addr = 0x00000000;
1193 return;
1194 }
1195 addr->s_addr = 0xffffffff << (32 - len);
1196 addr->s_addr = htonl(addr->s_addr);
1197}
1198
1199/* Convert mask from bit length form to in6_addr form.
1200 * This function never fails.
1201 */
1202void len2mask6(int len, struct in6_addr *addr)
1203{
1204 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1205 len -= 32;
1206 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1207 len -= 32;
1208 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1209 len -= 32;
1210 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1211}
1212
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001213/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001214 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001215 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001216 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001217 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1218 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001219int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001220{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001221 __label__ out_free, out_err;
1222 char *c, *s;
1223 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001224
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001225 s = strdup(str);
1226 if (!s)
1227 return 0;
1228
Willy Tarreaubaaee002006-06-26 02:48:02 +02001229 memset(mask, 0, sizeof(*mask));
1230 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001231
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001232 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001233 *c++ = '\0';
1234 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001235 if (!str2mask(c, mask))
1236 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001237 }
1238 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001239 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001240 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001241 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001242 struct hostent *he;
1243
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001244 if (!resolve)
1245 goto out_err;
1246
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001247 if ((he = gethostbyname(s)) == NULL) {
1248 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001249 }
1250 else
1251 *addr = *(struct in_addr *) *(he->h_addr_list);
1252 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001253
1254 ret_val = 1;
1255 out_free:
1256 free(s);
1257 return ret_val;
1258 out_err:
1259 ret_val = 0;
1260 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001261}
1262
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001263
1264/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001265 * converts <str> to two struct in6_addr* which must be pre-allocated.
1266 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001267 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001268 * Returns 1 if OK, 0 if error.
1269 */
1270int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1271{
1272 char *c, *s;
1273 int ret_val = 0;
1274 char *err;
1275 unsigned long len = 128;
1276
1277 s = strdup(str);
1278 if (!s)
1279 return 0;
1280
1281 memset(mask, 0, sizeof(*mask));
1282 memset(addr, 0, sizeof(*addr));
1283
1284 if ((c = strrchr(s, '/')) != NULL) {
1285 *c++ = '\0'; /* c points to the mask */
1286 if (!*c)
1287 goto out_free;
1288
1289 len = strtoul(c, &err, 10);
1290 if ((err && *err) || (unsigned)len > 128)
1291 goto out_free;
1292 }
1293 *mask = len; /* OK we have a valid mask in <len> */
1294
1295 if (!inet_pton(AF_INET6, s, addr))
1296 goto out_free;
1297
1298 ret_val = 1;
1299 out_free:
1300 free(s);
1301 return ret_val;
1302}
1303
1304
1305/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001306 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001307 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001308int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001309{
1310 int saw_digit, octets, ch;
1311 u_char tmp[4], *tp;
1312 const char *cp = addr;
1313
1314 saw_digit = 0;
1315 octets = 0;
1316 *(tp = tmp) = 0;
1317
1318 while (*addr) {
1319 unsigned char digit = (ch = *addr++) - '0';
1320 if (digit > 9 && ch != '.')
1321 break;
1322 if (digit <= 9) {
1323 u_int new = *tp * 10 + digit;
1324 if (new > 255)
1325 return 0;
1326 *tp = new;
1327 if (!saw_digit) {
1328 if (++octets > 4)
1329 return 0;
1330 saw_digit = 1;
1331 }
1332 } else if (ch == '.' && saw_digit) {
1333 if (octets == 4)
1334 return 0;
1335 *++tp = 0;
1336 saw_digit = 0;
1337 } else
1338 return 0;
1339 }
1340
1341 if (octets < 4)
1342 return 0;
1343
1344 memcpy(&dst->s_addr, tmp, 4);
1345 return addr-cp-1;
1346}
1347
1348/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001349 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001350 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001351 * the hostname. Actually only http and https are supported. <out> can be NULL.
1352 * This function returns the consumed length. It is useful if you parse complete
1353 * url like http://host:port/path, because the consumed length corresponds to
1354 * the first character of the path. If the conversion fails, it returns -1.
1355 *
1356 * This function tries to resolve the DNS name if haproxy is in starting mode.
1357 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001358 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001359int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001360{
1361 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001362 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001363 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001364 unsigned long long int http_code = 0;
1365 int default_port;
1366 struct hostent *he;
1367 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001368
1369 /* Firstly, try to find :// pattern */
1370 while (curr < url+ulen && url_code != 0x3a2f2f) {
1371 url_code = ((url_code & 0xffff) << 8);
1372 url_code += (unsigned char)*curr++;
1373 }
1374
1375 /* Secondly, if :// pattern is found, verify parsed stuff
1376 * before pattern is matching our http pattern.
1377 * If so parse ip address and port in uri.
1378 *
1379 * WARNING: Current code doesn't support dynamic async dns resolver.
1380 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001381 if (url_code != 0x3a2f2f)
1382 return -1;
1383
1384 /* Copy scheme, and utrn to lower case. */
1385 while (cp < curr - 3)
1386 http_code = (http_code << 8) + *cp++;
1387 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001388
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001389 /* HTTP or HTTPS url matching */
1390 if (http_code == 0x2020202068747470ULL) {
1391 default_port = 80;
1392 if (out)
1393 out->scheme = SCH_HTTP;
1394 }
1395 else if (http_code == 0x2020206874747073ULL) {
1396 default_port = 443;
1397 if (out)
1398 out->scheme = SCH_HTTPS;
1399 }
1400 else
1401 return -1;
1402
1403 /* If the next char is '[', the host address is IPv6. */
1404 if (*curr == '[') {
1405 curr++;
1406
1407 /* Check trash size */
1408 if (trash.size < ulen)
1409 return -1;
1410
1411 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001412 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001413 for (end = curr;
1414 end < url + ulen && *end != ']';
1415 end++, p++)
1416 *p = *end;
1417 if (*end != ']')
1418 return -1;
1419 *p = '\0';
1420
1421 /* Update out. */
1422 if (out) {
1423 out->host = curr;
1424 out->host_len = end - curr;
1425 }
1426
1427 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001428 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001429 return -1;
1430 end++;
1431
1432 /* Decode port. */
1433 if (*end == ':') {
1434 end++;
1435 default_port = read_uint(&end, url + ulen);
1436 }
1437 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1438 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1439 return end - url;
1440 }
1441 else {
1442 /* We are looking for IP address. If you want to parse and
1443 * resolve hostname found in url, you can use str2sa_range(), but
1444 * be warned this can slow down global daemon performances
1445 * while handling lagging dns responses.
1446 */
1447 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1448 if (ret) {
1449 /* Update out. */
1450 if (out) {
1451 out->host = curr;
1452 out->host_len = ret;
1453 }
1454
1455 curr += ret;
1456
1457 /* Decode port. */
1458 if (*curr == ':') {
1459 curr++;
1460 default_port = read_uint(&curr, url + ulen);
1461 }
1462 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1463
1464 /* Set family. */
1465 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1466 return curr - url;
1467 }
1468 else if (global.mode & MODE_STARTING) {
1469 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1470 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001471 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001472
1473 /* look for : or / or end */
1474 for (end = curr;
1475 end < url + ulen && *end != '/' && *end != ':';
1476 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001477 memcpy(trash.area, curr, end - curr);
1478 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001479
1480 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001481 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001482 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001483 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001484
1485 /* Update out. */
1486 if (out) {
1487 out->host = curr;
1488 out->host_len = end - curr;
1489 }
1490
1491 /* Decode port. */
1492 if (*end == ':') {
1493 end++;
1494 default_port = read_uint(&end, url + ulen);
1495 }
1496
1497 /* Copy IP address, set port and family. */
1498 switch (he->h_addrtype) {
1499 case AF_INET:
1500 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1501 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1502 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1503 return end - url;
1504
1505 case AF_INET6:
1506 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1507 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1508 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1509 return end - url;
1510 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001511 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001512 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001513 return -1;
1514}
1515
Willy Tarreau631f01c2011-09-05 00:36:48 +02001516/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1517 * address family is returned so that it's easy for the caller to adapt to the
1518 * output format. Zero is returned if the address family is not supported. -1
1519 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1520 * supported.
1521 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001522int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001523{
1524
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001525 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001526
1527 if (size < 5)
1528 return 0;
1529 *str = '\0';
1530
1531 switch (addr->ss_family) {
1532 case AF_INET:
1533 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1534 break;
1535 case AF_INET6:
1536 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1537 break;
1538 case AF_UNIX:
1539 memcpy(str, "unix", 5);
1540 return addr->ss_family;
1541 default:
1542 return 0;
1543 }
1544
1545 if (inet_ntop(addr->ss_family, ptr, str, size))
1546 return addr->ss_family;
1547
1548 /* failed */
1549 return -1;
1550}
1551
Simon Horman75ab8bd2014-06-16 09:39:41 +09001552/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1553 * address family is returned so that it's easy for the caller to adapt to the
1554 * output format. Zero is returned if the address family is not supported. -1
1555 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1556 * supported.
1557 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001558int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001559{
1560
1561 uint16_t port;
1562
1563
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001564 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001565 return 0;
1566 *str = '\0';
1567
1568 switch (addr->ss_family) {
1569 case AF_INET:
1570 port = ((struct sockaddr_in *)addr)->sin_port;
1571 break;
1572 case AF_INET6:
1573 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1574 break;
1575 case AF_UNIX:
1576 memcpy(str, "unix", 5);
1577 return addr->ss_family;
1578 default:
1579 return 0;
1580 }
1581
1582 snprintf(str, size, "%u", ntohs(port));
1583 return addr->ss_family;
1584}
1585
Willy Tarreau16e01562016-08-09 16:46:18 +02001586/* check if the given address is local to the system or not. It will return
1587 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1588 * it is. We don't want to iterate over all interfaces for this (and it is not
1589 * portable). So instead we try to bind in UDP to this address on a free non
1590 * privileged port and to connect to the same address, port 0 (connect doesn't
1591 * care). If it succeeds, we own the address. Note that non-inet addresses are
1592 * considered local since they're most likely AF_UNIX.
1593 */
1594int addr_is_local(const struct netns_entry *ns,
1595 const struct sockaddr_storage *orig)
1596{
1597 struct sockaddr_storage addr;
1598 int result;
1599 int fd;
1600
1601 if (!is_inet_addr(orig))
1602 return 1;
1603
1604 memcpy(&addr, orig, sizeof(addr));
1605 set_host_port(&addr, 0);
1606
1607 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1608 if (fd < 0)
1609 return -1;
1610
1611 result = -1;
1612 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1613 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1614 result = 0; // fail, non-local address
1615 else
1616 result = 1; // success, local address
1617 }
1618 else {
1619 if (errno == EADDRNOTAVAIL)
1620 result = 0; // definitely not local :-)
1621 }
1622 close(fd);
1623
1624 return result;
1625}
1626
Willy Tarreaubaaee002006-06-26 02:48:02 +02001627/* will try to encode the string <string> replacing all characters tagged in
1628 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1629 * prefixed by <escape>, and will store the result between <start> (included)
1630 * and <stop> (excluded), and will always terminate the string with a '\0'
1631 * before <stop>. The position of the '\0' is returned if the conversion
1632 * completes. If bytes are missing between <start> and <stop>, then the
1633 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1634 * cannot even be stored so we return <start> without writing the 0.
1635 * The input string must also be zero-terminated.
1636 */
1637const char hextab[16] = "0123456789ABCDEF";
1638char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001639 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001640 const char *string)
1641{
1642 if (start < stop) {
1643 stop--; /* reserve one byte for the final '\0' */
1644 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001645 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001646 *start++ = *string;
1647 else {
1648 if (start + 3 >= stop)
1649 break;
1650 *start++ = escape;
1651 *start++ = hextab[(*string >> 4) & 15];
1652 *start++ = hextab[*string & 15];
1653 }
1654 string++;
1655 }
1656 *start = '\0';
1657 }
1658 return start;
1659}
1660
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001661/*
1662 * Same behavior as encode_string() above, except that it encodes chunk
1663 * <chunk> instead of a string.
1664 */
1665char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001666 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001667 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001668{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001669 char *str = chunk->area;
1670 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001671
1672 if (start < stop) {
1673 stop--; /* reserve one byte for the final '\0' */
1674 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001675 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001676 *start++ = *str;
1677 else {
1678 if (start + 3 >= stop)
1679 break;
1680 *start++ = escape;
1681 *start++ = hextab[(*str >> 4) & 15];
1682 *start++ = hextab[*str & 15];
1683 }
1684 str++;
1685 }
1686 *start = '\0';
1687 }
1688 return start;
1689}
1690
Dragan Dosen0edd1092016-02-12 13:23:02 +01001691/*
1692 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001693 * character. The input <string> must be zero-terminated. The result will
1694 * be stored between <start> (included) and <stop> (excluded). This
1695 * function will always try to terminate the resulting string with a '\0'
1696 * before <stop>, and will return its position if the conversion
1697 * completes.
1698 */
1699char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001700 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001701 const char *string)
1702{
1703 if (start < stop) {
1704 stop--; /* reserve one byte for the final '\0' */
1705 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001706 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001707 *start++ = *string;
1708 else {
1709 if (start + 2 >= stop)
1710 break;
1711 *start++ = escape;
1712 *start++ = *string;
1713 }
1714 string++;
1715 }
1716 *start = '\0';
1717 }
1718 return start;
1719}
1720
1721/*
1722 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001723 * character. <chunk> contains the input to be escaped. The result will be
1724 * stored between <start> (included) and <stop> (excluded). The function
1725 * will always try to terminate the resulting string with a '\0' before
1726 * <stop>, and will return its position if the conversion completes.
1727 */
1728char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001729 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001730 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001731{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001732 char *str = chunk->area;
1733 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001734
1735 if (start < stop) {
1736 stop--; /* reserve one byte for the final '\0' */
1737 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001738 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001739 *start++ = *str;
1740 else {
1741 if (start + 2 >= stop)
1742 break;
1743 *start++ = escape;
1744 *start++ = *str;
1745 }
1746 str++;
1747 }
1748 *start = '\0';
1749 }
1750 return start;
1751}
1752
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001753/* Check a string for using it in a CSV output format. If the string contains
1754 * one of the following four char <">, <,>, CR or LF, the string is
1755 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1756 * <str> is the input string to be escaped. The function assumes that
1757 * the input string is null-terminated.
1758 *
1759 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001760 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001761 * format.
1762 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001763 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001764 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001765 * If <quote> is 1, the converter puts the quotes only if any reserved character
1766 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001767 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001768 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001769 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001770 * The function returns the converted string on its output. If an error
1771 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001772 * for using the function directly as printf() argument.
1773 *
1774 * If the output buffer is too short to contain the input string, the result
1775 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001776 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001777 * This function appends the encoding to the existing output chunk, and it
1778 * guarantees that it starts immediately at the first available character of
1779 * the chunk. Please use csv_enc() instead if you want to replace the output
1780 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001781 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001782const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001783{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001784 char *end = output->area + output->size;
1785 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001786 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001787
Willy Tarreaub631c292016-01-08 10:04:08 +01001788 if (quote == 1) {
1789 /* automatic quoting: first verify if we'll have to quote the string */
1790 if (!strpbrk(str, "\n\r,\""))
1791 quote = 0;
1792 }
1793
1794 if (quote)
1795 *ptr++ = '"';
1796
Willy Tarreau898529b2016-01-06 18:07:04 +01001797 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1798 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001799 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001800 ptr++;
1801 if (ptr >= end - 2) {
1802 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001803 break;
1804 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001805 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001806 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001807 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001808 str++;
1809 }
1810
Willy Tarreaub631c292016-01-08 10:04:08 +01001811 if (quote)
1812 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001813
Willy Tarreau898529b2016-01-06 18:07:04 +01001814 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001815 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001816 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001817}
1818
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001819/* Decode an URL-encoded string in-place. The resulting string might
1820 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001821 * aborted, the string is truncated before the issue and a negative value is
1822 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001823 * If the 'in_form' argument is non-nul the string is assumed to be part of
1824 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1825 * turned to a space. If it's zero, this will only be done after a question
1826 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001827 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001828int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001829{
1830 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001831 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001832
1833 in = string;
1834 out = string;
1835 while (*in) {
1836 switch (*in) {
1837 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001838 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001839 break;
1840 case '%' :
1841 if (!ishex(in[1]) || !ishex(in[2]))
1842 goto end;
1843 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1844 in += 2;
1845 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001846 case '?':
1847 in_form = 1;
1848 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001849 default:
1850 *out++ = *in;
1851 break;
1852 }
1853 in++;
1854 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001855 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001856 end:
1857 *out = 0;
1858 return ret;
1859}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001860
Willy Tarreau6911fa42007-03-04 18:06:08 +01001861unsigned int str2ui(const char *s)
1862{
1863 return __str2ui(s);
1864}
1865
1866unsigned int str2uic(const char *s)
1867{
1868 return __str2uic(s);
1869}
1870
1871unsigned int strl2ui(const char *s, int len)
1872{
1873 return __strl2ui(s, len);
1874}
1875
1876unsigned int strl2uic(const char *s, int len)
1877{
1878 return __strl2uic(s, len);
1879}
1880
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001881unsigned int read_uint(const char **s, const char *end)
1882{
1883 return __read_uint(s, end);
1884}
1885
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001886/* This function reads an unsigned integer from the string pointed to by <s> and
1887 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1888 * function automatically stops at <end>. If the number overflows, the 2^64-1
1889 * value is returned.
1890 */
1891unsigned long long int read_uint64(const char **s, const char *end)
1892{
1893 const char *ptr = *s;
1894 unsigned long long int i = 0, tmp;
1895 unsigned int j;
1896
1897 while (ptr < end) {
1898
1899 /* read next char */
1900 j = *ptr - '0';
1901 if (j > 9)
1902 goto read_uint64_end;
1903
1904 /* add char to the number and check overflow. */
1905 tmp = i * 10;
1906 if (tmp / 10 != i) {
1907 i = ULLONG_MAX;
1908 goto read_uint64_eat;
1909 }
1910 if (ULLONG_MAX - tmp < j) {
1911 i = ULLONG_MAX;
1912 goto read_uint64_eat;
1913 }
1914 i = tmp + j;
1915 ptr++;
1916 }
1917read_uint64_eat:
1918 /* eat each numeric char */
1919 while (ptr < end) {
1920 if ((unsigned int)(*ptr - '0') > 9)
1921 break;
1922 ptr++;
1923 }
1924read_uint64_end:
1925 *s = ptr;
1926 return i;
1927}
1928
1929/* This function reads an integer from the string pointed to by <s> and returns
1930 * it. The <s> pointer is adjusted to point to the first unread char. The function
1931 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1932 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1933 * returned.
1934 */
1935long long int read_int64(const char **s, const char *end)
1936{
1937 unsigned long long int i = 0;
1938 int neg = 0;
1939
1940 /* Look for minus char. */
1941 if (**s == '-') {
1942 neg = 1;
1943 (*s)++;
1944 }
1945 else if (**s == '+')
1946 (*s)++;
1947
1948 /* convert as positive number. */
1949 i = read_uint64(s, end);
1950
1951 if (neg) {
1952 if (i > 0x8000000000000000ULL)
1953 return LLONG_MIN;
1954 return -i;
1955 }
1956 if (i > 0x7fffffffffffffffULL)
1957 return LLONG_MAX;
1958 return i;
1959}
1960
Willy Tarreau6911fa42007-03-04 18:06:08 +01001961/* This one is 7 times faster than strtol() on athlon with checks.
1962 * It returns the value of the number composed of all valid digits read,
1963 * and can process negative numbers too.
1964 */
1965int strl2ic(const char *s, int len)
1966{
1967 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001968 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001969
1970 if (len > 0) {
1971 if (*s != '-') {
1972 /* positive number */
1973 while (len-- > 0) {
1974 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001975 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001976 if (j > 9)
1977 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001978 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001979 }
1980 } else {
1981 /* negative number */
1982 s++;
1983 while (--len > 0) {
1984 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001985 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001986 if (j > 9)
1987 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001988 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001989 }
1990 }
1991 }
1992 return i;
1993}
1994
1995
1996/* This function reads exactly <len> chars from <s> and converts them to a
1997 * signed integer which it stores into <ret>. It accurately detects any error
1998 * (truncated string, invalid chars, overflows). It is meant to be used in
1999 * applications designed for hostile environments. It returns zero when the
2000 * number has successfully been converted, non-zero otherwise. When an error
2001 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2002 * faster than strtol().
2003 */
2004int strl2irc(const char *s, int len, int *ret)
2005{
2006 int i = 0;
2007 int j;
2008
2009 if (!len)
2010 return 1;
2011
2012 if (*s != '-') {
2013 /* positive number */
2014 while (len-- > 0) {
2015 j = (*s++) - '0';
2016 if (j > 9) return 1; /* invalid char */
2017 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2018 i = i * 10;
2019 if (i + j < i) return 1; /* check for addition overflow */
2020 i = i + j;
2021 }
2022 } else {
2023 /* negative number */
2024 s++;
2025 while (--len > 0) {
2026 j = (*s++) - '0';
2027 if (j > 9) return 1; /* invalid char */
2028 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2029 i = i * 10;
2030 if (i - j > i) return 1; /* check for subtract overflow */
2031 i = i - j;
2032 }
2033 }
2034 *ret = i;
2035 return 0;
2036}
2037
2038
2039/* This function reads exactly <len> chars from <s> and converts them to a
2040 * signed integer which it stores into <ret>. It accurately detects any error
2041 * (truncated string, invalid chars, overflows). It is meant to be used in
2042 * applications designed for hostile environments. It returns zero when the
2043 * number has successfully been converted, non-zero otherwise. When an error
2044 * is returned, the <ret> value is left untouched. It is about 3 times slower
2045 * than str2irc().
2046 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002047
2048int strl2llrc(const char *s, int len, long long *ret)
2049{
2050 long long i = 0;
2051 int j;
2052
2053 if (!len)
2054 return 1;
2055
2056 if (*s != '-') {
2057 /* positive number */
2058 while (len-- > 0) {
2059 j = (*s++) - '0';
2060 if (j > 9) return 1; /* invalid char */
2061 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2062 i = i * 10LL;
2063 if (i + j < i) return 1; /* check for addition overflow */
2064 i = i + j;
2065 }
2066 } else {
2067 /* negative number */
2068 s++;
2069 while (--len > 0) {
2070 j = (*s++) - '0';
2071 if (j > 9) return 1; /* invalid char */
2072 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2073 i = i * 10LL;
2074 if (i - j > i) return 1; /* check for subtract overflow */
2075 i = i - j;
2076 }
2077 }
2078 *ret = i;
2079 return 0;
2080}
2081
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002082/* This function is used with pat_parse_dotted_ver(). It converts a string
2083 * composed by two number separated by a dot. Each part must contain in 16 bits
2084 * because internally they will be represented as a 32-bit quantity stored in
2085 * a 64-bit integer. It returns zero when the number has successfully been
2086 * converted, non-zero otherwise. When an error is returned, the <ret> value
2087 * is left untouched.
2088 *
2089 * "1.3" -> 0x0000000000010003
2090 * "65535.65535" -> 0x00000000ffffffff
2091 */
2092int strl2llrc_dotted(const char *text, int len, long long *ret)
2093{
2094 const char *end = &text[len];
2095 const char *p;
2096 long long major, minor;
2097
2098 /* Look for dot. */
2099 for (p = text; p < end; p++)
2100 if (*p == '.')
2101 break;
2102
2103 /* Convert major. */
2104 if (strl2llrc(text, p - text, &major) != 0)
2105 return 1;
2106
2107 /* Check major. */
2108 if (major >= 65536)
2109 return 1;
2110
2111 /* Convert minor. */
2112 minor = 0;
2113 if (p < end)
2114 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2115 return 1;
2116
2117 /* Check minor. */
2118 if (minor >= 65536)
2119 return 1;
2120
2121 /* Compose value. */
2122 *ret = (major << 16) | (minor & 0xffff);
2123 return 0;
2124}
2125
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002126/* This function parses a time value optionally followed by a unit suffix among
2127 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2128 * expected by the caller. The computation does its best to avoid overflows.
2129 * The value is returned in <ret> if everything is fine, and a NULL is returned
2130 * by the function. In case of error, a pointer to the error is returned and
2131 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002132 * Values resulting in values larger than or equal to 2^31 after conversion are
2133 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2134 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002135 */
2136const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2137{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002138 unsigned long long imult, idiv;
2139 unsigned long long omult, odiv;
2140 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002141
2142 omult = odiv = 1;
2143
2144 switch (unit_flags & TIME_UNIT_MASK) {
2145 case TIME_UNIT_US: omult = 1000000; break;
2146 case TIME_UNIT_MS: omult = 1000; break;
2147 case TIME_UNIT_S: break;
2148 case TIME_UNIT_MIN: odiv = 60; break;
2149 case TIME_UNIT_HOUR: odiv = 3600; break;
2150 case TIME_UNIT_DAY: odiv = 86400; break;
2151 default: break;
2152 }
2153
2154 value = 0;
2155
2156 while (1) {
2157 unsigned int j;
2158
2159 j = *text - '0';
2160 if (j > 9)
2161 break;
2162 text++;
2163 value *= 10;
2164 value += j;
2165 }
2166
2167 imult = idiv = 1;
2168 switch (*text) {
2169 case '\0': /* no unit = default unit */
2170 imult = omult = idiv = odiv = 1;
2171 break;
2172 case 's': /* second = unscaled unit */
2173 break;
2174 case 'u': /* microsecond : "us" */
2175 if (text[1] == 's') {
2176 idiv = 1000000;
2177 text++;
2178 }
2179 break;
2180 case 'm': /* millisecond : "ms" or minute: "m" */
2181 if (text[1] == 's') {
2182 idiv = 1000;
2183 text++;
2184 } else
2185 imult = 60;
2186 break;
2187 case 'h': /* hour : "h" */
2188 imult = 3600;
2189 break;
2190 case 'd': /* day : "d" */
2191 imult = 86400;
2192 break;
2193 default:
2194 return text;
2195 break;
2196 }
2197
2198 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2199 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2200 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2201 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2202
Willy Tarreau9faebe32019-06-07 19:00:37 +02002203 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2204 if (result >= 0x80000000)
2205 return PARSE_TIME_OVER;
2206 if (!result && value)
2207 return PARSE_TIME_UNDER;
2208 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002209 return NULL;
2210}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002211
Emeric Brun39132b22010-01-04 14:57:24 +01002212/* this function converts the string starting at <text> to an unsigned int
2213 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002214 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002215 */
2216const char *parse_size_err(const char *text, unsigned *ret) {
2217 unsigned value = 0;
2218
2219 while (1) {
2220 unsigned int j;
2221
2222 j = *text - '0';
2223 if (j > 9)
2224 break;
2225 if (value > ~0U / 10)
2226 return text;
2227 value *= 10;
2228 if (value > (value + j))
2229 return text;
2230 value += j;
2231 text++;
2232 }
2233
2234 switch (*text) {
2235 case '\0':
2236 break;
2237 case 'K':
2238 case 'k':
2239 if (value > ~0U >> 10)
2240 return text;
2241 value = value << 10;
2242 break;
2243 case 'M':
2244 case 'm':
2245 if (value > ~0U >> 20)
2246 return text;
2247 value = value << 20;
2248 break;
2249 case 'G':
2250 case 'g':
2251 if (value > ~0U >> 30)
2252 return text;
2253 value = value << 30;
2254 break;
2255 default:
2256 return text;
2257 }
2258
Godbach58048a22015-01-28 17:36:16 +08002259 if (*text != '\0' && *++text != '\0')
2260 return text;
2261
Emeric Brun39132b22010-01-04 14:57:24 +01002262 *ret = value;
2263 return NULL;
2264}
2265
Willy Tarreau126d4062013-12-03 17:50:47 +01002266/*
2267 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002268 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002269 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002270 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002271 */
2272int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2273{
2274 int len;
2275 const char *p = source;
2276 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002277 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002278
2279 len = strlen(source);
2280 if (len % 2) {
2281 memprintf(err, "an even number of hex digit is expected");
2282 return 0;
2283 }
2284
2285 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002286
Willy Tarreau126d4062013-12-03 17:50:47 +01002287 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002288 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002289 if (!*binstr) {
2290 memprintf(err, "out of memory while loading string pattern");
2291 return 0;
2292 }
2293 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002294 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002295 else {
2296 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002297 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002298 len, *binstrlen);
2299 return 0;
2300 }
2301 alloc = 0;
2302 }
2303 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002304
2305 i = j = 0;
2306 while (j < len) {
2307 if (!ishex(p[i++]))
2308 goto bad_input;
2309 if (!ishex(p[i++]))
2310 goto bad_input;
2311 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2312 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002313 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002314
2315bad_input:
2316 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002317 if (alloc) {
2318 free(*binstr);
2319 *binstr = NULL;
2320 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002321 return 0;
2322}
2323
Willy Tarreau946ba592009-05-10 15:41:18 +02002324/* copies at most <n> characters from <src> and always terminates with '\0' */
2325char *my_strndup(const char *src, int n)
2326{
2327 int len = 0;
2328 char *ret;
2329
2330 while (len < n && src[len])
2331 len++;
2332
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002333 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002334 if (!ret)
2335 return ret;
2336 memcpy(ret, src, len);
2337 ret[len] = '\0';
2338 return ret;
2339}
2340
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002341/*
2342 * search needle in haystack
2343 * returns the pointer if found, returns NULL otherwise
2344 */
2345const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2346{
2347 const void *c = NULL;
2348 unsigned char f;
2349
2350 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2351 return NULL;
2352
2353 f = *(char *)needle;
2354 c = haystack;
2355 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2356 if ((haystacklen - (c - haystack)) < needlelen)
2357 return NULL;
2358
2359 if (memcmp(c, needle, needlelen) == 0)
2360 return c;
2361 ++c;
2362 }
2363 return NULL;
2364}
2365
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002366/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002367size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2368{
2369 size_t ret = 0;
2370
2371 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2372 str++;
2373 ret++;
2374 }
2375 return ret;
2376}
2377
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002378/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002379size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2380{
2381 size_t ret = 0;
2382
2383 while (ret < len) {
2384 if(memchr(reject, *((int *)str), rejectlen))
2385 return ret;
2386 str++;
2387 ret++;
2388 }
2389 return ret;
2390}
2391
Willy Tarreau482b00d2009-10-04 22:48:42 +02002392/* This function returns the first unused key greater than or equal to <key> in
2393 * ID tree <root>. Zero is returned if no place is found.
2394 */
2395unsigned int get_next_id(struct eb_root *root, unsigned int key)
2396{
2397 struct eb32_node *used;
2398
2399 do {
2400 used = eb32_lookup_ge(root, key);
2401 if (!used || used->key > key)
2402 return key; /* key is available */
2403 key++;
2404 } while (key);
2405 return key;
2406}
2407
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002408/* dump the full tree to <file> in DOT format for debugging purposes. Will
2409 * optionally highlight node <subj> if found, depending on operation <op> :
2410 * 0 : nothing
2411 * >0 : insertion, node/leaf are surrounded in red
2412 * <0 : removal, node/leaf are dashed with no background
2413 * Will optionally add "desc" as a label on the graph if set and non-null.
2414 */
2415void 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 +01002416{
2417 struct eb32sc_node *node;
2418 unsigned long scope = -1;
2419
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002420 fprintf(file, "digraph ebtree {\n");
2421
2422 if (desc && *desc) {
2423 fprintf(file,
2424 " fontname=\"fixed\";\n"
2425 " fontsize=8;\n"
2426 " label=\"%s\";\n", desc);
2427 }
2428
Willy Tarreaued3cda02017-11-15 15:04:05 +01002429 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002430 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2431 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002432 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2433 );
2434
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002435 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002436 (long)eb_root_to_node(root),
2437 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002438 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2439
2440 node = eb32sc_first(root, scope);
2441 while (node) {
2442 if (node->node.node_p) {
2443 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002444 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2445 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2446 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002447
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002448 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002449 (long)node,
2450 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002451 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002452
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002453 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002454 (long)node,
2455 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002456 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2457
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002458 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002459 (long)node,
2460 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002461 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2462 }
2463
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002464 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2465 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2466 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002467
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002468 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002469 (long)node,
2470 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002471 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002472 node = eb32sc_next(node, scope);
2473 }
2474 fprintf(file, "}\n");
2475}
2476
Willy Tarreau348238b2010-01-18 15:05:57 +01002477/* This function compares a sample word possibly followed by blanks to another
2478 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2479 * otherwise zero. This intends to be used when checking HTTP headers for some
2480 * values. Note that it validates a word followed only by blanks but does not
2481 * validate a word followed by blanks then other chars.
2482 */
2483int word_match(const char *sample, int slen, const char *word, int wlen)
2484{
2485 if (slen < wlen)
2486 return 0;
2487
2488 while (wlen) {
2489 char c = *sample ^ *word;
2490 if (c && c != ('A' ^ 'a'))
2491 return 0;
2492 sample++;
2493 word++;
2494 slen--;
2495 wlen--;
2496 }
2497
2498 while (slen) {
2499 if (*sample != ' ' && *sample != '\t')
2500 return 0;
2501 sample++;
2502 slen--;
2503 }
2504 return 1;
2505}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002506
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002507/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2508 * is particularly fast because it avoids expensive operations such as
2509 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002510 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002511 */
2512unsigned int inetaddr_host(const char *text)
2513{
2514 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2515 register unsigned int dig100, dig10, dig1;
2516 int s;
2517 const char *p, *d;
2518
2519 dig1 = dig10 = dig100 = ascii_zero;
2520 s = 24;
2521
2522 p = text;
2523 while (1) {
2524 if (((unsigned)(*p - '0')) <= 9) {
2525 p++;
2526 continue;
2527 }
2528
2529 /* here, we have a complete byte between <text> and <p> (exclusive) */
2530 if (p == text)
2531 goto end;
2532
2533 d = p - 1;
2534 dig1 |= (unsigned int)(*d << s);
2535 if (d == text)
2536 goto end;
2537
2538 d--;
2539 dig10 |= (unsigned int)(*d << s);
2540 if (d == text)
2541 goto end;
2542
2543 d--;
2544 dig100 |= (unsigned int)(*d << s);
2545 end:
2546 if (!s || *p != '.')
2547 break;
2548
2549 s -= 8;
2550 text = ++p;
2551 }
2552
2553 dig100 -= ascii_zero;
2554 dig10 -= ascii_zero;
2555 dig1 -= ascii_zero;
2556 return ((dig100 * 10) + dig10) * 10 + dig1;
2557}
2558
2559/*
2560 * Idem except the first unparsed character has to be passed in <stop>.
2561 */
2562unsigned int inetaddr_host_lim(const char *text, const char *stop)
2563{
2564 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2565 register unsigned int dig100, dig10, dig1;
2566 int s;
2567 const char *p, *d;
2568
2569 dig1 = dig10 = dig100 = ascii_zero;
2570 s = 24;
2571
2572 p = text;
2573 while (1) {
2574 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2575 p++;
2576 continue;
2577 }
2578
2579 /* here, we have a complete byte between <text> and <p> (exclusive) */
2580 if (p == text)
2581 goto end;
2582
2583 d = p - 1;
2584 dig1 |= (unsigned int)(*d << s);
2585 if (d == text)
2586 goto end;
2587
2588 d--;
2589 dig10 |= (unsigned int)(*d << s);
2590 if (d == text)
2591 goto end;
2592
2593 d--;
2594 dig100 |= (unsigned int)(*d << s);
2595 end:
2596 if (!s || p == stop || *p != '.')
2597 break;
2598
2599 s -= 8;
2600 text = ++p;
2601 }
2602
2603 dig100 -= ascii_zero;
2604 dig10 -= ascii_zero;
2605 dig1 -= ascii_zero;
2606 return ((dig100 * 10) + dig10) * 10 + dig1;
2607}
2608
2609/*
2610 * Idem except the pointer to first unparsed byte is returned into <ret> which
2611 * must not be NULL.
2612 */
Willy Tarreau74172752010-10-15 23:21:42 +02002613unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002614{
2615 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2616 register unsigned int dig100, dig10, dig1;
2617 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002618 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002619
2620 dig1 = dig10 = dig100 = ascii_zero;
2621 s = 24;
2622
2623 p = text;
2624 while (1) {
2625 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2626 p++;
2627 continue;
2628 }
2629
2630 /* here, we have a complete byte between <text> and <p> (exclusive) */
2631 if (p == text)
2632 goto end;
2633
2634 d = p - 1;
2635 dig1 |= (unsigned int)(*d << s);
2636 if (d == text)
2637 goto end;
2638
2639 d--;
2640 dig10 |= (unsigned int)(*d << s);
2641 if (d == text)
2642 goto end;
2643
2644 d--;
2645 dig100 |= (unsigned int)(*d << s);
2646 end:
2647 if (!s || p == stop || *p != '.')
2648 break;
2649
2650 s -= 8;
2651 text = ++p;
2652 }
2653
2654 *ret = p;
2655 dig100 -= ascii_zero;
2656 dig10 -= ascii_zero;
2657 dig1 -= ascii_zero;
2658 return ((dig100 * 10) + dig10) * 10 + dig1;
2659}
2660
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002661/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2662 * or the number of chars read in case of success. Maybe this could be replaced
2663 * by one of the functions above. Also, apparently this function does not support
2664 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002665 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002666 */
2667int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2668{
2669 const char *addr;
2670 int saw_digit, octets, ch;
2671 u_char tmp[4], *tp;
2672 const char *cp = buf;
2673
2674 saw_digit = 0;
2675 octets = 0;
2676 *(tp = tmp) = 0;
2677
2678 for (addr = buf; addr - buf < len; addr++) {
2679 unsigned char digit = (ch = *addr) - '0';
2680
2681 if (digit > 9 && ch != '.')
2682 break;
2683
2684 if (digit <= 9) {
2685 u_int new = *tp * 10 + digit;
2686
2687 if (new > 255)
2688 return 0;
2689
2690 *tp = new;
2691
2692 if (!saw_digit) {
2693 if (++octets > 4)
2694 return 0;
2695 saw_digit = 1;
2696 }
2697 } else if (ch == '.' && saw_digit) {
2698 if (octets == 4)
2699 return 0;
2700
2701 *++tp = 0;
2702 saw_digit = 0;
2703 } else
2704 return 0;
2705 }
2706
2707 if (octets < 4)
2708 return 0;
2709
2710 memcpy(&dst->s_addr, tmp, 4);
2711 return addr - cp;
2712}
2713
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002714/* This function converts the string in <buf> of the len <len> to
2715 * struct in6_addr <dst> which must be allocated by the caller.
2716 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002717 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002718 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002719int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2720{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002721 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002722 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002723
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002724 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002725 return 0;
2726
2727 memcpy(null_term_ip6, buf, len);
2728 null_term_ip6[len] = '\0';
2729
Willy Tarreau075415a2013-12-12 11:29:39 +01002730 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002731 return 0;
2732
Willy Tarreau075415a2013-12-12 11:29:39 +01002733 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002734 return 1;
2735}
2736
Willy Tarreauacf95772010-06-14 19:09:21 +02002737/* To be used to quote config arg positions. Returns the short string at <ptr>
2738 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2739 * if ptr is NULL or empty. The string is locally allocated.
2740 */
2741const char *quote_arg(const char *ptr)
2742{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002743 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002744 int i;
2745
2746 if (!ptr || !*ptr)
2747 return "end of line";
2748 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002749 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002750 val[i] = *ptr++;
2751 val[i++] = '\'';
2752 val[i] = '\0';
2753 return val;
2754}
2755
Willy Tarreau5b180202010-07-18 10:40:48 +02002756/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2757int get_std_op(const char *str)
2758{
2759 int ret = -1;
2760
2761 if (*str == 'e' && str[1] == 'q')
2762 ret = STD_OP_EQ;
2763 else if (*str == 'n' && str[1] == 'e')
2764 ret = STD_OP_NE;
2765 else if (*str == 'l') {
2766 if (str[1] == 'e') ret = STD_OP_LE;
2767 else if (str[1] == 't') ret = STD_OP_LT;
2768 }
2769 else if (*str == 'g') {
2770 if (str[1] == 'e') ret = STD_OP_GE;
2771 else if (str[1] == 't') ret = STD_OP_GT;
2772 }
2773
2774 if (ret == -1 || str[2] != '\0')
2775 return -1;
2776 return ret;
2777}
2778
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002779/* hash a 32-bit integer to another 32-bit integer */
2780unsigned int full_hash(unsigned int a)
2781{
2782 return __full_hash(a);
2783}
2784
Willy Tarreauf3241112019-02-26 09:56:22 +01002785/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2786 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2787 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2788 * a popcount variant and is described here :
2789 * https://graphics.stanford.edu/~seander/bithacks.html
2790 */
2791unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2792{
2793 unsigned long a, b, c, d;
2794 unsigned int s;
2795 unsigned int t;
2796
2797 a = m - ((m >> 1) & ~0UL/3);
2798 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2799 c = (b + (b >> 4)) & ~0UL/0x11;
2800 d = (c + (c >> 8)) & ~0UL/0x101;
2801
2802 r++; // make r be 1..64
2803
2804 t = 0;
2805 s = LONGBITS;
2806 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002807 unsigned long d2 = (d >> 16) >> 16;
2808 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002809 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2810 }
2811
2812 t = (d >> (s - 16)) & 0xff;
2813 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2814 t = (c >> (s - 8)) & 0xf;
2815 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2816 t = (b >> (s - 4)) & 0x7;
2817 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2818 t = (a >> (s - 2)) & 0x3;
2819 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2820 t = (m >> (s - 1)) & 0x1;
2821 s -= ((t - r) & 256) >> 8;
2822
2823 return s - 1;
2824}
2825
2826/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2827 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2828 * using mask_prep_rank_map() below.
2829 */
2830unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2831 unsigned long a, unsigned long b,
2832 unsigned long c, unsigned long d)
2833{
2834 unsigned int s;
2835 unsigned int t;
2836
2837 r++; // make r be 1..64
2838
2839 t = 0;
2840 s = LONGBITS;
2841 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002842 unsigned long d2 = (d >> 16) >> 16;
2843 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002844 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2845 }
2846
2847 t = (d >> (s - 16)) & 0xff;
2848 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2849 t = (c >> (s - 8)) & 0xf;
2850 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2851 t = (b >> (s - 4)) & 0x7;
2852 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2853 t = (a >> (s - 2)) & 0x3;
2854 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2855 t = (m >> (s - 1)) & 0x1;
2856 s -= ((t - r) & 256) >> 8;
2857
2858 return s - 1;
2859}
2860
2861/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2862 * above.
2863 */
2864void mask_prep_rank_map(unsigned long m,
2865 unsigned long *a, unsigned long *b,
2866 unsigned long *c, unsigned long *d)
2867{
2868 *a = m - ((m >> 1) & ~0UL/3);
2869 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2870 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2871 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2872}
2873
David du Colombier4f92d322011-03-24 11:09:31 +01002874/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002875 * otherwise zero. Note that <addr> may not necessarily be aligned
2876 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002877 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002878int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002879{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002880 struct in_addr addr_copy;
2881
2882 memcpy(&addr_copy, addr, sizeof(addr_copy));
2883 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002884}
2885
2886/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002887 * otherwise zero. Note that <addr> may not necessarily be aligned
2888 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002889 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002890int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002891{
2892 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002893 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002894
Willy Tarreaueec1d382016-07-13 11:59:39 +02002895 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002896 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002897 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002898 (((int *)net)[i] & ((int *)mask)[i]))
2899 return 0;
2900 return 1;
2901}
2902
2903/* RFC 4291 prefix */
2904const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2905 0x00, 0x00, 0x00, 0x00,
2906 0x00, 0x00, 0xFF, 0xFF };
2907
Joseph Herlant32b83272018-11-15 11:58:28 -08002908/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002909 * Input and output may overlap.
2910 */
David du Colombier4f92d322011-03-24 11:09:31 +01002911void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2912{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002913 struct in_addr tmp_addr;
2914
2915 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002916 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002917 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002918}
2919
Joseph Herlant32b83272018-11-15 11:58:28 -08002920/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002921 * Return true if conversion is possible and false otherwise.
2922 */
2923int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2924{
2925 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2926 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2927 sizeof(struct in_addr));
2928 return 1;
2929 }
2930
2931 return 0;
2932}
2933
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002934/* compare two struct sockaddr_storage and return:
2935 * 0 (true) if the addr is the same in both
2936 * 1 (false) if the addr is not the same in both
2937 * -1 (unable) if one of the addr is not AF_INET*
2938 */
2939int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2940{
2941 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2942 return -1;
2943
2944 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2945 return -1;
2946
2947 if (ss1->ss_family != ss2->ss_family)
2948 return 1;
2949
2950 switch (ss1->ss_family) {
2951 case AF_INET:
2952 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2953 &((struct sockaddr_in *)ss2)->sin_addr,
2954 sizeof(struct in_addr)) != 0;
2955 case AF_INET6:
2956 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2957 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2958 sizeof(struct in6_addr)) != 0;
2959 }
2960
2961 return 1;
2962}
2963
Baptiste Assmann08396c82016-01-31 00:27:17 +01002964/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002965 * The caller must allocate and clear <dest> before calling.
2966 * The source must be in either AF_INET or AF_INET6 family, or the destination
2967 * address will be undefined. If the destination address used to hold a port,
2968 * it is preserved, so that this function can be used to switch to another
2969 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002970 */
2971struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2972{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002973 int prev_port;
2974
2975 prev_port = get_net_port(dest);
2976 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002977 dest->ss_family = source->ss_family;
2978
2979 /* copy new addr and apply it */
2980 switch (source->ss_family) {
2981 case AF_INET:
2982 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002983 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002984 break;
2985 case AF_INET6:
2986 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 +01002987 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002988 break;
2989 }
2990
2991 return dest;
2992}
2993
William Lallemand421f5b52012-02-06 18:15:57 +01002994char *human_time(int t, short hz_div) {
2995 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2996 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002997 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002998 int cnt=2; // print two numbers
2999
3000 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003001 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003002 return rv;
3003 }
3004
3005 if (unlikely(hz_div > 1))
3006 t /= hz_div;
3007
3008 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003009 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003010 cnt--;
3011 }
3012
3013 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003014 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003015 cnt--;
3016 }
3017
3018 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003019 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003020 cnt--;
3021 }
3022
3023 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003024 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003025
3026 return rv;
3027}
3028
3029const char *monthname[12] = {
3030 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3031 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3032};
3033
3034/* date2str_log: write a date in the format :
3035 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3036 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3037 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3038 *
3039 * without using sprintf. return a pointer to the last char written (\0) or
3040 * NULL if there isn't enough space.
3041 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003042char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003043{
3044
3045 if (size < 25) /* the size is fixed: 24 chars + \0 */
3046 return NULL;
3047
3048 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003049 if (!dst)
3050 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003051 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003052
William Lallemand421f5b52012-02-06 18:15:57 +01003053 memcpy(dst, monthname[tm->tm_mon], 3); // month
3054 dst += 3;
3055 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003056
William Lallemand421f5b52012-02-06 18:15:57 +01003057 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003058 if (!dst)
3059 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003060 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003061
William Lallemand421f5b52012-02-06 18:15:57 +01003062 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003063 if (!dst)
3064 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003065 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003066
William Lallemand421f5b52012-02-06 18:15:57 +01003067 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003068 if (!dst)
3069 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003070 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003071
William Lallemand421f5b52012-02-06 18:15:57 +01003072 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003073 if (!dst)
3074 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003075 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003076
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003077 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003078 if (!dst)
3079 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003080 *dst = '\0';
3081
3082 return dst;
3083}
3084
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003085/* Base year used to compute leap years */
3086#define TM_YEAR_BASE 1900
3087
3088/* Return the difference in seconds between two times (leap seconds are ignored).
3089 * Retrieved from glibc 2.18 source code.
3090 */
3091static int my_tm_diff(const struct tm *a, const struct tm *b)
3092{
3093 /* Compute intervening leap days correctly even if year is negative.
3094 * Take care to avoid int overflow in leap day calculations,
3095 * but it's OK to assume that A and B are close to each other.
3096 */
3097 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3098 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3099 int a100 = a4 / 25 - (a4 % 25 < 0);
3100 int b100 = b4 / 25 - (b4 % 25 < 0);
3101 int a400 = a100 >> 2;
3102 int b400 = b100 >> 2;
3103 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3104 int years = a->tm_year - b->tm_year;
3105 int days = (365 * years + intervening_leap_days
3106 + (a->tm_yday - b->tm_yday));
3107 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3108 + (a->tm_min - b->tm_min))
3109 + (a->tm_sec - b->tm_sec));
3110}
3111
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003112/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003113 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003114 * The string returned has the same format as returned by strftime(... "%z", tm).
3115 * Offsets are kept in an internal cache for better performances.
3116 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003117const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003118{
3119 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003120 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003121
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003122 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003123 struct tm tm_gmt;
3124 int diff;
3125 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003126
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003127 /* Pretend DST not active if its status is unknown */
3128 if (isdst < 0)
3129 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003130
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003131 /* Fetch the offset and initialize it if needed */
3132 gmt_offset = gmt_offsets[isdst & 0x01];
3133 if (unlikely(!*gmt_offset)) {
3134 get_gmtime(t, &tm_gmt);
3135 diff = my_tm_diff(tm, &tm_gmt);
3136 if (diff < 0) {
3137 diff = -diff;
3138 *gmt_offset = '-';
3139 } else {
3140 *gmt_offset = '+';
3141 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003142 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003143 diff /= 60; /* Convert to minutes */
3144 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3145 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003146
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003147 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003148}
3149
William Lallemand421f5b52012-02-06 18:15:57 +01003150/* gmt2str_log: write a date in the format :
3151 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3152 * return a pointer to the last char written (\0) or
3153 * NULL if there isn't enough space.
3154 */
3155char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3156{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003157 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003158 return NULL;
3159
3160 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003161 if (!dst)
3162 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003163 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003164
William Lallemand421f5b52012-02-06 18:15:57 +01003165 memcpy(dst, monthname[tm->tm_mon], 3); // month
3166 dst += 3;
3167 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003168
William Lallemand421f5b52012-02-06 18:15:57 +01003169 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003170 if (!dst)
3171 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003172 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003173
William Lallemand421f5b52012-02-06 18:15:57 +01003174 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003175 if (!dst)
3176 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003177 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003178
William Lallemand421f5b52012-02-06 18:15:57 +01003179 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003180 if (!dst)
3181 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003182 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003183
William Lallemand421f5b52012-02-06 18:15:57 +01003184 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003185 if (!dst)
3186 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003187 *dst++ = ' ';
3188 *dst++ = '+';
3189 *dst++ = '0';
3190 *dst++ = '0';
3191 *dst++ = '0';
3192 *dst++ = '0';
3193 *dst = '\0';
3194
3195 return dst;
3196}
3197
Yuxans Yao4e25b012012-10-19 10:36:09 +08003198/* localdate2str_log: write a date in the format :
3199 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003200 * Both t and tm must represent the same time.
3201 * return a pointer to the last char written (\0) or
3202 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003203 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003204char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003205{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003206 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003207 if (size < 27) /* the size is fixed: 26 chars + \0 */
3208 return NULL;
3209
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003210 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003211
Yuxans Yao4e25b012012-10-19 10:36:09 +08003212 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003213 if (!dst)
3214 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003215 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003216
Yuxans Yao4e25b012012-10-19 10:36:09 +08003217 memcpy(dst, monthname[tm->tm_mon], 3); // month
3218 dst += 3;
3219 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003220
Yuxans Yao4e25b012012-10-19 10:36:09 +08003221 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003222 if (!dst)
3223 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003224 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003225
Yuxans Yao4e25b012012-10-19 10:36:09 +08003226 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003227 if (!dst)
3228 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003229 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003230
Yuxans Yao4e25b012012-10-19 10:36:09 +08003231 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003232 if (!dst)
3233 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003234 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003235
Yuxans Yao4e25b012012-10-19 10:36:09 +08003236 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003237 if (!dst)
3238 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003239 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003240
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003241 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003242 dst += 5;
3243 *dst = '\0';
3244
3245 return dst;
3246}
3247
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003248/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3249 * It is meant as a portable replacement for timegm() for use with valid inputs.
3250 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3251 */
3252time_t my_timegm(const struct tm *tm)
3253{
3254 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3255 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3256 * sum of the extra N days for elapsed months. The sum of all these N
3257 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3258 * in a 5-bit word. This means that with 60 bits we can represent a
3259 * matrix of all these values at once, which is fast and efficient to
3260 * access. The extra February day for leap years is not counted here.
3261 *
3262 * Jan : none = 0 (0)
3263 * Feb : Jan = 3 (3)
3264 * Mar : Jan..Feb = 3 (3 + 0)
3265 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3266 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3267 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3268 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3269 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3270 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3271 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3272 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3273 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3274 */
3275 uint64_t extra =
3276 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3277 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3278 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3279 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3280
3281 unsigned int y = tm->tm_year + 1900;
3282 unsigned int m = tm->tm_mon;
3283 unsigned long days = 0;
3284
3285 /* days since 1/1/1970 for full years */
3286 days += days_since_zero(y) - days_since_zero(1970);
3287
3288 /* days for full months in the current year */
3289 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3290
3291 /* count + 1 after March for leap years. A leap year is a year multiple
3292 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3293 * is leap, 1900 isn't, 1904 is.
3294 */
3295 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3296 days++;
3297
3298 days += tm->tm_mday - 1;
3299 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3300}
3301
Thierry Fournier93127942016-01-20 18:49:45 +01003302/* This function check a char. It returns true and updates
3303 * <date> and <len> pointer to the new position if the
3304 * character is found.
3305 */
3306static inline int parse_expect_char(const char **date, int *len, char c)
3307{
3308 if (*len < 1 || **date != c)
3309 return 0;
3310 (*len)--;
3311 (*date)++;
3312 return 1;
3313}
3314
3315/* This function expects a string <str> of len <l>. It return true and updates.
3316 * <date> and <len> if the string matches, otherwise, it returns false.
3317 */
3318static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3319{
3320 if (*len < l || strncmp(*date, str, l) != 0)
3321 return 0;
3322 (*len) -= l;
3323 (*date) += l;
3324 return 1;
3325}
3326
3327/* This macro converts 3 chars name in integer. */
3328#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3329
3330/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3331 * / %x54.75.65 ; "Tue", case-sensitive
3332 * / %x57.65.64 ; "Wed", case-sensitive
3333 * / %x54.68.75 ; "Thu", case-sensitive
3334 * / %x46.72.69 ; "Fri", case-sensitive
3335 * / %x53.61.74 ; "Sat", case-sensitive
3336 * / %x53.75.6E ; "Sun", case-sensitive
3337 *
3338 * This array must be alphabetically sorted
3339 */
3340static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3341{
3342 if (*len < 3)
3343 return 0;
3344 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3345 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3346 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3347 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3348 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3349 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3350 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3351 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3352 default: return 0;
3353 }
3354 *len -= 3;
3355 *date += 3;
3356 return 1;
3357}
3358
3359/* month = %x4A.61.6E ; "Jan", case-sensitive
3360 * / %x46.65.62 ; "Feb", case-sensitive
3361 * / %x4D.61.72 ; "Mar", case-sensitive
3362 * / %x41.70.72 ; "Apr", case-sensitive
3363 * / %x4D.61.79 ; "May", case-sensitive
3364 * / %x4A.75.6E ; "Jun", case-sensitive
3365 * / %x4A.75.6C ; "Jul", case-sensitive
3366 * / %x41.75.67 ; "Aug", case-sensitive
3367 * / %x53.65.70 ; "Sep", case-sensitive
3368 * / %x4F.63.74 ; "Oct", case-sensitive
3369 * / %x4E.6F.76 ; "Nov", case-sensitive
3370 * / %x44.65.63 ; "Dec", case-sensitive
3371 *
3372 * This array must be alphabetically sorted
3373 */
3374static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3375{
3376 if (*len < 3)
3377 return 0;
3378 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3379 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3380 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3381 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3382 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3383 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3384 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3385 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3386 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3387 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3388 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3389 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3390 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3391 default: return 0;
3392 }
3393 *len -= 3;
3394 *date += 3;
3395 return 1;
3396}
3397
3398/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3399 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3400 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3401 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3402 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3403 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3404 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3405 *
3406 * This array must be alphabetically sorted
3407 */
3408static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3409{
3410 if (*len < 6) /* Minimum length. */
3411 return 0;
3412 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3413 case STR2I3('M','o','n'):
3414 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3415 tm->tm_wday = 1;
3416 return 1;
3417 case STR2I3('T','u','e'):
3418 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3419 tm->tm_wday = 2;
3420 return 1;
3421 case STR2I3('W','e','d'):
3422 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3423 tm->tm_wday = 3;
3424 return 1;
3425 case STR2I3('T','h','u'):
3426 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3427 tm->tm_wday = 4;
3428 return 1;
3429 case STR2I3('F','r','i'):
3430 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3431 tm->tm_wday = 5;
3432 return 1;
3433 case STR2I3('S','a','t'):
3434 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3435 tm->tm_wday = 6;
3436 return 1;
3437 case STR2I3('S','u','n'):
3438 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3439 tm->tm_wday = 7;
3440 return 1;
3441 }
3442 return 0;
3443}
3444
3445/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3446static inline int parse_digit(const char **date, int *len, int *digit)
3447{
3448 if (*len < 1 || **date < '0' || **date > '9')
3449 return 0;
3450 *digit = (**date - '0');
3451 (*date)++;
3452 (*len)--;
3453 return 1;
3454}
3455
3456/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3457static inline int parse_2digit(const char **date, int *len, int *digit)
3458{
3459 int value;
3460
3461 RET0_UNLESS(parse_digit(date, len, &value));
3462 (*digit) = value * 10;
3463 RET0_UNLESS(parse_digit(date, len, &value));
3464 (*digit) += value;
3465
3466 return 1;
3467}
3468
3469/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3470static inline int parse_4digit(const char **date, int *len, int *digit)
3471{
3472 int value;
3473
3474 RET0_UNLESS(parse_digit(date, len, &value));
3475 (*digit) = value * 1000;
3476
3477 RET0_UNLESS(parse_digit(date, len, &value));
3478 (*digit) += value * 100;
3479
3480 RET0_UNLESS(parse_digit(date, len, &value));
3481 (*digit) += value * 10;
3482
3483 RET0_UNLESS(parse_digit(date, len, &value));
3484 (*digit) += value;
3485
3486 return 1;
3487}
3488
3489/* time-of-day = hour ":" minute ":" second
3490 * ; 00:00:00 - 23:59:60 (leap second)
3491 *
3492 * hour = 2DIGIT
3493 * minute = 2DIGIT
3494 * second = 2DIGIT
3495 */
3496static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3497{
3498 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3499 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3500 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3501 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3502 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3503 return 1;
3504}
3505
3506/* From RFC7231
3507 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3508 *
3509 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3510 * ; fixed length/zone/capitalization subset of the format
3511 * ; see Section 3.3 of [RFC5322]
3512 *
3513 *
3514 * date1 = day SP month SP year
3515 * ; e.g., 02 Jun 1982
3516 *
3517 * day = 2DIGIT
3518 * year = 4DIGIT
3519 *
3520 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3521 *
3522 * time-of-day = hour ":" minute ":" second
3523 * ; 00:00:00 - 23:59:60 (leap second)
3524 *
3525 * hour = 2DIGIT
3526 * minute = 2DIGIT
3527 * second = 2DIGIT
3528 *
3529 * DIGIT = decimal 0-9
3530 */
3531int parse_imf_date(const char *date, int len, struct tm *tm)
3532{
David Carlier327298c2016-11-20 10:42:38 +00003533 /* tm_gmtoff, if present, ought to be zero'ed */
3534 memset(tm, 0, sizeof(*tm));
3535
Thierry Fournier93127942016-01-20 18:49:45 +01003536 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3537 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3538 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3539 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3540 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3541 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3542 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3543 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3544 tm->tm_year -= 1900;
3545 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3546 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3547 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3548 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3549 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003550 return 1;
3551}
3552
3553/* From RFC7231
3554 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3555 *
3556 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3557 * date2 = day "-" month "-" 2DIGIT
3558 * ; e.g., 02-Jun-82
3559 *
3560 * day = 2DIGIT
3561 */
3562int parse_rfc850_date(const char *date, int len, struct tm *tm)
3563{
3564 int year;
3565
David Carlier327298c2016-11-20 10:42:38 +00003566 /* tm_gmtoff, if present, ought to be zero'ed */
3567 memset(tm, 0, sizeof(*tm));
3568
Thierry Fournier93127942016-01-20 18:49:45 +01003569 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3570 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3571 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3572 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3573 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3574 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3575 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3576
3577 /* year = 2DIGIT
3578 *
3579 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3580 * two-digit year, MUST interpret a timestamp that appears to be more
3581 * than 50 years in the future as representing the most recent year in
3582 * the past that had the same last two digits.
3583 */
3584 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3585
3586 /* expect SP */
3587 if (!parse_expect_char(&date, &len, ' ')) {
3588 /* Maybe we have the date with 4 digits. */
3589 RET0_UNLESS(parse_2digit(&date, &len, &year));
3590 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3591 /* expect SP */
3592 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3593 } else {
3594 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3595 * tm_year is the number of year since 1900, so for +1900, we
3596 * do nothing, and for +2000, we add 100.
3597 */
3598 if (tm->tm_year <= 60)
3599 tm->tm_year += 100;
3600 }
3601
3602 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3603 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3604 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3605 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003606
3607 return 1;
3608}
3609
3610/* From RFC7231
3611 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3612 *
3613 * asctime-date = day-name SP date3 SP time-of-day SP year
3614 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3615 * ; e.g., Jun 2
3616 *
3617 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3618 * whitespace in an HTTP-date beyond that specifically included as SP in
3619 * the grammar.
3620 */
3621int parse_asctime_date(const char *date, int len, struct tm *tm)
3622{
David Carlier327298c2016-11-20 10:42:38 +00003623 /* tm_gmtoff, if present, ought to be zero'ed */
3624 memset(tm, 0, sizeof(*tm));
3625
Thierry Fournier93127942016-01-20 18:49:45 +01003626 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3627 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3628 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3629 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3630
3631 /* expect SP and 1DIGIT or 2DIGIT */
3632 if (parse_expect_char(&date, &len, ' '))
3633 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3634 else
3635 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3636
3637 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3638 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3639 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3640 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3641 tm->tm_year -= 1900;
3642 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003643 return 1;
3644}
3645
3646/* From RFC7231
3647 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3648 *
3649 * HTTP-date = IMF-fixdate / obs-date
3650 * obs-date = rfc850-date / asctime-date
3651 *
3652 * parses an HTTP date in the RFC format and is accepted
3653 * alternatives. <date> is the strinf containing the date,
3654 * len is the len of the string. <tm> is filled with the
3655 * parsed time. We must considers this time as GMT.
3656 */
3657int parse_http_date(const char *date, int len, struct tm *tm)
3658{
3659 if (parse_imf_date(date, len, tm))
3660 return 1;
3661
3662 if (parse_rfc850_date(date, len, tm))
3663 return 1;
3664
3665 if (parse_asctime_date(date, len, tm))
3666 return 1;
3667
3668 return 0;
3669}
3670
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003671/* Dynamically allocates a string of the proper length to hold the formatted
3672 * output. NULL is returned on error. The caller is responsible for freeing the
3673 * memory area using free(). The resulting string is returned in <out> if the
3674 * pointer is not NULL. A previous version of <out> might be used to build the
3675 * new string, and it will be freed before returning if it is not NULL, which
3676 * makes it possible to build complex strings from iterative calls without
3677 * having to care about freeing intermediate values, as in the example below :
3678 *
3679 * memprintf(&err, "invalid argument: '%s'", arg);
3680 * ...
3681 * memprintf(&err, "parser said : <%s>\n", *err);
3682 * ...
3683 * free(*err);
3684 *
3685 * This means that <err> must be initialized to NULL before first invocation.
3686 * The return value also holds the allocated string, which eases error checking
3687 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003688 * passed instead and it will be ignored. The returned message will then also
3689 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003690 *
3691 * It is also convenient to use it without any free except the last one :
3692 * err = NULL;
3693 * if (!fct1(err)) report(*err);
3694 * if (!fct2(err)) report(*err);
3695 * if (!fct3(err)) report(*err);
3696 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003697 *
3698 * memprintf relies on memvprintf. This last version can be called from any
3699 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003700 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003701char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003702{
3703 va_list args;
3704 char *ret = NULL;
3705 int allocated = 0;
3706 int needed = 0;
3707
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003708 if (!out)
3709 return NULL;
3710
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003711 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003712 char buf1;
3713
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003714 /* vsnprintf() will return the required length even when the
3715 * target buffer is NULL. We do this in a loop just in case
3716 * intermediate evaluations get wrong.
3717 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003718 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003719 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003720 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003721 if (needed < allocated) {
3722 /* Note: on Solaris 8, the first iteration always
3723 * returns -1 if allocated is zero, so we force a
3724 * retry.
3725 */
3726 if (!allocated)
3727 needed = 0;
3728 else
3729 break;
3730 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003731
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003732 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003733 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003734 } while (ret);
3735
3736 if (needed < 0) {
3737 /* an error was encountered */
3738 free(ret);
3739 ret = NULL;
3740 }
3741
3742 if (out) {
3743 free(*out);
3744 *out = ret;
3745 }
3746
3747 return ret;
3748}
William Lallemand421f5b52012-02-06 18:15:57 +01003749
Christopher Faulet93a518f2017-10-24 11:25:33 +02003750char *memprintf(char **out, const char *format, ...)
3751{
3752 va_list args;
3753 char *ret = NULL;
3754
3755 va_start(args, format);
3756 ret = memvprintf(out, format, args);
3757 va_end(args);
3758
3759 return ret;
3760}
3761
Willy Tarreau21c705b2012-09-14 11:40:36 +02003762/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3763 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003764 * freed by the caller. It also supports being passed a NULL which results in the same
3765 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003766 * Example of use :
3767 * parse(cmd, &err); (callee: memprintf(&err, ...))
3768 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3769 * free(err);
3770 */
3771char *indent_msg(char **out, int level)
3772{
3773 char *ret, *in, *p;
3774 int needed = 0;
3775 int lf = 0;
3776 int lastlf = 0;
3777 int len;
3778
Willy Tarreau70eec382012-10-10 08:56:47 +02003779 if (!out || !*out)
3780 return NULL;
3781
Willy Tarreau21c705b2012-09-14 11:40:36 +02003782 in = *out - 1;
3783 while ((in = strchr(in + 1, '\n')) != NULL) {
3784 lastlf = in - *out;
3785 lf++;
3786 }
3787
3788 if (!lf) /* single line, no LF, return it as-is */
3789 return *out;
3790
3791 len = strlen(*out);
3792
3793 if (lf == 1 && lastlf == len - 1) {
3794 /* single line, LF at end, strip it and return as-is */
3795 (*out)[lastlf] = 0;
3796 return *out;
3797 }
3798
3799 /* OK now we have at least one LF, we need to process the whole string
3800 * as a multi-line string. What we'll do :
3801 * - prefix with an LF if there is none
3802 * - add <level> spaces before each line
3803 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3804 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3805 */
3806
3807 needed = 1 + level * (lf + 1) + len + 1;
3808 p = ret = malloc(needed);
3809 in = *out;
3810
3811 /* skip initial LFs */
3812 while (*in == '\n')
3813 in++;
3814
3815 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3816 while (*in) {
3817 *p++ = '\n';
3818 memset(p, ' ', level);
3819 p += level;
3820 do {
3821 *p++ = *in++;
3822 } while (*in && *in != '\n');
3823 if (*in)
3824 in++;
3825 }
3826 *p = 0;
3827
3828 free(*out);
3829 *out = ret;
3830
3831 return ret;
3832}
3833
Willy Tarreaua2c99112019-08-21 13:17:37 +02003834/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3835 * and end of lines replaced with <eol> if not 0. The first line to indent has
3836 * to be indicated in <first> (starts at zero), so that it is possible to skip
3837 * indenting the first line if it has to be appended after an existing message.
3838 * Empty strings are never indented, and NULL strings are considered empty both
3839 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3840 * character, non-zero otherwise.
3841 */
3842int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3843{
3844 int bol, lf;
3845 int pfxlen = pfx ? strlen(pfx) : 0;
3846
3847 if (!in)
3848 return 0;
3849
3850 bol = 1;
3851 lf = 0;
3852 while (*in) {
3853 if (bol && pfxlen) {
3854 if (first > 0)
3855 first--;
3856 else
3857 b_putblk(out, pfx, pfxlen);
3858 bol = 0;
3859 }
3860
3861 lf = (*in == '\n');
3862 bol |= lf;
3863 b_putchr(out, (lf && eol) ? eol : *in);
3864 in++;
3865 }
3866 return lf;
3867}
3868
Willy Tarreau9d22e562019-03-29 18:49:09 +01003869/* removes environment variable <name> from the environment as found in
3870 * environ. This is only provided as an alternative for systems without
3871 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003872 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003873 * <name> and to replace the matching pointers with the last pointer of
3874 * the array (since variables are not ordered).
3875 * It always returns 0 (success).
3876 */
3877int my_unsetenv(const char *name)
3878{
3879 extern char **environ;
3880 char **p = environ;
3881 int vars;
3882 int next;
3883 int len;
3884
3885 len = strlen(name);
3886 for (vars = 0; p[vars]; vars++)
3887 ;
3888 next = 0;
3889 while (next < vars) {
3890 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3891 next++;
3892 continue;
3893 }
3894 if (next < vars - 1)
3895 p[next] = p[vars - 1];
3896 p[--vars] = NULL;
3897 }
3898 return 0;
3899}
3900
Willy Tarreaudad36a32013-03-11 01:20:04 +01003901/* Convert occurrences of environment variables in the input string to their
3902 * corresponding value. A variable is identified as a series of alphanumeric
3903 * characters or underscores following a '$' sign. The <in> string must be
3904 * free()able. NULL returns NULL. The resulting string might be reallocated if
3905 * some expansion is made. Variable names may also be enclosed into braces if
3906 * needed (eg: to concatenate alphanum characters).
3907 */
3908char *env_expand(char *in)
3909{
3910 char *txt_beg;
3911 char *out;
3912 char *txt_end;
3913 char *var_beg;
3914 char *var_end;
3915 char *value;
3916 char *next;
3917 int out_len;
3918 int val_len;
3919
3920 if (!in)
3921 return in;
3922
3923 value = out = NULL;
3924 out_len = 0;
3925
3926 txt_beg = in;
3927 do {
3928 /* look for next '$' sign in <in> */
3929 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3930
3931 if (!*txt_end && !out) /* end and no expansion performed */
3932 return in;
3933
3934 val_len = 0;
3935 next = txt_end;
3936 if (*txt_end == '$') {
3937 char save;
3938
3939 var_beg = txt_end + 1;
3940 if (*var_beg == '{')
3941 var_beg++;
3942
3943 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003944 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003945 var_end++;
3946 }
3947
3948 next = var_end;
3949 if (*var_end == '}' && (var_beg > txt_end + 1))
3950 next++;
3951
3952 /* get value of the variable name at this location */
3953 save = *var_end;
3954 *var_end = '\0';
3955 value = getenv(var_beg);
3956 *var_end = save;
3957 val_len = value ? strlen(value) : 0;
3958 }
3959
Hubert Verstraete831962e2016-06-28 22:44:26 +02003960 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003961 if (txt_end > txt_beg) {
3962 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3963 out_len += txt_end - txt_beg;
3964 }
3965 if (val_len) {
3966 memcpy(out + out_len, value, val_len);
3967 out_len += val_len;
3968 }
3969 out[out_len] = 0;
3970 txt_beg = next;
3971 } while (*txt_beg);
3972
3973 /* here we know that <out> was allocated and that we don't need <in> anymore */
3974 free(in);
3975 return out;
3976}
3977
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003978
3979/* same as strstr() but case-insensitive and with limit length */
3980const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3981{
3982 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003983 unsigned int slen, plen;
3984 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003985
3986 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3987 return NULL;
3988
3989 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3990 return str1;
3991
3992 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3993 return NULL;
3994
3995 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 +02003996 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003997 start++;
3998 slen--;
3999 tmp1++;
4000
4001 if (tmp1 >= len_str1)
4002 return NULL;
4003
4004 /* if pattern longer than string */
4005 if (slen < plen)
4006 return NULL;
4007 }
4008
4009 sptr = start;
4010 pptr = (char *)str2;
4011
4012 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004013 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004014 sptr++;
4015 pptr++;
4016 tmp2++;
4017
4018 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4019 return start;
4020 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4021 return NULL;
4022 }
4023 }
4024 return NULL;
4025}
4026
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004027/* This function read the next valid utf8 char.
4028 * <s> is the byte srray to be decode, <len> is its length.
4029 * The function returns decoded char encoded like this:
4030 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4031 * are the length read. The decoded character is stored in <c>.
4032 */
4033unsigned char utf8_next(const char *s, int len, unsigned int *c)
4034{
4035 const unsigned char *p = (unsigned char *)s;
4036 int dec;
4037 unsigned char code = UTF8_CODE_OK;
4038
4039 if (len < 1)
4040 return UTF8_CODE_OK;
4041
4042 /* Check the type of UTF8 sequence
4043 *
4044 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4045 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4046 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4047 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4048 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4049 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4050 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4051 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4052 */
4053 switch (*p) {
4054 case 0x00 ... 0x7f:
4055 *c = *p;
4056 return UTF8_CODE_OK | 1;
4057
4058 case 0x80 ... 0xbf:
4059 *c = *p;
4060 return UTF8_CODE_BADSEQ | 1;
4061
4062 case 0xc0 ... 0xdf:
4063 if (len < 2) {
4064 *c = *p;
4065 return UTF8_CODE_BADSEQ | 1;
4066 }
4067 *c = *p & 0x1f;
4068 dec = 1;
4069 break;
4070
4071 case 0xe0 ... 0xef:
4072 if (len < 3) {
4073 *c = *p;
4074 return UTF8_CODE_BADSEQ | 1;
4075 }
4076 *c = *p & 0x0f;
4077 dec = 2;
4078 break;
4079
4080 case 0xf0 ... 0xf7:
4081 if (len < 4) {
4082 *c = *p;
4083 return UTF8_CODE_BADSEQ | 1;
4084 }
4085 *c = *p & 0x07;
4086 dec = 3;
4087 break;
4088
4089 case 0xf8 ... 0xfb:
4090 if (len < 5) {
4091 *c = *p;
4092 return UTF8_CODE_BADSEQ | 1;
4093 }
4094 *c = *p & 0x03;
4095 dec = 4;
4096 break;
4097
4098 case 0xfc ... 0xfd:
4099 if (len < 6) {
4100 *c = *p;
4101 return UTF8_CODE_BADSEQ | 1;
4102 }
4103 *c = *p & 0x01;
4104 dec = 5;
4105 break;
4106
4107 case 0xfe ... 0xff:
4108 default:
4109 *c = *p;
4110 return UTF8_CODE_BADSEQ | 1;
4111 }
4112
4113 p++;
4114
4115 while (dec > 0) {
4116
4117 /* need 0x10 for the 2 first bits */
4118 if ( ( *p & 0xc0 ) != 0x80 )
4119 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4120
4121 /* add data at char */
4122 *c = ( *c << 6 ) | ( *p & 0x3f );
4123
4124 dec--;
4125 p++;
4126 }
4127
4128 /* Check ovelong encoding.
4129 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4130 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4131 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4132 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004133 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004134 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4135 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4136 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4137 code |= UTF8_CODE_OVERLONG;
4138
4139 /* Check invalid UTF8 range. */
4140 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4141 (*c >= 0xfffe && *c <= 0xffff))
4142 code |= UTF8_CODE_INVRANGE;
4143
4144 return code | ((p-(unsigned char *)s)&0x0f);
4145}
4146
Maxime de Roucydc887852016-05-13 23:52:54 +02004147/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4148 * On failure : return 0 and <err> filled with an error message.
4149 * The caller is responsible for freeing the <err> and <str> copy
4150 * memory area using free()
4151 */
4152int list_append_word(struct list *li, const char *str, char **err)
4153{
4154 struct wordlist *wl;
4155
4156 wl = calloc(1, sizeof(*wl));
4157 if (!wl) {
4158 memprintf(err, "out of memory");
4159 goto fail_wl;
4160 }
4161
4162 wl->s = strdup(str);
4163 if (!wl->s) {
4164 memprintf(err, "out of memory");
4165 goto fail_wl_s;
4166 }
4167
4168 LIST_ADDQ(li, &wl->list);
4169
4170 return 1;
4171
4172fail_wl_s:
4173 free(wl->s);
4174fail_wl:
4175 free(wl);
4176 return 0;
4177}
4178
Willy Tarreau37101052019-05-20 16:48:20 +02004179/* indicates if a memory location may safely be read or not. The trick consists
4180 * in performing a harmless syscall using this location as an input and letting
4181 * the operating system report whether it's OK or not. For this we have the
4182 * stat() syscall, which will return EFAULT when the memory location supposed
4183 * to contain the file name is not readable. If it is readable it will then
4184 * either return 0 if the area contains an existing file name, or -1 with
4185 * another code. This must not be abused, and some audit systems might detect
4186 * this as abnormal activity. It's used only for unsafe dumps.
4187 */
4188int may_access(const void *ptr)
4189{
4190 struct stat buf;
4191
4192 if (stat(ptr, &buf) == 0)
4193 return 1;
4194 if (errno == EFAULT)
4195 return 0;
4196 return 1;
4197}
4198
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004199/* print a string of text buffer to <out>. The format is :
4200 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4201 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4202 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4203 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004204int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004205{
4206 unsigned char c;
4207 int ptr = 0;
4208
4209 while (buf[ptr] && ptr < bsize) {
4210 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004211 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004212 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004213 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004214 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004215 }
4216 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004217 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004218 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004219 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004220 switch (c) {
4221 case ' ': c = ' '; break;
4222 case '\t': c = 't'; break;
4223 case '\n': c = 'n'; break;
4224 case '\r': c = 'r'; break;
4225 case '\e': c = 'e'; break;
4226 case '\\': c = '\\'; break;
4227 case '=': c = '='; break;
4228 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004229 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004230 }
4231 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004232 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004233 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004234 out->area[out->data++] = '\\';
4235 out->area[out->data++] = 'x';
4236 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4237 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004238 }
4239 ptr++;
4240 }
4241
4242 return ptr;
4243}
4244
4245/* print a buffer in hexa.
4246 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4247 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004248int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004249{
4250 unsigned char c;
4251 int ptr = 0;
4252
4253 while (ptr < bsize) {
4254 c = buf[ptr];
4255
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004256 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004257 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004258 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4259 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004260
4261 ptr++;
4262 }
4263 return ptr;
4264}
4265
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004266/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4267 * prepending each line with prefix <pfx>. The output is *not* initialized.
4268 * The output will not wrap pas the buffer's end so it is more optimal if the
4269 * caller makes sure the buffer is aligned first. A trailing zero will always
4270 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004271 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4272 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004273 */
Willy Tarreau37101052019-05-20 16:48:20 +02004274void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004275{
4276 const unsigned char *d = buf;
4277 int i, j, start;
4278
4279 d = (const unsigned char *)(((unsigned long)buf) & -16);
4280 start = ((unsigned long)buf) & 15;
4281
4282 for (i = 0; i < start + len; i += 16) {
4283 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4284
Willy Tarreau37101052019-05-20 16:48:20 +02004285 // 0: unchecked, 1: checked safe, 2: danger
4286 unsafe = !!unsafe;
4287 if (unsafe && !may_access(d + i))
4288 unsafe = 2;
4289
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004290 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004291 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004292 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004293 else if (unsafe > 1)
4294 chunk_strcat(out, "** ");
4295 else
4296 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004297
4298 if (j == 7)
4299 chunk_strcat(out, "- ");
4300 }
4301 chunk_strcat(out, " ");
4302 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004303 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004304 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004305 else if (unsafe > 1)
4306 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004307 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004308 chunk_appendf(out, "%c", d[i + j]);
4309 else
4310 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004311 }
4312 chunk_strcat(out, "\n");
4313 }
4314}
4315
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004316/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4317 * enclosed in brackets after the address itself, formatted on 14 chars
4318 * including the "0x" prefix. This is meant to be used as a prefix for code
4319 * areas. For example:
4320 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4321 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4322 * is emitted. A NULL <pfx> will be considered empty.
4323 */
4324void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4325{
4326 int ok = 0;
4327 int i;
4328
4329 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4330
4331 for (i = 0; i < n; i++) {
4332 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4333 ok = may_access(addr + i);
4334 if (ok)
4335 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4336 else
4337 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4338 }
4339}
4340
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004341/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4342 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4343 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4344 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4345 * lines are respected within the limit of 70 output chars. Lines that are
4346 * continuation of a previous truncated line begin with "+" instead of " "
4347 * after the offset. The new pointer is returned.
4348 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004349int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004350 int *line, int ptr)
4351{
4352 int end;
4353 unsigned char c;
4354
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004355 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004356 if (end > out->size)
4357 return ptr;
4358
4359 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4360
4361 while (ptr < len && ptr < bsize) {
4362 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004363 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004364 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004365 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004366 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004367 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004368 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004369 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004370 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004371 switch (c) {
4372 case '\t': c = 't'; break;
4373 case '\n': c = 'n'; break;
4374 case '\r': c = 'r'; break;
4375 case '\e': c = 'e'; break;
4376 case '\\': c = '\\'; break;
4377 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004378 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004379 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004380 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004381 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004382 out->area[out->data++] = '\\';
4383 out->area[out->data++] = 'x';
4384 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4385 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004386 }
4387 if (buf[ptr++] == '\n') {
4388 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004389 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004390 *line = ptr;
4391 return ptr;
4392 }
4393 }
4394 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004395 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004396 return ptr;
4397}
4398
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004399/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004400 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4401 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004402 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004403void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4404 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004405{
Willy Tarreau73459792017-04-11 07:58:08 +02004406 unsigned int i;
4407 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004408
4409 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4410 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004411 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004412 for (j = 0; j < 8; j++) {
4413 if (b + j >= 0 && b + j < len)
4414 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4415 else
4416 fprintf(out, " ");
4417 }
4418
4419 if (b + j >= 0 && b + j < len)
4420 fputc('-', out);
4421 else
4422 fputc(' ', out);
4423
4424 for (j = 8; j < 16; j++) {
4425 if (b + j >= 0 && b + j < len)
4426 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4427 else
4428 fprintf(out, " ");
4429 }
4430
4431 fprintf(out, " ");
4432 for (j = 0; j < 16; j++) {
4433 if (b + j >= 0 && b + j < len) {
4434 if (isprint((unsigned char)buf[b + j]))
4435 fputc((unsigned char)buf[b + j], out);
4436 else
4437 fputc('.', out);
4438 }
4439 else
4440 fputc(' ', out);
4441 }
4442 fputc('\n', out);
4443 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004444}
4445
Willy Tarreaubb869862020-04-16 10:52:41 +02004446/* Tries to report the executable path name on platforms supporting this. If
4447 * not found or not possible, returns NULL.
4448 */
4449const char *get_exec_path()
4450{
4451 const char *ret = NULL;
4452
4453#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4454 long execfn = getauxval(AT_EXECFN);
4455
4456 if (execfn && execfn != ENOENT)
4457 ret = (const char *)execfn;
4458#endif
4459 return ret;
4460}
4461
Baruch Siache1651b22020-07-24 07:52:20 +03004462#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004463/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4464 * also returns the symbol size in <size>, otherwise returns 0 there.
4465 */
4466static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4467{
4468 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004469#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004470 const ElfW(Sym) *sym;
4471
4472 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4473 if (ret)
4474 *size = sym ? sym->st_size : 0;
4475#else
4476 ret = dladdr(addr, dli);
4477 *size = 0;
4478#endif
4479 return ret;
4480}
4481#endif
4482
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004483/* Tries to append to buffer <buf> some indications about the symbol at address
4484 * <addr> using the following form:
4485 * lib:+0xoffset (unresolvable address from lib's base)
4486 * main+0xoffset (unresolvable address from main (+/-))
4487 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4488 * name (resolved exact exec address)
4489 * lib:name (resolved exact lib address)
4490 * name+0xoffset/0xsize (resolved address within exec symbol)
4491 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4492 *
4493 * The file name (lib or executable) is limited to what lies between the last
4494 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4495 * 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 +03004496 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004497 *
4498 * The symbol's base address is returned, or NULL when unresolved, in order to
4499 * allow the caller to match it against known ones.
4500 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004501const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004502{
4503 const struct {
4504 const void *func;
4505 const char *name;
4506 } fcts[] = {
4507 { .func = process_stream, .name = "process_stream" },
4508 { .func = task_run_applet, .name = "task_run_applet" },
4509 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4510 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4511 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4512 { .func = listener_accept, .name = "listener_accept" },
4513 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4514 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4515#ifdef USE_LUA
4516 { .func = hlua_process_task, .name = "hlua_process_task" },
4517#endif
4518#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4519 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4520 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4521#endif
4522 };
4523
Baruch Siache1651b22020-07-24 07:52:20 +03004524#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004525 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004526 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004527 const char *fname, *p;
4528#endif
4529 int i;
4530
4531 if (pfx)
4532 chunk_appendf(buf, "%s", pfx);
4533
4534 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4535 if (addr == fcts[i].func) {
4536 chunk_appendf(buf, "%s", fcts[i].name);
4537 return addr;
4538 }
4539 }
4540
Baruch Siache1651b22020-07-24 07:52:20 +03004541#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004542 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004543 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004544 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004545
4546 /* 1. prefix the library name if it's not the same object as the one
4547 * that contains the main function. The name is picked between last '/'
4548 * and first following '.'.
4549 */
4550 if (!dladdr(main, &dli_main))
4551 dli_main.dli_fbase = NULL;
4552
4553 if (dli_main.dli_fbase != dli.dli_fbase) {
4554 fname = dli.dli_fname;
4555 p = strrchr(fname, '/');
4556 if (p++)
4557 fname = p;
4558 p = strchr(fname, '.');
4559 if (!p)
4560 p = fname + strlen(fname);
4561
4562 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4563 }
4564
4565 /* 2. symbol name */
4566 if (dli.dli_sname) {
4567 /* known, dump it and return symbol's address (exact or relative) */
4568 chunk_appendf(buf, "%s", dli.dli_sname);
4569 if (addr != dli.dli_saddr) {
4570 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004571 if (size)
4572 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004573 }
4574 return dli.dli_saddr;
4575 }
4576 else if (dli_main.dli_fbase != dli.dli_fbase) {
4577 /* unresolved symbol from a known library, report relative offset */
4578 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4579 return NULL;
4580 }
Baruch Siache1651b22020-07-24 07:52:20 +03004581#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004582 unknown:
4583 /* unresolved symbol from the main file, report relative offset to main */
4584 if ((void*)addr < (void*)main)
4585 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4586 else
4587 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4588 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004589}
4590
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004591/*
4592 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004593 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004594 *
4595 * First, initializes the value with <sz> as address to 0 and initializes the
4596 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4597 * address updating <sz> pointed value to the size of this array.
4598 *
4599 * Returns 1 if succeeded, 0 if not.
4600 */
4601int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4602{
4603 unsigned int *n;
4604 const char *s, *end;
4605
4606 s = str;
4607 *sz = 0;
4608 end = str + strlen(str);
4609 *nums = n = NULL;
4610
4611 while (1) {
4612 unsigned int r;
4613
4614 if (s >= end)
4615 break;
4616
4617 r = read_uint(&s, end);
4618 /* Expected characters after having read an uint: '\0' or '.',
4619 * if '.', must not be terminal.
4620 */
4621 if (*s != '\0'&& (*s++ != '.' || s == end))
4622 return 0;
4623
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004624 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004625 if (!n)
4626 return 0;
4627
4628 n[(*sz)++] = r;
4629 }
4630 *nums = n;
4631
4632 return 1;
4633}
4634
Willy Tarreau4d589e72019-08-23 19:02:26 +02004635
4636/* returns the number of bytes needed to encode <v> as a varint. An inline
4637 * version exists for use with constants (__varint_bytes()).
4638 */
4639int varint_bytes(uint64_t v)
4640{
4641 int len = 1;
4642
4643 if (v >= 240) {
4644 v = (v - 240) >> 4;
4645 while (1) {
4646 len++;
4647 if (v < 128)
4648 break;
4649 v = (v - 128) >> 7;
4650 }
4651 }
4652 return len;
4653}
4654
Willy Tarreau52bf8392020-03-08 00:42:37 +01004655
4656/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004657static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004658
4659/* This is a thread-safe implementation of xoroshiro128** described below:
4660 * http://prng.di.unimi.it/
4661 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4662 * supports fast jumps and passes all common quality tests. It is thread-safe,
4663 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4664 * local lock on other ones.
4665 */
4666uint64_t ha_random64()
4667{
4668 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004669 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4670 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004671
4672#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4673 static HA_SPINLOCK_T rand_lock;
4674
4675 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4676#endif
4677
4678 old[0] = ha_random_state[0];
4679 old[1] = ha_random_state[1];
4680
4681#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4682 do {
4683#endif
4684 result = rotl64(old[0] * 5, 7) * 9;
4685 new[1] = old[0] ^ old[1];
4686 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4687 new[1] = rotl64(new[1], 37); // c
4688
4689#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4690 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4691#else
4692 ha_random_state[0] = new[0];
4693 ha_random_state[1] = new[1];
4694#if defined(USE_THREAD)
4695 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4696#endif
4697#endif
4698 return result;
4699}
4700
4701/* seeds the random state using up to <len> bytes from <seed>, starting with
4702 * the first non-zero byte.
4703 */
4704void ha_random_seed(const unsigned char *seed, size_t len)
4705{
4706 size_t pos;
4707
4708 /* the seed must not be all zeroes, so we pre-fill it with alternating
4709 * bits and overwrite part of them with the block starting at the first
4710 * non-zero byte from the seed.
4711 */
4712 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4713
4714 for (pos = 0; pos < len; pos++)
4715 if (seed[pos] != 0)
4716 break;
4717
4718 if (pos == len)
4719 return;
4720
4721 seed += pos;
4722 len -= pos;
4723
4724 if (len > sizeof(ha_random_state))
4725 len = sizeof(ha_random_state);
4726
4727 memcpy(ha_random_state, seed, len);
4728}
4729
4730/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4731 * and is equivalent to calling ha_random64() as many times. It is used to
4732 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4733 * different generators (i.e. different processes after a fork). The <dist>
4734 * argument is the distance to jump to and is used in a loop so it rather not
4735 * be too large if the processing time is a concern.
4736 *
4737 * BEWARE: this function is NOT thread-safe and must not be called during
4738 * concurrent accesses to ha_random64().
4739 */
4740void ha_random_jump96(uint32_t dist)
4741{
4742 while (dist--) {
4743 uint64_t s0 = 0;
4744 uint64_t s1 = 0;
4745 int b;
4746
4747 for (b = 0; b < 64; b++) {
4748 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4749 s0 ^= ha_random_state[0];
4750 s1 ^= ha_random_state[1];
4751 }
4752 ha_random64();
4753 }
4754
4755 for (b = 0; b < 64; b++) {
4756 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4757 s0 ^= ha_random_state[0];
4758 s1 ^= ha_random_state[1];
4759 }
4760 ha_random64();
4761 }
4762 ha_random_state[0] = s0;
4763 ha_random_state[1] = s1;
4764 }
4765}
4766
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004767/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4768 * bytes large.
4769 */
4770void ha_generate_uuid(struct buffer *output)
4771{
4772 uint32_t rnd[4];
4773 uint64_t last;
4774
4775 last = ha_random64();
4776 rnd[0] = last;
4777 rnd[1] = last >> 32;
4778
4779 last = ha_random64();
4780 rnd[2] = last;
4781 rnd[3] = last >> 32;
4782
4783 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4784 rnd[0],
4785 rnd[1] & 0xFFFF,
4786 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4787 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4788 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4789}
4790
4791
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004792/* only used by parse_line() below. It supports writing in place provided that
4793 * <in> is updated to the next location before calling it. In that case, the
4794 * char at <in> may be overwritten.
4795 */
4796#define EMIT_CHAR(x) \
4797 do { \
4798 char __c = (char)(x); \
4799 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4800 err |= PARSE_ERR_OVERLAP; \
4801 if (outpos >= outmax) \
4802 err |= PARSE_ERR_TOOLARGE; \
4803 if (!err) \
4804 out[outpos] = __c; \
4805 outpos++; \
4806 } while (0)
4807
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004808/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004809 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4810 * extraneous ones are not emitted but <outlen> is updated so that the caller
4811 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4812 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004813 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4814 * it is guaranteed that at least one arg will point to the zero. It is safe
4815 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004816 *
4817 * <out> may overlap with <in> provided that it never goes further, in which
4818 * case the parser will accept to perform in-place parsing and unquoting/
4819 * unescaping but only if environment variables do not lead to expansion that
4820 * causes overlapping, otherwise the input string being destroyed, the error
4821 * will not be recoverable. Note that even during out-of-place <in> will
4822 * experience temporary modifications in-place for variable resolution and must
4823 * be writable, and will also receive zeroes to delimit words when using
4824 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4825 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4826 * starting point of the first invalid character sequence or unmatched
4827 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4828 * error reporting might be difficult since zeroes will have been inserted into
4829 * the string. One solution for the caller may consist in replacing all args
4830 * delimiters with spaces in this case.
4831 */
4832uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4833{
4834 char *quote = NULL;
4835 char *brace = NULL;
4836 unsigned char hex1, hex2;
4837 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004838 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004839 size_t outpos = 0;
4840 int squote = 0;
4841 int dquote = 0;
4842 int arg = 0;
4843 uint32_t err = 0;
4844
4845 *nbargs = 0;
4846 *outlen = 0;
4847
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004848 /* argsmax may be -1 here, protecting args[] from any write */
4849 if (arg < argsmax)
4850 args[arg] = out;
4851
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004852 while (1) {
4853 if (*in >= '-' && *in != '\\') {
4854 /* speedup: directly send all regular chars starting
4855 * with '-', '.', '/', alnum etc...
4856 */
4857 EMIT_CHAR(*in++);
4858 continue;
4859 }
4860 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4861 /* end of line */
4862 break;
4863 }
4864 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4865 /* comment */
4866 break;
4867 }
4868 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4869 if (dquote) {
4870 dquote = 0;
4871 quote = NULL;
4872 }
4873 else {
4874 dquote = 1;
4875 quote = in;
4876 }
4877 in++;
4878 continue;
4879 }
4880 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4881 if (squote) {
4882 squote = 0;
4883 quote = NULL;
4884 }
4885 else {
4886 squote = 1;
4887 quote = in;
4888 }
4889 in++;
4890 continue;
4891 }
4892 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4893 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4894 * C equivalent value but only when they have a special meaning and within
4895 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4896 */
4897 char tosend = *in;
4898
4899 switch (in[1]) {
4900 case ' ':
4901 case '\\':
4902 tosend = in[1];
4903 in++;
4904 break;
4905
4906 case 't':
4907 tosend = '\t';
4908 in++;
4909 break;
4910
4911 case 'n':
4912 tosend = '\n';
4913 in++;
4914 break;
4915
4916 case 'r':
4917 tosend = '\r';
4918 in++;
4919 break;
4920
4921 case '#':
4922 /* escaping of "#" only if comments are supported */
4923 if (opts & PARSE_OPT_SHARP)
4924 in++;
4925 tosend = *in;
4926 break;
4927
4928 case '\'':
4929 /* escaping of "'" only outside single quotes and only if single quotes are supported */
4930 if (opts & PARSE_OPT_SQUOTE && !squote)
4931 in++;
4932 tosend = *in;
4933 break;
4934
4935 case '"':
4936 /* escaping of '"' only outside single quotes and only if double quotes are supported */
4937 if (opts & PARSE_OPT_DQUOTE && !squote)
4938 in++;
4939 tosend = *in;
4940 break;
4941
4942 case '$':
4943 /* escaping of '$' only inside double quotes and only if env supported */
4944 if (opts & PARSE_OPT_ENV && dquote)
4945 in++;
4946 tosend = *in;
4947 break;
4948
4949 case 'x':
4950 if (!ishex(in[2]) || !ishex(in[3])) {
4951 /* invalid or incomplete hex sequence */
4952 err |= PARSE_ERR_HEX;
4953 if (errptr)
4954 *errptr = in;
4955 goto leave;
4956 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02004957 hex1 = toupper((unsigned char)in[2]) - '0';
4958 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004959 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
4960 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
4961 tosend = (hex1 << 4) + hex2;
4962 in += 3;
4963 break;
4964
4965 default:
4966 /* other combinations are not escape sequences */
4967 break;
4968 }
4969
4970 in++;
4971 EMIT_CHAR(tosend);
4972 }
4973 else if (isspace((unsigned char)*in) && !squote && !dquote) {
4974 /* a non-escaped space is an argument separator */
4975 while (isspace((unsigned char)*in))
4976 in++;
4977 EMIT_CHAR(0);
4978 arg++;
4979 if (arg < argsmax)
4980 args[arg] = out + outpos;
4981 else
4982 err |= PARSE_ERR_TOOMANY;
4983 }
4984 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
4985 /* environment variables are evaluated anywhere, or only
4986 * inside double quotes if they are supported.
4987 */
4988 char *var_name;
4989 char save_char;
4990 char *value;
4991
4992 in++;
4993
4994 if (*in == '{')
4995 brace = in++;
4996
4997 if (!isalpha((unsigned char)*in) && *in != '_') {
4998 /* unacceptable character in variable name */
4999 err |= PARSE_ERR_VARNAME;
5000 if (errptr)
5001 *errptr = in;
5002 goto leave;
5003 }
5004
5005 var_name = in;
5006 while (isalnum((unsigned char)*in) || *in == '_')
5007 in++;
5008
5009 save_char = *in;
5010 *in = '\0';
5011 value = getenv(var_name);
5012 *in = save_char;
5013
5014 if (brace) {
5015 if (*in != '}') {
5016 /* unmatched brace */
5017 err |= PARSE_ERR_BRACE;
5018 if (errptr)
5019 *errptr = brace;
5020 goto leave;
5021 }
5022 in++;
5023 brace = NULL;
5024 }
5025
5026 if (value) {
5027 while (*value)
5028 EMIT_CHAR(*value++);
5029 }
5030 }
5031 else {
5032 /* any other regular char */
5033 EMIT_CHAR(*in++);
5034 }
5035 }
5036
5037 /* end of output string */
5038 EMIT_CHAR(0);
5039 arg++;
5040
5041 if (quote) {
5042 /* unmatched quote */
5043 err |= PARSE_ERR_QUOTE;
5044 if (errptr)
5045 *errptr = quote;
5046 goto leave;
5047 }
5048 leave:
5049 *nbargs = arg;
5050 *outlen = outpos;
5051
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005052 /* empty all trailing args by making them point to the trailing zero,
5053 * at least the last one in any case.
5054 */
5055 if (arg > argsmax)
5056 arg = argsmax;
5057
5058 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005059 args[arg++] = out + outpos - 1;
5060
5061 return err;
5062}
5063#undef EMIT_CHAR
5064
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005065/* This is used to sanitize an input line that's about to be used for error reporting.
5066 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5067 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5068 * If non-printable chars are present in the output. It returns the new offset <pos>
5069 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5070 * be at least 6 to support two "..." otherwise the result is undefined. The line
5071 * itself must have at least 7 chars allocated for the same reason.
5072 */
5073size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5074{
5075 size_t shift = 0;
5076 char *out = line;
5077 char *in = line;
5078 char *end = line + width;
5079
5080 if (pos >= width) {
5081 /* if we have to shift, we'll be out of context, so let's
5082 * try to put <pos> at the center of width.
5083 */
5084 shift = pos - width / 2;
5085 in += shift + 3;
5086 end = out + width - 3;
5087 out[0] = out[1] = out[2] = '.';
5088 out += 3;
5089 }
5090
5091 while (out < end && *in) {
5092 if (isspace((unsigned char)*in))
5093 *out++ = ' ';
5094 else if (isprint((unsigned char)*in))
5095 *out++ = *in;
5096 else
5097 *out++ = '?';
5098 in++;
5099 }
5100
5101 if (end < line + width) {
5102 out[0] = out[1] = out[2] = '.';
5103 out += 3;
5104 }
5105
5106 *out++ = 0;
5107 return pos - shift;
5108}
5109
Willy Tarreaubaaee002006-06-26 02:48:02 +02005110/*
5111 * Local variables:
5112 * c-indent-level: 8
5113 * c-basic-offset: 8
5114 * End:
5115 */