blob: 0c4366408b7e0d8c4aef64ce494179eb7bc72f7e [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 Tarreaue835bd82020-09-16 11:35:47 +0200880 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100881
882 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200883 if (fqdn)
884 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200885
Willy Tarreaudad36a32013-03-11 01:20:04 +0100886 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100887 if (str2 == NULL) {
888 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100889 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100890 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200891
Willy Tarreau9f69f462015-09-08 16:01:25 +0200892 if (!*str2) {
893 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
894 goto out;
895 }
896
Willy Tarreau24709282013-03-10 21:32:12 +0100897 memset(&ss, 0, sizeof(ss));
898
Willy Tarreaue835bd82020-09-16 11:35:47 +0200899 /* prepare the default socket types */
900 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM)
901 sock_type = ctrl_type = SOCK_DGRAM;
902 else
903 sock_type = ctrl_type = SOCK_STREAM;
904
905 if (strncmp(str2, "stream+", 7) == 0) {
906 str2 += 7;
907 sock_type = ctrl_type = SOCK_STREAM;
908 }
909 else if (strncmp(str2, "dgram+", 6) == 0) {
910 str2 += 6;
911 sock_type = ctrl_type = SOCK_DGRAM;
912 }
913
Willy Tarreau24709282013-03-10 21:32:12 +0100914 if (strncmp(str2, "unix@", 5) == 0) {
915 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200916 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100917 ss.ss_family = AF_UNIX;
918 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200919 else if (strncmp(str2, "abns@", 5) == 0) {
920 str2 += 5;
921 abstract = 1;
922 ss.ss_family = AF_UNIX;
923 }
Willy Tarreau24709282013-03-10 21:32:12 +0100924 else if (strncmp(str2, "ipv4@", 5) == 0) {
925 str2 += 5;
926 ss.ss_family = AF_INET;
927 }
928 else if (strncmp(str2, "ipv6@", 5) == 0) {
929 str2 += 5;
930 ss.ss_family = AF_INET6;
931 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200932 else if (strncmp(str2, "udp4@", 5) == 0) {
933 str2 += 5;
934 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200935 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200936 is_udp = 1;
937 }
938 else if (strncmp(str2, "udp6@", 5) == 0) {
939 str2 += 5;
940 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200941 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200942 is_udp = 1;
943 }
944 else if (strncmp(str2, "udp@", 4) == 0) {
945 str2 += 4;
946 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200947 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200948 is_udp = 1;
949 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200950 else if (strncmp(str2, "fd@", 3) == 0) {
951 str2 += 3;
952 ss.ss_family = AF_CUST_EXISTING_FD;
953 }
954 else if (strncmp(str2, "sockpair@", 9) == 0) {
955 str2 += 9;
956 ss.ss_family = AF_CUST_SOCKPAIR;
957 }
Willy Tarreau24709282013-03-10 21:32:12 +0100958 else if (*str2 == '/') {
959 ss.ss_family = AF_UNIX;
960 }
961 else
962 ss.ss_family = AF_UNSPEC;
963
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200964 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200965 struct sockaddr_storage ss2;
966 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200967 char *endptr;
968
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200969 new_fd = strtol(str2, &endptr, 10);
970 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200971 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
972 goto out;
973 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200974
Willy Tarreaua215be22020-09-16 10:14:16 +0200975 /* just verify that it's a socket */
976 addr_len = sizeof(ss2);
977 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
978 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
979 goto out;
980 }
981
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200982 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
983 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200984 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200985 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100986 char *endptr;
987
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200988 new_fd = strtol(str2, &endptr, 10);
989 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100990 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100991 goto out;
992 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200993
Willy Tarreau6edc7222020-09-15 17:41:56 +0200994 if (opts & PA_O_SOCKET_FD) {
995 socklen_t addr_len;
996 int type;
997
998 addr_len = sizeof(ss);
999 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1000 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1001 goto out;
1002 }
1003
1004 addr_len = sizeof(type);
1005 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001006 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001007 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1008 goto out;
1009 }
1010
1011 porta = portl = porth = get_host_port(&ss);
1012 } else if (opts & PA_O_RAW_FD) {
1013 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1014 ((struct sockaddr_in *)&ss)->sin_port = 0;
1015 } else {
1016 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1017 goto out;
1018 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001019 }
1020 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001021 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001022 int prefix_path_len;
1023 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001024 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001025
1026 /* complete unix socket path name during startup or soft-restart is
1027 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1028 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001029 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001030 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001031 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001032
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001033 adr_len = strlen(str2);
1034 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001035 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1036 goto out;
1037 }
1038
Willy Tarreauccfccef2014-05-10 01:49:15 +02001039 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001040 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001041 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001042 memcpy(un->sun_path, pfx, prefix_path_len);
1043 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001044 }
Willy Tarreau24709282013-03-10 21:32:12 +01001045 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001046 char *end = str2 + strlen(str2);
1047 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001048
mildisff5d5102015-10-26 18:50:08 +01001049 /* search for : or ] whatever comes first */
1050 for (chr = end-1; chr > str2; chr--) {
1051 if (*chr == ']' || *chr == ':')
1052 break;
1053 }
1054
1055 if (*chr == ':') {
1056 /* Found a colon before a closing-bracket, must be a port separator.
1057 * This guarantee backward compatibility.
1058 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001059 if (!(opts & PA_O_PORT_OK)) {
1060 memprintf(err, "port specification not permitted here in '%s'", str);
1061 goto out;
1062 }
mildisff5d5102015-10-26 18:50:08 +01001063 *chr++ = '\0';
1064 port1 = chr;
1065 }
1066 else {
1067 /* Either no colon and no closing-bracket
1068 * or directly ending with a closing-bracket.
1069 * However, no port.
1070 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001071 if (opts & PA_O_PORT_MAND) {
1072 memprintf(err, "missing port specification in '%s'", str);
1073 goto out;
1074 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001075 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001076 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001077
Willy Tarreau90807112020-02-25 08:16:33 +01001078 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001079 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001080 if (port2) {
1081 if (!(opts & PA_O_PORT_RANGE)) {
1082 memprintf(err, "port range not permitted here in '%s'", str);
1083 goto out;
1084 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001085 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001086 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001087 else
1088 port2 = port1;
1089 portl = atoi(port1);
1090 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001091
1092 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1093 memprintf(err, "invalid port '%s'", port1);
1094 goto out;
1095 }
1096
1097 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1098 memprintf(err, "invalid port '%s'", port2);
1099 goto out;
1100 }
1101
1102 if (portl > porth) {
1103 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1104 goto out;
1105 }
1106
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001107 porta = portl;
1108 }
1109 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001110 if (!(opts & PA_O_PORT_OFS)) {
1111 memprintf(err, "port offset not permitted here in '%s'", str);
1112 goto out;
1113 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001114 portl = atoi(port1 + 1);
1115 porta = -portl;
1116 }
1117 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001118 if (!(opts & PA_O_PORT_OFS)) {
1119 memprintf(err, "port offset not permitted here in '%s'", str);
1120 goto out;
1121 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001122 porth = atoi(port1 + 1);
1123 porta = porth;
1124 }
1125 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001126 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001127 goto out;
1128 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001129 else if (opts & PA_O_PORT_MAND) {
1130 memprintf(err, "missing port specification in '%s'", str);
1131 goto out;
1132 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001133
1134 /* first try to parse the IP without resolving. If it fails, it
1135 * tells us we need to keep a copy of the FQDN to resolve later
1136 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001137 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001138 */
1139 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001140 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1141 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001142 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1143 goto out;
1144 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001145
Willy Tarreauceccdd72016-11-02 22:27:10 +01001146 if (fqdn) {
1147 if (str2 != back)
1148 memmove(back, str2, strlen(str2) + 1);
1149 *fqdn = back;
1150 back = NULL;
1151 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001152 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001153 set_host_port(&ss, porta);
Emeric Brun3835c0d2020-07-07 09:46:09 +02001154 if (is_udp) {
1155 if (ss.ss_family == AF_INET6)
1156 ss.ss_family = AF_CUST_UDP6;
1157 else
1158 ss.ss_family = AF_CUST_UDP4;
1159 }
1160
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001161 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001162
Willy Tarreaue835bd82020-09-16 11:35:47 +02001163 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1164 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1165 goto out;
1166 }
1167 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1168 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1169 goto out;
1170 }
1171
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001172 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001173 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001174 if (port)
1175 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001176 if (low)
1177 *low = portl;
1178 if (high)
1179 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001180 if (fd)
1181 *fd = new_fd;
Willy Tarreau24709282013-03-10 21:32:12 +01001182 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001183 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001184}
1185
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001186/* converts <str> to a struct in_addr containing a network mask. It can be
1187 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001188 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001189 */
1190int str2mask(const char *str, struct in_addr *mask)
1191{
1192 if (strchr(str, '.') != NULL) { /* dotted notation */
1193 if (!inet_pton(AF_INET, str, mask))
1194 return 0;
1195 }
1196 else { /* mask length */
1197 char *err;
1198 unsigned long len = strtol(str, &err, 10);
1199
1200 if (!*str || (err && *err) || (unsigned)len > 32)
1201 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001202
1203 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001204 }
1205 return 1;
1206}
1207
Tim Duesterhus47185172018-01-25 16:24:49 +01001208/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001209 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001210 * if the conversion succeeds otherwise zero.
1211 */
1212int str2mask6(const char *str, struct in6_addr *mask)
1213{
1214 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1215 if (!inet_pton(AF_INET6, str, mask))
1216 return 0;
1217 }
1218 else { /* mask length */
1219 char *err;
1220 unsigned long len = strtol(str, &err, 10);
1221
1222 if (!*str || (err && *err) || (unsigned)len > 128)
1223 return 0;
1224
1225 len2mask6(len, mask);
1226 }
1227 return 1;
1228}
1229
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001230/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1231 * succeeds otherwise zero.
1232 */
1233int cidr2dotted(int cidr, struct in_addr *mask) {
1234
1235 if (cidr < 0 || cidr > 32)
1236 return 0;
1237
1238 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1239 return 1;
1240}
1241
Thierry Fournier70473a52016-02-17 17:12:14 +01001242/* Convert mask from bit length form to in_addr form.
1243 * This function never fails.
1244 */
1245void len2mask4(int len, struct in_addr *addr)
1246{
1247 if (len >= 32) {
1248 addr->s_addr = 0xffffffff;
1249 return;
1250 }
1251 if (len <= 0) {
1252 addr->s_addr = 0x00000000;
1253 return;
1254 }
1255 addr->s_addr = 0xffffffff << (32 - len);
1256 addr->s_addr = htonl(addr->s_addr);
1257}
1258
1259/* Convert mask from bit length form to in6_addr form.
1260 * This function never fails.
1261 */
1262void len2mask6(int len, struct in6_addr *addr)
1263{
1264 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1265 len -= 32;
1266 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1267 len -= 32;
1268 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1269 len -= 32;
1270 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1271}
1272
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001273/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001274 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001275 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001276 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001277 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1278 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001279int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001280{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001281 __label__ out_free, out_err;
1282 char *c, *s;
1283 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001284
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001285 s = strdup(str);
1286 if (!s)
1287 return 0;
1288
Willy Tarreaubaaee002006-06-26 02:48:02 +02001289 memset(mask, 0, sizeof(*mask));
1290 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001291
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001292 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001293 *c++ = '\0';
1294 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001295 if (!str2mask(c, mask))
1296 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001297 }
1298 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001299 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001300 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001301 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001302 struct hostent *he;
1303
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001304 if (!resolve)
1305 goto out_err;
1306
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001307 if ((he = gethostbyname(s)) == NULL) {
1308 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001309 }
1310 else
1311 *addr = *(struct in_addr *) *(he->h_addr_list);
1312 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001313
1314 ret_val = 1;
1315 out_free:
1316 free(s);
1317 return ret_val;
1318 out_err:
1319 ret_val = 0;
1320 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001321}
1322
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001323
1324/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001325 * converts <str> to two struct in6_addr* which must be pre-allocated.
1326 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001327 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001328 * Returns 1 if OK, 0 if error.
1329 */
1330int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1331{
1332 char *c, *s;
1333 int ret_val = 0;
1334 char *err;
1335 unsigned long len = 128;
1336
1337 s = strdup(str);
1338 if (!s)
1339 return 0;
1340
1341 memset(mask, 0, sizeof(*mask));
1342 memset(addr, 0, sizeof(*addr));
1343
1344 if ((c = strrchr(s, '/')) != NULL) {
1345 *c++ = '\0'; /* c points to the mask */
1346 if (!*c)
1347 goto out_free;
1348
1349 len = strtoul(c, &err, 10);
1350 if ((err && *err) || (unsigned)len > 128)
1351 goto out_free;
1352 }
1353 *mask = len; /* OK we have a valid mask in <len> */
1354
1355 if (!inet_pton(AF_INET6, s, addr))
1356 goto out_free;
1357
1358 ret_val = 1;
1359 out_free:
1360 free(s);
1361 return ret_val;
1362}
1363
1364
1365/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001366 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001367 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001368int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001369{
1370 int saw_digit, octets, ch;
1371 u_char tmp[4], *tp;
1372 const char *cp = addr;
1373
1374 saw_digit = 0;
1375 octets = 0;
1376 *(tp = tmp) = 0;
1377
1378 while (*addr) {
1379 unsigned char digit = (ch = *addr++) - '0';
1380 if (digit > 9 && ch != '.')
1381 break;
1382 if (digit <= 9) {
1383 u_int new = *tp * 10 + digit;
1384 if (new > 255)
1385 return 0;
1386 *tp = new;
1387 if (!saw_digit) {
1388 if (++octets > 4)
1389 return 0;
1390 saw_digit = 1;
1391 }
1392 } else if (ch == '.' && saw_digit) {
1393 if (octets == 4)
1394 return 0;
1395 *++tp = 0;
1396 saw_digit = 0;
1397 } else
1398 return 0;
1399 }
1400
1401 if (octets < 4)
1402 return 0;
1403
1404 memcpy(&dst->s_addr, tmp, 4);
1405 return addr-cp-1;
1406}
1407
1408/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001409 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001410 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001411 * the hostname. Actually only http and https are supported. <out> can be NULL.
1412 * This function returns the consumed length. It is useful if you parse complete
1413 * url like http://host:port/path, because the consumed length corresponds to
1414 * the first character of the path. If the conversion fails, it returns -1.
1415 *
1416 * This function tries to resolve the DNS name if haproxy is in starting mode.
1417 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001418 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001419int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001420{
1421 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001422 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001423 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001424 unsigned long long int http_code = 0;
1425 int default_port;
1426 struct hostent *he;
1427 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001428
1429 /* Firstly, try to find :// pattern */
1430 while (curr < url+ulen && url_code != 0x3a2f2f) {
1431 url_code = ((url_code & 0xffff) << 8);
1432 url_code += (unsigned char)*curr++;
1433 }
1434
1435 /* Secondly, if :// pattern is found, verify parsed stuff
1436 * before pattern is matching our http pattern.
1437 * If so parse ip address and port in uri.
1438 *
1439 * WARNING: Current code doesn't support dynamic async dns resolver.
1440 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001441 if (url_code != 0x3a2f2f)
1442 return -1;
1443
1444 /* Copy scheme, and utrn to lower case. */
1445 while (cp < curr - 3)
1446 http_code = (http_code << 8) + *cp++;
1447 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001448
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001449 /* HTTP or HTTPS url matching */
1450 if (http_code == 0x2020202068747470ULL) {
1451 default_port = 80;
1452 if (out)
1453 out->scheme = SCH_HTTP;
1454 }
1455 else if (http_code == 0x2020206874747073ULL) {
1456 default_port = 443;
1457 if (out)
1458 out->scheme = SCH_HTTPS;
1459 }
1460 else
1461 return -1;
1462
1463 /* If the next char is '[', the host address is IPv6. */
1464 if (*curr == '[') {
1465 curr++;
1466
1467 /* Check trash size */
1468 if (trash.size < ulen)
1469 return -1;
1470
1471 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001472 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001473 for (end = curr;
1474 end < url + ulen && *end != ']';
1475 end++, p++)
1476 *p = *end;
1477 if (*end != ']')
1478 return -1;
1479 *p = '\0';
1480
1481 /* Update out. */
1482 if (out) {
1483 out->host = curr;
1484 out->host_len = end - curr;
1485 }
1486
1487 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001488 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001489 return -1;
1490 end++;
1491
1492 /* Decode port. */
1493 if (*end == ':') {
1494 end++;
1495 default_port = read_uint(&end, url + ulen);
1496 }
1497 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1498 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1499 return end - url;
1500 }
1501 else {
1502 /* We are looking for IP address. If you want to parse and
1503 * resolve hostname found in url, you can use str2sa_range(), but
1504 * be warned this can slow down global daemon performances
1505 * while handling lagging dns responses.
1506 */
1507 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1508 if (ret) {
1509 /* Update out. */
1510 if (out) {
1511 out->host = curr;
1512 out->host_len = ret;
1513 }
1514
1515 curr += ret;
1516
1517 /* Decode port. */
1518 if (*curr == ':') {
1519 curr++;
1520 default_port = read_uint(&curr, url + ulen);
1521 }
1522 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1523
1524 /* Set family. */
1525 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1526 return curr - url;
1527 }
1528 else if (global.mode & MODE_STARTING) {
1529 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1530 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001531 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001532
1533 /* look for : or / or end */
1534 for (end = curr;
1535 end < url + ulen && *end != '/' && *end != ':';
1536 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001537 memcpy(trash.area, curr, end - curr);
1538 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001539
1540 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001541 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001542 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001543 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001544
1545 /* Update out. */
1546 if (out) {
1547 out->host = curr;
1548 out->host_len = end - curr;
1549 }
1550
1551 /* Decode port. */
1552 if (*end == ':') {
1553 end++;
1554 default_port = read_uint(&end, url + ulen);
1555 }
1556
1557 /* Copy IP address, set port and family. */
1558 switch (he->h_addrtype) {
1559 case AF_INET:
1560 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1561 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1562 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1563 return end - url;
1564
1565 case AF_INET6:
1566 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1567 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1568 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1569 return end - url;
1570 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001571 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001572 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001573 return -1;
1574}
1575
Willy Tarreau631f01c2011-09-05 00:36:48 +02001576/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1577 * address family is returned so that it's easy for the caller to adapt to the
1578 * output format. Zero is returned if the address family is not supported. -1
1579 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1580 * supported.
1581 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001582int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001583{
1584
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001585 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001586
1587 if (size < 5)
1588 return 0;
1589 *str = '\0';
1590
1591 switch (addr->ss_family) {
1592 case AF_INET:
1593 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1594 break;
1595 case AF_INET6:
1596 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1597 break;
1598 case AF_UNIX:
1599 memcpy(str, "unix", 5);
1600 return addr->ss_family;
1601 default:
1602 return 0;
1603 }
1604
1605 if (inet_ntop(addr->ss_family, ptr, str, size))
1606 return addr->ss_family;
1607
1608 /* failed */
1609 return -1;
1610}
1611
Simon Horman75ab8bd2014-06-16 09:39:41 +09001612/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1613 * address family is returned so that it's easy for the caller to adapt to the
1614 * output format. Zero is returned if the address family is not supported. -1
1615 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1616 * supported.
1617 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001618int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001619{
1620
1621 uint16_t port;
1622
1623
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001624 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001625 return 0;
1626 *str = '\0';
1627
1628 switch (addr->ss_family) {
1629 case AF_INET:
1630 port = ((struct sockaddr_in *)addr)->sin_port;
1631 break;
1632 case AF_INET6:
1633 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1634 break;
1635 case AF_UNIX:
1636 memcpy(str, "unix", 5);
1637 return addr->ss_family;
1638 default:
1639 return 0;
1640 }
1641
1642 snprintf(str, size, "%u", ntohs(port));
1643 return addr->ss_family;
1644}
1645
Willy Tarreau16e01562016-08-09 16:46:18 +02001646/* check if the given address is local to the system or not. It will return
1647 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1648 * it is. We don't want to iterate over all interfaces for this (and it is not
1649 * portable). So instead we try to bind in UDP to this address on a free non
1650 * privileged port and to connect to the same address, port 0 (connect doesn't
1651 * care). If it succeeds, we own the address. Note that non-inet addresses are
1652 * considered local since they're most likely AF_UNIX.
1653 */
1654int addr_is_local(const struct netns_entry *ns,
1655 const struct sockaddr_storage *orig)
1656{
1657 struct sockaddr_storage addr;
1658 int result;
1659 int fd;
1660
1661 if (!is_inet_addr(orig))
1662 return 1;
1663
1664 memcpy(&addr, orig, sizeof(addr));
1665 set_host_port(&addr, 0);
1666
1667 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1668 if (fd < 0)
1669 return -1;
1670
1671 result = -1;
1672 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1673 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1674 result = 0; // fail, non-local address
1675 else
1676 result = 1; // success, local address
1677 }
1678 else {
1679 if (errno == EADDRNOTAVAIL)
1680 result = 0; // definitely not local :-)
1681 }
1682 close(fd);
1683
1684 return result;
1685}
1686
Willy Tarreaubaaee002006-06-26 02:48:02 +02001687/* will try to encode the string <string> replacing all characters tagged in
1688 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1689 * prefixed by <escape>, and will store the result between <start> (included)
1690 * and <stop> (excluded), and will always terminate the string with a '\0'
1691 * before <stop>. The position of the '\0' is returned if the conversion
1692 * completes. If bytes are missing between <start> and <stop>, then the
1693 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1694 * cannot even be stored so we return <start> without writing the 0.
1695 * The input string must also be zero-terminated.
1696 */
1697const char hextab[16] = "0123456789ABCDEF";
1698char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001699 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001700 const char *string)
1701{
1702 if (start < stop) {
1703 stop--; /* reserve one byte for the final '\0' */
1704 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001705 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001706 *start++ = *string;
1707 else {
1708 if (start + 3 >= stop)
1709 break;
1710 *start++ = escape;
1711 *start++ = hextab[(*string >> 4) & 15];
1712 *start++ = hextab[*string & 15];
1713 }
1714 string++;
1715 }
1716 *start = '\0';
1717 }
1718 return start;
1719}
1720
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001721/*
1722 * Same behavior as encode_string() above, except that it encodes chunk
1723 * <chunk> instead of a string.
1724 */
1725char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001726 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001727 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001728{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001729 char *str = chunk->area;
1730 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001731
1732 if (start < stop) {
1733 stop--; /* reserve one byte for the final '\0' */
1734 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001735 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001736 *start++ = *str;
1737 else {
1738 if (start + 3 >= stop)
1739 break;
1740 *start++ = escape;
1741 *start++ = hextab[(*str >> 4) & 15];
1742 *start++ = hextab[*str & 15];
1743 }
1744 str++;
1745 }
1746 *start = '\0';
1747 }
1748 return start;
1749}
1750
Dragan Dosen0edd1092016-02-12 13:23:02 +01001751/*
1752 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001753 * character. The input <string> must be zero-terminated. The result will
1754 * be stored between <start> (included) and <stop> (excluded). This
1755 * function will always try to terminate the resulting string with a '\0'
1756 * before <stop>, and will return its position if the conversion
1757 * completes.
1758 */
1759char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001760 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001761 const char *string)
1762{
1763 if (start < stop) {
1764 stop--; /* reserve one byte for the final '\0' */
1765 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001766 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001767 *start++ = *string;
1768 else {
1769 if (start + 2 >= stop)
1770 break;
1771 *start++ = escape;
1772 *start++ = *string;
1773 }
1774 string++;
1775 }
1776 *start = '\0';
1777 }
1778 return start;
1779}
1780
1781/*
1782 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001783 * character. <chunk> contains the input to be escaped. The result will be
1784 * stored between <start> (included) and <stop> (excluded). The function
1785 * will always try to terminate the resulting string with a '\0' before
1786 * <stop>, and will return its position if the conversion completes.
1787 */
1788char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001789 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001790 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001791{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001792 char *str = chunk->area;
1793 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001794
1795 if (start < stop) {
1796 stop--; /* reserve one byte for the final '\0' */
1797 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001798 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001799 *start++ = *str;
1800 else {
1801 if (start + 2 >= stop)
1802 break;
1803 *start++ = escape;
1804 *start++ = *str;
1805 }
1806 str++;
1807 }
1808 *start = '\0';
1809 }
1810 return start;
1811}
1812
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001813/* Check a string for using it in a CSV output format. If the string contains
1814 * one of the following four char <">, <,>, CR or LF, the string is
1815 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1816 * <str> is the input string to be escaped. The function assumes that
1817 * the input string is null-terminated.
1818 *
1819 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001820 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001821 * format.
1822 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001823 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001824 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001825 * If <quote> is 1, the converter puts the quotes only if any reserved character
1826 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001827 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001828 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001829 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001830 * The function returns the converted string on its output. If an error
1831 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001832 * for using the function directly as printf() argument.
1833 *
1834 * If the output buffer is too short to contain the input string, the result
1835 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001836 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001837 * This function appends the encoding to the existing output chunk, and it
1838 * guarantees that it starts immediately at the first available character of
1839 * the chunk. Please use csv_enc() instead if you want to replace the output
1840 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001841 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001842const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001843{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001844 char *end = output->area + output->size;
1845 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001846 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001847
Willy Tarreaub631c292016-01-08 10:04:08 +01001848 if (quote == 1) {
1849 /* automatic quoting: first verify if we'll have to quote the string */
1850 if (!strpbrk(str, "\n\r,\""))
1851 quote = 0;
1852 }
1853
1854 if (quote)
1855 *ptr++ = '"';
1856
Willy Tarreau898529b2016-01-06 18:07:04 +01001857 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1858 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001859 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001860 ptr++;
1861 if (ptr >= end - 2) {
1862 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001863 break;
1864 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001865 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001866 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001867 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001868 str++;
1869 }
1870
Willy Tarreaub631c292016-01-08 10:04:08 +01001871 if (quote)
1872 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001873
Willy Tarreau898529b2016-01-06 18:07:04 +01001874 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001875 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001876 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001877}
1878
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001879/* Decode an URL-encoded string in-place. The resulting string might
1880 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001881 * aborted, the string is truncated before the issue and a negative value is
1882 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001883 * If the 'in_form' argument is non-nul the string is assumed to be part of
1884 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1885 * turned to a space. If it's zero, this will only be done after a question
1886 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001887 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001888int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001889{
1890 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001891 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001892
1893 in = string;
1894 out = string;
1895 while (*in) {
1896 switch (*in) {
1897 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001898 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001899 break;
1900 case '%' :
1901 if (!ishex(in[1]) || !ishex(in[2]))
1902 goto end;
1903 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1904 in += 2;
1905 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001906 case '?':
1907 in_form = 1;
1908 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001909 default:
1910 *out++ = *in;
1911 break;
1912 }
1913 in++;
1914 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001915 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001916 end:
1917 *out = 0;
1918 return ret;
1919}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001920
Willy Tarreau6911fa42007-03-04 18:06:08 +01001921unsigned int str2ui(const char *s)
1922{
1923 return __str2ui(s);
1924}
1925
1926unsigned int str2uic(const char *s)
1927{
1928 return __str2uic(s);
1929}
1930
1931unsigned int strl2ui(const char *s, int len)
1932{
1933 return __strl2ui(s, len);
1934}
1935
1936unsigned int strl2uic(const char *s, int len)
1937{
1938 return __strl2uic(s, len);
1939}
1940
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001941unsigned int read_uint(const char **s, const char *end)
1942{
1943 return __read_uint(s, end);
1944}
1945
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001946/* This function reads an unsigned integer from the string pointed to by <s> and
1947 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1948 * function automatically stops at <end>. If the number overflows, the 2^64-1
1949 * value is returned.
1950 */
1951unsigned long long int read_uint64(const char **s, const char *end)
1952{
1953 const char *ptr = *s;
1954 unsigned long long int i = 0, tmp;
1955 unsigned int j;
1956
1957 while (ptr < end) {
1958
1959 /* read next char */
1960 j = *ptr - '0';
1961 if (j > 9)
1962 goto read_uint64_end;
1963
1964 /* add char to the number and check overflow. */
1965 tmp = i * 10;
1966 if (tmp / 10 != i) {
1967 i = ULLONG_MAX;
1968 goto read_uint64_eat;
1969 }
1970 if (ULLONG_MAX - tmp < j) {
1971 i = ULLONG_MAX;
1972 goto read_uint64_eat;
1973 }
1974 i = tmp + j;
1975 ptr++;
1976 }
1977read_uint64_eat:
1978 /* eat each numeric char */
1979 while (ptr < end) {
1980 if ((unsigned int)(*ptr - '0') > 9)
1981 break;
1982 ptr++;
1983 }
1984read_uint64_end:
1985 *s = ptr;
1986 return i;
1987}
1988
1989/* This function reads an integer from the string pointed to by <s> and returns
1990 * it. The <s> pointer is adjusted to point to the first unread char. The function
1991 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1992 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1993 * returned.
1994 */
1995long long int read_int64(const char **s, const char *end)
1996{
1997 unsigned long long int i = 0;
1998 int neg = 0;
1999
2000 /* Look for minus char. */
2001 if (**s == '-') {
2002 neg = 1;
2003 (*s)++;
2004 }
2005 else if (**s == '+')
2006 (*s)++;
2007
2008 /* convert as positive number. */
2009 i = read_uint64(s, end);
2010
2011 if (neg) {
2012 if (i > 0x8000000000000000ULL)
2013 return LLONG_MIN;
2014 return -i;
2015 }
2016 if (i > 0x7fffffffffffffffULL)
2017 return LLONG_MAX;
2018 return i;
2019}
2020
Willy Tarreau6911fa42007-03-04 18:06:08 +01002021/* This one is 7 times faster than strtol() on athlon with checks.
2022 * It returns the value of the number composed of all valid digits read,
2023 * and can process negative numbers too.
2024 */
2025int strl2ic(const char *s, int len)
2026{
2027 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002028 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002029
2030 if (len > 0) {
2031 if (*s != '-') {
2032 /* positive number */
2033 while (len-- > 0) {
2034 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002035 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002036 if (j > 9)
2037 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002038 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002039 }
2040 } else {
2041 /* negative number */
2042 s++;
2043 while (--len > 0) {
2044 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002045 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002046 if (j > 9)
2047 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002048 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002049 }
2050 }
2051 }
2052 return i;
2053}
2054
2055
2056/* This function reads exactly <len> chars from <s> and converts them to a
2057 * signed integer which it stores into <ret>. It accurately detects any error
2058 * (truncated string, invalid chars, overflows). It is meant to be used in
2059 * applications designed for hostile environments. It returns zero when the
2060 * number has successfully been converted, non-zero otherwise. When an error
2061 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2062 * faster than strtol().
2063 */
2064int strl2irc(const char *s, int len, int *ret)
2065{
2066 int i = 0;
2067 int j;
2068
2069 if (!len)
2070 return 1;
2071
2072 if (*s != '-') {
2073 /* positive number */
2074 while (len-- > 0) {
2075 j = (*s++) - '0';
2076 if (j > 9) return 1; /* invalid char */
2077 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2078 i = i * 10;
2079 if (i + j < i) return 1; /* check for addition overflow */
2080 i = i + j;
2081 }
2082 } else {
2083 /* negative number */
2084 s++;
2085 while (--len > 0) {
2086 j = (*s++) - '0';
2087 if (j > 9) return 1; /* invalid char */
2088 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2089 i = i * 10;
2090 if (i - j > i) return 1; /* check for subtract overflow */
2091 i = i - j;
2092 }
2093 }
2094 *ret = i;
2095 return 0;
2096}
2097
2098
2099/* This function reads exactly <len> chars from <s> and converts them to a
2100 * signed integer which it stores into <ret>. It accurately detects any error
2101 * (truncated string, invalid chars, overflows). It is meant to be used in
2102 * applications designed for hostile environments. It returns zero when the
2103 * number has successfully been converted, non-zero otherwise. When an error
2104 * is returned, the <ret> value is left untouched. It is about 3 times slower
2105 * than str2irc().
2106 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002107
2108int strl2llrc(const char *s, int len, long long *ret)
2109{
2110 long long i = 0;
2111 int j;
2112
2113 if (!len)
2114 return 1;
2115
2116 if (*s != '-') {
2117 /* positive number */
2118 while (len-- > 0) {
2119 j = (*s++) - '0';
2120 if (j > 9) return 1; /* invalid char */
2121 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2122 i = i * 10LL;
2123 if (i + j < i) return 1; /* check for addition overflow */
2124 i = i + j;
2125 }
2126 } else {
2127 /* negative number */
2128 s++;
2129 while (--len > 0) {
2130 j = (*s++) - '0';
2131 if (j > 9) return 1; /* invalid char */
2132 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2133 i = i * 10LL;
2134 if (i - j > i) return 1; /* check for subtract overflow */
2135 i = i - j;
2136 }
2137 }
2138 *ret = i;
2139 return 0;
2140}
2141
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002142/* This function is used with pat_parse_dotted_ver(). It converts a string
2143 * composed by two number separated by a dot. Each part must contain in 16 bits
2144 * because internally they will be represented as a 32-bit quantity stored in
2145 * a 64-bit integer. It returns zero when the number has successfully been
2146 * converted, non-zero otherwise. When an error is returned, the <ret> value
2147 * is left untouched.
2148 *
2149 * "1.3" -> 0x0000000000010003
2150 * "65535.65535" -> 0x00000000ffffffff
2151 */
2152int strl2llrc_dotted(const char *text, int len, long long *ret)
2153{
2154 const char *end = &text[len];
2155 const char *p;
2156 long long major, minor;
2157
2158 /* Look for dot. */
2159 for (p = text; p < end; p++)
2160 if (*p == '.')
2161 break;
2162
2163 /* Convert major. */
2164 if (strl2llrc(text, p - text, &major) != 0)
2165 return 1;
2166
2167 /* Check major. */
2168 if (major >= 65536)
2169 return 1;
2170
2171 /* Convert minor. */
2172 minor = 0;
2173 if (p < end)
2174 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2175 return 1;
2176
2177 /* Check minor. */
2178 if (minor >= 65536)
2179 return 1;
2180
2181 /* Compose value. */
2182 *ret = (major << 16) | (minor & 0xffff);
2183 return 0;
2184}
2185
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002186/* This function parses a time value optionally followed by a unit suffix among
2187 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2188 * expected by the caller. The computation does its best to avoid overflows.
2189 * The value is returned in <ret> if everything is fine, and a NULL is returned
2190 * by the function. In case of error, a pointer to the error is returned and
2191 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002192 * Values resulting in values larger than or equal to 2^31 after conversion are
2193 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2194 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002195 */
2196const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2197{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002198 unsigned long long imult, idiv;
2199 unsigned long long omult, odiv;
2200 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002201
2202 omult = odiv = 1;
2203
2204 switch (unit_flags & TIME_UNIT_MASK) {
2205 case TIME_UNIT_US: omult = 1000000; break;
2206 case TIME_UNIT_MS: omult = 1000; break;
2207 case TIME_UNIT_S: break;
2208 case TIME_UNIT_MIN: odiv = 60; break;
2209 case TIME_UNIT_HOUR: odiv = 3600; break;
2210 case TIME_UNIT_DAY: odiv = 86400; break;
2211 default: break;
2212 }
2213
2214 value = 0;
2215
2216 while (1) {
2217 unsigned int j;
2218
2219 j = *text - '0';
2220 if (j > 9)
2221 break;
2222 text++;
2223 value *= 10;
2224 value += j;
2225 }
2226
2227 imult = idiv = 1;
2228 switch (*text) {
2229 case '\0': /* no unit = default unit */
2230 imult = omult = idiv = odiv = 1;
2231 break;
2232 case 's': /* second = unscaled unit */
2233 break;
2234 case 'u': /* microsecond : "us" */
2235 if (text[1] == 's') {
2236 idiv = 1000000;
2237 text++;
2238 }
2239 break;
2240 case 'm': /* millisecond : "ms" or minute: "m" */
2241 if (text[1] == 's') {
2242 idiv = 1000;
2243 text++;
2244 } else
2245 imult = 60;
2246 break;
2247 case 'h': /* hour : "h" */
2248 imult = 3600;
2249 break;
2250 case 'd': /* day : "d" */
2251 imult = 86400;
2252 break;
2253 default:
2254 return text;
2255 break;
2256 }
2257
2258 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2259 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2260 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2261 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2262
Willy Tarreau9faebe32019-06-07 19:00:37 +02002263 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2264 if (result >= 0x80000000)
2265 return PARSE_TIME_OVER;
2266 if (!result && value)
2267 return PARSE_TIME_UNDER;
2268 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002269 return NULL;
2270}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002271
Emeric Brun39132b22010-01-04 14:57:24 +01002272/* this function converts the string starting at <text> to an unsigned int
2273 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002274 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002275 */
2276const char *parse_size_err(const char *text, unsigned *ret) {
2277 unsigned value = 0;
2278
2279 while (1) {
2280 unsigned int j;
2281
2282 j = *text - '0';
2283 if (j > 9)
2284 break;
2285 if (value > ~0U / 10)
2286 return text;
2287 value *= 10;
2288 if (value > (value + j))
2289 return text;
2290 value += j;
2291 text++;
2292 }
2293
2294 switch (*text) {
2295 case '\0':
2296 break;
2297 case 'K':
2298 case 'k':
2299 if (value > ~0U >> 10)
2300 return text;
2301 value = value << 10;
2302 break;
2303 case 'M':
2304 case 'm':
2305 if (value > ~0U >> 20)
2306 return text;
2307 value = value << 20;
2308 break;
2309 case 'G':
2310 case 'g':
2311 if (value > ~0U >> 30)
2312 return text;
2313 value = value << 30;
2314 break;
2315 default:
2316 return text;
2317 }
2318
Godbach58048a22015-01-28 17:36:16 +08002319 if (*text != '\0' && *++text != '\0')
2320 return text;
2321
Emeric Brun39132b22010-01-04 14:57:24 +01002322 *ret = value;
2323 return NULL;
2324}
2325
Willy Tarreau126d4062013-12-03 17:50:47 +01002326/*
2327 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002328 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002329 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002330 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002331 */
2332int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2333{
2334 int len;
2335 const char *p = source;
2336 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002337 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002338
2339 len = strlen(source);
2340 if (len % 2) {
2341 memprintf(err, "an even number of hex digit is expected");
2342 return 0;
2343 }
2344
2345 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002346
Willy Tarreau126d4062013-12-03 17:50:47 +01002347 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002348 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002349 if (!*binstr) {
2350 memprintf(err, "out of memory while loading string pattern");
2351 return 0;
2352 }
2353 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002354 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002355 else {
2356 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002357 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002358 len, *binstrlen);
2359 return 0;
2360 }
2361 alloc = 0;
2362 }
2363 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002364
2365 i = j = 0;
2366 while (j < len) {
2367 if (!ishex(p[i++]))
2368 goto bad_input;
2369 if (!ishex(p[i++]))
2370 goto bad_input;
2371 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2372 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002373 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002374
2375bad_input:
2376 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002377 if (alloc) {
2378 free(*binstr);
2379 *binstr = NULL;
2380 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002381 return 0;
2382}
2383
Willy Tarreau946ba592009-05-10 15:41:18 +02002384/* copies at most <n> characters from <src> and always terminates with '\0' */
2385char *my_strndup(const char *src, int n)
2386{
2387 int len = 0;
2388 char *ret;
2389
2390 while (len < n && src[len])
2391 len++;
2392
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002393 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002394 if (!ret)
2395 return ret;
2396 memcpy(ret, src, len);
2397 ret[len] = '\0';
2398 return ret;
2399}
2400
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002401/*
2402 * search needle in haystack
2403 * returns the pointer if found, returns NULL otherwise
2404 */
2405const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2406{
2407 const void *c = NULL;
2408 unsigned char f;
2409
2410 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2411 return NULL;
2412
2413 f = *(char *)needle;
2414 c = haystack;
2415 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2416 if ((haystacklen - (c - haystack)) < needlelen)
2417 return NULL;
2418
2419 if (memcmp(c, needle, needlelen) == 0)
2420 return c;
2421 ++c;
2422 }
2423 return NULL;
2424}
2425
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002426/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002427size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2428{
2429 size_t ret = 0;
2430
2431 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2432 str++;
2433 ret++;
2434 }
2435 return ret;
2436}
2437
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002438/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002439size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2440{
2441 size_t ret = 0;
2442
2443 while (ret < len) {
2444 if(memchr(reject, *((int *)str), rejectlen))
2445 return ret;
2446 str++;
2447 ret++;
2448 }
2449 return ret;
2450}
2451
Willy Tarreau482b00d2009-10-04 22:48:42 +02002452/* This function returns the first unused key greater than or equal to <key> in
2453 * ID tree <root>. Zero is returned if no place is found.
2454 */
2455unsigned int get_next_id(struct eb_root *root, unsigned int key)
2456{
2457 struct eb32_node *used;
2458
2459 do {
2460 used = eb32_lookup_ge(root, key);
2461 if (!used || used->key > key)
2462 return key; /* key is available */
2463 key++;
2464 } while (key);
2465 return key;
2466}
2467
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002468/* dump the full tree to <file> in DOT format for debugging purposes. Will
2469 * optionally highlight node <subj> if found, depending on operation <op> :
2470 * 0 : nothing
2471 * >0 : insertion, node/leaf are surrounded in red
2472 * <0 : removal, node/leaf are dashed with no background
2473 * Will optionally add "desc" as a label on the graph if set and non-null.
2474 */
2475void 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 +01002476{
2477 struct eb32sc_node *node;
2478 unsigned long scope = -1;
2479
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002480 fprintf(file, "digraph ebtree {\n");
2481
2482 if (desc && *desc) {
2483 fprintf(file,
2484 " fontname=\"fixed\";\n"
2485 " fontsize=8;\n"
2486 " label=\"%s\";\n", desc);
2487 }
2488
Willy Tarreaued3cda02017-11-15 15:04:05 +01002489 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002490 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2491 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002492 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2493 );
2494
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002495 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002496 (long)eb_root_to_node(root),
2497 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002498 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2499
2500 node = eb32sc_first(root, scope);
2501 while (node) {
2502 if (node->node.node_p) {
2503 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002504 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2505 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2506 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002507
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002508 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002509 (long)node,
2510 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002511 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002512
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002513 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002514 (long)node,
2515 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002516 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2517
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002518 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002519 (long)node,
2520 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002521 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2522 }
2523
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002524 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2525 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2526 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002527
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002528 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002529 (long)node,
2530 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002531 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002532 node = eb32sc_next(node, scope);
2533 }
2534 fprintf(file, "}\n");
2535}
2536
Willy Tarreau348238b2010-01-18 15:05:57 +01002537/* This function compares a sample word possibly followed by blanks to another
2538 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2539 * otherwise zero. This intends to be used when checking HTTP headers for some
2540 * values. Note that it validates a word followed only by blanks but does not
2541 * validate a word followed by blanks then other chars.
2542 */
2543int word_match(const char *sample, int slen, const char *word, int wlen)
2544{
2545 if (slen < wlen)
2546 return 0;
2547
2548 while (wlen) {
2549 char c = *sample ^ *word;
2550 if (c && c != ('A' ^ 'a'))
2551 return 0;
2552 sample++;
2553 word++;
2554 slen--;
2555 wlen--;
2556 }
2557
2558 while (slen) {
2559 if (*sample != ' ' && *sample != '\t')
2560 return 0;
2561 sample++;
2562 slen--;
2563 }
2564 return 1;
2565}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002566
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002567/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2568 * is particularly fast because it avoids expensive operations such as
2569 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002570 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002571 */
2572unsigned int inetaddr_host(const char *text)
2573{
2574 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2575 register unsigned int dig100, dig10, dig1;
2576 int s;
2577 const char *p, *d;
2578
2579 dig1 = dig10 = dig100 = ascii_zero;
2580 s = 24;
2581
2582 p = text;
2583 while (1) {
2584 if (((unsigned)(*p - '0')) <= 9) {
2585 p++;
2586 continue;
2587 }
2588
2589 /* here, we have a complete byte between <text> and <p> (exclusive) */
2590 if (p == text)
2591 goto end;
2592
2593 d = p - 1;
2594 dig1 |= (unsigned int)(*d << s);
2595 if (d == text)
2596 goto end;
2597
2598 d--;
2599 dig10 |= (unsigned int)(*d << s);
2600 if (d == text)
2601 goto end;
2602
2603 d--;
2604 dig100 |= (unsigned int)(*d << s);
2605 end:
2606 if (!s || *p != '.')
2607 break;
2608
2609 s -= 8;
2610 text = ++p;
2611 }
2612
2613 dig100 -= ascii_zero;
2614 dig10 -= ascii_zero;
2615 dig1 -= ascii_zero;
2616 return ((dig100 * 10) + dig10) * 10 + dig1;
2617}
2618
2619/*
2620 * Idem except the first unparsed character has to be passed in <stop>.
2621 */
2622unsigned int inetaddr_host_lim(const char *text, const char *stop)
2623{
2624 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2625 register unsigned int dig100, dig10, dig1;
2626 int s;
2627 const char *p, *d;
2628
2629 dig1 = dig10 = dig100 = ascii_zero;
2630 s = 24;
2631
2632 p = text;
2633 while (1) {
2634 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2635 p++;
2636 continue;
2637 }
2638
2639 /* here, we have a complete byte between <text> and <p> (exclusive) */
2640 if (p == text)
2641 goto end;
2642
2643 d = p - 1;
2644 dig1 |= (unsigned int)(*d << s);
2645 if (d == text)
2646 goto end;
2647
2648 d--;
2649 dig10 |= (unsigned int)(*d << s);
2650 if (d == text)
2651 goto end;
2652
2653 d--;
2654 dig100 |= (unsigned int)(*d << s);
2655 end:
2656 if (!s || p == stop || *p != '.')
2657 break;
2658
2659 s -= 8;
2660 text = ++p;
2661 }
2662
2663 dig100 -= ascii_zero;
2664 dig10 -= ascii_zero;
2665 dig1 -= ascii_zero;
2666 return ((dig100 * 10) + dig10) * 10 + dig1;
2667}
2668
2669/*
2670 * Idem except the pointer to first unparsed byte is returned into <ret> which
2671 * must not be NULL.
2672 */
Willy Tarreau74172752010-10-15 23:21:42 +02002673unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002674{
2675 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2676 register unsigned int dig100, dig10, dig1;
2677 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002678 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002679
2680 dig1 = dig10 = dig100 = ascii_zero;
2681 s = 24;
2682
2683 p = text;
2684 while (1) {
2685 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2686 p++;
2687 continue;
2688 }
2689
2690 /* here, we have a complete byte between <text> and <p> (exclusive) */
2691 if (p == text)
2692 goto end;
2693
2694 d = p - 1;
2695 dig1 |= (unsigned int)(*d << s);
2696 if (d == text)
2697 goto end;
2698
2699 d--;
2700 dig10 |= (unsigned int)(*d << s);
2701 if (d == text)
2702 goto end;
2703
2704 d--;
2705 dig100 |= (unsigned int)(*d << s);
2706 end:
2707 if (!s || p == stop || *p != '.')
2708 break;
2709
2710 s -= 8;
2711 text = ++p;
2712 }
2713
2714 *ret = p;
2715 dig100 -= ascii_zero;
2716 dig10 -= ascii_zero;
2717 dig1 -= ascii_zero;
2718 return ((dig100 * 10) + dig10) * 10 + dig1;
2719}
2720
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002721/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2722 * or the number of chars read in case of success. Maybe this could be replaced
2723 * by one of the functions above. Also, apparently this function does not support
2724 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002725 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002726 */
2727int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2728{
2729 const char *addr;
2730 int saw_digit, octets, ch;
2731 u_char tmp[4], *tp;
2732 const char *cp = buf;
2733
2734 saw_digit = 0;
2735 octets = 0;
2736 *(tp = tmp) = 0;
2737
2738 for (addr = buf; addr - buf < len; addr++) {
2739 unsigned char digit = (ch = *addr) - '0';
2740
2741 if (digit > 9 && ch != '.')
2742 break;
2743
2744 if (digit <= 9) {
2745 u_int new = *tp * 10 + digit;
2746
2747 if (new > 255)
2748 return 0;
2749
2750 *tp = new;
2751
2752 if (!saw_digit) {
2753 if (++octets > 4)
2754 return 0;
2755 saw_digit = 1;
2756 }
2757 } else if (ch == '.' && saw_digit) {
2758 if (octets == 4)
2759 return 0;
2760
2761 *++tp = 0;
2762 saw_digit = 0;
2763 } else
2764 return 0;
2765 }
2766
2767 if (octets < 4)
2768 return 0;
2769
2770 memcpy(&dst->s_addr, tmp, 4);
2771 return addr - cp;
2772}
2773
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002774/* This function converts the string in <buf> of the len <len> to
2775 * struct in6_addr <dst> which must be allocated by the caller.
2776 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002777 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002778 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002779int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2780{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002781 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002782 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002783
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002784 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002785 return 0;
2786
2787 memcpy(null_term_ip6, buf, len);
2788 null_term_ip6[len] = '\0';
2789
Willy Tarreau075415a2013-12-12 11:29:39 +01002790 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002791 return 0;
2792
Willy Tarreau075415a2013-12-12 11:29:39 +01002793 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002794 return 1;
2795}
2796
Willy Tarreauacf95772010-06-14 19:09:21 +02002797/* To be used to quote config arg positions. Returns the short string at <ptr>
2798 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2799 * if ptr is NULL or empty. The string is locally allocated.
2800 */
2801const char *quote_arg(const char *ptr)
2802{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002803 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002804 int i;
2805
2806 if (!ptr || !*ptr)
2807 return "end of line";
2808 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002809 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002810 val[i] = *ptr++;
2811 val[i++] = '\'';
2812 val[i] = '\0';
2813 return val;
2814}
2815
Willy Tarreau5b180202010-07-18 10:40:48 +02002816/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2817int get_std_op(const char *str)
2818{
2819 int ret = -1;
2820
2821 if (*str == 'e' && str[1] == 'q')
2822 ret = STD_OP_EQ;
2823 else if (*str == 'n' && str[1] == 'e')
2824 ret = STD_OP_NE;
2825 else if (*str == 'l') {
2826 if (str[1] == 'e') ret = STD_OP_LE;
2827 else if (str[1] == 't') ret = STD_OP_LT;
2828 }
2829 else if (*str == 'g') {
2830 if (str[1] == 'e') ret = STD_OP_GE;
2831 else if (str[1] == 't') ret = STD_OP_GT;
2832 }
2833
2834 if (ret == -1 || str[2] != '\0')
2835 return -1;
2836 return ret;
2837}
2838
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002839/* hash a 32-bit integer to another 32-bit integer */
2840unsigned int full_hash(unsigned int a)
2841{
2842 return __full_hash(a);
2843}
2844
Willy Tarreauf3241112019-02-26 09:56:22 +01002845/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2846 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2847 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2848 * a popcount variant and is described here :
2849 * https://graphics.stanford.edu/~seander/bithacks.html
2850 */
2851unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2852{
2853 unsigned long a, b, c, d;
2854 unsigned int s;
2855 unsigned int t;
2856
2857 a = m - ((m >> 1) & ~0UL/3);
2858 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2859 c = (b + (b >> 4)) & ~0UL/0x11;
2860 d = (c + (c >> 8)) & ~0UL/0x101;
2861
2862 r++; // make r be 1..64
2863
2864 t = 0;
2865 s = LONGBITS;
2866 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002867 unsigned long d2 = (d >> 16) >> 16;
2868 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002869 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2870 }
2871
2872 t = (d >> (s - 16)) & 0xff;
2873 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2874 t = (c >> (s - 8)) & 0xf;
2875 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2876 t = (b >> (s - 4)) & 0x7;
2877 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2878 t = (a >> (s - 2)) & 0x3;
2879 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2880 t = (m >> (s - 1)) & 0x1;
2881 s -= ((t - r) & 256) >> 8;
2882
2883 return s - 1;
2884}
2885
2886/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2887 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2888 * using mask_prep_rank_map() below.
2889 */
2890unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2891 unsigned long a, unsigned long b,
2892 unsigned long c, unsigned long d)
2893{
2894 unsigned int s;
2895 unsigned int t;
2896
2897 r++; // make r be 1..64
2898
2899 t = 0;
2900 s = LONGBITS;
2901 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002902 unsigned long d2 = (d >> 16) >> 16;
2903 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002904 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2905 }
2906
2907 t = (d >> (s - 16)) & 0xff;
2908 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2909 t = (c >> (s - 8)) & 0xf;
2910 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2911 t = (b >> (s - 4)) & 0x7;
2912 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2913 t = (a >> (s - 2)) & 0x3;
2914 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2915 t = (m >> (s - 1)) & 0x1;
2916 s -= ((t - r) & 256) >> 8;
2917
2918 return s - 1;
2919}
2920
2921/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2922 * above.
2923 */
2924void mask_prep_rank_map(unsigned long m,
2925 unsigned long *a, unsigned long *b,
2926 unsigned long *c, unsigned long *d)
2927{
2928 *a = m - ((m >> 1) & ~0UL/3);
2929 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2930 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2931 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2932}
2933
David du Colombier4f92d322011-03-24 11:09:31 +01002934/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002935 * otherwise zero. Note that <addr> may not necessarily be aligned
2936 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002937 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002938int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002939{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002940 struct in_addr addr_copy;
2941
2942 memcpy(&addr_copy, addr, sizeof(addr_copy));
2943 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002944}
2945
2946/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002947 * otherwise zero. Note that <addr> may not necessarily be aligned
2948 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002949 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002950int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002951{
2952 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002953 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002954
Willy Tarreaueec1d382016-07-13 11:59:39 +02002955 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002956 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002957 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002958 (((int *)net)[i] & ((int *)mask)[i]))
2959 return 0;
2960 return 1;
2961}
2962
2963/* RFC 4291 prefix */
2964const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2965 0x00, 0x00, 0x00, 0x00,
2966 0x00, 0x00, 0xFF, 0xFF };
2967
Joseph Herlant32b83272018-11-15 11:58:28 -08002968/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002969 * Input and output may overlap.
2970 */
David du Colombier4f92d322011-03-24 11:09:31 +01002971void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2972{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002973 struct in_addr tmp_addr;
2974
2975 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002976 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002977 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002978}
2979
Joseph Herlant32b83272018-11-15 11:58:28 -08002980/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002981 * Return true if conversion is possible and false otherwise.
2982 */
2983int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2984{
2985 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2986 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2987 sizeof(struct in_addr));
2988 return 1;
2989 }
2990
2991 return 0;
2992}
2993
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002994/* compare two struct sockaddr_storage and return:
2995 * 0 (true) if the addr is the same in both
2996 * 1 (false) if the addr is not the same in both
2997 * -1 (unable) if one of the addr is not AF_INET*
2998 */
2999int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3000{
3001 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3002 return -1;
3003
3004 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3005 return -1;
3006
3007 if (ss1->ss_family != ss2->ss_family)
3008 return 1;
3009
3010 switch (ss1->ss_family) {
3011 case AF_INET:
3012 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3013 &((struct sockaddr_in *)ss2)->sin_addr,
3014 sizeof(struct in_addr)) != 0;
3015 case AF_INET6:
3016 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3017 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3018 sizeof(struct in6_addr)) != 0;
3019 }
3020
3021 return 1;
3022}
3023
Baptiste Assmann08396c82016-01-31 00:27:17 +01003024/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003025 * The caller must allocate and clear <dest> before calling.
3026 * The source must be in either AF_INET or AF_INET6 family, or the destination
3027 * address will be undefined. If the destination address used to hold a port,
3028 * it is preserved, so that this function can be used to switch to another
3029 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003030 */
3031struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3032{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003033 int prev_port;
3034
3035 prev_port = get_net_port(dest);
3036 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003037 dest->ss_family = source->ss_family;
3038
3039 /* copy new addr and apply it */
3040 switch (source->ss_family) {
3041 case AF_INET:
3042 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003043 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003044 break;
3045 case AF_INET6:
3046 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 +01003047 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003048 break;
3049 }
3050
3051 return dest;
3052}
3053
William Lallemand421f5b52012-02-06 18:15:57 +01003054char *human_time(int t, short hz_div) {
3055 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3056 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003057 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003058 int cnt=2; // print two numbers
3059
3060 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003061 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003062 return rv;
3063 }
3064
3065 if (unlikely(hz_div > 1))
3066 t /= hz_div;
3067
3068 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003069 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003070 cnt--;
3071 }
3072
3073 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003074 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003075 cnt--;
3076 }
3077
3078 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003079 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003080 cnt--;
3081 }
3082
3083 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003084 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003085
3086 return rv;
3087}
3088
3089const char *monthname[12] = {
3090 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3091 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3092};
3093
3094/* date2str_log: write a date in the format :
3095 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3096 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3097 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3098 *
3099 * without using sprintf. return a pointer to the last char written (\0) or
3100 * NULL if there isn't enough space.
3101 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003102char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003103{
3104
3105 if (size < 25) /* the size is fixed: 24 chars + \0 */
3106 return NULL;
3107
3108 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003109 if (!dst)
3110 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003111 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003112
William Lallemand421f5b52012-02-06 18:15:57 +01003113 memcpy(dst, monthname[tm->tm_mon], 3); // month
3114 dst += 3;
3115 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003116
William Lallemand421f5b52012-02-06 18:15:57 +01003117 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003118 if (!dst)
3119 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003120 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003121
William Lallemand421f5b52012-02-06 18:15:57 +01003122 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003123 if (!dst)
3124 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003125 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003126
William Lallemand421f5b52012-02-06 18:15:57 +01003127 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003128 if (!dst)
3129 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003130 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003131
William Lallemand421f5b52012-02-06 18:15:57 +01003132 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003133 if (!dst)
3134 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003135 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003136
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003137 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003138 if (!dst)
3139 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003140 *dst = '\0';
3141
3142 return dst;
3143}
3144
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003145/* Base year used to compute leap years */
3146#define TM_YEAR_BASE 1900
3147
3148/* Return the difference in seconds between two times (leap seconds are ignored).
3149 * Retrieved from glibc 2.18 source code.
3150 */
3151static int my_tm_diff(const struct tm *a, const struct tm *b)
3152{
3153 /* Compute intervening leap days correctly even if year is negative.
3154 * Take care to avoid int overflow in leap day calculations,
3155 * but it's OK to assume that A and B are close to each other.
3156 */
3157 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3158 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3159 int a100 = a4 / 25 - (a4 % 25 < 0);
3160 int b100 = b4 / 25 - (b4 % 25 < 0);
3161 int a400 = a100 >> 2;
3162 int b400 = b100 >> 2;
3163 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3164 int years = a->tm_year - b->tm_year;
3165 int days = (365 * years + intervening_leap_days
3166 + (a->tm_yday - b->tm_yday));
3167 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3168 + (a->tm_min - b->tm_min))
3169 + (a->tm_sec - b->tm_sec));
3170}
3171
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003172/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003173 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003174 * The string returned has the same format as returned by strftime(... "%z", tm).
3175 * Offsets are kept in an internal cache for better performances.
3176 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003177const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003178{
3179 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003180 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003181
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003182 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003183 struct tm tm_gmt;
3184 int diff;
3185 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003186
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003187 /* Pretend DST not active if its status is unknown */
3188 if (isdst < 0)
3189 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003190
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003191 /* Fetch the offset and initialize it if needed */
3192 gmt_offset = gmt_offsets[isdst & 0x01];
3193 if (unlikely(!*gmt_offset)) {
3194 get_gmtime(t, &tm_gmt);
3195 diff = my_tm_diff(tm, &tm_gmt);
3196 if (diff < 0) {
3197 diff = -diff;
3198 *gmt_offset = '-';
3199 } else {
3200 *gmt_offset = '+';
3201 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003202 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003203 diff /= 60; /* Convert to minutes */
3204 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3205 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003206
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003207 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003208}
3209
William Lallemand421f5b52012-02-06 18:15:57 +01003210/* gmt2str_log: write a date in the format :
3211 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3212 * return a pointer to the last char written (\0) or
3213 * NULL if there isn't enough space.
3214 */
3215char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3216{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003217 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003218 return NULL;
3219
3220 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003221 if (!dst)
3222 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003223 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003224
William Lallemand421f5b52012-02-06 18:15:57 +01003225 memcpy(dst, monthname[tm->tm_mon], 3); // month
3226 dst += 3;
3227 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003228
William Lallemand421f5b52012-02-06 18:15:57 +01003229 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003230 if (!dst)
3231 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003232 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003233
William Lallemand421f5b52012-02-06 18:15:57 +01003234 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003235 if (!dst)
3236 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003237 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003238
William Lallemand421f5b52012-02-06 18:15:57 +01003239 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003240 if (!dst)
3241 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003242 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003243
William Lallemand421f5b52012-02-06 18:15:57 +01003244 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003245 if (!dst)
3246 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003247 *dst++ = ' ';
3248 *dst++ = '+';
3249 *dst++ = '0';
3250 *dst++ = '0';
3251 *dst++ = '0';
3252 *dst++ = '0';
3253 *dst = '\0';
3254
3255 return dst;
3256}
3257
Yuxans Yao4e25b012012-10-19 10:36:09 +08003258/* localdate2str_log: write a date in the format :
3259 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003260 * Both t and tm must represent the same time.
3261 * return a pointer to the last char written (\0) or
3262 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003263 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003264char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003265{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003266 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003267 if (size < 27) /* the size is fixed: 26 chars + \0 */
3268 return NULL;
3269
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003270 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003271
Yuxans Yao4e25b012012-10-19 10:36:09 +08003272 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003273 if (!dst)
3274 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003275 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003276
Yuxans Yao4e25b012012-10-19 10:36:09 +08003277 memcpy(dst, monthname[tm->tm_mon], 3); // month
3278 dst += 3;
3279 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003280
Yuxans Yao4e25b012012-10-19 10:36:09 +08003281 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003282 if (!dst)
3283 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003284 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003285
Yuxans Yao4e25b012012-10-19 10:36:09 +08003286 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003287 if (!dst)
3288 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003289 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003290
Yuxans Yao4e25b012012-10-19 10:36:09 +08003291 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003292 if (!dst)
3293 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003294 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003295
Yuxans Yao4e25b012012-10-19 10:36:09 +08003296 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003297 if (!dst)
3298 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003299 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003300
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003301 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003302 dst += 5;
3303 *dst = '\0';
3304
3305 return dst;
3306}
3307
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003308/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3309 * It is meant as a portable replacement for timegm() for use with valid inputs.
3310 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3311 */
3312time_t my_timegm(const struct tm *tm)
3313{
3314 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3315 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3316 * sum of the extra N days for elapsed months. The sum of all these N
3317 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3318 * in a 5-bit word. This means that with 60 bits we can represent a
3319 * matrix of all these values at once, which is fast and efficient to
3320 * access. The extra February day for leap years is not counted here.
3321 *
3322 * Jan : none = 0 (0)
3323 * Feb : Jan = 3 (3)
3324 * Mar : Jan..Feb = 3 (3 + 0)
3325 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3326 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3327 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3328 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3329 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3330 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3331 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3332 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3333 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3334 */
3335 uint64_t extra =
3336 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3337 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3338 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3339 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3340
3341 unsigned int y = tm->tm_year + 1900;
3342 unsigned int m = tm->tm_mon;
3343 unsigned long days = 0;
3344
3345 /* days since 1/1/1970 for full years */
3346 days += days_since_zero(y) - days_since_zero(1970);
3347
3348 /* days for full months in the current year */
3349 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3350
3351 /* count + 1 after March for leap years. A leap year is a year multiple
3352 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3353 * is leap, 1900 isn't, 1904 is.
3354 */
3355 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3356 days++;
3357
3358 days += tm->tm_mday - 1;
3359 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3360}
3361
Thierry Fournier93127942016-01-20 18:49:45 +01003362/* This function check a char. It returns true and updates
3363 * <date> and <len> pointer to the new position if the
3364 * character is found.
3365 */
3366static inline int parse_expect_char(const char **date, int *len, char c)
3367{
3368 if (*len < 1 || **date != c)
3369 return 0;
3370 (*len)--;
3371 (*date)++;
3372 return 1;
3373}
3374
3375/* This function expects a string <str> of len <l>. It return true and updates.
3376 * <date> and <len> if the string matches, otherwise, it returns false.
3377 */
3378static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3379{
3380 if (*len < l || strncmp(*date, str, l) != 0)
3381 return 0;
3382 (*len) -= l;
3383 (*date) += l;
3384 return 1;
3385}
3386
3387/* This macro converts 3 chars name in integer. */
3388#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3389
3390/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3391 * / %x54.75.65 ; "Tue", case-sensitive
3392 * / %x57.65.64 ; "Wed", case-sensitive
3393 * / %x54.68.75 ; "Thu", case-sensitive
3394 * / %x46.72.69 ; "Fri", case-sensitive
3395 * / %x53.61.74 ; "Sat", case-sensitive
3396 * / %x53.75.6E ; "Sun", case-sensitive
3397 *
3398 * This array must be alphabetically sorted
3399 */
3400static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3401{
3402 if (*len < 3)
3403 return 0;
3404 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3405 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3406 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3407 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3408 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3409 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3410 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3411 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3412 default: return 0;
3413 }
3414 *len -= 3;
3415 *date += 3;
3416 return 1;
3417}
3418
3419/* month = %x4A.61.6E ; "Jan", case-sensitive
3420 * / %x46.65.62 ; "Feb", case-sensitive
3421 * / %x4D.61.72 ; "Mar", case-sensitive
3422 * / %x41.70.72 ; "Apr", case-sensitive
3423 * / %x4D.61.79 ; "May", case-sensitive
3424 * / %x4A.75.6E ; "Jun", case-sensitive
3425 * / %x4A.75.6C ; "Jul", case-sensitive
3426 * / %x41.75.67 ; "Aug", case-sensitive
3427 * / %x53.65.70 ; "Sep", case-sensitive
3428 * / %x4F.63.74 ; "Oct", case-sensitive
3429 * / %x4E.6F.76 ; "Nov", case-sensitive
3430 * / %x44.65.63 ; "Dec", case-sensitive
3431 *
3432 * This array must be alphabetically sorted
3433 */
3434static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3435{
3436 if (*len < 3)
3437 return 0;
3438 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3439 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3440 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3441 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3442 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3443 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3444 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3445 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3446 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3447 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3448 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3449 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3450 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3451 default: return 0;
3452 }
3453 *len -= 3;
3454 *date += 3;
3455 return 1;
3456}
3457
3458/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3459 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3460 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3461 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3462 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3463 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3464 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3465 *
3466 * This array must be alphabetically sorted
3467 */
3468static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3469{
3470 if (*len < 6) /* Minimum length. */
3471 return 0;
3472 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3473 case STR2I3('M','o','n'):
3474 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3475 tm->tm_wday = 1;
3476 return 1;
3477 case STR2I3('T','u','e'):
3478 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3479 tm->tm_wday = 2;
3480 return 1;
3481 case STR2I3('W','e','d'):
3482 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3483 tm->tm_wday = 3;
3484 return 1;
3485 case STR2I3('T','h','u'):
3486 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3487 tm->tm_wday = 4;
3488 return 1;
3489 case STR2I3('F','r','i'):
3490 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3491 tm->tm_wday = 5;
3492 return 1;
3493 case STR2I3('S','a','t'):
3494 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3495 tm->tm_wday = 6;
3496 return 1;
3497 case STR2I3('S','u','n'):
3498 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3499 tm->tm_wday = 7;
3500 return 1;
3501 }
3502 return 0;
3503}
3504
3505/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3506static inline int parse_digit(const char **date, int *len, int *digit)
3507{
3508 if (*len < 1 || **date < '0' || **date > '9')
3509 return 0;
3510 *digit = (**date - '0');
3511 (*date)++;
3512 (*len)--;
3513 return 1;
3514}
3515
3516/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3517static inline int parse_2digit(const char **date, int *len, int *digit)
3518{
3519 int value;
3520
3521 RET0_UNLESS(parse_digit(date, len, &value));
3522 (*digit) = value * 10;
3523 RET0_UNLESS(parse_digit(date, len, &value));
3524 (*digit) += value;
3525
3526 return 1;
3527}
3528
3529/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3530static inline int parse_4digit(const char **date, int *len, int *digit)
3531{
3532 int value;
3533
3534 RET0_UNLESS(parse_digit(date, len, &value));
3535 (*digit) = value * 1000;
3536
3537 RET0_UNLESS(parse_digit(date, len, &value));
3538 (*digit) += value * 100;
3539
3540 RET0_UNLESS(parse_digit(date, len, &value));
3541 (*digit) += value * 10;
3542
3543 RET0_UNLESS(parse_digit(date, len, &value));
3544 (*digit) += value;
3545
3546 return 1;
3547}
3548
3549/* time-of-day = hour ":" minute ":" second
3550 * ; 00:00:00 - 23:59:60 (leap second)
3551 *
3552 * hour = 2DIGIT
3553 * minute = 2DIGIT
3554 * second = 2DIGIT
3555 */
3556static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3557{
3558 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3559 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3560 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3561 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3562 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3563 return 1;
3564}
3565
3566/* From RFC7231
3567 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3568 *
3569 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3570 * ; fixed length/zone/capitalization subset of the format
3571 * ; see Section 3.3 of [RFC5322]
3572 *
3573 *
3574 * date1 = day SP month SP year
3575 * ; e.g., 02 Jun 1982
3576 *
3577 * day = 2DIGIT
3578 * year = 4DIGIT
3579 *
3580 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3581 *
3582 * time-of-day = hour ":" minute ":" second
3583 * ; 00:00:00 - 23:59:60 (leap second)
3584 *
3585 * hour = 2DIGIT
3586 * minute = 2DIGIT
3587 * second = 2DIGIT
3588 *
3589 * DIGIT = decimal 0-9
3590 */
3591int parse_imf_date(const char *date, int len, struct tm *tm)
3592{
David Carlier327298c2016-11-20 10:42:38 +00003593 /* tm_gmtoff, if present, ought to be zero'ed */
3594 memset(tm, 0, sizeof(*tm));
3595
Thierry Fournier93127942016-01-20 18:49:45 +01003596 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3597 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3598 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3599 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3600 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3601 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3602 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3603 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3604 tm->tm_year -= 1900;
3605 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3606 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3607 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3608 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3609 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003610 return 1;
3611}
3612
3613/* From RFC7231
3614 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3615 *
3616 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3617 * date2 = day "-" month "-" 2DIGIT
3618 * ; e.g., 02-Jun-82
3619 *
3620 * day = 2DIGIT
3621 */
3622int parse_rfc850_date(const char *date, int len, struct tm *tm)
3623{
3624 int year;
3625
David Carlier327298c2016-11-20 10:42:38 +00003626 /* tm_gmtoff, if present, ought to be zero'ed */
3627 memset(tm, 0, sizeof(*tm));
3628
Thierry Fournier93127942016-01-20 18:49:45 +01003629 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3630 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3631 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3632 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3633 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3634 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3635 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3636
3637 /* year = 2DIGIT
3638 *
3639 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3640 * two-digit year, MUST interpret a timestamp that appears to be more
3641 * than 50 years in the future as representing the most recent year in
3642 * the past that had the same last two digits.
3643 */
3644 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3645
3646 /* expect SP */
3647 if (!parse_expect_char(&date, &len, ' ')) {
3648 /* Maybe we have the date with 4 digits. */
3649 RET0_UNLESS(parse_2digit(&date, &len, &year));
3650 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3651 /* expect SP */
3652 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3653 } else {
3654 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3655 * tm_year is the number of year since 1900, so for +1900, we
3656 * do nothing, and for +2000, we add 100.
3657 */
3658 if (tm->tm_year <= 60)
3659 tm->tm_year += 100;
3660 }
3661
3662 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3663 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3664 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3665 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003666
3667 return 1;
3668}
3669
3670/* From RFC7231
3671 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3672 *
3673 * asctime-date = day-name SP date3 SP time-of-day SP year
3674 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3675 * ; e.g., Jun 2
3676 *
3677 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3678 * whitespace in an HTTP-date beyond that specifically included as SP in
3679 * the grammar.
3680 */
3681int parse_asctime_date(const char *date, int len, struct tm *tm)
3682{
David Carlier327298c2016-11-20 10:42:38 +00003683 /* tm_gmtoff, if present, ought to be zero'ed */
3684 memset(tm, 0, sizeof(*tm));
3685
Thierry Fournier93127942016-01-20 18:49:45 +01003686 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3687 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3688 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3689 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3690
3691 /* expect SP and 1DIGIT or 2DIGIT */
3692 if (parse_expect_char(&date, &len, ' '))
3693 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3694 else
3695 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3696
3697 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3698 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3699 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3700 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3701 tm->tm_year -= 1900;
3702 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003703 return 1;
3704}
3705
3706/* From RFC7231
3707 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3708 *
3709 * HTTP-date = IMF-fixdate / obs-date
3710 * obs-date = rfc850-date / asctime-date
3711 *
3712 * parses an HTTP date in the RFC format and is accepted
3713 * alternatives. <date> is the strinf containing the date,
3714 * len is the len of the string. <tm> is filled with the
3715 * parsed time. We must considers this time as GMT.
3716 */
3717int parse_http_date(const char *date, int len, struct tm *tm)
3718{
3719 if (parse_imf_date(date, len, tm))
3720 return 1;
3721
3722 if (parse_rfc850_date(date, len, tm))
3723 return 1;
3724
3725 if (parse_asctime_date(date, len, tm))
3726 return 1;
3727
3728 return 0;
3729}
3730
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003731/* Dynamically allocates a string of the proper length to hold the formatted
3732 * output. NULL is returned on error. The caller is responsible for freeing the
3733 * memory area using free(). The resulting string is returned in <out> if the
3734 * pointer is not NULL. A previous version of <out> might be used to build the
3735 * new string, and it will be freed before returning if it is not NULL, which
3736 * makes it possible to build complex strings from iterative calls without
3737 * having to care about freeing intermediate values, as in the example below :
3738 *
3739 * memprintf(&err, "invalid argument: '%s'", arg);
3740 * ...
3741 * memprintf(&err, "parser said : <%s>\n", *err);
3742 * ...
3743 * free(*err);
3744 *
3745 * This means that <err> must be initialized to NULL before first invocation.
3746 * The return value also holds the allocated string, which eases error checking
3747 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003748 * passed instead and it will be ignored. The returned message will then also
3749 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003750 *
3751 * It is also convenient to use it without any free except the last one :
3752 * err = NULL;
3753 * if (!fct1(err)) report(*err);
3754 * if (!fct2(err)) report(*err);
3755 * if (!fct3(err)) report(*err);
3756 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003757 *
3758 * memprintf relies on memvprintf. This last version can be called from any
3759 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003760 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003761char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003762{
3763 va_list args;
3764 char *ret = NULL;
3765 int allocated = 0;
3766 int needed = 0;
3767
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003768 if (!out)
3769 return NULL;
3770
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003771 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003772 char buf1;
3773
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003774 /* vsnprintf() will return the required length even when the
3775 * target buffer is NULL. We do this in a loop just in case
3776 * intermediate evaluations get wrong.
3777 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003778 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003779 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003780 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003781 if (needed < allocated) {
3782 /* Note: on Solaris 8, the first iteration always
3783 * returns -1 if allocated is zero, so we force a
3784 * retry.
3785 */
3786 if (!allocated)
3787 needed = 0;
3788 else
3789 break;
3790 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003791
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003792 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003793 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003794 } while (ret);
3795
3796 if (needed < 0) {
3797 /* an error was encountered */
3798 free(ret);
3799 ret = NULL;
3800 }
3801
3802 if (out) {
3803 free(*out);
3804 *out = ret;
3805 }
3806
3807 return ret;
3808}
William Lallemand421f5b52012-02-06 18:15:57 +01003809
Christopher Faulet93a518f2017-10-24 11:25:33 +02003810char *memprintf(char **out, const char *format, ...)
3811{
3812 va_list args;
3813 char *ret = NULL;
3814
3815 va_start(args, format);
3816 ret = memvprintf(out, format, args);
3817 va_end(args);
3818
3819 return ret;
3820}
3821
Willy Tarreau21c705b2012-09-14 11:40:36 +02003822/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3823 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003824 * freed by the caller. It also supports being passed a NULL which results in the same
3825 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003826 * Example of use :
3827 * parse(cmd, &err); (callee: memprintf(&err, ...))
3828 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3829 * free(err);
3830 */
3831char *indent_msg(char **out, int level)
3832{
3833 char *ret, *in, *p;
3834 int needed = 0;
3835 int lf = 0;
3836 int lastlf = 0;
3837 int len;
3838
Willy Tarreau70eec382012-10-10 08:56:47 +02003839 if (!out || !*out)
3840 return NULL;
3841
Willy Tarreau21c705b2012-09-14 11:40:36 +02003842 in = *out - 1;
3843 while ((in = strchr(in + 1, '\n')) != NULL) {
3844 lastlf = in - *out;
3845 lf++;
3846 }
3847
3848 if (!lf) /* single line, no LF, return it as-is */
3849 return *out;
3850
3851 len = strlen(*out);
3852
3853 if (lf == 1 && lastlf == len - 1) {
3854 /* single line, LF at end, strip it and return as-is */
3855 (*out)[lastlf] = 0;
3856 return *out;
3857 }
3858
3859 /* OK now we have at least one LF, we need to process the whole string
3860 * as a multi-line string. What we'll do :
3861 * - prefix with an LF if there is none
3862 * - add <level> spaces before each line
3863 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3864 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3865 */
3866
3867 needed = 1 + level * (lf + 1) + len + 1;
3868 p = ret = malloc(needed);
3869 in = *out;
3870
3871 /* skip initial LFs */
3872 while (*in == '\n')
3873 in++;
3874
3875 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3876 while (*in) {
3877 *p++ = '\n';
3878 memset(p, ' ', level);
3879 p += level;
3880 do {
3881 *p++ = *in++;
3882 } while (*in && *in != '\n');
3883 if (*in)
3884 in++;
3885 }
3886 *p = 0;
3887
3888 free(*out);
3889 *out = ret;
3890
3891 return ret;
3892}
3893
Willy Tarreaua2c99112019-08-21 13:17:37 +02003894/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3895 * and end of lines replaced with <eol> if not 0. The first line to indent has
3896 * to be indicated in <first> (starts at zero), so that it is possible to skip
3897 * indenting the first line if it has to be appended after an existing message.
3898 * Empty strings are never indented, and NULL strings are considered empty both
3899 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3900 * character, non-zero otherwise.
3901 */
3902int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3903{
3904 int bol, lf;
3905 int pfxlen = pfx ? strlen(pfx) : 0;
3906
3907 if (!in)
3908 return 0;
3909
3910 bol = 1;
3911 lf = 0;
3912 while (*in) {
3913 if (bol && pfxlen) {
3914 if (first > 0)
3915 first--;
3916 else
3917 b_putblk(out, pfx, pfxlen);
3918 bol = 0;
3919 }
3920
3921 lf = (*in == '\n');
3922 bol |= lf;
3923 b_putchr(out, (lf && eol) ? eol : *in);
3924 in++;
3925 }
3926 return lf;
3927}
3928
Willy Tarreau9d22e562019-03-29 18:49:09 +01003929/* removes environment variable <name> from the environment as found in
3930 * environ. This is only provided as an alternative for systems without
3931 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003932 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003933 * <name> and to replace the matching pointers with the last pointer of
3934 * the array (since variables are not ordered).
3935 * It always returns 0 (success).
3936 */
3937int my_unsetenv(const char *name)
3938{
3939 extern char **environ;
3940 char **p = environ;
3941 int vars;
3942 int next;
3943 int len;
3944
3945 len = strlen(name);
3946 for (vars = 0; p[vars]; vars++)
3947 ;
3948 next = 0;
3949 while (next < vars) {
3950 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3951 next++;
3952 continue;
3953 }
3954 if (next < vars - 1)
3955 p[next] = p[vars - 1];
3956 p[--vars] = NULL;
3957 }
3958 return 0;
3959}
3960
Willy Tarreaudad36a32013-03-11 01:20:04 +01003961/* Convert occurrences of environment variables in the input string to their
3962 * corresponding value. A variable is identified as a series of alphanumeric
3963 * characters or underscores following a '$' sign. The <in> string must be
3964 * free()able. NULL returns NULL. The resulting string might be reallocated if
3965 * some expansion is made. Variable names may also be enclosed into braces if
3966 * needed (eg: to concatenate alphanum characters).
3967 */
3968char *env_expand(char *in)
3969{
3970 char *txt_beg;
3971 char *out;
3972 char *txt_end;
3973 char *var_beg;
3974 char *var_end;
3975 char *value;
3976 char *next;
3977 int out_len;
3978 int val_len;
3979
3980 if (!in)
3981 return in;
3982
3983 value = out = NULL;
3984 out_len = 0;
3985
3986 txt_beg = in;
3987 do {
3988 /* look for next '$' sign in <in> */
3989 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3990
3991 if (!*txt_end && !out) /* end and no expansion performed */
3992 return in;
3993
3994 val_len = 0;
3995 next = txt_end;
3996 if (*txt_end == '$') {
3997 char save;
3998
3999 var_beg = txt_end + 1;
4000 if (*var_beg == '{')
4001 var_beg++;
4002
4003 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004004 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004005 var_end++;
4006 }
4007
4008 next = var_end;
4009 if (*var_end == '}' && (var_beg > txt_end + 1))
4010 next++;
4011
4012 /* get value of the variable name at this location */
4013 save = *var_end;
4014 *var_end = '\0';
4015 value = getenv(var_beg);
4016 *var_end = save;
4017 val_len = value ? strlen(value) : 0;
4018 }
4019
Hubert Verstraete831962e2016-06-28 22:44:26 +02004020 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004021 if (txt_end > txt_beg) {
4022 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4023 out_len += txt_end - txt_beg;
4024 }
4025 if (val_len) {
4026 memcpy(out + out_len, value, val_len);
4027 out_len += val_len;
4028 }
4029 out[out_len] = 0;
4030 txt_beg = next;
4031 } while (*txt_beg);
4032
4033 /* here we know that <out> was allocated and that we don't need <in> anymore */
4034 free(in);
4035 return out;
4036}
4037
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004038
4039/* same as strstr() but case-insensitive and with limit length */
4040const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4041{
4042 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004043 unsigned int slen, plen;
4044 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004045
4046 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4047 return NULL;
4048
4049 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4050 return str1;
4051
4052 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4053 return NULL;
4054
4055 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 +02004056 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004057 start++;
4058 slen--;
4059 tmp1++;
4060
4061 if (tmp1 >= len_str1)
4062 return NULL;
4063
4064 /* if pattern longer than string */
4065 if (slen < plen)
4066 return NULL;
4067 }
4068
4069 sptr = start;
4070 pptr = (char *)str2;
4071
4072 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004073 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004074 sptr++;
4075 pptr++;
4076 tmp2++;
4077
4078 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4079 return start;
4080 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4081 return NULL;
4082 }
4083 }
4084 return NULL;
4085}
4086
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004087/* This function read the next valid utf8 char.
4088 * <s> is the byte srray to be decode, <len> is its length.
4089 * The function returns decoded char encoded like this:
4090 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4091 * are the length read. The decoded character is stored in <c>.
4092 */
4093unsigned char utf8_next(const char *s, int len, unsigned int *c)
4094{
4095 const unsigned char *p = (unsigned char *)s;
4096 int dec;
4097 unsigned char code = UTF8_CODE_OK;
4098
4099 if (len < 1)
4100 return UTF8_CODE_OK;
4101
4102 /* Check the type of UTF8 sequence
4103 *
4104 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4105 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4106 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4107 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4108 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4109 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4110 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4111 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4112 */
4113 switch (*p) {
4114 case 0x00 ... 0x7f:
4115 *c = *p;
4116 return UTF8_CODE_OK | 1;
4117
4118 case 0x80 ... 0xbf:
4119 *c = *p;
4120 return UTF8_CODE_BADSEQ | 1;
4121
4122 case 0xc0 ... 0xdf:
4123 if (len < 2) {
4124 *c = *p;
4125 return UTF8_CODE_BADSEQ | 1;
4126 }
4127 *c = *p & 0x1f;
4128 dec = 1;
4129 break;
4130
4131 case 0xe0 ... 0xef:
4132 if (len < 3) {
4133 *c = *p;
4134 return UTF8_CODE_BADSEQ | 1;
4135 }
4136 *c = *p & 0x0f;
4137 dec = 2;
4138 break;
4139
4140 case 0xf0 ... 0xf7:
4141 if (len < 4) {
4142 *c = *p;
4143 return UTF8_CODE_BADSEQ | 1;
4144 }
4145 *c = *p & 0x07;
4146 dec = 3;
4147 break;
4148
4149 case 0xf8 ... 0xfb:
4150 if (len < 5) {
4151 *c = *p;
4152 return UTF8_CODE_BADSEQ | 1;
4153 }
4154 *c = *p & 0x03;
4155 dec = 4;
4156 break;
4157
4158 case 0xfc ... 0xfd:
4159 if (len < 6) {
4160 *c = *p;
4161 return UTF8_CODE_BADSEQ | 1;
4162 }
4163 *c = *p & 0x01;
4164 dec = 5;
4165 break;
4166
4167 case 0xfe ... 0xff:
4168 default:
4169 *c = *p;
4170 return UTF8_CODE_BADSEQ | 1;
4171 }
4172
4173 p++;
4174
4175 while (dec > 0) {
4176
4177 /* need 0x10 for the 2 first bits */
4178 if ( ( *p & 0xc0 ) != 0x80 )
4179 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4180
4181 /* add data at char */
4182 *c = ( *c << 6 ) | ( *p & 0x3f );
4183
4184 dec--;
4185 p++;
4186 }
4187
4188 /* Check ovelong encoding.
4189 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4190 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4191 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4192 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004193 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004194 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4195 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4196 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4197 code |= UTF8_CODE_OVERLONG;
4198
4199 /* Check invalid UTF8 range. */
4200 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4201 (*c >= 0xfffe && *c <= 0xffff))
4202 code |= UTF8_CODE_INVRANGE;
4203
4204 return code | ((p-(unsigned char *)s)&0x0f);
4205}
4206
Maxime de Roucydc887852016-05-13 23:52:54 +02004207/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4208 * On failure : return 0 and <err> filled with an error message.
4209 * The caller is responsible for freeing the <err> and <str> copy
4210 * memory area using free()
4211 */
4212int list_append_word(struct list *li, const char *str, char **err)
4213{
4214 struct wordlist *wl;
4215
4216 wl = calloc(1, sizeof(*wl));
4217 if (!wl) {
4218 memprintf(err, "out of memory");
4219 goto fail_wl;
4220 }
4221
4222 wl->s = strdup(str);
4223 if (!wl->s) {
4224 memprintf(err, "out of memory");
4225 goto fail_wl_s;
4226 }
4227
4228 LIST_ADDQ(li, &wl->list);
4229
4230 return 1;
4231
4232fail_wl_s:
4233 free(wl->s);
4234fail_wl:
4235 free(wl);
4236 return 0;
4237}
4238
Willy Tarreau37101052019-05-20 16:48:20 +02004239/* indicates if a memory location may safely be read or not. The trick consists
4240 * in performing a harmless syscall using this location as an input and letting
4241 * the operating system report whether it's OK or not. For this we have the
4242 * stat() syscall, which will return EFAULT when the memory location supposed
4243 * to contain the file name is not readable. If it is readable it will then
4244 * either return 0 if the area contains an existing file name, or -1 with
4245 * another code. This must not be abused, and some audit systems might detect
4246 * this as abnormal activity. It's used only for unsafe dumps.
4247 */
4248int may_access(const void *ptr)
4249{
4250 struct stat buf;
4251
4252 if (stat(ptr, &buf) == 0)
4253 return 1;
4254 if (errno == EFAULT)
4255 return 0;
4256 return 1;
4257}
4258
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004259/* print a string of text buffer to <out>. The format is :
4260 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4261 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4262 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4263 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004264int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004265{
4266 unsigned char c;
4267 int ptr = 0;
4268
4269 while (buf[ptr] && ptr < bsize) {
4270 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004271 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004272 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004273 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004274 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004275 }
4276 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004277 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004278 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004279 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004280 switch (c) {
4281 case ' ': c = ' '; break;
4282 case '\t': c = 't'; break;
4283 case '\n': c = 'n'; break;
4284 case '\r': c = 'r'; break;
4285 case '\e': c = 'e'; break;
4286 case '\\': c = '\\'; break;
4287 case '=': c = '='; break;
4288 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004289 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004290 }
4291 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004292 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004293 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004294 out->area[out->data++] = '\\';
4295 out->area[out->data++] = 'x';
4296 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4297 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004298 }
4299 ptr++;
4300 }
4301
4302 return ptr;
4303}
4304
4305/* print a buffer in hexa.
4306 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4307 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004308int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004309{
4310 unsigned char c;
4311 int ptr = 0;
4312
4313 while (ptr < bsize) {
4314 c = buf[ptr];
4315
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004316 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004317 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004318 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4319 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004320
4321 ptr++;
4322 }
4323 return ptr;
4324}
4325
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004326/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4327 * prepending each line with prefix <pfx>. The output is *not* initialized.
4328 * The output will not wrap pas the buffer's end so it is more optimal if the
4329 * caller makes sure the buffer is aligned first. A trailing zero will always
4330 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004331 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4332 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004333 */
Willy Tarreau37101052019-05-20 16:48:20 +02004334void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004335{
4336 const unsigned char *d = buf;
4337 int i, j, start;
4338
4339 d = (const unsigned char *)(((unsigned long)buf) & -16);
4340 start = ((unsigned long)buf) & 15;
4341
4342 for (i = 0; i < start + len; i += 16) {
4343 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4344
Willy Tarreau37101052019-05-20 16:48:20 +02004345 // 0: unchecked, 1: checked safe, 2: danger
4346 unsafe = !!unsafe;
4347 if (unsafe && !may_access(d + i))
4348 unsafe = 2;
4349
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004350 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004351 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004352 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004353 else if (unsafe > 1)
4354 chunk_strcat(out, "** ");
4355 else
4356 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004357
4358 if (j == 7)
4359 chunk_strcat(out, "- ");
4360 }
4361 chunk_strcat(out, " ");
4362 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004363 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004364 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004365 else if (unsafe > 1)
4366 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004367 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004368 chunk_appendf(out, "%c", d[i + j]);
4369 else
4370 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004371 }
4372 chunk_strcat(out, "\n");
4373 }
4374}
4375
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004376/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4377 * enclosed in brackets after the address itself, formatted on 14 chars
4378 * including the "0x" prefix. This is meant to be used as a prefix for code
4379 * areas. For example:
4380 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4381 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4382 * is emitted. A NULL <pfx> will be considered empty.
4383 */
4384void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4385{
4386 int ok = 0;
4387 int i;
4388
4389 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4390
4391 for (i = 0; i < n; i++) {
4392 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4393 ok = may_access(addr + i);
4394 if (ok)
4395 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4396 else
4397 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4398 }
4399}
4400
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004401/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4402 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4403 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4404 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4405 * lines are respected within the limit of 70 output chars. Lines that are
4406 * continuation of a previous truncated line begin with "+" instead of " "
4407 * after the offset. The new pointer is returned.
4408 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004409int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004410 int *line, int ptr)
4411{
4412 int end;
4413 unsigned char c;
4414
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004415 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004416 if (end > out->size)
4417 return ptr;
4418
4419 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4420
4421 while (ptr < len && ptr < bsize) {
4422 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004423 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004424 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004425 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004426 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004427 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004428 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004429 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004430 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004431 switch (c) {
4432 case '\t': c = 't'; break;
4433 case '\n': c = 'n'; break;
4434 case '\r': c = 'r'; break;
4435 case '\e': c = 'e'; break;
4436 case '\\': c = '\\'; break;
4437 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004438 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004439 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004440 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004441 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004442 out->area[out->data++] = '\\';
4443 out->area[out->data++] = 'x';
4444 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4445 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004446 }
4447 if (buf[ptr++] == '\n') {
4448 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004449 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004450 *line = ptr;
4451 return ptr;
4452 }
4453 }
4454 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004455 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004456 return ptr;
4457}
4458
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004459/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004460 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4461 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004462 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004463void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4464 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004465{
Willy Tarreau73459792017-04-11 07:58:08 +02004466 unsigned int i;
4467 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004468
4469 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4470 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004471 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004472 for (j = 0; j < 8; j++) {
4473 if (b + j >= 0 && b + j < len)
4474 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4475 else
4476 fprintf(out, " ");
4477 }
4478
4479 if (b + j >= 0 && b + j < len)
4480 fputc('-', out);
4481 else
4482 fputc(' ', out);
4483
4484 for (j = 8; j < 16; j++) {
4485 if (b + j >= 0 && b + j < len)
4486 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4487 else
4488 fprintf(out, " ");
4489 }
4490
4491 fprintf(out, " ");
4492 for (j = 0; j < 16; j++) {
4493 if (b + j >= 0 && b + j < len) {
4494 if (isprint((unsigned char)buf[b + j]))
4495 fputc((unsigned char)buf[b + j], out);
4496 else
4497 fputc('.', out);
4498 }
4499 else
4500 fputc(' ', out);
4501 }
4502 fputc('\n', out);
4503 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004504}
4505
Willy Tarreaubb869862020-04-16 10:52:41 +02004506/* Tries to report the executable path name on platforms supporting this. If
4507 * not found or not possible, returns NULL.
4508 */
4509const char *get_exec_path()
4510{
4511 const char *ret = NULL;
4512
4513#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4514 long execfn = getauxval(AT_EXECFN);
4515
4516 if (execfn && execfn != ENOENT)
4517 ret = (const char *)execfn;
4518#endif
4519 return ret;
4520}
4521
Baruch Siache1651b22020-07-24 07:52:20 +03004522#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004523/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4524 * also returns the symbol size in <size>, otherwise returns 0 there.
4525 */
4526static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4527{
4528 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004529#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004530 const ElfW(Sym) *sym;
4531
4532 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4533 if (ret)
4534 *size = sym ? sym->st_size : 0;
4535#else
4536 ret = dladdr(addr, dli);
4537 *size = 0;
4538#endif
4539 return ret;
4540}
4541#endif
4542
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004543/* Tries to append to buffer <buf> some indications about the symbol at address
4544 * <addr> using the following form:
4545 * lib:+0xoffset (unresolvable address from lib's base)
4546 * main+0xoffset (unresolvable address from main (+/-))
4547 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4548 * name (resolved exact exec address)
4549 * lib:name (resolved exact lib address)
4550 * name+0xoffset/0xsize (resolved address within exec symbol)
4551 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4552 *
4553 * The file name (lib or executable) is limited to what lies between the last
4554 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4555 * 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 +03004556 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004557 *
4558 * The symbol's base address is returned, or NULL when unresolved, in order to
4559 * allow the caller to match it against known ones.
4560 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004561const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004562{
4563 const struct {
4564 const void *func;
4565 const char *name;
4566 } fcts[] = {
4567 { .func = process_stream, .name = "process_stream" },
4568 { .func = task_run_applet, .name = "task_run_applet" },
4569 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4570 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4571 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4572 { .func = listener_accept, .name = "listener_accept" },
4573 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4574 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4575#ifdef USE_LUA
4576 { .func = hlua_process_task, .name = "hlua_process_task" },
4577#endif
4578#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4579 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4580 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4581#endif
4582 };
4583
Baruch Siache1651b22020-07-24 07:52:20 +03004584#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004585 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004586 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004587 const char *fname, *p;
4588#endif
4589 int i;
4590
4591 if (pfx)
4592 chunk_appendf(buf, "%s", pfx);
4593
4594 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4595 if (addr == fcts[i].func) {
4596 chunk_appendf(buf, "%s", fcts[i].name);
4597 return addr;
4598 }
4599 }
4600
Baruch Siache1651b22020-07-24 07:52:20 +03004601#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004602 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004603 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004604 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004605
4606 /* 1. prefix the library name if it's not the same object as the one
4607 * that contains the main function. The name is picked between last '/'
4608 * and first following '.'.
4609 */
4610 if (!dladdr(main, &dli_main))
4611 dli_main.dli_fbase = NULL;
4612
4613 if (dli_main.dli_fbase != dli.dli_fbase) {
4614 fname = dli.dli_fname;
4615 p = strrchr(fname, '/');
4616 if (p++)
4617 fname = p;
4618 p = strchr(fname, '.');
4619 if (!p)
4620 p = fname + strlen(fname);
4621
4622 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4623 }
4624
4625 /* 2. symbol name */
4626 if (dli.dli_sname) {
4627 /* known, dump it and return symbol's address (exact or relative) */
4628 chunk_appendf(buf, "%s", dli.dli_sname);
4629 if (addr != dli.dli_saddr) {
4630 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004631 if (size)
4632 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004633 }
4634 return dli.dli_saddr;
4635 }
4636 else if (dli_main.dli_fbase != dli.dli_fbase) {
4637 /* unresolved symbol from a known library, report relative offset */
4638 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4639 return NULL;
4640 }
Baruch Siache1651b22020-07-24 07:52:20 +03004641#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004642 unknown:
4643 /* unresolved symbol from the main file, report relative offset to main */
4644 if ((void*)addr < (void*)main)
4645 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4646 else
4647 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4648 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004649}
4650
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004651/*
4652 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004653 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004654 *
4655 * First, initializes the value with <sz> as address to 0 and initializes the
4656 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4657 * address updating <sz> pointed value to the size of this array.
4658 *
4659 * Returns 1 if succeeded, 0 if not.
4660 */
4661int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4662{
4663 unsigned int *n;
4664 const char *s, *end;
4665
4666 s = str;
4667 *sz = 0;
4668 end = str + strlen(str);
4669 *nums = n = NULL;
4670
4671 while (1) {
4672 unsigned int r;
4673
4674 if (s >= end)
4675 break;
4676
4677 r = read_uint(&s, end);
4678 /* Expected characters after having read an uint: '\0' or '.',
4679 * if '.', must not be terminal.
4680 */
4681 if (*s != '\0'&& (*s++ != '.' || s == end))
4682 return 0;
4683
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004684 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004685 if (!n)
4686 return 0;
4687
4688 n[(*sz)++] = r;
4689 }
4690 *nums = n;
4691
4692 return 1;
4693}
4694
Willy Tarreau4d589e72019-08-23 19:02:26 +02004695
4696/* returns the number of bytes needed to encode <v> as a varint. An inline
4697 * version exists for use with constants (__varint_bytes()).
4698 */
4699int varint_bytes(uint64_t v)
4700{
4701 int len = 1;
4702
4703 if (v >= 240) {
4704 v = (v - 240) >> 4;
4705 while (1) {
4706 len++;
4707 if (v < 128)
4708 break;
4709 v = (v - 128) >> 7;
4710 }
4711 }
4712 return len;
4713}
4714
Willy Tarreau52bf8392020-03-08 00:42:37 +01004715
4716/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004717static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004718
4719/* This is a thread-safe implementation of xoroshiro128** described below:
4720 * http://prng.di.unimi.it/
4721 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4722 * supports fast jumps and passes all common quality tests. It is thread-safe,
4723 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4724 * local lock on other ones.
4725 */
4726uint64_t ha_random64()
4727{
4728 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004729 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4730 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004731
4732#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4733 static HA_SPINLOCK_T rand_lock;
4734
4735 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4736#endif
4737
4738 old[0] = ha_random_state[0];
4739 old[1] = ha_random_state[1];
4740
4741#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4742 do {
4743#endif
4744 result = rotl64(old[0] * 5, 7) * 9;
4745 new[1] = old[0] ^ old[1];
4746 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4747 new[1] = rotl64(new[1], 37); // c
4748
4749#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4750 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4751#else
4752 ha_random_state[0] = new[0];
4753 ha_random_state[1] = new[1];
4754#if defined(USE_THREAD)
4755 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4756#endif
4757#endif
4758 return result;
4759}
4760
4761/* seeds the random state using up to <len> bytes from <seed>, starting with
4762 * the first non-zero byte.
4763 */
4764void ha_random_seed(const unsigned char *seed, size_t len)
4765{
4766 size_t pos;
4767
4768 /* the seed must not be all zeroes, so we pre-fill it with alternating
4769 * bits and overwrite part of them with the block starting at the first
4770 * non-zero byte from the seed.
4771 */
4772 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4773
4774 for (pos = 0; pos < len; pos++)
4775 if (seed[pos] != 0)
4776 break;
4777
4778 if (pos == len)
4779 return;
4780
4781 seed += pos;
4782 len -= pos;
4783
4784 if (len > sizeof(ha_random_state))
4785 len = sizeof(ha_random_state);
4786
4787 memcpy(ha_random_state, seed, len);
4788}
4789
4790/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4791 * and is equivalent to calling ha_random64() as many times. It is used to
4792 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4793 * different generators (i.e. different processes after a fork). The <dist>
4794 * argument is the distance to jump to and is used in a loop so it rather not
4795 * be too large if the processing time is a concern.
4796 *
4797 * BEWARE: this function is NOT thread-safe and must not be called during
4798 * concurrent accesses to ha_random64().
4799 */
4800void ha_random_jump96(uint32_t dist)
4801{
4802 while (dist--) {
4803 uint64_t s0 = 0;
4804 uint64_t s1 = 0;
4805 int b;
4806
4807 for (b = 0; b < 64; b++) {
4808 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4809 s0 ^= ha_random_state[0];
4810 s1 ^= ha_random_state[1];
4811 }
4812 ha_random64();
4813 }
4814
4815 for (b = 0; b < 64; b++) {
4816 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4817 s0 ^= ha_random_state[0];
4818 s1 ^= ha_random_state[1];
4819 }
4820 ha_random64();
4821 }
4822 ha_random_state[0] = s0;
4823 ha_random_state[1] = s1;
4824 }
4825}
4826
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004827/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4828 * bytes large.
4829 */
4830void ha_generate_uuid(struct buffer *output)
4831{
4832 uint32_t rnd[4];
4833 uint64_t last;
4834
4835 last = ha_random64();
4836 rnd[0] = last;
4837 rnd[1] = last >> 32;
4838
4839 last = ha_random64();
4840 rnd[2] = last;
4841 rnd[3] = last >> 32;
4842
4843 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4844 rnd[0],
4845 rnd[1] & 0xFFFF,
4846 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4847 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4848 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4849}
4850
4851
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004852/* only used by parse_line() below. It supports writing in place provided that
4853 * <in> is updated to the next location before calling it. In that case, the
4854 * char at <in> may be overwritten.
4855 */
4856#define EMIT_CHAR(x) \
4857 do { \
4858 char __c = (char)(x); \
4859 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4860 err |= PARSE_ERR_OVERLAP; \
4861 if (outpos >= outmax) \
4862 err |= PARSE_ERR_TOOLARGE; \
4863 if (!err) \
4864 out[outpos] = __c; \
4865 outpos++; \
4866 } while (0)
4867
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004868/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004869 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4870 * extraneous ones are not emitted but <outlen> is updated so that the caller
4871 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4872 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004873 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4874 * it is guaranteed that at least one arg will point to the zero. It is safe
4875 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004876 *
4877 * <out> may overlap with <in> provided that it never goes further, in which
4878 * case the parser will accept to perform in-place parsing and unquoting/
4879 * unescaping but only if environment variables do not lead to expansion that
4880 * causes overlapping, otherwise the input string being destroyed, the error
4881 * will not be recoverable. Note that even during out-of-place <in> will
4882 * experience temporary modifications in-place for variable resolution and must
4883 * be writable, and will also receive zeroes to delimit words when using
4884 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4885 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4886 * starting point of the first invalid character sequence or unmatched
4887 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4888 * error reporting might be difficult since zeroes will have been inserted into
4889 * the string. One solution for the caller may consist in replacing all args
4890 * delimiters with spaces in this case.
4891 */
4892uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4893{
4894 char *quote = NULL;
4895 char *brace = NULL;
4896 unsigned char hex1, hex2;
4897 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004898 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004899 size_t outpos = 0;
4900 int squote = 0;
4901 int dquote = 0;
4902 int arg = 0;
4903 uint32_t err = 0;
4904
4905 *nbargs = 0;
4906 *outlen = 0;
4907
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004908 /* argsmax may be -1 here, protecting args[] from any write */
4909 if (arg < argsmax)
4910 args[arg] = out;
4911
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004912 while (1) {
4913 if (*in >= '-' && *in != '\\') {
4914 /* speedup: directly send all regular chars starting
4915 * with '-', '.', '/', alnum etc...
4916 */
4917 EMIT_CHAR(*in++);
4918 continue;
4919 }
4920 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4921 /* end of line */
4922 break;
4923 }
4924 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4925 /* comment */
4926 break;
4927 }
4928 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4929 if (dquote) {
4930 dquote = 0;
4931 quote = NULL;
4932 }
4933 else {
4934 dquote = 1;
4935 quote = in;
4936 }
4937 in++;
4938 continue;
4939 }
4940 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4941 if (squote) {
4942 squote = 0;
4943 quote = NULL;
4944 }
4945 else {
4946 squote = 1;
4947 quote = in;
4948 }
4949 in++;
4950 continue;
4951 }
4952 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4953 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4954 * C equivalent value but only when they have a special meaning and within
4955 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4956 */
4957 char tosend = *in;
4958
4959 switch (in[1]) {
4960 case ' ':
4961 case '\\':
4962 tosend = in[1];
4963 in++;
4964 break;
4965
4966 case 't':
4967 tosend = '\t';
4968 in++;
4969 break;
4970
4971 case 'n':
4972 tosend = '\n';
4973 in++;
4974 break;
4975
4976 case 'r':
4977 tosend = '\r';
4978 in++;
4979 break;
4980
4981 case '#':
4982 /* escaping of "#" only if comments are supported */
4983 if (opts & PARSE_OPT_SHARP)
4984 in++;
4985 tosend = *in;
4986 break;
4987
4988 case '\'':
4989 /* escaping of "'" only outside single quotes and only if single quotes are supported */
4990 if (opts & PARSE_OPT_SQUOTE && !squote)
4991 in++;
4992 tosend = *in;
4993 break;
4994
4995 case '"':
4996 /* escaping of '"' only outside single quotes and only if double quotes are supported */
4997 if (opts & PARSE_OPT_DQUOTE && !squote)
4998 in++;
4999 tosend = *in;
5000 break;
5001
5002 case '$':
5003 /* escaping of '$' only inside double quotes and only if env supported */
5004 if (opts & PARSE_OPT_ENV && dquote)
5005 in++;
5006 tosend = *in;
5007 break;
5008
5009 case 'x':
5010 if (!ishex(in[2]) || !ishex(in[3])) {
5011 /* invalid or incomplete hex sequence */
5012 err |= PARSE_ERR_HEX;
5013 if (errptr)
5014 *errptr = in;
5015 goto leave;
5016 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005017 hex1 = toupper((unsigned char)in[2]) - '0';
5018 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005019 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5020 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5021 tosend = (hex1 << 4) + hex2;
5022 in += 3;
5023 break;
5024
5025 default:
5026 /* other combinations are not escape sequences */
5027 break;
5028 }
5029
5030 in++;
5031 EMIT_CHAR(tosend);
5032 }
5033 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5034 /* a non-escaped space is an argument separator */
5035 while (isspace((unsigned char)*in))
5036 in++;
5037 EMIT_CHAR(0);
5038 arg++;
5039 if (arg < argsmax)
5040 args[arg] = out + outpos;
5041 else
5042 err |= PARSE_ERR_TOOMANY;
5043 }
5044 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5045 /* environment variables are evaluated anywhere, or only
5046 * inside double quotes if they are supported.
5047 */
5048 char *var_name;
5049 char save_char;
5050 char *value;
5051
5052 in++;
5053
5054 if (*in == '{')
5055 brace = in++;
5056
5057 if (!isalpha((unsigned char)*in) && *in != '_') {
5058 /* unacceptable character in variable name */
5059 err |= PARSE_ERR_VARNAME;
5060 if (errptr)
5061 *errptr = in;
5062 goto leave;
5063 }
5064
5065 var_name = in;
5066 while (isalnum((unsigned char)*in) || *in == '_')
5067 in++;
5068
5069 save_char = *in;
5070 *in = '\0';
5071 value = getenv(var_name);
5072 *in = save_char;
5073
5074 if (brace) {
5075 if (*in != '}') {
5076 /* unmatched brace */
5077 err |= PARSE_ERR_BRACE;
5078 if (errptr)
5079 *errptr = brace;
5080 goto leave;
5081 }
5082 in++;
5083 brace = NULL;
5084 }
5085
5086 if (value) {
5087 while (*value)
5088 EMIT_CHAR(*value++);
5089 }
5090 }
5091 else {
5092 /* any other regular char */
5093 EMIT_CHAR(*in++);
5094 }
5095 }
5096
5097 /* end of output string */
5098 EMIT_CHAR(0);
5099 arg++;
5100
5101 if (quote) {
5102 /* unmatched quote */
5103 err |= PARSE_ERR_QUOTE;
5104 if (errptr)
5105 *errptr = quote;
5106 goto leave;
5107 }
5108 leave:
5109 *nbargs = arg;
5110 *outlen = outpos;
5111
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005112 /* empty all trailing args by making them point to the trailing zero,
5113 * at least the last one in any case.
5114 */
5115 if (arg > argsmax)
5116 arg = argsmax;
5117
5118 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005119 args[arg++] = out + outpos - 1;
5120
5121 return err;
5122}
5123#undef EMIT_CHAR
5124
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005125/* This is used to sanitize an input line that's about to be used for error reporting.
5126 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5127 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5128 * If non-printable chars are present in the output. It returns the new offset <pos>
5129 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5130 * be at least 6 to support two "..." otherwise the result is undefined. The line
5131 * itself must have at least 7 chars allocated for the same reason.
5132 */
5133size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5134{
5135 size_t shift = 0;
5136 char *out = line;
5137 char *in = line;
5138 char *end = line + width;
5139
5140 if (pos >= width) {
5141 /* if we have to shift, we'll be out of context, so let's
5142 * try to put <pos> at the center of width.
5143 */
5144 shift = pos - width / 2;
5145 in += shift + 3;
5146 end = out + width - 3;
5147 out[0] = out[1] = out[2] = '.';
5148 out += 3;
5149 }
5150
5151 while (out < end && *in) {
5152 if (isspace((unsigned char)*in))
5153 *out++ = ' ';
5154 else if (isprint((unsigned char)*in))
5155 *out++ = *in;
5156 else
5157 *out++ = '?';
5158 in++;
5159 }
5160
5161 if (end < line + width) {
5162 out[0] = out[1] = out[2] = '.';
5163 out += 3;
5164 }
5165
5166 *out++ = 0;
5167 return pos - shift;
5168}
5169
Willy Tarreaubaaee002006-06-26 02:48:02 +02005170/*
5171 * Local variables:
5172 * c-indent-level: 8
5173 * c-basic-offset: 8
5174 * End:
5175 */