blob: db17fda0c213adefb766249e2869fae90040c848 [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
Willy Tarreau6edc7222020-09-15 17:41:56 +0200966 if (opts & PA_O_SOCKET_FD) {
967 socklen_t addr_len;
968 int type;
969
970 addr_len = sizeof(ss);
971 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
972 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
973 goto out;
974 }
975
976 addr_len = sizeof(type);
977 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
978 (type == SOCK_STREAM) != !!(opts & PA_O_STREAM)) {
979 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
980 goto out;
981 }
982
983 porta = portl = porth = get_host_port(&ss);
984 } else if (opts & PA_O_RAW_FD) {
985 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
986 ((struct sockaddr_in *)&ss)->sin_port = 0;
987 } else {
988 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
989 goto out;
990 }
Willy Tarreau40aa0702013-03-10 23:51:38 +0100991 }
992 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200993 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100994 int prefix_path_len;
995 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200996 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100997
998 /* complete unix socket path name during startup or soft-restart is
999 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1000 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001001 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001002 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001003 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001004
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001005 adr_len = strlen(str2);
1006 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001007 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1008 goto out;
1009 }
1010
Willy Tarreauccfccef2014-05-10 01:49:15 +02001011 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001012 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001013 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001014 memcpy(un->sun_path, pfx, prefix_path_len);
1015 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001016 }
Willy Tarreau24709282013-03-10 21:32:12 +01001017 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001018 char *end = str2 + strlen(str2);
1019 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001020
mildisff5d5102015-10-26 18:50:08 +01001021 /* search for : or ] whatever comes first */
1022 for (chr = end-1; chr > str2; chr--) {
1023 if (*chr == ']' || *chr == ':')
1024 break;
1025 }
1026
1027 if (*chr == ':') {
1028 /* Found a colon before a closing-bracket, must be a port separator.
1029 * This guarantee backward compatibility.
1030 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001031 if (!(opts & PA_O_PORT_OK)) {
1032 memprintf(err, "port specification not permitted here in '%s'", str);
1033 goto out;
1034 }
mildisff5d5102015-10-26 18:50:08 +01001035 *chr++ = '\0';
1036 port1 = chr;
1037 }
1038 else {
1039 /* Either no colon and no closing-bracket
1040 * or directly ending with a closing-bracket.
1041 * However, no port.
1042 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001043 if (opts & PA_O_PORT_MAND) {
1044 memprintf(err, "missing port specification in '%s'", str);
1045 goto out;
1046 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001047 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001048 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001049
Willy Tarreau90807112020-02-25 08:16:33 +01001050 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001051 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001052 if (port2) {
1053 if (!(opts & PA_O_PORT_RANGE)) {
1054 memprintf(err, "port range not permitted here in '%s'", str);
1055 goto out;
1056 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001057 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001058 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001059 else
1060 port2 = port1;
1061 portl = atoi(port1);
1062 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001063
1064 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1065 memprintf(err, "invalid port '%s'", port1);
1066 goto out;
1067 }
1068
1069 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1070 memprintf(err, "invalid port '%s'", port2);
1071 goto out;
1072 }
1073
1074 if (portl > porth) {
1075 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1076 goto out;
1077 }
1078
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001079 porta = portl;
1080 }
1081 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001082 if (!(opts & PA_O_PORT_OFS)) {
1083 memprintf(err, "port offset not permitted here in '%s'", str);
1084 goto out;
1085 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001086 portl = atoi(port1 + 1);
1087 porta = -portl;
1088 }
1089 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001090 if (!(opts & PA_O_PORT_OFS)) {
1091 memprintf(err, "port offset not permitted here in '%s'", str);
1092 goto out;
1093 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001094 porth = atoi(port1 + 1);
1095 porta = porth;
1096 }
1097 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001098 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001099 goto out;
1100 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001101 else if (opts & PA_O_PORT_MAND) {
1102 memprintf(err, "missing port specification in '%s'", str);
1103 goto out;
1104 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001105
1106 /* first try to parse the IP without resolving. If it fails, it
1107 * tells us we need to keep a copy of the FQDN to resolve later
1108 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001109 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001110 */
1111 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001112 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1113 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001114 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1115 goto out;
1116 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001117
Willy Tarreauceccdd72016-11-02 22:27:10 +01001118 if (fqdn) {
1119 if (str2 != back)
1120 memmove(back, str2, strlen(str2) + 1);
1121 *fqdn = back;
1122 back = NULL;
1123 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001124 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001125 set_host_port(&ss, porta);
Emeric Brun3835c0d2020-07-07 09:46:09 +02001126 if (is_udp) {
1127 if (ss.ss_family == AF_INET6)
1128 ss.ss_family = AF_CUST_UDP6;
1129 else
1130 ss.ss_family = AF_CUST_UDP4;
1131 }
1132
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001133 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001134
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001135 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001136 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001137 if (port)
1138 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001139 if (low)
1140 *low = portl;
1141 if (high)
1142 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001143 if (fd)
1144 *fd = new_fd;
Willy Tarreau24709282013-03-10 21:32:12 +01001145 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001146 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001147}
1148
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001149/* converts <str> to a struct in_addr containing a network mask. It can be
1150 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001151 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001152 */
1153int str2mask(const char *str, struct in_addr *mask)
1154{
1155 if (strchr(str, '.') != NULL) { /* dotted notation */
1156 if (!inet_pton(AF_INET, str, mask))
1157 return 0;
1158 }
1159 else { /* mask length */
1160 char *err;
1161 unsigned long len = strtol(str, &err, 10);
1162
1163 if (!*str || (err && *err) || (unsigned)len > 32)
1164 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001165
1166 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001167 }
1168 return 1;
1169}
1170
Tim Duesterhus47185172018-01-25 16:24:49 +01001171/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001172 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001173 * if the conversion succeeds otherwise zero.
1174 */
1175int str2mask6(const char *str, struct in6_addr *mask)
1176{
1177 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1178 if (!inet_pton(AF_INET6, str, mask))
1179 return 0;
1180 }
1181 else { /* mask length */
1182 char *err;
1183 unsigned long len = strtol(str, &err, 10);
1184
1185 if (!*str || (err && *err) || (unsigned)len > 128)
1186 return 0;
1187
1188 len2mask6(len, mask);
1189 }
1190 return 1;
1191}
1192
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001193/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1194 * succeeds otherwise zero.
1195 */
1196int cidr2dotted(int cidr, struct in_addr *mask) {
1197
1198 if (cidr < 0 || cidr > 32)
1199 return 0;
1200
1201 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1202 return 1;
1203}
1204
Thierry Fournier70473a52016-02-17 17:12:14 +01001205/* Convert mask from bit length form to in_addr form.
1206 * This function never fails.
1207 */
1208void len2mask4(int len, struct in_addr *addr)
1209{
1210 if (len >= 32) {
1211 addr->s_addr = 0xffffffff;
1212 return;
1213 }
1214 if (len <= 0) {
1215 addr->s_addr = 0x00000000;
1216 return;
1217 }
1218 addr->s_addr = 0xffffffff << (32 - len);
1219 addr->s_addr = htonl(addr->s_addr);
1220}
1221
1222/* Convert mask from bit length form to in6_addr form.
1223 * This function never fails.
1224 */
1225void len2mask6(int len, struct in6_addr *addr)
1226{
1227 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1228 len -= 32;
1229 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1230 len -= 32;
1231 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1232 len -= 32;
1233 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1234}
1235
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001236/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001237 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001238 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001239 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001240 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1241 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001242int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001243{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001244 __label__ out_free, out_err;
1245 char *c, *s;
1246 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001247
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001248 s = strdup(str);
1249 if (!s)
1250 return 0;
1251
Willy Tarreaubaaee002006-06-26 02:48:02 +02001252 memset(mask, 0, sizeof(*mask));
1253 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001254
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001255 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001256 *c++ = '\0';
1257 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001258 if (!str2mask(c, mask))
1259 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001260 }
1261 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001262 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001263 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001264 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001265 struct hostent *he;
1266
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001267 if (!resolve)
1268 goto out_err;
1269
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001270 if ((he = gethostbyname(s)) == NULL) {
1271 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001272 }
1273 else
1274 *addr = *(struct in_addr *) *(he->h_addr_list);
1275 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001276
1277 ret_val = 1;
1278 out_free:
1279 free(s);
1280 return ret_val;
1281 out_err:
1282 ret_val = 0;
1283 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001284}
1285
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001286
1287/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001288 * converts <str> to two struct in6_addr* which must be pre-allocated.
1289 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001290 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001291 * Returns 1 if OK, 0 if error.
1292 */
1293int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1294{
1295 char *c, *s;
1296 int ret_val = 0;
1297 char *err;
1298 unsigned long len = 128;
1299
1300 s = strdup(str);
1301 if (!s)
1302 return 0;
1303
1304 memset(mask, 0, sizeof(*mask));
1305 memset(addr, 0, sizeof(*addr));
1306
1307 if ((c = strrchr(s, '/')) != NULL) {
1308 *c++ = '\0'; /* c points to the mask */
1309 if (!*c)
1310 goto out_free;
1311
1312 len = strtoul(c, &err, 10);
1313 if ((err && *err) || (unsigned)len > 128)
1314 goto out_free;
1315 }
1316 *mask = len; /* OK we have a valid mask in <len> */
1317
1318 if (!inet_pton(AF_INET6, s, addr))
1319 goto out_free;
1320
1321 ret_val = 1;
1322 out_free:
1323 free(s);
1324 return ret_val;
1325}
1326
1327
1328/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001329 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001330 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001331int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001332{
1333 int saw_digit, octets, ch;
1334 u_char tmp[4], *tp;
1335 const char *cp = addr;
1336
1337 saw_digit = 0;
1338 octets = 0;
1339 *(tp = tmp) = 0;
1340
1341 while (*addr) {
1342 unsigned char digit = (ch = *addr++) - '0';
1343 if (digit > 9 && ch != '.')
1344 break;
1345 if (digit <= 9) {
1346 u_int new = *tp * 10 + digit;
1347 if (new > 255)
1348 return 0;
1349 *tp = new;
1350 if (!saw_digit) {
1351 if (++octets > 4)
1352 return 0;
1353 saw_digit = 1;
1354 }
1355 } else if (ch == '.' && saw_digit) {
1356 if (octets == 4)
1357 return 0;
1358 *++tp = 0;
1359 saw_digit = 0;
1360 } else
1361 return 0;
1362 }
1363
1364 if (octets < 4)
1365 return 0;
1366
1367 memcpy(&dst->s_addr, tmp, 4);
1368 return addr-cp-1;
1369}
1370
1371/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001372 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001373 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001374 * the hostname. Actually only http and https are supported. <out> can be NULL.
1375 * This function returns the consumed length. It is useful if you parse complete
1376 * url like http://host:port/path, because the consumed length corresponds to
1377 * the first character of the path. If the conversion fails, it returns -1.
1378 *
1379 * This function tries to resolve the DNS name if haproxy is in starting mode.
1380 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001381 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001382int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001383{
1384 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001385 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001386 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001387 unsigned long long int http_code = 0;
1388 int default_port;
1389 struct hostent *he;
1390 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001391
1392 /* Firstly, try to find :// pattern */
1393 while (curr < url+ulen && url_code != 0x3a2f2f) {
1394 url_code = ((url_code & 0xffff) << 8);
1395 url_code += (unsigned char)*curr++;
1396 }
1397
1398 /* Secondly, if :// pattern is found, verify parsed stuff
1399 * before pattern is matching our http pattern.
1400 * If so parse ip address and port in uri.
1401 *
1402 * WARNING: Current code doesn't support dynamic async dns resolver.
1403 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001404 if (url_code != 0x3a2f2f)
1405 return -1;
1406
1407 /* Copy scheme, and utrn to lower case. */
1408 while (cp < curr - 3)
1409 http_code = (http_code << 8) + *cp++;
1410 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001411
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001412 /* HTTP or HTTPS url matching */
1413 if (http_code == 0x2020202068747470ULL) {
1414 default_port = 80;
1415 if (out)
1416 out->scheme = SCH_HTTP;
1417 }
1418 else if (http_code == 0x2020206874747073ULL) {
1419 default_port = 443;
1420 if (out)
1421 out->scheme = SCH_HTTPS;
1422 }
1423 else
1424 return -1;
1425
1426 /* If the next char is '[', the host address is IPv6. */
1427 if (*curr == '[') {
1428 curr++;
1429
1430 /* Check trash size */
1431 if (trash.size < ulen)
1432 return -1;
1433
1434 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001435 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001436 for (end = curr;
1437 end < url + ulen && *end != ']';
1438 end++, p++)
1439 *p = *end;
1440 if (*end != ']')
1441 return -1;
1442 *p = '\0';
1443
1444 /* Update out. */
1445 if (out) {
1446 out->host = curr;
1447 out->host_len = end - curr;
1448 }
1449
1450 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001451 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001452 return -1;
1453 end++;
1454
1455 /* Decode port. */
1456 if (*end == ':') {
1457 end++;
1458 default_port = read_uint(&end, url + ulen);
1459 }
1460 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1461 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1462 return end - url;
1463 }
1464 else {
1465 /* We are looking for IP address. If you want to parse and
1466 * resolve hostname found in url, you can use str2sa_range(), but
1467 * be warned this can slow down global daemon performances
1468 * while handling lagging dns responses.
1469 */
1470 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1471 if (ret) {
1472 /* Update out. */
1473 if (out) {
1474 out->host = curr;
1475 out->host_len = ret;
1476 }
1477
1478 curr += ret;
1479
1480 /* Decode port. */
1481 if (*curr == ':') {
1482 curr++;
1483 default_port = read_uint(&curr, url + ulen);
1484 }
1485 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1486
1487 /* Set family. */
1488 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1489 return curr - url;
1490 }
1491 else if (global.mode & MODE_STARTING) {
1492 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1493 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001494 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001495
1496 /* look for : or / or end */
1497 for (end = curr;
1498 end < url + ulen && *end != '/' && *end != ':';
1499 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001500 memcpy(trash.area, curr, end - curr);
1501 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001502
1503 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001504 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001505 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001506 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001507
1508 /* Update out. */
1509 if (out) {
1510 out->host = curr;
1511 out->host_len = end - curr;
1512 }
1513
1514 /* Decode port. */
1515 if (*end == ':') {
1516 end++;
1517 default_port = read_uint(&end, url + ulen);
1518 }
1519
1520 /* Copy IP address, set port and family. */
1521 switch (he->h_addrtype) {
1522 case AF_INET:
1523 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1524 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1525 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1526 return end - url;
1527
1528 case AF_INET6:
1529 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1530 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1531 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1532 return end - url;
1533 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001534 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001535 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001536 return -1;
1537}
1538
Willy Tarreau631f01c2011-09-05 00:36:48 +02001539/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1540 * address family is returned so that it's easy for the caller to adapt to the
1541 * output format. Zero is returned if the address family is not supported. -1
1542 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1543 * supported.
1544 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001545int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001546{
1547
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001548 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001549
1550 if (size < 5)
1551 return 0;
1552 *str = '\0';
1553
1554 switch (addr->ss_family) {
1555 case AF_INET:
1556 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1557 break;
1558 case AF_INET6:
1559 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1560 break;
1561 case AF_UNIX:
1562 memcpy(str, "unix", 5);
1563 return addr->ss_family;
1564 default:
1565 return 0;
1566 }
1567
1568 if (inet_ntop(addr->ss_family, ptr, str, size))
1569 return addr->ss_family;
1570
1571 /* failed */
1572 return -1;
1573}
1574
Simon Horman75ab8bd2014-06-16 09:39:41 +09001575/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1576 * address family is returned so that it's easy for the caller to adapt to the
1577 * output format. Zero is returned if the address family is not supported. -1
1578 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1579 * supported.
1580 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001581int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001582{
1583
1584 uint16_t port;
1585
1586
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001587 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001588 return 0;
1589 *str = '\0';
1590
1591 switch (addr->ss_family) {
1592 case AF_INET:
1593 port = ((struct sockaddr_in *)addr)->sin_port;
1594 break;
1595 case AF_INET6:
1596 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1597 break;
1598 case AF_UNIX:
1599 memcpy(str, "unix", 5);
1600 return addr->ss_family;
1601 default:
1602 return 0;
1603 }
1604
1605 snprintf(str, size, "%u", ntohs(port));
1606 return addr->ss_family;
1607}
1608
Willy Tarreau16e01562016-08-09 16:46:18 +02001609/* check if the given address is local to the system or not. It will return
1610 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1611 * it is. We don't want to iterate over all interfaces for this (and it is not
1612 * portable). So instead we try to bind in UDP to this address on a free non
1613 * privileged port and to connect to the same address, port 0 (connect doesn't
1614 * care). If it succeeds, we own the address. Note that non-inet addresses are
1615 * considered local since they're most likely AF_UNIX.
1616 */
1617int addr_is_local(const struct netns_entry *ns,
1618 const struct sockaddr_storage *orig)
1619{
1620 struct sockaddr_storage addr;
1621 int result;
1622 int fd;
1623
1624 if (!is_inet_addr(orig))
1625 return 1;
1626
1627 memcpy(&addr, orig, sizeof(addr));
1628 set_host_port(&addr, 0);
1629
1630 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1631 if (fd < 0)
1632 return -1;
1633
1634 result = -1;
1635 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1636 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1637 result = 0; // fail, non-local address
1638 else
1639 result = 1; // success, local address
1640 }
1641 else {
1642 if (errno == EADDRNOTAVAIL)
1643 result = 0; // definitely not local :-)
1644 }
1645 close(fd);
1646
1647 return result;
1648}
1649
Willy Tarreaubaaee002006-06-26 02:48:02 +02001650/* will try to encode the string <string> replacing all characters tagged in
1651 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1652 * prefixed by <escape>, and will store the result between <start> (included)
1653 * and <stop> (excluded), and will always terminate the string with a '\0'
1654 * before <stop>. The position of the '\0' is returned if the conversion
1655 * completes. If bytes are missing between <start> and <stop>, then the
1656 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1657 * cannot even be stored so we return <start> without writing the 0.
1658 * The input string must also be zero-terminated.
1659 */
1660const char hextab[16] = "0123456789ABCDEF";
1661char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001662 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001663 const char *string)
1664{
1665 if (start < stop) {
1666 stop--; /* reserve one byte for the final '\0' */
1667 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001668 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001669 *start++ = *string;
1670 else {
1671 if (start + 3 >= stop)
1672 break;
1673 *start++ = escape;
1674 *start++ = hextab[(*string >> 4) & 15];
1675 *start++ = hextab[*string & 15];
1676 }
1677 string++;
1678 }
1679 *start = '\0';
1680 }
1681 return start;
1682}
1683
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001684/*
1685 * Same behavior as encode_string() above, except that it encodes chunk
1686 * <chunk> instead of a string.
1687 */
1688char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001689 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001690 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001691{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001692 char *str = chunk->area;
1693 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001694
1695 if (start < stop) {
1696 stop--; /* reserve one byte for the final '\0' */
1697 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001698 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001699 *start++ = *str;
1700 else {
1701 if (start + 3 >= stop)
1702 break;
1703 *start++ = escape;
1704 *start++ = hextab[(*str >> 4) & 15];
1705 *start++ = hextab[*str & 15];
1706 }
1707 str++;
1708 }
1709 *start = '\0';
1710 }
1711 return start;
1712}
1713
Dragan Dosen0edd1092016-02-12 13:23:02 +01001714/*
1715 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001716 * character. The input <string> must be zero-terminated. The result will
1717 * be stored between <start> (included) and <stop> (excluded). This
1718 * function will always try to terminate the resulting string with a '\0'
1719 * before <stop>, and will return its position if the conversion
1720 * completes.
1721 */
1722char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001723 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001724 const char *string)
1725{
1726 if (start < stop) {
1727 stop--; /* reserve one byte for the final '\0' */
1728 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001729 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001730 *start++ = *string;
1731 else {
1732 if (start + 2 >= stop)
1733 break;
1734 *start++ = escape;
1735 *start++ = *string;
1736 }
1737 string++;
1738 }
1739 *start = '\0';
1740 }
1741 return start;
1742}
1743
1744/*
1745 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001746 * character. <chunk> contains the input to be escaped. The result will be
1747 * stored between <start> (included) and <stop> (excluded). The function
1748 * will always try to terminate the resulting string with a '\0' before
1749 * <stop>, and will return its position if the conversion completes.
1750 */
1751char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001752 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001753 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001754{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001755 char *str = chunk->area;
1756 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001757
1758 if (start < stop) {
1759 stop--; /* reserve one byte for the final '\0' */
1760 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001761 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001762 *start++ = *str;
1763 else {
1764 if (start + 2 >= stop)
1765 break;
1766 *start++ = escape;
1767 *start++ = *str;
1768 }
1769 str++;
1770 }
1771 *start = '\0';
1772 }
1773 return start;
1774}
1775
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001776/* Check a string for using it in a CSV output format. If the string contains
1777 * one of the following four char <">, <,>, CR or LF, the string is
1778 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1779 * <str> is the input string to be escaped. The function assumes that
1780 * the input string is null-terminated.
1781 *
1782 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001783 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001784 * format.
1785 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001786 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001787 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001788 * If <quote> is 1, the converter puts the quotes only if any reserved character
1789 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001790 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001791 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001792 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001793 * The function returns the converted string on its output. If an error
1794 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001795 * for using the function directly as printf() argument.
1796 *
1797 * If the output buffer is too short to contain the input string, the result
1798 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001799 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001800 * This function appends the encoding to the existing output chunk, and it
1801 * guarantees that it starts immediately at the first available character of
1802 * the chunk. Please use csv_enc() instead if you want to replace the output
1803 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001804 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001805const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001806{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001807 char *end = output->area + output->size;
1808 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001809 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001810
Willy Tarreaub631c292016-01-08 10:04:08 +01001811 if (quote == 1) {
1812 /* automatic quoting: first verify if we'll have to quote the string */
1813 if (!strpbrk(str, "\n\r,\""))
1814 quote = 0;
1815 }
1816
1817 if (quote)
1818 *ptr++ = '"';
1819
Willy Tarreau898529b2016-01-06 18:07:04 +01001820 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1821 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001822 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001823 ptr++;
1824 if (ptr >= end - 2) {
1825 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001826 break;
1827 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001828 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001829 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001830 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001831 str++;
1832 }
1833
Willy Tarreaub631c292016-01-08 10:04:08 +01001834 if (quote)
1835 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001836
Willy Tarreau898529b2016-01-06 18:07:04 +01001837 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001838 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001839 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001840}
1841
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001842/* Decode an URL-encoded string in-place. The resulting string might
1843 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001844 * aborted, the string is truncated before the issue and a negative value is
1845 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001846 * If the 'in_form' argument is non-nul the string is assumed to be part of
1847 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1848 * turned to a space. If it's zero, this will only be done after a question
1849 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001850 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001851int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001852{
1853 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001854 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001855
1856 in = string;
1857 out = string;
1858 while (*in) {
1859 switch (*in) {
1860 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001861 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001862 break;
1863 case '%' :
1864 if (!ishex(in[1]) || !ishex(in[2]))
1865 goto end;
1866 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1867 in += 2;
1868 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001869 case '?':
1870 in_form = 1;
1871 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001872 default:
1873 *out++ = *in;
1874 break;
1875 }
1876 in++;
1877 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001878 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001879 end:
1880 *out = 0;
1881 return ret;
1882}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001883
Willy Tarreau6911fa42007-03-04 18:06:08 +01001884unsigned int str2ui(const char *s)
1885{
1886 return __str2ui(s);
1887}
1888
1889unsigned int str2uic(const char *s)
1890{
1891 return __str2uic(s);
1892}
1893
1894unsigned int strl2ui(const char *s, int len)
1895{
1896 return __strl2ui(s, len);
1897}
1898
1899unsigned int strl2uic(const char *s, int len)
1900{
1901 return __strl2uic(s, len);
1902}
1903
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001904unsigned int read_uint(const char **s, const char *end)
1905{
1906 return __read_uint(s, end);
1907}
1908
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001909/* This function reads an unsigned integer from the string pointed to by <s> and
1910 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1911 * function automatically stops at <end>. If the number overflows, the 2^64-1
1912 * value is returned.
1913 */
1914unsigned long long int read_uint64(const char **s, const char *end)
1915{
1916 const char *ptr = *s;
1917 unsigned long long int i = 0, tmp;
1918 unsigned int j;
1919
1920 while (ptr < end) {
1921
1922 /* read next char */
1923 j = *ptr - '0';
1924 if (j > 9)
1925 goto read_uint64_end;
1926
1927 /* add char to the number and check overflow. */
1928 tmp = i * 10;
1929 if (tmp / 10 != i) {
1930 i = ULLONG_MAX;
1931 goto read_uint64_eat;
1932 }
1933 if (ULLONG_MAX - tmp < j) {
1934 i = ULLONG_MAX;
1935 goto read_uint64_eat;
1936 }
1937 i = tmp + j;
1938 ptr++;
1939 }
1940read_uint64_eat:
1941 /* eat each numeric char */
1942 while (ptr < end) {
1943 if ((unsigned int)(*ptr - '0') > 9)
1944 break;
1945 ptr++;
1946 }
1947read_uint64_end:
1948 *s = ptr;
1949 return i;
1950}
1951
1952/* This function reads an integer from the string pointed to by <s> and returns
1953 * it. The <s> pointer is adjusted to point to the first unread char. The function
1954 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1955 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1956 * returned.
1957 */
1958long long int read_int64(const char **s, const char *end)
1959{
1960 unsigned long long int i = 0;
1961 int neg = 0;
1962
1963 /* Look for minus char. */
1964 if (**s == '-') {
1965 neg = 1;
1966 (*s)++;
1967 }
1968 else if (**s == '+')
1969 (*s)++;
1970
1971 /* convert as positive number. */
1972 i = read_uint64(s, end);
1973
1974 if (neg) {
1975 if (i > 0x8000000000000000ULL)
1976 return LLONG_MIN;
1977 return -i;
1978 }
1979 if (i > 0x7fffffffffffffffULL)
1980 return LLONG_MAX;
1981 return i;
1982}
1983
Willy Tarreau6911fa42007-03-04 18:06:08 +01001984/* This one is 7 times faster than strtol() on athlon with checks.
1985 * It returns the value of the number composed of all valid digits read,
1986 * and can process negative numbers too.
1987 */
1988int strl2ic(const char *s, int len)
1989{
1990 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001991 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001992
1993 if (len > 0) {
1994 if (*s != '-') {
1995 /* positive number */
1996 while (len-- > 0) {
1997 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001998 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001999 if (j > 9)
2000 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002001 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002002 }
2003 } else {
2004 /* negative number */
2005 s++;
2006 while (--len > 0) {
2007 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002008 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002009 if (j > 9)
2010 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002011 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002012 }
2013 }
2014 }
2015 return i;
2016}
2017
2018
2019/* This function reads exactly <len> chars from <s> and converts them to a
2020 * signed integer which it stores into <ret>. It accurately detects any error
2021 * (truncated string, invalid chars, overflows). It is meant to be used in
2022 * applications designed for hostile environments. It returns zero when the
2023 * number has successfully been converted, non-zero otherwise. When an error
2024 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2025 * faster than strtol().
2026 */
2027int strl2irc(const char *s, int len, int *ret)
2028{
2029 int i = 0;
2030 int j;
2031
2032 if (!len)
2033 return 1;
2034
2035 if (*s != '-') {
2036 /* positive number */
2037 while (len-- > 0) {
2038 j = (*s++) - '0';
2039 if (j > 9) return 1; /* invalid char */
2040 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2041 i = i * 10;
2042 if (i + j < i) return 1; /* check for addition overflow */
2043 i = i + j;
2044 }
2045 } else {
2046 /* negative number */
2047 s++;
2048 while (--len > 0) {
2049 j = (*s++) - '0';
2050 if (j > 9) return 1; /* invalid char */
2051 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2052 i = i * 10;
2053 if (i - j > i) return 1; /* check for subtract overflow */
2054 i = i - j;
2055 }
2056 }
2057 *ret = i;
2058 return 0;
2059}
2060
2061
2062/* This function reads exactly <len> chars from <s> and converts them to a
2063 * signed integer which it stores into <ret>. It accurately detects any error
2064 * (truncated string, invalid chars, overflows). It is meant to be used in
2065 * applications designed for hostile environments. It returns zero when the
2066 * number has successfully been converted, non-zero otherwise. When an error
2067 * is returned, the <ret> value is left untouched. It is about 3 times slower
2068 * than str2irc().
2069 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002070
2071int strl2llrc(const char *s, int len, long long *ret)
2072{
2073 long long i = 0;
2074 int j;
2075
2076 if (!len)
2077 return 1;
2078
2079 if (*s != '-') {
2080 /* positive number */
2081 while (len-- > 0) {
2082 j = (*s++) - '0';
2083 if (j > 9) return 1; /* invalid char */
2084 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2085 i = i * 10LL;
2086 if (i + j < i) return 1; /* check for addition overflow */
2087 i = i + j;
2088 }
2089 } else {
2090 /* negative number */
2091 s++;
2092 while (--len > 0) {
2093 j = (*s++) - '0';
2094 if (j > 9) return 1; /* invalid char */
2095 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2096 i = i * 10LL;
2097 if (i - j > i) return 1; /* check for subtract overflow */
2098 i = i - j;
2099 }
2100 }
2101 *ret = i;
2102 return 0;
2103}
2104
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002105/* This function is used with pat_parse_dotted_ver(). It converts a string
2106 * composed by two number separated by a dot. Each part must contain in 16 bits
2107 * because internally they will be represented as a 32-bit quantity stored in
2108 * a 64-bit integer. It returns zero when the number has successfully been
2109 * converted, non-zero otherwise. When an error is returned, the <ret> value
2110 * is left untouched.
2111 *
2112 * "1.3" -> 0x0000000000010003
2113 * "65535.65535" -> 0x00000000ffffffff
2114 */
2115int strl2llrc_dotted(const char *text, int len, long long *ret)
2116{
2117 const char *end = &text[len];
2118 const char *p;
2119 long long major, minor;
2120
2121 /* Look for dot. */
2122 for (p = text; p < end; p++)
2123 if (*p == '.')
2124 break;
2125
2126 /* Convert major. */
2127 if (strl2llrc(text, p - text, &major) != 0)
2128 return 1;
2129
2130 /* Check major. */
2131 if (major >= 65536)
2132 return 1;
2133
2134 /* Convert minor. */
2135 minor = 0;
2136 if (p < end)
2137 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2138 return 1;
2139
2140 /* Check minor. */
2141 if (minor >= 65536)
2142 return 1;
2143
2144 /* Compose value. */
2145 *ret = (major << 16) | (minor & 0xffff);
2146 return 0;
2147}
2148
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002149/* This function parses a time value optionally followed by a unit suffix among
2150 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2151 * expected by the caller. The computation does its best to avoid overflows.
2152 * The value is returned in <ret> if everything is fine, and a NULL is returned
2153 * by the function. In case of error, a pointer to the error is returned and
2154 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002155 * Values resulting in values larger than or equal to 2^31 after conversion are
2156 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2157 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002158 */
2159const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2160{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002161 unsigned long long imult, idiv;
2162 unsigned long long omult, odiv;
2163 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002164
2165 omult = odiv = 1;
2166
2167 switch (unit_flags & TIME_UNIT_MASK) {
2168 case TIME_UNIT_US: omult = 1000000; break;
2169 case TIME_UNIT_MS: omult = 1000; break;
2170 case TIME_UNIT_S: break;
2171 case TIME_UNIT_MIN: odiv = 60; break;
2172 case TIME_UNIT_HOUR: odiv = 3600; break;
2173 case TIME_UNIT_DAY: odiv = 86400; break;
2174 default: break;
2175 }
2176
2177 value = 0;
2178
2179 while (1) {
2180 unsigned int j;
2181
2182 j = *text - '0';
2183 if (j > 9)
2184 break;
2185 text++;
2186 value *= 10;
2187 value += j;
2188 }
2189
2190 imult = idiv = 1;
2191 switch (*text) {
2192 case '\0': /* no unit = default unit */
2193 imult = omult = idiv = odiv = 1;
2194 break;
2195 case 's': /* second = unscaled unit */
2196 break;
2197 case 'u': /* microsecond : "us" */
2198 if (text[1] == 's') {
2199 idiv = 1000000;
2200 text++;
2201 }
2202 break;
2203 case 'm': /* millisecond : "ms" or minute: "m" */
2204 if (text[1] == 's') {
2205 idiv = 1000;
2206 text++;
2207 } else
2208 imult = 60;
2209 break;
2210 case 'h': /* hour : "h" */
2211 imult = 3600;
2212 break;
2213 case 'd': /* day : "d" */
2214 imult = 86400;
2215 break;
2216 default:
2217 return text;
2218 break;
2219 }
2220
2221 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2222 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2223 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2224 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2225
Willy Tarreau9faebe32019-06-07 19:00:37 +02002226 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2227 if (result >= 0x80000000)
2228 return PARSE_TIME_OVER;
2229 if (!result && value)
2230 return PARSE_TIME_UNDER;
2231 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002232 return NULL;
2233}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002234
Emeric Brun39132b22010-01-04 14:57:24 +01002235/* this function converts the string starting at <text> to an unsigned int
2236 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002237 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002238 */
2239const char *parse_size_err(const char *text, unsigned *ret) {
2240 unsigned value = 0;
2241
2242 while (1) {
2243 unsigned int j;
2244
2245 j = *text - '0';
2246 if (j > 9)
2247 break;
2248 if (value > ~0U / 10)
2249 return text;
2250 value *= 10;
2251 if (value > (value + j))
2252 return text;
2253 value += j;
2254 text++;
2255 }
2256
2257 switch (*text) {
2258 case '\0':
2259 break;
2260 case 'K':
2261 case 'k':
2262 if (value > ~0U >> 10)
2263 return text;
2264 value = value << 10;
2265 break;
2266 case 'M':
2267 case 'm':
2268 if (value > ~0U >> 20)
2269 return text;
2270 value = value << 20;
2271 break;
2272 case 'G':
2273 case 'g':
2274 if (value > ~0U >> 30)
2275 return text;
2276 value = value << 30;
2277 break;
2278 default:
2279 return text;
2280 }
2281
Godbach58048a22015-01-28 17:36:16 +08002282 if (*text != '\0' && *++text != '\0')
2283 return text;
2284
Emeric Brun39132b22010-01-04 14:57:24 +01002285 *ret = value;
2286 return NULL;
2287}
2288
Willy Tarreau126d4062013-12-03 17:50:47 +01002289/*
2290 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002291 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002292 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002293 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002294 */
2295int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2296{
2297 int len;
2298 const char *p = source;
2299 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002300 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002301
2302 len = strlen(source);
2303 if (len % 2) {
2304 memprintf(err, "an even number of hex digit is expected");
2305 return 0;
2306 }
2307
2308 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002309
Willy Tarreau126d4062013-12-03 17:50:47 +01002310 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002311 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002312 if (!*binstr) {
2313 memprintf(err, "out of memory while loading string pattern");
2314 return 0;
2315 }
2316 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002317 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002318 else {
2319 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002320 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002321 len, *binstrlen);
2322 return 0;
2323 }
2324 alloc = 0;
2325 }
2326 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002327
2328 i = j = 0;
2329 while (j < len) {
2330 if (!ishex(p[i++]))
2331 goto bad_input;
2332 if (!ishex(p[i++]))
2333 goto bad_input;
2334 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2335 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002336 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002337
2338bad_input:
2339 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002340 if (alloc) {
2341 free(*binstr);
2342 *binstr = NULL;
2343 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002344 return 0;
2345}
2346
Willy Tarreau946ba592009-05-10 15:41:18 +02002347/* copies at most <n> characters from <src> and always terminates with '\0' */
2348char *my_strndup(const char *src, int n)
2349{
2350 int len = 0;
2351 char *ret;
2352
2353 while (len < n && src[len])
2354 len++;
2355
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002356 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002357 if (!ret)
2358 return ret;
2359 memcpy(ret, src, len);
2360 ret[len] = '\0';
2361 return ret;
2362}
2363
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002364/*
2365 * search needle in haystack
2366 * returns the pointer if found, returns NULL otherwise
2367 */
2368const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2369{
2370 const void *c = NULL;
2371 unsigned char f;
2372
2373 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2374 return NULL;
2375
2376 f = *(char *)needle;
2377 c = haystack;
2378 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2379 if ((haystacklen - (c - haystack)) < needlelen)
2380 return NULL;
2381
2382 if (memcmp(c, needle, needlelen) == 0)
2383 return c;
2384 ++c;
2385 }
2386 return NULL;
2387}
2388
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002389/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002390size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2391{
2392 size_t ret = 0;
2393
2394 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2395 str++;
2396 ret++;
2397 }
2398 return ret;
2399}
2400
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002401/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002402size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2403{
2404 size_t ret = 0;
2405
2406 while (ret < len) {
2407 if(memchr(reject, *((int *)str), rejectlen))
2408 return ret;
2409 str++;
2410 ret++;
2411 }
2412 return ret;
2413}
2414
Willy Tarreau482b00d2009-10-04 22:48:42 +02002415/* This function returns the first unused key greater than or equal to <key> in
2416 * ID tree <root>. Zero is returned if no place is found.
2417 */
2418unsigned int get_next_id(struct eb_root *root, unsigned int key)
2419{
2420 struct eb32_node *used;
2421
2422 do {
2423 used = eb32_lookup_ge(root, key);
2424 if (!used || used->key > key)
2425 return key; /* key is available */
2426 key++;
2427 } while (key);
2428 return key;
2429}
2430
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002431/* dump the full tree to <file> in DOT format for debugging purposes. Will
2432 * optionally highlight node <subj> if found, depending on operation <op> :
2433 * 0 : nothing
2434 * >0 : insertion, node/leaf are surrounded in red
2435 * <0 : removal, node/leaf are dashed with no background
2436 * Will optionally add "desc" as a label on the graph if set and non-null.
2437 */
2438void 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 +01002439{
2440 struct eb32sc_node *node;
2441 unsigned long scope = -1;
2442
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002443 fprintf(file, "digraph ebtree {\n");
2444
2445 if (desc && *desc) {
2446 fprintf(file,
2447 " fontname=\"fixed\";\n"
2448 " fontsize=8;\n"
2449 " label=\"%s\";\n", desc);
2450 }
2451
Willy Tarreaued3cda02017-11-15 15:04:05 +01002452 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002453 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2454 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002455 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2456 );
2457
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002458 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002459 (long)eb_root_to_node(root),
2460 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002461 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2462
2463 node = eb32sc_first(root, scope);
2464 while (node) {
2465 if (node->node.node_p) {
2466 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002467 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2468 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2469 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002470
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002471 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002472 (long)node,
2473 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002474 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002475
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002476 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002477 (long)node,
2478 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002479 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2480
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002481 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002482 (long)node,
2483 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002484 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2485 }
2486
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002487 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2488 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2489 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002490
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002491 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002492 (long)node,
2493 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002494 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002495 node = eb32sc_next(node, scope);
2496 }
2497 fprintf(file, "}\n");
2498}
2499
Willy Tarreau348238b2010-01-18 15:05:57 +01002500/* This function compares a sample word possibly followed by blanks to another
2501 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2502 * otherwise zero. This intends to be used when checking HTTP headers for some
2503 * values. Note that it validates a word followed only by blanks but does not
2504 * validate a word followed by blanks then other chars.
2505 */
2506int word_match(const char *sample, int slen, const char *word, int wlen)
2507{
2508 if (slen < wlen)
2509 return 0;
2510
2511 while (wlen) {
2512 char c = *sample ^ *word;
2513 if (c && c != ('A' ^ 'a'))
2514 return 0;
2515 sample++;
2516 word++;
2517 slen--;
2518 wlen--;
2519 }
2520
2521 while (slen) {
2522 if (*sample != ' ' && *sample != '\t')
2523 return 0;
2524 sample++;
2525 slen--;
2526 }
2527 return 1;
2528}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002529
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002530/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2531 * is particularly fast because it avoids expensive operations such as
2532 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002533 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002534 */
2535unsigned int inetaddr_host(const char *text)
2536{
2537 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2538 register unsigned int dig100, dig10, dig1;
2539 int s;
2540 const char *p, *d;
2541
2542 dig1 = dig10 = dig100 = ascii_zero;
2543 s = 24;
2544
2545 p = text;
2546 while (1) {
2547 if (((unsigned)(*p - '0')) <= 9) {
2548 p++;
2549 continue;
2550 }
2551
2552 /* here, we have a complete byte between <text> and <p> (exclusive) */
2553 if (p == text)
2554 goto end;
2555
2556 d = p - 1;
2557 dig1 |= (unsigned int)(*d << s);
2558 if (d == text)
2559 goto end;
2560
2561 d--;
2562 dig10 |= (unsigned int)(*d << s);
2563 if (d == text)
2564 goto end;
2565
2566 d--;
2567 dig100 |= (unsigned int)(*d << s);
2568 end:
2569 if (!s || *p != '.')
2570 break;
2571
2572 s -= 8;
2573 text = ++p;
2574 }
2575
2576 dig100 -= ascii_zero;
2577 dig10 -= ascii_zero;
2578 dig1 -= ascii_zero;
2579 return ((dig100 * 10) + dig10) * 10 + dig1;
2580}
2581
2582/*
2583 * Idem except the first unparsed character has to be passed in <stop>.
2584 */
2585unsigned int inetaddr_host_lim(const char *text, const char *stop)
2586{
2587 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2588 register unsigned int dig100, dig10, dig1;
2589 int s;
2590 const char *p, *d;
2591
2592 dig1 = dig10 = dig100 = ascii_zero;
2593 s = 24;
2594
2595 p = text;
2596 while (1) {
2597 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2598 p++;
2599 continue;
2600 }
2601
2602 /* here, we have a complete byte between <text> and <p> (exclusive) */
2603 if (p == text)
2604 goto end;
2605
2606 d = p - 1;
2607 dig1 |= (unsigned int)(*d << s);
2608 if (d == text)
2609 goto end;
2610
2611 d--;
2612 dig10 |= (unsigned int)(*d << s);
2613 if (d == text)
2614 goto end;
2615
2616 d--;
2617 dig100 |= (unsigned int)(*d << s);
2618 end:
2619 if (!s || p == stop || *p != '.')
2620 break;
2621
2622 s -= 8;
2623 text = ++p;
2624 }
2625
2626 dig100 -= ascii_zero;
2627 dig10 -= ascii_zero;
2628 dig1 -= ascii_zero;
2629 return ((dig100 * 10) + dig10) * 10 + dig1;
2630}
2631
2632/*
2633 * Idem except the pointer to first unparsed byte is returned into <ret> which
2634 * must not be NULL.
2635 */
Willy Tarreau74172752010-10-15 23:21:42 +02002636unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002637{
2638 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2639 register unsigned int dig100, dig10, dig1;
2640 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002641 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002642
2643 dig1 = dig10 = dig100 = ascii_zero;
2644 s = 24;
2645
2646 p = text;
2647 while (1) {
2648 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2649 p++;
2650 continue;
2651 }
2652
2653 /* here, we have a complete byte between <text> and <p> (exclusive) */
2654 if (p == text)
2655 goto end;
2656
2657 d = p - 1;
2658 dig1 |= (unsigned int)(*d << s);
2659 if (d == text)
2660 goto end;
2661
2662 d--;
2663 dig10 |= (unsigned int)(*d << s);
2664 if (d == text)
2665 goto end;
2666
2667 d--;
2668 dig100 |= (unsigned int)(*d << s);
2669 end:
2670 if (!s || p == stop || *p != '.')
2671 break;
2672
2673 s -= 8;
2674 text = ++p;
2675 }
2676
2677 *ret = p;
2678 dig100 -= ascii_zero;
2679 dig10 -= ascii_zero;
2680 dig1 -= ascii_zero;
2681 return ((dig100 * 10) + dig10) * 10 + dig1;
2682}
2683
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002684/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2685 * or the number of chars read in case of success. Maybe this could be replaced
2686 * by one of the functions above. Also, apparently this function does not support
2687 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002688 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002689 */
2690int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2691{
2692 const char *addr;
2693 int saw_digit, octets, ch;
2694 u_char tmp[4], *tp;
2695 const char *cp = buf;
2696
2697 saw_digit = 0;
2698 octets = 0;
2699 *(tp = tmp) = 0;
2700
2701 for (addr = buf; addr - buf < len; addr++) {
2702 unsigned char digit = (ch = *addr) - '0';
2703
2704 if (digit > 9 && ch != '.')
2705 break;
2706
2707 if (digit <= 9) {
2708 u_int new = *tp * 10 + digit;
2709
2710 if (new > 255)
2711 return 0;
2712
2713 *tp = new;
2714
2715 if (!saw_digit) {
2716 if (++octets > 4)
2717 return 0;
2718 saw_digit = 1;
2719 }
2720 } else if (ch == '.' && saw_digit) {
2721 if (octets == 4)
2722 return 0;
2723
2724 *++tp = 0;
2725 saw_digit = 0;
2726 } else
2727 return 0;
2728 }
2729
2730 if (octets < 4)
2731 return 0;
2732
2733 memcpy(&dst->s_addr, tmp, 4);
2734 return addr - cp;
2735}
2736
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002737/* This function converts the string in <buf> of the len <len> to
2738 * struct in6_addr <dst> which must be allocated by the caller.
2739 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002740 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002741 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002742int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2743{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002744 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002745 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002746
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002747 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002748 return 0;
2749
2750 memcpy(null_term_ip6, buf, len);
2751 null_term_ip6[len] = '\0';
2752
Willy Tarreau075415a2013-12-12 11:29:39 +01002753 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002754 return 0;
2755
Willy Tarreau075415a2013-12-12 11:29:39 +01002756 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002757 return 1;
2758}
2759
Willy Tarreauacf95772010-06-14 19:09:21 +02002760/* To be used to quote config arg positions. Returns the short string at <ptr>
2761 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2762 * if ptr is NULL or empty. The string is locally allocated.
2763 */
2764const char *quote_arg(const char *ptr)
2765{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002766 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002767 int i;
2768
2769 if (!ptr || !*ptr)
2770 return "end of line";
2771 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002772 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002773 val[i] = *ptr++;
2774 val[i++] = '\'';
2775 val[i] = '\0';
2776 return val;
2777}
2778
Willy Tarreau5b180202010-07-18 10:40:48 +02002779/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2780int get_std_op(const char *str)
2781{
2782 int ret = -1;
2783
2784 if (*str == 'e' && str[1] == 'q')
2785 ret = STD_OP_EQ;
2786 else if (*str == 'n' && str[1] == 'e')
2787 ret = STD_OP_NE;
2788 else if (*str == 'l') {
2789 if (str[1] == 'e') ret = STD_OP_LE;
2790 else if (str[1] == 't') ret = STD_OP_LT;
2791 }
2792 else if (*str == 'g') {
2793 if (str[1] == 'e') ret = STD_OP_GE;
2794 else if (str[1] == 't') ret = STD_OP_GT;
2795 }
2796
2797 if (ret == -1 || str[2] != '\0')
2798 return -1;
2799 return ret;
2800}
2801
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002802/* hash a 32-bit integer to another 32-bit integer */
2803unsigned int full_hash(unsigned int a)
2804{
2805 return __full_hash(a);
2806}
2807
Willy Tarreauf3241112019-02-26 09:56:22 +01002808/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2809 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2810 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2811 * a popcount variant and is described here :
2812 * https://graphics.stanford.edu/~seander/bithacks.html
2813 */
2814unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2815{
2816 unsigned long a, b, c, d;
2817 unsigned int s;
2818 unsigned int t;
2819
2820 a = m - ((m >> 1) & ~0UL/3);
2821 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2822 c = (b + (b >> 4)) & ~0UL/0x11;
2823 d = (c + (c >> 8)) & ~0UL/0x101;
2824
2825 r++; // make r be 1..64
2826
2827 t = 0;
2828 s = LONGBITS;
2829 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002830 unsigned long d2 = (d >> 16) >> 16;
2831 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002832 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2833 }
2834
2835 t = (d >> (s - 16)) & 0xff;
2836 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2837 t = (c >> (s - 8)) & 0xf;
2838 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2839 t = (b >> (s - 4)) & 0x7;
2840 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2841 t = (a >> (s - 2)) & 0x3;
2842 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2843 t = (m >> (s - 1)) & 0x1;
2844 s -= ((t - r) & 256) >> 8;
2845
2846 return s - 1;
2847}
2848
2849/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2850 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2851 * using mask_prep_rank_map() below.
2852 */
2853unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2854 unsigned long a, unsigned long b,
2855 unsigned long c, unsigned long d)
2856{
2857 unsigned int s;
2858 unsigned int t;
2859
2860 r++; // make r be 1..64
2861
2862 t = 0;
2863 s = LONGBITS;
2864 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002865 unsigned long d2 = (d >> 16) >> 16;
2866 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002867 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2868 }
2869
2870 t = (d >> (s - 16)) & 0xff;
2871 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2872 t = (c >> (s - 8)) & 0xf;
2873 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2874 t = (b >> (s - 4)) & 0x7;
2875 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2876 t = (a >> (s - 2)) & 0x3;
2877 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2878 t = (m >> (s - 1)) & 0x1;
2879 s -= ((t - r) & 256) >> 8;
2880
2881 return s - 1;
2882}
2883
2884/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2885 * above.
2886 */
2887void mask_prep_rank_map(unsigned long m,
2888 unsigned long *a, unsigned long *b,
2889 unsigned long *c, unsigned long *d)
2890{
2891 *a = m - ((m >> 1) & ~0UL/3);
2892 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2893 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2894 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2895}
2896
David du Colombier4f92d322011-03-24 11:09:31 +01002897/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002898 * otherwise zero. Note that <addr> may not necessarily be aligned
2899 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002900 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002901int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002902{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002903 struct in_addr addr_copy;
2904
2905 memcpy(&addr_copy, addr, sizeof(addr_copy));
2906 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002907}
2908
2909/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002910 * otherwise zero. Note that <addr> may not necessarily be aligned
2911 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002912 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002913int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002914{
2915 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002916 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002917
Willy Tarreaueec1d382016-07-13 11:59:39 +02002918 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002919 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002920 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002921 (((int *)net)[i] & ((int *)mask)[i]))
2922 return 0;
2923 return 1;
2924}
2925
2926/* RFC 4291 prefix */
2927const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2928 0x00, 0x00, 0x00, 0x00,
2929 0x00, 0x00, 0xFF, 0xFF };
2930
Joseph Herlant32b83272018-11-15 11:58:28 -08002931/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002932 * Input and output may overlap.
2933 */
David du Colombier4f92d322011-03-24 11:09:31 +01002934void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2935{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002936 struct in_addr tmp_addr;
2937
2938 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002939 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002940 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002941}
2942
Joseph Herlant32b83272018-11-15 11:58:28 -08002943/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002944 * Return true if conversion is possible and false otherwise.
2945 */
2946int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2947{
2948 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2949 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2950 sizeof(struct in_addr));
2951 return 1;
2952 }
2953
2954 return 0;
2955}
2956
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002957/* compare two struct sockaddr_storage and return:
2958 * 0 (true) if the addr is the same in both
2959 * 1 (false) if the addr is not the same in both
2960 * -1 (unable) if one of the addr is not AF_INET*
2961 */
2962int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2963{
2964 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2965 return -1;
2966
2967 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2968 return -1;
2969
2970 if (ss1->ss_family != ss2->ss_family)
2971 return 1;
2972
2973 switch (ss1->ss_family) {
2974 case AF_INET:
2975 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2976 &((struct sockaddr_in *)ss2)->sin_addr,
2977 sizeof(struct in_addr)) != 0;
2978 case AF_INET6:
2979 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2980 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2981 sizeof(struct in6_addr)) != 0;
2982 }
2983
2984 return 1;
2985}
2986
Baptiste Assmann08396c82016-01-31 00:27:17 +01002987/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002988 * The caller must allocate and clear <dest> before calling.
2989 * The source must be in either AF_INET or AF_INET6 family, or the destination
2990 * address will be undefined. If the destination address used to hold a port,
2991 * it is preserved, so that this function can be used to switch to another
2992 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002993 */
2994struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2995{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002996 int prev_port;
2997
2998 prev_port = get_net_port(dest);
2999 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003000 dest->ss_family = source->ss_family;
3001
3002 /* copy new addr and apply it */
3003 switch (source->ss_family) {
3004 case AF_INET:
3005 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003006 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003007 break;
3008 case AF_INET6:
3009 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 +01003010 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003011 break;
3012 }
3013
3014 return dest;
3015}
3016
William Lallemand421f5b52012-02-06 18:15:57 +01003017char *human_time(int t, short hz_div) {
3018 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3019 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003020 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003021 int cnt=2; // print two numbers
3022
3023 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003024 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003025 return rv;
3026 }
3027
3028 if (unlikely(hz_div > 1))
3029 t /= hz_div;
3030
3031 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003032 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003033 cnt--;
3034 }
3035
3036 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003037 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003038 cnt--;
3039 }
3040
3041 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003042 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003043 cnt--;
3044 }
3045
3046 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003047 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003048
3049 return rv;
3050}
3051
3052const char *monthname[12] = {
3053 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3054 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3055};
3056
3057/* date2str_log: write a date in the format :
3058 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3059 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3060 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3061 *
3062 * without using sprintf. return a pointer to the last char written (\0) or
3063 * NULL if there isn't enough space.
3064 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003065char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003066{
3067
3068 if (size < 25) /* the size is fixed: 24 chars + \0 */
3069 return NULL;
3070
3071 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003072 if (!dst)
3073 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003074 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003075
William Lallemand421f5b52012-02-06 18:15:57 +01003076 memcpy(dst, monthname[tm->tm_mon], 3); // month
3077 dst += 3;
3078 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003079
William Lallemand421f5b52012-02-06 18:15:57 +01003080 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003081 if (!dst)
3082 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003083 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003084
William Lallemand421f5b52012-02-06 18:15:57 +01003085 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003086 if (!dst)
3087 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003088 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003089
William Lallemand421f5b52012-02-06 18:15:57 +01003090 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003091 if (!dst)
3092 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003093 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003094
William Lallemand421f5b52012-02-06 18:15:57 +01003095 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003096 if (!dst)
3097 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003098 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003099
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003100 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003101 if (!dst)
3102 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003103 *dst = '\0';
3104
3105 return dst;
3106}
3107
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003108/* Base year used to compute leap years */
3109#define TM_YEAR_BASE 1900
3110
3111/* Return the difference in seconds between two times (leap seconds are ignored).
3112 * Retrieved from glibc 2.18 source code.
3113 */
3114static int my_tm_diff(const struct tm *a, const struct tm *b)
3115{
3116 /* Compute intervening leap days correctly even if year is negative.
3117 * Take care to avoid int overflow in leap day calculations,
3118 * but it's OK to assume that A and B are close to each other.
3119 */
3120 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3121 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3122 int a100 = a4 / 25 - (a4 % 25 < 0);
3123 int b100 = b4 / 25 - (b4 % 25 < 0);
3124 int a400 = a100 >> 2;
3125 int b400 = b100 >> 2;
3126 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3127 int years = a->tm_year - b->tm_year;
3128 int days = (365 * years + intervening_leap_days
3129 + (a->tm_yday - b->tm_yday));
3130 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3131 + (a->tm_min - b->tm_min))
3132 + (a->tm_sec - b->tm_sec));
3133}
3134
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003135/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003136 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003137 * The string returned has the same format as returned by strftime(... "%z", tm).
3138 * Offsets are kept in an internal cache for better performances.
3139 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003140const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003141{
3142 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003143 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003144
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003145 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003146 struct tm tm_gmt;
3147 int diff;
3148 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003149
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003150 /* Pretend DST not active if its status is unknown */
3151 if (isdst < 0)
3152 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003153
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003154 /* Fetch the offset and initialize it if needed */
3155 gmt_offset = gmt_offsets[isdst & 0x01];
3156 if (unlikely(!*gmt_offset)) {
3157 get_gmtime(t, &tm_gmt);
3158 diff = my_tm_diff(tm, &tm_gmt);
3159 if (diff < 0) {
3160 diff = -diff;
3161 *gmt_offset = '-';
3162 } else {
3163 *gmt_offset = '+';
3164 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003165 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003166 diff /= 60; /* Convert to minutes */
3167 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3168 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003169
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003170 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003171}
3172
William Lallemand421f5b52012-02-06 18:15:57 +01003173/* gmt2str_log: write a date in the format :
3174 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3175 * return a pointer to the last char written (\0) or
3176 * NULL if there isn't enough space.
3177 */
3178char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3179{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003180 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003181 return NULL;
3182
3183 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003184 if (!dst)
3185 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003186 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003187
William Lallemand421f5b52012-02-06 18:15:57 +01003188 memcpy(dst, monthname[tm->tm_mon], 3); // month
3189 dst += 3;
3190 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003191
William Lallemand421f5b52012-02-06 18:15:57 +01003192 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003193 if (!dst)
3194 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003195 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003196
William Lallemand421f5b52012-02-06 18:15:57 +01003197 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003198 if (!dst)
3199 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003200 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003201
William Lallemand421f5b52012-02-06 18:15:57 +01003202 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003203 if (!dst)
3204 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003205 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003206
William Lallemand421f5b52012-02-06 18:15:57 +01003207 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003208 if (!dst)
3209 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003210 *dst++ = ' ';
3211 *dst++ = '+';
3212 *dst++ = '0';
3213 *dst++ = '0';
3214 *dst++ = '0';
3215 *dst++ = '0';
3216 *dst = '\0';
3217
3218 return dst;
3219}
3220
Yuxans Yao4e25b012012-10-19 10:36:09 +08003221/* localdate2str_log: write a date in the format :
3222 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003223 * Both t and tm must represent the same time.
3224 * return a pointer to the last char written (\0) or
3225 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003226 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003227char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003228{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003229 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003230 if (size < 27) /* the size is fixed: 26 chars + \0 */
3231 return NULL;
3232
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003233 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003234
Yuxans Yao4e25b012012-10-19 10:36:09 +08003235 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003236 if (!dst)
3237 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003238 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003239
Yuxans Yao4e25b012012-10-19 10:36:09 +08003240 memcpy(dst, monthname[tm->tm_mon], 3); // month
3241 dst += 3;
3242 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003243
Yuxans Yao4e25b012012-10-19 10:36:09 +08003244 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003245 if (!dst)
3246 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003247 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003248
Yuxans Yao4e25b012012-10-19 10:36:09 +08003249 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003250 if (!dst)
3251 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003252 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003253
Yuxans Yao4e25b012012-10-19 10:36:09 +08003254 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003255 if (!dst)
3256 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003257 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003258
Yuxans Yao4e25b012012-10-19 10:36:09 +08003259 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003260 if (!dst)
3261 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003262 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003263
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003264 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003265 dst += 5;
3266 *dst = '\0';
3267
3268 return dst;
3269}
3270
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003271/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3272 * It is meant as a portable replacement for timegm() for use with valid inputs.
3273 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3274 */
3275time_t my_timegm(const struct tm *tm)
3276{
3277 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3278 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3279 * sum of the extra N days for elapsed months. The sum of all these N
3280 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3281 * in a 5-bit word. This means that with 60 bits we can represent a
3282 * matrix of all these values at once, which is fast and efficient to
3283 * access. The extra February day for leap years is not counted here.
3284 *
3285 * Jan : none = 0 (0)
3286 * Feb : Jan = 3 (3)
3287 * Mar : Jan..Feb = 3 (3 + 0)
3288 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3289 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3290 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3291 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3292 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3293 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3294 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3295 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3296 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3297 */
3298 uint64_t extra =
3299 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3300 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3301 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3302 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3303
3304 unsigned int y = tm->tm_year + 1900;
3305 unsigned int m = tm->tm_mon;
3306 unsigned long days = 0;
3307
3308 /* days since 1/1/1970 for full years */
3309 days += days_since_zero(y) - days_since_zero(1970);
3310
3311 /* days for full months in the current year */
3312 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3313
3314 /* count + 1 after March for leap years. A leap year is a year multiple
3315 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3316 * is leap, 1900 isn't, 1904 is.
3317 */
3318 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3319 days++;
3320
3321 days += tm->tm_mday - 1;
3322 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3323}
3324
Thierry Fournier93127942016-01-20 18:49:45 +01003325/* This function check a char. It returns true and updates
3326 * <date> and <len> pointer to the new position if the
3327 * character is found.
3328 */
3329static inline int parse_expect_char(const char **date, int *len, char c)
3330{
3331 if (*len < 1 || **date != c)
3332 return 0;
3333 (*len)--;
3334 (*date)++;
3335 return 1;
3336}
3337
3338/* This function expects a string <str> of len <l>. It return true and updates.
3339 * <date> and <len> if the string matches, otherwise, it returns false.
3340 */
3341static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3342{
3343 if (*len < l || strncmp(*date, str, l) != 0)
3344 return 0;
3345 (*len) -= l;
3346 (*date) += l;
3347 return 1;
3348}
3349
3350/* This macro converts 3 chars name in integer. */
3351#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3352
3353/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3354 * / %x54.75.65 ; "Tue", case-sensitive
3355 * / %x57.65.64 ; "Wed", case-sensitive
3356 * / %x54.68.75 ; "Thu", case-sensitive
3357 * / %x46.72.69 ; "Fri", case-sensitive
3358 * / %x53.61.74 ; "Sat", case-sensitive
3359 * / %x53.75.6E ; "Sun", case-sensitive
3360 *
3361 * This array must be alphabetically sorted
3362 */
3363static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3364{
3365 if (*len < 3)
3366 return 0;
3367 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3368 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3369 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3370 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3371 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3372 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3373 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3374 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3375 default: return 0;
3376 }
3377 *len -= 3;
3378 *date += 3;
3379 return 1;
3380}
3381
3382/* month = %x4A.61.6E ; "Jan", case-sensitive
3383 * / %x46.65.62 ; "Feb", case-sensitive
3384 * / %x4D.61.72 ; "Mar", case-sensitive
3385 * / %x41.70.72 ; "Apr", case-sensitive
3386 * / %x4D.61.79 ; "May", case-sensitive
3387 * / %x4A.75.6E ; "Jun", case-sensitive
3388 * / %x4A.75.6C ; "Jul", case-sensitive
3389 * / %x41.75.67 ; "Aug", case-sensitive
3390 * / %x53.65.70 ; "Sep", case-sensitive
3391 * / %x4F.63.74 ; "Oct", case-sensitive
3392 * / %x4E.6F.76 ; "Nov", case-sensitive
3393 * / %x44.65.63 ; "Dec", case-sensitive
3394 *
3395 * This array must be alphabetically sorted
3396 */
3397static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3398{
3399 if (*len < 3)
3400 return 0;
3401 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3402 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3403 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3404 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3405 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3406 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3407 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3408 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3409 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3410 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3411 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3412 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3413 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3414 default: return 0;
3415 }
3416 *len -= 3;
3417 *date += 3;
3418 return 1;
3419}
3420
3421/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3422 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3423 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3424 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3425 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3426 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3427 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3428 *
3429 * This array must be alphabetically sorted
3430 */
3431static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3432{
3433 if (*len < 6) /* Minimum length. */
3434 return 0;
3435 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3436 case STR2I3('M','o','n'):
3437 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3438 tm->tm_wday = 1;
3439 return 1;
3440 case STR2I3('T','u','e'):
3441 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3442 tm->tm_wday = 2;
3443 return 1;
3444 case STR2I3('W','e','d'):
3445 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3446 tm->tm_wday = 3;
3447 return 1;
3448 case STR2I3('T','h','u'):
3449 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3450 tm->tm_wday = 4;
3451 return 1;
3452 case STR2I3('F','r','i'):
3453 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3454 tm->tm_wday = 5;
3455 return 1;
3456 case STR2I3('S','a','t'):
3457 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3458 tm->tm_wday = 6;
3459 return 1;
3460 case STR2I3('S','u','n'):
3461 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3462 tm->tm_wday = 7;
3463 return 1;
3464 }
3465 return 0;
3466}
3467
3468/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3469static inline int parse_digit(const char **date, int *len, int *digit)
3470{
3471 if (*len < 1 || **date < '0' || **date > '9')
3472 return 0;
3473 *digit = (**date - '0');
3474 (*date)++;
3475 (*len)--;
3476 return 1;
3477}
3478
3479/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3480static inline int parse_2digit(const char **date, int *len, int *digit)
3481{
3482 int value;
3483
3484 RET0_UNLESS(parse_digit(date, len, &value));
3485 (*digit) = value * 10;
3486 RET0_UNLESS(parse_digit(date, len, &value));
3487 (*digit) += value;
3488
3489 return 1;
3490}
3491
3492/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3493static inline int parse_4digit(const char **date, int *len, int *digit)
3494{
3495 int value;
3496
3497 RET0_UNLESS(parse_digit(date, len, &value));
3498 (*digit) = value * 1000;
3499
3500 RET0_UNLESS(parse_digit(date, len, &value));
3501 (*digit) += value * 100;
3502
3503 RET0_UNLESS(parse_digit(date, len, &value));
3504 (*digit) += value * 10;
3505
3506 RET0_UNLESS(parse_digit(date, len, &value));
3507 (*digit) += value;
3508
3509 return 1;
3510}
3511
3512/* time-of-day = hour ":" minute ":" second
3513 * ; 00:00:00 - 23:59:60 (leap second)
3514 *
3515 * hour = 2DIGIT
3516 * minute = 2DIGIT
3517 * second = 2DIGIT
3518 */
3519static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3520{
3521 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3522 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3523 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3524 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3525 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3526 return 1;
3527}
3528
3529/* From RFC7231
3530 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3531 *
3532 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3533 * ; fixed length/zone/capitalization subset of the format
3534 * ; see Section 3.3 of [RFC5322]
3535 *
3536 *
3537 * date1 = day SP month SP year
3538 * ; e.g., 02 Jun 1982
3539 *
3540 * day = 2DIGIT
3541 * year = 4DIGIT
3542 *
3543 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3544 *
3545 * time-of-day = hour ":" minute ":" second
3546 * ; 00:00:00 - 23:59:60 (leap second)
3547 *
3548 * hour = 2DIGIT
3549 * minute = 2DIGIT
3550 * second = 2DIGIT
3551 *
3552 * DIGIT = decimal 0-9
3553 */
3554int parse_imf_date(const char *date, int len, struct tm *tm)
3555{
David Carlier327298c2016-11-20 10:42:38 +00003556 /* tm_gmtoff, if present, ought to be zero'ed */
3557 memset(tm, 0, sizeof(*tm));
3558
Thierry Fournier93127942016-01-20 18:49:45 +01003559 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3560 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3561 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3562 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3563 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3564 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3565 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3566 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3567 tm->tm_year -= 1900;
3568 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3569 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3570 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3571 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3572 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003573 return 1;
3574}
3575
3576/* From RFC7231
3577 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3578 *
3579 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3580 * date2 = day "-" month "-" 2DIGIT
3581 * ; e.g., 02-Jun-82
3582 *
3583 * day = 2DIGIT
3584 */
3585int parse_rfc850_date(const char *date, int len, struct tm *tm)
3586{
3587 int year;
3588
David Carlier327298c2016-11-20 10:42:38 +00003589 /* tm_gmtoff, if present, ought to be zero'ed */
3590 memset(tm, 0, sizeof(*tm));
3591
Thierry Fournier93127942016-01-20 18:49:45 +01003592 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3593 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3594 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3595 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3596 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3597 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3598 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3599
3600 /* year = 2DIGIT
3601 *
3602 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3603 * two-digit year, MUST interpret a timestamp that appears to be more
3604 * than 50 years in the future as representing the most recent year in
3605 * the past that had the same last two digits.
3606 */
3607 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3608
3609 /* expect SP */
3610 if (!parse_expect_char(&date, &len, ' ')) {
3611 /* Maybe we have the date with 4 digits. */
3612 RET0_UNLESS(parse_2digit(&date, &len, &year));
3613 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3614 /* expect SP */
3615 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3616 } else {
3617 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3618 * tm_year is the number of year since 1900, so for +1900, we
3619 * do nothing, and for +2000, we add 100.
3620 */
3621 if (tm->tm_year <= 60)
3622 tm->tm_year += 100;
3623 }
3624
3625 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3626 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3627 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3628 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003629
3630 return 1;
3631}
3632
3633/* From RFC7231
3634 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3635 *
3636 * asctime-date = day-name SP date3 SP time-of-day SP year
3637 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3638 * ; e.g., Jun 2
3639 *
3640 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3641 * whitespace in an HTTP-date beyond that specifically included as SP in
3642 * the grammar.
3643 */
3644int parse_asctime_date(const char *date, int len, struct tm *tm)
3645{
David Carlier327298c2016-11-20 10:42:38 +00003646 /* tm_gmtoff, if present, ought to be zero'ed */
3647 memset(tm, 0, sizeof(*tm));
3648
Thierry Fournier93127942016-01-20 18:49:45 +01003649 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3650 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3651 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3652 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3653
3654 /* expect SP and 1DIGIT or 2DIGIT */
3655 if (parse_expect_char(&date, &len, ' '))
3656 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3657 else
3658 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3659
3660 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3661 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3662 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3663 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3664 tm->tm_year -= 1900;
3665 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003666 return 1;
3667}
3668
3669/* From RFC7231
3670 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3671 *
3672 * HTTP-date = IMF-fixdate / obs-date
3673 * obs-date = rfc850-date / asctime-date
3674 *
3675 * parses an HTTP date in the RFC format and is accepted
3676 * alternatives. <date> is the strinf containing the date,
3677 * len is the len of the string. <tm> is filled with the
3678 * parsed time. We must considers this time as GMT.
3679 */
3680int parse_http_date(const char *date, int len, struct tm *tm)
3681{
3682 if (parse_imf_date(date, len, tm))
3683 return 1;
3684
3685 if (parse_rfc850_date(date, len, tm))
3686 return 1;
3687
3688 if (parse_asctime_date(date, len, tm))
3689 return 1;
3690
3691 return 0;
3692}
3693
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003694/* Dynamically allocates a string of the proper length to hold the formatted
3695 * output. NULL is returned on error. The caller is responsible for freeing the
3696 * memory area using free(). The resulting string is returned in <out> if the
3697 * pointer is not NULL. A previous version of <out> might be used to build the
3698 * new string, and it will be freed before returning if it is not NULL, which
3699 * makes it possible to build complex strings from iterative calls without
3700 * having to care about freeing intermediate values, as in the example below :
3701 *
3702 * memprintf(&err, "invalid argument: '%s'", arg);
3703 * ...
3704 * memprintf(&err, "parser said : <%s>\n", *err);
3705 * ...
3706 * free(*err);
3707 *
3708 * This means that <err> must be initialized to NULL before first invocation.
3709 * The return value also holds the allocated string, which eases error checking
3710 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003711 * passed instead and it will be ignored. The returned message will then also
3712 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003713 *
3714 * It is also convenient to use it without any free except the last one :
3715 * err = NULL;
3716 * if (!fct1(err)) report(*err);
3717 * if (!fct2(err)) report(*err);
3718 * if (!fct3(err)) report(*err);
3719 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003720 *
3721 * memprintf relies on memvprintf. This last version can be called from any
3722 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003723 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003724char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003725{
3726 va_list args;
3727 char *ret = NULL;
3728 int allocated = 0;
3729 int needed = 0;
3730
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003731 if (!out)
3732 return NULL;
3733
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003734 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003735 char buf1;
3736
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003737 /* vsnprintf() will return the required length even when the
3738 * target buffer is NULL. We do this in a loop just in case
3739 * intermediate evaluations get wrong.
3740 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003741 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003742 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003743 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003744 if (needed < allocated) {
3745 /* Note: on Solaris 8, the first iteration always
3746 * returns -1 if allocated is zero, so we force a
3747 * retry.
3748 */
3749 if (!allocated)
3750 needed = 0;
3751 else
3752 break;
3753 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003754
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003755 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003756 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003757 } while (ret);
3758
3759 if (needed < 0) {
3760 /* an error was encountered */
3761 free(ret);
3762 ret = NULL;
3763 }
3764
3765 if (out) {
3766 free(*out);
3767 *out = ret;
3768 }
3769
3770 return ret;
3771}
William Lallemand421f5b52012-02-06 18:15:57 +01003772
Christopher Faulet93a518f2017-10-24 11:25:33 +02003773char *memprintf(char **out, const char *format, ...)
3774{
3775 va_list args;
3776 char *ret = NULL;
3777
3778 va_start(args, format);
3779 ret = memvprintf(out, format, args);
3780 va_end(args);
3781
3782 return ret;
3783}
3784
Willy Tarreau21c705b2012-09-14 11:40:36 +02003785/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3786 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003787 * freed by the caller. It also supports being passed a NULL which results in the same
3788 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003789 * Example of use :
3790 * parse(cmd, &err); (callee: memprintf(&err, ...))
3791 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3792 * free(err);
3793 */
3794char *indent_msg(char **out, int level)
3795{
3796 char *ret, *in, *p;
3797 int needed = 0;
3798 int lf = 0;
3799 int lastlf = 0;
3800 int len;
3801
Willy Tarreau70eec382012-10-10 08:56:47 +02003802 if (!out || !*out)
3803 return NULL;
3804
Willy Tarreau21c705b2012-09-14 11:40:36 +02003805 in = *out - 1;
3806 while ((in = strchr(in + 1, '\n')) != NULL) {
3807 lastlf = in - *out;
3808 lf++;
3809 }
3810
3811 if (!lf) /* single line, no LF, return it as-is */
3812 return *out;
3813
3814 len = strlen(*out);
3815
3816 if (lf == 1 && lastlf == len - 1) {
3817 /* single line, LF at end, strip it and return as-is */
3818 (*out)[lastlf] = 0;
3819 return *out;
3820 }
3821
3822 /* OK now we have at least one LF, we need to process the whole string
3823 * as a multi-line string. What we'll do :
3824 * - prefix with an LF if there is none
3825 * - add <level> spaces before each line
3826 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3827 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3828 */
3829
3830 needed = 1 + level * (lf + 1) + len + 1;
3831 p = ret = malloc(needed);
3832 in = *out;
3833
3834 /* skip initial LFs */
3835 while (*in == '\n')
3836 in++;
3837
3838 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3839 while (*in) {
3840 *p++ = '\n';
3841 memset(p, ' ', level);
3842 p += level;
3843 do {
3844 *p++ = *in++;
3845 } while (*in && *in != '\n');
3846 if (*in)
3847 in++;
3848 }
3849 *p = 0;
3850
3851 free(*out);
3852 *out = ret;
3853
3854 return ret;
3855}
3856
Willy Tarreaua2c99112019-08-21 13:17:37 +02003857/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3858 * and end of lines replaced with <eol> if not 0. The first line to indent has
3859 * to be indicated in <first> (starts at zero), so that it is possible to skip
3860 * indenting the first line if it has to be appended after an existing message.
3861 * Empty strings are never indented, and NULL strings are considered empty both
3862 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3863 * character, non-zero otherwise.
3864 */
3865int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3866{
3867 int bol, lf;
3868 int pfxlen = pfx ? strlen(pfx) : 0;
3869
3870 if (!in)
3871 return 0;
3872
3873 bol = 1;
3874 lf = 0;
3875 while (*in) {
3876 if (bol && pfxlen) {
3877 if (first > 0)
3878 first--;
3879 else
3880 b_putblk(out, pfx, pfxlen);
3881 bol = 0;
3882 }
3883
3884 lf = (*in == '\n');
3885 bol |= lf;
3886 b_putchr(out, (lf && eol) ? eol : *in);
3887 in++;
3888 }
3889 return lf;
3890}
3891
Willy Tarreau9d22e562019-03-29 18:49:09 +01003892/* removes environment variable <name> from the environment as found in
3893 * environ. This is only provided as an alternative for systems without
3894 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003895 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003896 * <name> and to replace the matching pointers with the last pointer of
3897 * the array (since variables are not ordered).
3898 * It always returns 0 (success).
3899 */
3900int my_unsetenv(const char *name)
3901{
3902 extern char **environ;
3903 char **p = environ;
3904 int vars;
3905 int next;
3906 int len;
3907
3908 len = strlen(name);
3909 for (vars = 0; p[vars]; vars++)
3910 ;
3911 next = 0;
3912 while (next < vars) {
3913 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3914 next++;
3915 continue;
3916 }
3917 if (next < vars - 1)
3918 p[next] = p[vars - 1];
3919 p[--vars] = NULL;
3920 }
3921 return 0;
3922}
3923
Willy Tarreaudad36a32013-03-11 01:20:04 +01003924/* Convert occurrences of environment variables in the input string to their
3925 * corresponding value. A variable is identified as a series of alphanumeric
3926 * characters or underscores following a '$' sign. The <in> string must be
3927 * free()able. NULL returns NULL. The resulting string might be reallocated if
3928 * some expansion is made. Variable names may also be enclosed into braces if
3929 * needed (eg: to concatenate alphanum characters).
3930 */
3931char *env_expand(char *in)
3932{
3933 char *txt_beg;
3934 char *out;
3935 char *txt_end;
3936 char *var_beg;
3937 char *var_end;
3938 char *value;
3939 char *next;
3940 int out_len;
3941 int val_len;
3942
3943 if (!in)
3944 return in;
3945
3946 value = out = NULL;
3947 out_len = 0;
3948
3949 txt_beg = in;
3950 do {
3951 /* look for next '$' sign in <in> */
3952 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3953
3954 if (!*txt_end && !out) /* end and no expansion performed */
3955 return in;
3956
3957 val_len = 0;
3958 next = txt_end;
3959 if (*txt_end == '$') {
3960 char save;
3961
3962 var_beg = txt_end + 1;
3963 if (*var_beg == '{')
3964 var_beg++;
3965
3966 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003967 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003968 var_end++;
3969 }
3970
3971 next = var_end;
3972 if (*var_end == '}' && (var_beg > txt_end + 1))
3973 next++;
3974
3975 /* get value of the variable name at this location */
3976 save = *var_end;
3977 *var_end = '\0';
3978 value = getenv(var_beg);
3979 *var_end = save;
3980 val_len = value ? strlen(value) : 0;
3981 }
3982
Hubert Verstraete831962e2016-06-28 22:44:26 +02003983 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003984 if (txt_end > txt_beg) {
3985 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3986 out_len += txt_end - txt_beg;
3987 }
3988 if (val_len) {
3989 memcpy(out + out_len, value, val_len);
3990 out_len += val_len;
3991 }
3992 out[out_len] = 0;
3993 txt_beg = next;
3994 } while (*txt_beg);
3995
3996 /* here we know that <out> was allocated and that we don't need <in> anymore */
3997 free(in);
3998 return out;
3999}
4000
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004001
4002/* same as strstr() but case-insensitive and with limit length */
4003const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4004{
4005 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004006 unsigned int slen, plen;
4007 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004008
4009 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4010 return NULL;
4011
4012 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4013 return str1;
4014
4015 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4016 return NULL;
4017
4018 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 +02004019 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004020 start++;
4021 slen--;
4022 tmp1++;
4023
4024 if (tmp1 >= len_str1)
4025 return NULL;
4026
4027 /* if pattern longer than string */
4028 if (slen < plen)
4029 return NULL;
4030 }
4031
4032 sptr = start;
4033 pptr = (char *)str2;
4034
4035 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004036 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004037 sptr++;
4038 pptr++;
4039 tmp2++;
4040
4041 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4042 return start;
4043 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4044 return NULL;
4045 }
4046 }
4047 return NULL;
4048}
4049
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004050/* This function read the next valid utf8 char.
4051 * <s> is the byte srray to be decode, <len> is its length.
4052 * The function returns decoded char encoded like this:
4053 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4054 * are the length read. The decoded character is stored in <c>.
4055 */
4056unsigned char utf8_next(const char *s, int len, unsigned int *c)
4057{
4058 const unsigned char *p = (unsigned char *)s;
4059 int dec;
4060 unsigned char code = UTF8_CODE_OK;
4061
4062 if (len < 1)
4063 return UTF8_CODE_OK;
4064
4065 /* Check the type of UTF8 sequence
4066 *
4067 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4068 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4069 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4070 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4071 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4072 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4073 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4074 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4075 */
4076 switch (*p) {
4077 case 0x00 ... 0x7f:
4078 *c = *p;
4079 return UTF8_CODE_OK | 1;
4080
4081 case 0x80 ... 0xbf:
4082 *c = *p;
4083 return UTF8_CODE_BADSEQ | 1;
4084
4085 case 0xc0 ... 0xdf:
4086 if (len < 2) {
4087 *c = *p;
4088 return UTF8_CODE_BADSEQ | 1;
4089 }
4090 *c = *p & 0x1f;
4091 dec = 1;
4092 break;
4093
4094 case 0xe0 ... 0xef:
4095 if (len < 3) {
4096 *c = *p;
4097 return UTF8_CODE_BADSEQ | 1;
4098 }
4099 *c = *p & 0x0f;
4100 dec = 2;
4101 break;
4102
4103 case 0xf0 ... 0xf7:
4104 if (len < 4) {
4105 *c = *p;
4106 return UTF8_CODE_BADSEQ | 1;
4107 }
4108 *c = *p & 0x07;
4109 dec = 3;
4110 break;
4111
4112 case 0xf8 ... 0xfb:
4113 if (len < 5) {
4114 *c = *p;
4115 return UTF8_CODE_BADSEQ | 1;
4116 }
4117 *c = *p & 0x03;
4118 dec = 4;
4119 break;
4120
4121 case 0xfc ... 0xfd:
4122 if (len < 6) {
4123 *c = *p;
4124 return UTF8_CODE_BADSEQ | 1;
4125 }
4126 *c = *p & 0x01;
4127 dec = 5;
4128 break;
4129
4130 case 0xfe ... 0xff:
4131 default:
4132 *c = *p;
4133 return UTF8_CODE_BADSEQ | 1;
4134 }
4135
4136 p++;
4137
4138 while (dec > 0) {
4139
4140 /* need 0x10 for the 2 first bits */
4141 if ( ( *p & 0xc0 ) != 0x80 )
4142 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4143
4144 /* add data at char */
4145 *c = ( *c << 6 ) | ( *p & 0x3f );
4146
4147 dec--;
4148 p++;
4149 }
4150
4151 /* Check ovelong encoding.
4152 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4153 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4154 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4155 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004156 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004157 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4158 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4159 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4160 code |= UTF8_CODE_OVERLONG;
4161
4162 /* Check invalid UTF8 range. */
4163 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4164 (*c >= 0xfffe && *c <= 0xffff))
4165 code |= UTF8_CODE_INVRANGE;
4166
4167 return code | ((p-(unsigned char *)s)&0x0f);
4168}
4169
Maxime de Roucydc887852016-05-13 23:52:54 +02004170/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4171 * On failure : return 0 and <err> filled with an error message.
4172 * The caller is responsible for freeing the <err> and <str> copy
4173 * memory area using free()
4174 */
4175int list_append_word(struct list *li, const char *str, char **err)
4176{
4177 struct wordlist *wl;
4178
4179 wl = calloc(1, sizeof(*wl));
4180 if (!wl) {
4181 memprintf(err, "out of memory");
4182 goto fail_wl;
4183 }
4184
4185 wl->s = strdup(str);
4186 if (!wl->s) {
4187 memprintf(err, "out of memory");
4188 goto fail_wl_s;
4189 }
4190
4191 LIST_ADDQ(li, &wl->list);
4192
4193 return 1;
4194
4195fail_wl_s:
4196 free(wl->s);
4197fail_wl:
4198 free(wl);
4199 return 0;
4200}
4201
Willy Tarreau37101052019-05-20 16:48:20 +02004202/* indicates if a memory location may safely be read or not. The trick consists
4203 * in performing a harmless syscall using this location as an input and letting
4204 * the operating system report whether it's OK or not. For this we have the
4205 * stat() syscall, which will return EFAULT when the memory location supposed
4206 * to contain the file name is not readable. If it is readable it will then
4207 * either return 0 if the area contains an existing file name, or -1 with
4208 * another code. This must not be abused, and some audit systems might detect
4209 * this as abnormal activity. It's used only for unsafe dumps.
4210 */
4211int may_access(const void *ptr)
4212{
4213 struct stat buf;
4214
4215 if (stat(ptr, &buf) == 0)
4216 return 1;
4217 if (errno == EFAULT)
4218 return 0;
4219 return 1;
4220}
4221
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004222/* print a string of text buffer to <out>. The format is :
4223 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4224 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4225 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4226 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004227int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004228{
4229 unsigned char c;
4230 int ptr = 0;
4231
4232 while (buf[ptr] && ptr < bsize) {
4233 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004234 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004235 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004236 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004237 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004238 }
4239 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004240 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004241 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004242 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004243 switch (c) {
4244 case ' ': c = ' '; break;
4245 case '\t': c = 't'; break;
4246 case '\n': c = 'n'; break;
4247 case '\r': c = 'r'; break;
4248 case '\e': c = 'e'; break;
4249 case '\\': c = '\\'; break;
4250 case '=': c = '='; break;
4251 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004252 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004253 }
4254 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004255 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004256 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004257 out->area[out->data++] = '\\';
4258 out->area[out->data++] = 'x';
4259 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4260 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004261 }
4262 ptr++;
4263 }
4264
4265 return ptr;
4266}
4267
4268/* print a buffer in hexa.
4269 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4270 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004271int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004272{
4273 unsigned char c;
4274 int ptr = 0;
4275
4276 while (ptr < bsize) {
4277 c = buf[ptr];
4278
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004279 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004280 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004281 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4282 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004283
4284 ptr++;
4285 }
4286 return ptr;
4287}
4288
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004289/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4290 * prepending each line with prefix <pfx>. The output is *not* initialized.
4291 * The output will not wrap pas the buffer's end so it is more optimal if the
4292 * caller makes sure the buffer is aligned first. A trailing zero will always
4293 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004294 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4295 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004296 */
Willy Tarreau37101052019-05-20 16:48:20 +02004297void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004298{
4299 const unsigned char *d = buf;
4300 int i, j, start;
4301
4302 d = (const unsigned char *)(((unsigned long)buf) & -16);
4303 start = ((unsigned long)buf) & 15;
4304
4305 for (i = 0; i < start + len; i += 16) {
4306 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4307
Willy Tarreau37101052019-05-20 16:48:20 +02004308 // 0: unchecked, 1: checked safe, 2: danger
4309 unsafe = !!unsafe;
4310 if (unsafe && !may_access(d + i))
4311 unsafe = 2;
4312
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004313 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004314 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004315 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004316 else if (unsafe > 1)
4317 chunk_strcat(out, "** ");
4318 else
4319 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004320
4321 if (j == 7)
4322 chunk_strcat(out, "- ");
4323 }
4324 chunk_strcat(out, " ");
4325 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004326 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004327 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004328 else if (unsafe > 1)
4329 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004330 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004331 chunk_appendf(out, "%c", d[i + j]);
4332 else
4333 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004334 }
4335 chunk_strcat(out, "\n");
4336 }
4337}
4338
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004339/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4340 * enclosed in brackets after the address itself, formatted on 14 chars
4341 * including the "0x" prefix. This is meant to be used as a prefix for code
4342 * areas. For example:
4343 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4344 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4345 * is emitted. A NULL <pfx> will be considered empty.
4346 */
4347void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4348{
4349 int ok = 0;
4350 int i;
4351
4352 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4353
4354 for (i = 0; i < n; i++) {
4355 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4356 ok = may_access(addr + i);
4357 if (ok)
4358 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4359 else
4360 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4361 }
4362}
4363
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004364/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4365 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4366 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4367 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4368 * lines are respected within the limit of 70 output chars. Lines that are
4369 * continuation of a previous truncated line begin with "+" instead of " "
4370 * after the offset. The new pointer is returned.
4371 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004372int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004373 int *line, int ptr)
4374{
4375 int end;
4376 unsigned char c;
4377
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004378 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004379 if (end > out->size)
4380 return ptr;
4381
4382 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4383
4384 while (ptr < len && ptr < bsize) {
4385 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004386 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004387 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004388 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004389 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004390 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004391 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004392 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004393 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004394 switch (c) {
4395 case '\t': c = 't'; break;
4396 case '\n': c = 'n'; break;
4397 case '\r': c = 'r'; break;
4398 case '\e': c = 'e'; break;
4399 case '\\': c = '\\'; break;
4400 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004401 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004402 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004403 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004404 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004405 out->area[out->data++] = '\\';
4406 out->area[out->data++] = 'x';
4407 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4408 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004409 }
4410 if (buf[ptr++] == '\n') {
4411 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004412 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004413 *line = ptr;
4414 return ptr;
4415 }
4416 }
4417 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004418 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004419 return ptr;
4420}
4421
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004422/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004423 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4424 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004425 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004426void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4427 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004428{
Willy Tarreau73459792017-04-11 07:58:08 +02004429 unsigned int i;
4430 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004431
4432 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4433 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004434 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004435 for (j = 0; j < 8; j++) {
4436 if (b + j >= 0 && b + j < len)
4437 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4438 else
4439 fprintf(out, " ");
4440 }
4441
4442 if (b + j >= 0 && b + j < len)
4443 fputc('-', out);
4444 else
4445 fputc(' ', out);
4446
4447 for (j = 8; j < 16; j++) {
4448 if (b + j >= 0 && b + j < len)
4449 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4450 else
4451 fprintf(out, " ");
4452 }
4453
4454 fprintf(out, " ");
4455 for (j = 0; j < 16; j++) {
4456 if (b + j >= 0 && b + j < len) {
4457 if (isprint((unsigned char)buf[b + j]))
4458 fputc((unsigned char)buf[b + j], out);
4459 else
4460 fputc('.', out);
4461 }
4462 else
4463 fputc(' ', out);
4464 }
4465 fputc('\n', out);
4466 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004467}
4468
Willy Tarreaubb869862020-04-16 10:52:41 +02004469/* Tries to report the executable path name on platforms supporting this. If
4470 * not found or not possible, returns NULL.
4471 */
4472const char *get_exec_path()
4473{
4474 const char *ret = NULL;
4475
4476#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4477 long execfn = getauxval(AT_EXECFN);
4478
4479 if (execfn && execfn != ENOENT)
4480 ret = (const char *)execfn;
4481#endif
4482 return ret;
4483}
4484
Baruch Siache1651b22020-07-24 07:52:20 +03004485#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004486/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4487 * also returns the symbol size in <size>, otherwise returns 0 there.
4488 */
4489static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4490{
4491 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004492#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004493 const ElfW(Sym) *sym;
4494
4495 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4496 if (ret)
4497 *size = sym ? sym->st_size : 0;
4498#else
4499 ret = dladdr(addr, dli);
4500 *size = 0;
4501#endif
4502 return ret;
4503}
4504#endif
4505
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004506/* Tries to append to buffer <buf> some indications about the symbol at address
4507 * <addr> using the following form:
4508 * lib:+0xoffset (unresolvable address from lib's base)
4509 * main+0xoffset (unresolvable address from main (+/-))
4510 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4511 * name (resolved exact exec address)
4512 * lib:name (resolved exact lib address)
4513 * name+0xoffset/0xsize (resolved address within exec symbol)
4514 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4515 *
4516 * The file name (lib or executable) is limited to what lies between the last
4517 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4518 * 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 +03004519 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004520 *
4521 * The symbol's base address is returned, or NULL when unresolved, in order to
4522 * allow the caller to match it against known ones.
4523 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004524const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004525{
4526 const struct {
4527 const void *func;
4528 const char *name;
4529 } fcts[] = {
4530 { .func = process_stream, .name = "process_stream" },
4531 { .func = task_run_applet, .name = "task_run_applet" },
4532 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4533 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4534 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4535 { .func = listener_accept, .name = "listener_accept" },
4536 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4537 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4538#ifdef USE_LUA
4539 { .func = hlua_process_task, .name = "hlua_process_task" },
4540#endif
4541#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4542 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4543 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4544#endif
4545 };
4546
Baruch Siache1651b22020-07-24 07:52:20 +03004547#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004548 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004549 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004550 const char *fname, *p;
4551#endif
4552 int i;
4553
4554 if (pfx)
4555 chunk_appendf(buf, "%s", pfx);
4556
4557 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4558 if (addr == fcts[i].func) {
4559 chunk_appendf(buf, "%s", fcts[i].name);
4560 return addr;
4561 }
4562 }
4563
Baruch Siache1651b22020-07-24 07:52:20 +03004564#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004565 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004566 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004567 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004568
4569 /* 1. prefix the library name if it's not the same object as the one
4570 * that contains the main function. The name is picked between last '/'
4571 * and first following '.'.
4572 */
4573 if (!dladdr(main, &dli_main))
4574 dli_main.dli_fbase = NULL;
4575
4576 if (dli_main.dli_fbase != dli.dli_fbase) {
4577 fname = dli.dli_fname;
4578 p = strrchr(fname, '/');
4579 if (p++)
4580 fname = p;
4581 p = strchr(fname, '.');
4582 if (!p)
4583 p = fname + strlen(fname);
4584
4585 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4586 }
4587
4588 /* 2. symbol name */
4589 if (dli.dli_sname) {
4590 /* known, dump it and return symbol's address (exact or relative) */
4591 chunk_appendf(buf, "%s", dli.dli_sname);
4592 if (addr != dli.dli_saddr) {
4593 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004594 if (size)
4595 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004596 }
4597 return dli.dli_saddr;
4598 }
4599 else if (dli_main.dli_fbase != dli.dli_fbase) {
4600 /* unresolved symbol from a known library, report relative offset */
4601 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4602 return NULL;
4603 }
Baruch Siache1651b22020-07-24 07:52:20 +03004604#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004605 unknown:
4606 /* unresolved symbol from the main file, report relative offset to main */
4607 if ((void*)addr < (void*)main)
4608 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4609 else
4610 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4611 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004612}
4613
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004614/*
4615 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004616 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004617 *
4618 * First, initializes the value with <sz> as address to 0 and initializes the
4619 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4620 * address updating <sz> pointed value to the size of this array.
4621 *
4622 * Returns 1 if succeeded, 0 if not.
4623 */
4624int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4625{
4626 unsigned int *n;
4627 const char *s, *end;
4628
4629 s = str;
4630 *sz = 0;
4631 end = str + strlen(str);
4632 *nums = n = NULL;
4633
4634 while (1) {
4635 unsigned int r;
4636
4637 if (s >= end)
4638 break;
4639
4640 r = read_uint(&s, end);
4641 /* Expected characters after having read an uint: '\0' or '.',
4642 * if '.', must not be terminal.
4643 */
4644 if (*s != '\0'&& (*s++ != '.' || s == end))
4645 return 0;
4646
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004647 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004648 if (!n)
4649 return 0;
4650
4651 n[(*sz)++] = r;
4652 }
4653 *nums = n;
4654
4655 return 1;
4656}
4657
Willy Tarreau4d589e72019-08-23 19:02:26 +02004658
4659/* returns the number of bytes needed to encode <v> as a varint. An inline
4660 * version exists for use with constants (__varint_bytes()).
4661 */
4662int varint_bytes(uint64_t v)
4663{
4664 int len = 1;
4665
4666 if (v >= 240) {
4667 v = (v - 240) >> 4;
4668 while (1) {
4669 len++;
4670 if (v < 128)
4671 break;
4672 v = (v - 128) >> 7;
4673 }
4674 }
4675 return len;
4676}
4677
Willy Tarreau52bf8392020-03-08 00:42:37 +01004678
4679/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004680static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004681
4682/* This is a thread-safe implementation of xoroshiro128** described below:
4683 * http://prng.di.unimi.it/
4684 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4685 * supports fast jumps and passes all common quality tests. It is thread-safe,
4686 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4687 * local lock on other ones.
4688 */
4689uint64_t ha_random64()
4690{
4691 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004692 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4693 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004694
4695#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4696 static HA_SPINLOCK_T rand_lock;
4697
4698 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4699#endif
4700
4701 old[0] = ha_random_state[0];
4702 old[1] = ha_random_state[1];
4703
4704#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4705 do {
4706#endif
4707 result = rotl64(old[0] * 5, 7) * 9;
4708 new[1] = old[0] ^ old[1];
4709 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4710 new[1] = rotl64(new[1], 37); // c
4711
4712#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4713 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4714#else
4715 ha_random_state[0] = new[0];
4716 ha_random_state[1] = new[1];
4717#if defined(USE_THREAD)
4718 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4719#endif
4720#endif
4721 return result;
4722}
4723
4724/* seeds the random state using up to <len> bytes from <seed>, starting with
4725 * the first non-zero byte.
4726 */
4727void ha_random_seed(const unsigned char *seed, size_t len)
4728{
4729 size_t pos;
4730
4731 /* the seed must not be all zeroes, so we pre-fill it with alternating
4732 * bits and overwrite part of them with the block starting at the first
4733 * non-zero byte from the seed.
4734 */
4735 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4736
4737 for (pos = 0; pos < len; pos++)
4738 if (seed[pos] != 0)
4739 break;
4740
4741 if (pos == len)
4742 return;
4743
4744 seed += pos;
4745 len -= pos;
4746
4747 if (len > sizeof(ha_random_state))
4748 len = sizeof(ha_random_state);
4749
4750 memcpy(ha_random_state, seed, len);
4751}
4752
4753/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4754 * and is equivalent to calling ha_random64() as many times. It is used to
4755 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4756 * different generators (i.e. different processes after a fork). The <dist>
4757 * argument is the distance to jump to and is used in a loop so it rather not
4758 * be too large if the processing time is a concern.
4759 *
4760 * BEWARE: this function is NOT thread-safe and must not be called during
4761 * concurrent accesses to ha_random64().
4762 */
4763void ha_random_jump96(uint32_t dist)
4764{
4765 while (dist--) {
4766 uint64_t s0 = 0;
4767 uint64_t s1 = 0;
4768 int b;
4769
4770 for (b = 0; b < 64; b++) {
4771 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4772 s0 ^= ha_random_state[0];
4773 s1 ^= ha_random_state[1];
4774 }
4775 ha_random64();
4776 }
4777
4778 for (b = 0; b < 64; b++) {
4779 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4780 s0 ^= ha_random_state[0];
4781 s1 ^= ha_random_state[1];
4782 }
4783 ha_random64();
4784 }
4785 ha_random_state[0] = s0;
4786 ha_random_state[1] = s1;
4787 }
4788}
4789
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004790/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4791 * bytes large.
4792 */
4793void ha_generate_uuid(struct buffer *output)
4794{
4795 uint32_t rnd[4];
4796 uint64_t last;
4797
4798 last = ha_random64();
4799 rnd[0] = last;
4800 rnd[1] = last >> 32;
4801
4802 last = ha_random64();
4803 rnd[2] = last;
4804 rnd[3] = last >> 32;
4805
4806 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4807 rnd[0],
4808 rnd[1] & 0xFFFF,
4809 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4810 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4811 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4812}
4813
4814
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004815/* only used by parse_line() below. It supports writing in place provided that
4816 * <in> is updated to the next location before calling it. In that case, the
4817 * char at <in> may be overwritten.
4818 */
4819#define EMIT_CHAR(x) \
4820 do { \
4821 char __c = (char)(x); \
4822 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4823 err |= PARSE_ERR_OVERLAP; \
4824 if (outpos >= outmax) \
4825 err |= PARSE_ERR_TOOLARGE; \
4826 if (!err) \
4827 out[outpos] = __c; \
4828 outpos++; \
4829 } while (0)
4830
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004831/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004832 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4833 * extraneous ones are not emitted but <outlen> is updated so that the caller
4834 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4835 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004836 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4837 * it is guaranteed that at least one arg will point to the zero. It is safe
4838 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004839 *
4840 * <out> may overlap with <in> provided that it never goes further, in which
4841 * case the parser will accept to perform in-place parsing and unquoting/
4842 * unescaping but only if environment variables do not lead to expansion that
4843 * causes overlapping, otherwise the input string being destroyed, the error
4844 * will not be recoverable. Note that even during out-of-place <in> will
4845 * experience temporary modifications in-place for variable resolution and must
4846 * be writable, and will also receive zeroes to delimit words when using
4847 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4848 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4849 * starting point of the first invalid character sequence or unmatched
4850 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4851 * error reporting might be difficult since zeroes will have been inserted into
4852 * the string. One solution for the caller may consist in replacing all args
4853 * delimiters with spaces in this case.
4854 */
4855uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4856{
4857 char *quote = NULL;
4858 char *brace = NULL;
4859 unsigned char hex1, hex2;
4860 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004861 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004862 size_t outpos = 0;
4863 int squote = 0;
4864 int dquote = 0;
4865 int arg = 0;
4866 uint32_t err = 0;
4867
4868 *nbargs = 0;
4869 *outlen = 0;
4870
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004871 /* argsmax may be -1 here, protecting args[] from any write */
4872 if (arg < argsmax)
4873 args[arg] = out;
4874
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004875 while (1) {
4876 if (*in >= '-' && *in != '\\') {
4877 /* speedup: directly send all regular chars starting
4878 * with '-', '.', '/', alnum etc...
4879 */
4880 EMIT_CHAR(*in++);
4881 continue;
4882 }
4883 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4884 /* end of line */
4885 break;
4886 }
4887 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4888 /* comment */
4889 break;
4890 }
4891 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4892 if (dquote) {
4893 dquote = 0;
4894 quote = NULL;
4895 }
4896 else {
4897 dquote = 1;
4898 quote = in;
4899 }
4900 in++;
4901 continue;
4902 }
4903 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4904 if (squote) {
4905 squote = 0;
4906 quote = NULL;
4907 }
4908 else {
4909 squote = 1;
4910 quote = in;
4911 }
4912 in++;
4913 continue;
4914 }
4915 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4916 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4917 * C equivalent value but only when they have a special meaning and within
4918 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4919 */
4920 char tosend = *in;
4921
4922 switch (in[1]) {
4923 case ' ':
4924 case '\\':
4925 tosend = in[1];
4926 in++;
4927 break;
4928
4929 case 't':
4930 tosend = '\t';
4931 in++;
4932 break;
4933
4934 case 'n':
4935 tosend = '\n';
4936 in++;
4937 break;
4938
4939 case 'r':
4940 tosend = '\r';
4941 in++;
4942 break;
4943
4944 case '#':
4945 /* escaping of "#" only if comments are supported */
4946 if (opts & PARSE_OPT_SHARP)
4947 in++;
4948 tosend = *in;
4949 break;
4950
4951 case '\'':
4952 /* escaping of "'" only outside single quotes and only if single quotes are supported */
4953 if (opts & PARSE_OPT_SQUOTE && !squote)
4954 in++;
4955 tosend = *in;
4956 break;
4957
4958 case '"':
4959 /* escaping of '"' only outside single quotes and only if double quotes are supported */
4960 if (opts & PARSE_OPT_DQUOTE && !squote)
4961 in++;
4962 tosend = *in;
4963 break;
4964
4965 case '$':
4966 /* escaping of '$' only inside double quotes and only if env supported */
4967 if (opts & PARSE_OPT_ENV && dquote)
4968 in++;
4969 tosend = *in;
4970 break;
4971
4972 case 'x':
4973 if (!ishex(in[2]) || !ishex(in[3])) {
4974 /* invalid or incomplete hex sequence */
4975 err |= PARSE_ERR_HEX;
4976 if (errptr)
4977 *errptr = in;
4978 goto leave;
4979 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02004980 hex1 = toupper((unsigned char)in[2]) - '0';
4981 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004982 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
4983 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
4984 tosend = (hex1 << 4) + hex2;
4985 in += 3;
4986 break;
4987
4988 default:
4989 /* other combinations are not escape sequences */
4990 break;
4991 }
4992
4993 in++;
4994 EMIT_CHAR(tosend);
4995 }
4996 else if (isspace((unsigned char)*in) && !squote && !dquote) {
4997 /* a non-escaped space is an argument separator */
4998 while (isspace((unsigned char)*in))
4999 in++;
5000 EMIT_CHAR(0);
5001 arg++;
5002 if (arg < argsmax)
5003 args[arg] = out + outpos;
5004 else
5005 err |= PARSE_ERR_TOOMANY;
5006 }
5007 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5008 /* environment variables are evaluated anywhere, or only
5009 * inside double quotes if they are supported.
5010 */
5011 char *var_name;
5012 char save_char;
5013 char *value;
5014
5015 in++;
5016
5017 if (*in == '{')
5018 brace = in++;
5019
5020 if (!isalpha((unsigned char)*in) && *in != '_') {
5021 /* unacceptable character in variable name */
5022 err |= PARSE_ERR_VARNAME;
5023 if (errptr)
5024 *errptr = in;
5025 goto leave;
5026 }
5027
5028 var_name = in;
5029 while (isalnum((unsigned char)*in) || *in == '_')
5030 in++;
5031
5032 save_char = *in;
5033 *in = '\0';
5034 value = getenv(var_name);
5035 *in = save_char;
5036
5037 if (brace) {
5038 if (*in != '}') {
5039 /* unmatched brace */
5040 err |= PARSE_ERR_BRACE;
5041 if (errptr)
5042 *errptr = brace;
5043 goto leave;
5044 }
5045 in++;
5046 brace = NULL;
5047 }
5048
5049 if (value) {
5050 while (*value)
5051 EMIT_CHAR(*value++);
5052 }
5053 }
5054 else {
5055 /* any other regular char */
5056 EMIT_CHAR(*in++);
5057 }
5058 }
5059
5060 /* end of output string */
5061 EMIT_CHAR(0);
5062 arg++;
5063
5064 if (quote) {
5065 /* unmatched quote */
5066 err |= PARSE_ERR_QUOTE;
5067 if (errptr)
5068 *errptr = quote;
5069 goto leave;
5070 }
5071 leave:
5072 *nbargs = arg;
5073 *outlen = outpos;
5074
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005075 /* empty all trailing args by making them point to the trailing zero,
5076 * at least the last one in any case.
5077 */
5078 if (arg > argsmax)
5079 arg = argsmax;
5080
5081 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005082 args[arg++] = out + outpos - 1;
5083
5084 return err;
5085}
5086#undef EMIT_CHAR
5087
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005088/* This is used to sanitize an input line that's about to be used for error reporting.
5089 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5090 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5091 * If non-printable chars are present in the output. It returns the new offset <pos>
5092 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5093 * be at least 6 to support two "..." otherwise the result is undefined. The line
5094 * itself must have at least 7 chars allocated for the same reason.
5095 */
5096size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5097{
5098 size_t shift = 0;
5099 char *out = line;
5100 char *in = line;
5101 char *end = line + width;
5102
5103 if (pos >= width) {
5104 /* if we have to shift, we'll be out of context, so let's
5105 * try to put <pos> at the center of width.
5106 */
5107 shift = pos - width / 2;
5108 in += shift + 3;
5109 end = out + width - 3;
5110 out[0] = out[1] = out[2] = '.';
5111 out += 3;
5112 }
5113
5114 while (out < end && *in) {
5115 if (isspace((unsigned char)*in))
5116 *out++ = ' ';
5117 else if (isprint((unsigned char)*in))
5118 *out++ = *in;
5119 else
5120 *out++ = '?';
5121 in++;
5122 }
5123
5124 if (end < line + width) {
5125 out[0] = out[1] = out[2] = '.';
5126 out += 3;
5127 }
5128
5129 *out++ = 0;
5130 return pos - shift;
5131}
5132
Willy Tarreaubaaee002006-06-26 02:48:02 +02005133/*
5134 * Local variables:
5135 * c-indent-level: 8
5136 * c-basic-offset: 8
5137 * End:
5138 */