blob: 0f0bbae80a494f7af72fbfa6304007cb21a4db8c [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;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200878 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200879 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100880
881 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200882 if (fqdn)
883 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200884
Willy Tarreaudad36a32013-03-11 01:20:04 +0100885 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100886 if (str2 == NULL) {
887 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100888 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100889 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200890
Willy Tarreau9f69f462015-09-08 16:01:25 +0200891 if (!*str2) {
892 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
893 goto out;
894 }
895
Willy Tarreau24709282013-03-10 21:32:12 +0100896 memset(&ss, 0, sizeof(ss));
897
Willy Tarreaue835bd82020-09-16 11:35:47 +0200898 /* prepare the default socket types */
899 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM)
900 sock_type = ctrl_type = SOCK_DGRAM;
901 else
902 sock_type = ctrl_type = SOCK_STREAM;
903
904 if (strncmp(str2, "stream+", 7) == 0) {
905 str2 += 7;
906 sock_type = ctrl_type = SOCK_STREAM;
907 }
908 else if (strncmp(str2, "dgram+", 6) == 0) {
909 str2 += 6;
910 sock_type = ctrl_type = SOCK_DGRAM;
911 }
912
Willy Tarreau24709282013-03-10 21:32:12 +0100913 if (strncmp(str2, "unix@", 5) == 0) {
914 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200915 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100916 ss.ss_family = AF_UNIX;
917 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200918 else if (strncmp(str2, "abns@", 5) == 0) {
919 str2 += 5;
920 abstract = 1;
921 ss.ss_family = AF_UNIX;
922 }
Willy Tarreau24709282013-03-10 21:32:12 +0100923 else if (strncmp(str2, "ipv4@", 5) == 0) {
924 str2 += 5;
925 ss.ss_family = AF_INET;
926 }
927 else if (strncmp(str2, "ipv6@", 5) == 0) {
928 str2 += 5;
929 ss.ss_family = AF_INET6;
930 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200931 else if (strncmp(str2, "udp4@", 5) == 0) {
932 str2 += 5;
933 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200934 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200935 }
936 else if (strncmp(str2, "udp6@", 5) == 0) {
937 str2 += 5;
938 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200939 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200940 }
941 else if (strncmp(str2, "udp@", 4) == 0) {
942 str2 += 4;
943 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200944 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200945 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200946 else if (strncmp(str2, "fd@", 3) == 0) {
947 str2 += 3;
948 ss.ss_family = AF_CUST_EXISTING_FD;
949 }
950 else if (strncmp(str2, "sockpair@", 9) == 0) {
951 str2 += 9;
952 ss.ss_family = AF_CUST_SOCKPAIR;
953 }
Willy Tarreau24709282013-03-10 21:32:12 +0100954 else if (*str2 == '/') {
955 ss.ss_family = AF_UNIX;
956 }
957 else
958 ss.ss_family = AF_UNSPEC;
959
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200960 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200961 struct sockaddr_storage ss2;
962 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200963 char *endptr;
964
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200965 new_fd = strtol(str2, &endptr, 10);
966 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200967 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
968 goto out;
969 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200970
Willy Tarreaua215be22020-09-16 10:14:16 +0200971 /* just verify that it's a socket */
972 addr_len = sizeof(ss2);
973 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
974 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
975 goto out;
976 }
977
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200978 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
979 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200980 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200981 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100982 char *endptr;
983
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200984 new_fd = strtol(str2, &endptr, 10);
985 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100986 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100987 goto out;
988 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200989
Willy Tarreau6edc7222020-09-15 17:41:56 +0200990 if (opts & PA_O_SOCKET_FD) {
991 socklen_t addr_len;
992 int type;
993
994 addr_len = sizeof(ss);
995 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
996 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
997 goto out;
998 }
999
1000 addr_len = sizeof(type);
1001 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001002 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001003 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1004 goto out;
1005 }
1006
1007 porta = portl = porth = get_host_port(&ss);
1008 } else if (opts & PA_O_RAW_FD) {
1009 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1010 ((struct sockaddr_in *)&ss)->sin_port = 0;
1011 } else {
1012 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1013 goto out;
1014 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001015 }
1016 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001017 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001018 int prefix_path_len;
1019 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001020 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001021
1022 /* complete unix socket path name during startup or soft-restart is
1023 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1024 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001025 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001026 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001027 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001028
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001029 adr_len = strlen(str2);
1030 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001031 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1032 goto out;
1033 }
1034
Willy Tarreauccfccef2014-05-10 01:49:15 +02001035 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001036 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001037 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001038 memcpy(un->sun_path, pfx, prefix_path_len);
1039 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001040 }
Willy Tarreau24709282013-03-10 21:32:12 +01001041 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001042 char *end = str2 + strlen(str2);
1043 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001044
mildisff5d5102015-10-26 18:50:08 +01001045 /* search for : or ] whatever comes first */
1046 for (chr = end-1; chr > str2; chr--) {
1047 if (*chr == ']' || *chr == ':')
1048 break;
1049 }
1050
1051 if (*chr == ':') {
1052 /* Found a colon before a closing-bracket, must be a port separator.
1053 * This guarantee backward compatibility.
1054 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001055 if (!(opts & PA_O_PORT_OK)) {
1056 memprintf(err, "port specification not permitted here in '%s'", str);
1057 goto out;
1058 }
mildisff5d5102015-10-26 18:50:08 +01001059 *chr++ = '\0';
1060 port1 = chr;
1061 }
1062 else {
1063 /* Either no colon and no closing-bracket
1064 * or directly ending with a closing-bracket.
1065 * However, no port.
1066 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001067 if (opts & PA_O_PORT_MAND) {
1068 memprintf(err, "missing port specification in '%s'", str);
1069 goto out;
1070 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001071 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001072 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001073
Willy Tarreau90807112020-02-25 08:16:33 +01001074 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001075 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001076 if (port2) {
1077 if (!(opts & PA_O_PORT_RANGE)) {
1078 memprintf(err, "port range not permitted here in '%s'", str);
1079 goto out;
1080 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001081 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001082 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001083 else
1084 port2 = port1;
1085 portl = atoi(port1);
1086 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001087
1088 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1089 memprintf(err, "invalid port '%s'", port1);
1090 goto out;
1091 }
1092
1093 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1094 memprintf(err, "invalid port '%s'", port2);
1095 goto out;
1096 }
1097
1098 if (portl > porth) {
1099 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1100 goto out;
1101 }
1102
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001103 porta = portl;
1104 }
1105 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001106 if (!(opts & PA_O_PORT_OFS)) {
1107 memprintf(err, "port offset not permitted here in '%s'", str);
1108 goto out;
1109 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001110 portl = atoi(port1 + 1);
1111 porta = -portl;
1112 }
1113 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001114 if (!(opts & PA_O_PORT_OFS)) {
1115 memprintf(err, "port offset not permitted here in '%s'", str);
1116 goto out;
1117 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001118 porth = atoi(port1 + 1);
1119 porta = porth;
1120 }
1121 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001122 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001123 goto out;
1124 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001125 else if (opts & PA_O_PORT_MAND) {
1126 memprintf(err, "missing port specification in '%s'", str);
1127 goto out;
1128 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001129
1130 /* first try to parse the IP without resolving. If it fails, it
1131 * tells us we need to keep a copy of the FQDN to resolve later
1132 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001133 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001134 */
1135 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001136 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1137 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001138 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1139 goto out;
1140 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001141
Willy Tarreauceccdd72016-11-02 22:27:10 +01001142 if (fqdn) {
1143 if (str2 != back)
1144 memmove(back, str2, strlen(str2) + 1);
1145 *fqdn = back;
1146 back = NULL;
1147 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001148 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001149 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001150 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001151
Willy Tarreaue835bd82020-09-16 11:35:47 +02001152 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1153 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1154 goto out;
1155 }
1156 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1157 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1158 goto out;
1159 }
1160
Willy Tarreau62a976c2020-09-16 15:20:59 +02001161 if (opts & PA_O_SOCKET_FD && sock_type == SOCK_DGRAM && ctrl_type == SOCK_DGRAM) {
1162 /* FIXME: for now UDP is still its own family. However some UDP clients
1163 * (logs, dns) use AF_INET and are not aware of AF_CUST_UDP*. Since we
1164 * only want this mapping for listeners and they are the only ones
1165 * setting PA_O_SOCKET_FD, for now we condition this mapping to this.
1166 */
1167 if (ss.ss_family == AF_INET6)
1168 ss.ss_family = AF_CUST_UDP6;
1169 else if (ss.ss_family == AF_INET)
1170 ss.ss_family = AF_CUST_UDP4;
1171 }
1172
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001173 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001174 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001175 if (port)
1176 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001177 if (low)
1178 *low = portl;
1179 if (high)
1180 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001181 if (fd)
1182 *fd = new_fd;
Willy Tarreau24709282013-03-10 21:32:12 +01001183 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001184 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001185}
1186
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001187/* converts <str> to a struct in_addr containing a network mask. It can be
1188 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001189 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001190 */
1191int str2mask(const char *str, struct in_addr *mask)
1192{
1193 if (strchr(str, '.') != NULL) { /* dotted notation */
1194 if (!inet_pton(AF_INET, str, mask))
1195 return 0;
1196 }
1197 else { /* mask length */
1198 char *err;
1199 unsigned long len = strtol(str, &err, 10);
1200
1201 if (!*str || (err && *err) || (unsigned)len > 32)
1202 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001203
1204 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001205 }
1206 return 1;
1207}
1208
Tim Duesterhus47185172018-01-25 16:24:49 +01001209/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001210 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001211 * if the conversion succeeds otherwise zero.
1212 */
1213int str2mask6(const char *str, struct in6_addr *mask)
1214{
1215 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1216 if (!inet_pton(AF_INET6, str, mask))
1217 return 0;
1218 }
1219 else { /* mask length */
1220 char *err;
1221 unsigned long len = strtol(str, &err, 10);
1222
1223 if (!*str || (err && *err) || (unsigned)len > 128)
1224 return 0;
1225
1226 len2mask6(len, mask);
1227 }
1228 return 1;
1229}
1230
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001231/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1232 * succeeds otherwise zero.
1233 */
1234int cidr2dotted(int cidr, struct in_addr *mask) {
1235
1236 if (cidr < 0 || cidr > 32)
1237 return 0;
1238
1239 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1240 return 1;
1241}
1242
Thierry Fournier70473a52016-02-17 17:12:14 +01001243/* Convert mask from bit length form to in_addr form.
1244 * This function never fails.
1245 */
1246void len2mask4(int len, struct in_addr *addr)
1247{
1248 if (len >= 32) {
1249 addr->s_addr = 0xffffffff;
1250 return;
1251 }
1252 if (len <= 0) {
1253 addr->s_addr = 0x00000000;
1254 return;
1255 }
1256 addr->s_addr = 0xffffffff << (32 - len);
1257 addr->s_addr = htonl(addr->s_addr);
1258}
1259
1260/* Convert mask from bit length form to in6_addr form.
1261 * This function never fails.
1262 */
1263void len2mask6(int len, struct in6_addr *addr)
1264{
1265 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1266 len -= 32;
1267 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1268 len -= 32;
1269 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1270 len -= 32;
1271 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1272}
1273
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001274/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001275 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001276 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001277 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001278 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1279 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001280int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001281{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001282 __label__ out_free, out_err;
1283 char *c, *s;
1284 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001285
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001286 s = strdup(str);
1287 if (!s)
1288 return 0;
1289
Willy Tarreaubaaee002006-06-26 02:48:02 +02001290 memset(mask, 0, sizeof(*mask));
1291 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001292
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001293 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001294 *c++ = '\0';
1295 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001296 if (!str2mask(c, mask))
1297 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001298 }
1299 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001300 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001301 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001302 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001303 struct hostent *he;
1304
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001305 if (!resolve)
1306 goto out_err;
1307
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001308 if ((he = gethostbyname(s)) == NULL) {
1309 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001310 }
1311 else
1312 *addr = *(struct in_addr *) *(he->h_addr_list);
1313 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001314
1315 ret_val = 1;
1316 out_free:
1317 free(s);
1318 return ret_val;
1319 out_err:
1320 ret_val = 0;
1321 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001322}
1323
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001324
1325/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001326 * converts <str> to two struct in6_addr* which must be pre-allocated.
1327 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001328 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001329 * Returns 1 if OK, 0 if error.
1330 */
1331int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1332{
1333 char *c, *s;
1334 int ret_val = 0;
1335 char *err;
1336 unsigned long len = 128;
1337
1338 s = strdup(str);
1339 if (!s)
1340 return 0;
1341
1342 memset(mask, 0, sizeof(*mask));
1343 memset(addr, 0, sizeof(*addr));
1344
1345 if ((c = strrchr(s, '/')) != NULL) {
1346 *c++ = '\0'; /* c points to the mask */
1347 if (!*c)
1348 goto out_free;
1349
1350 len = strtoul(c, &err, 10);
1351 if ((err && *err) || (unsigned)len > 128)
1352 goto out_free;
1353 }
1354 *mask = len; /* OK we have a valid mask in <len> */
1355
1356 if (!inet_pton(AF_INET6, s, addr))
1357 goto out_free;
1358
1359 ret_val = 1;
1360 out_free:
1361 free(s);
1362 return ret_val;
1363}
1364
1365
1366/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001367 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001368 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001369int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001370{
1371 int saw_digit, octets, ch;
1372 u_char tmp[4], *tp;
1373 const char *cp = addr;
1374
1375 saw_digit = 0;
1376 octets = 0;
1377 *(tp = tmp) = 0;
1378
1379 while (*addr) {
1380 unsigned char digit = (ch = *addr++) - '0';
1381 if (digit > 9 && ch != '.')
1382 break;
1383 if (digit <= 9) {
1384 u_int new = *tp * 10 + digit;
1385 if (new > 255)
1386 return 0;
1387 *tp = new;
1388 if (!saw_digit) {
1389 if (++octets > 4)
1390 return 0;
1391 saw_digit = 1;
1392 }
1393 } else if (ch == '.' && saw_digit) {
1394 if (octets == 4)
1395 return 0;
1396 *++tp = 0;
1397 saw_digit = 0;
1398 } else
1399 return 0;
1400 }
1401
1402 if (octets < 4)
1403 return 0;
1404
1405 memcpy(&dst->s_addr, tmp, 4);
1406 return addr-cp-1;
1407}
1408
1409/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001410 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001411 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001412 * the hostname. Actually only http and https are supported. <out> can be NULL.
1413 * This function returns the consumed length. It is useful if you parse complete
1414 * url like http://host:port/path, because the consumed length corresponds to
1415 * the first character of the path. If the conversion fails, it returns -1.
1416 *
1417 * This function tries to resolve the DNS name if haproxy is in starting mode.
1418 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001419 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001420int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001421{
1422 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001423 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001424 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001425 unsigned long long int http_code = 0;
1426 int default_port;
1427 struct hostent *he;
1428 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001429
1430 /* Firstly, try to find :// pattern */
1431 while (curr < url+ulen && url_code != 0x3a2f2f) {
1432 url_code = ((url_code & 0xffff) << 8);
1433 url_code += (unsigned char)*curr++;
1434 }
1435
1436 /* Secondly, if :// pattern is found, verify parsed stuff
1437 * before pattern is matching our http pattern.
1438 * If so parse ip address and port in uri.
1439 *
1440 * WARNING: Current code doesn't support dynamic async dns resolver.
1441 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001442 if (url_code != 0x3a2f2f)
1443 return -1;
1444
1445 /* Copy scheme, and utrn to lower case. */
1446 while (cp < curr - 3)
1447 http_code = (http_code << 8) + *cp++;
1448 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001449
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001450 /* HTTP or HTTPS url matching */
1451 if (http_code == 0x2020202068747470ULL) {
1452 default_port = 80;
1453 if (out)
1454 out->scheme = SCH_HTTP;
1455 }
1456 else if (http_code == 0x2020206874747073ULL) {
1457 default_port = 443;
1458 if (out)
1459 out->scheme = SCH_HTTPS;
1460 }
1461 else
1462 return -1;
1463
1464 /* If the next char is '[', the host address is IPv6. */
1465 if (*curr == '[') {
1466 curr++;
1467
1468 /* Check trash size */
1469 if (trash.size < ulen)
1470 return -1;
1471
1472 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001473 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001474 for (end = curr;
1475 end < url + ulen && *end != ']';
1476 end++, p++)
1477 *p = *end;
1478 if (*end != ']')
1479 return -1;
1480 *p = '\0';
1481
1482 /* Update out. */
1483 if (out) {
1484 out->host = curr;
1485 out->host_len = end - curr;
1486 }
1487
1488 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001489 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001490 return -1;
1491 end++;
1492
1493 /* Decode port. */
1494 if (*end == ':') {
1495 end++;
1496 default_port = read_uint(&end, url + ulen);
1497 }
1498 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1499 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1500 return end - url;
1501 }
1502 else {
1503 /* We are looking for IP address. If you want to parse and
1504 * resolve hostname found in url, you can use str2sa_range(), but
1505 * be warned this can slow down global daemon performances
1506 * while handling lagging dns responses.
1507 */
1508 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1509 if (ret) {
1510 /* Update out. */
1511 if (out) {
1512 out->host = curr;
1513 out->host_len = ret;
1514 }
1515
1516 curr += ret;
1517
1518 /* Decode port. */
1519 if (*curr == ':') {
1520 curr++;
1521 default_port = read_uint(&curr, url + ulen);
1522 }
1523 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1524
1525 /* Set family. */
1526 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1527 return curr - url;
1528 }
1529 else if (global.mode & MODE_STARTING) {
1530 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1531 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001532 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001533
1534 /* look for : or / or end */
1535 for (end = curr;
1536 end < url + ulen && *end != '/' && *end != ':';
1537 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001538 memcpy(trash.area, curr, end - curr);
1539 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001540
1541 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001542 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001543 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001544 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001545
1546 /* Update out. */
1547 if (out) {
1548 out->host = curr;
1549 out->host_len = end - curr;
1550 }
1551
1552 /* Decode port. */
1553 if (*end == ':') {
1554 end++;
1555 default_port = read_uint(&end, url + ulen);
1556 }
1557
1558 /* Copy IP address, set port and family. */
1559 switch (he->h_addrtype) {
1560 case AF_INET:
1561 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1562 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1563 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1564 return end - url;
1565
1566 case AF_INET6:
1567 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1568 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1569 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1570 return end - url;
1571 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001572 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001573 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001574 return -1;
1575}
1576
Willy Tarreau631f01c2011-09-05 00:36:48 +02001577/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1578 * address family is returned so that it's easy for the caller to adapt to the
1579 * output format. Zero is returned if the address family is not supported. -1
1580 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1581 * supported.
1582 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001583int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001584{
1585
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001586 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001587
1588 if (size < 5)
1589 return 0;
1590 *str = '\0';
1591
1592 switch (addr->ss_family) {
1593 case AF_INET:
1594 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1595 break;
1596 case AF_INET6:
1597 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1598 break;
1599 case AF_UNIX:
1600 memcpy(str, "unix", 5);
1601 return addr->ss_family;
1602 default:
1603 return 0;
1604 }
1605
1606 if (inet_ntop(addr->ss_family, ptr, str, size))
1607 return addr->ss_family;
1608
1609 /* failed */
1610 return -1;
1611}
1612
Simon Horman75ab8bd2014-06-16 09:39:41 +09001613/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1614 * address family is returned so that it's easy for the caller to adapt to the
1615 * output format. Zero is returned if the address family is not supported. -1
1616 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1617 * supported.
1618 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001619int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001620{
1621
1622 uint16_t port;
1623
1624
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001625 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001626 return 0;
1627 *str = '\0';
1628
1629 switch (addr->ss_family) {
1630 case AF_INET:
1631 port = ((struct sockaddr_in *)addr)->sin_port;
1632 break;
1633 case AF_INET6:
1634 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1635 break;
1636 case AF_UNIX:
1637 memcpy(str, "unix", 5);
1638 return addr->ss_family;
1639 default:
1640 return 0;
1641 }
1642
1643 snprintf(str, size, "%u", ntohs(port));
1644 return addr->ss_family;
1645}
1646
Willy Tarreau16e01562016-08-09 16:46:18 +02001647/* check if the given address is local to the system or not. It will return
1648 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1649 * it is. We don't want to iterate over all interfaces for this (and it is not
1650 * portable). So instead we try to bind in UDP to this address on a free non
1651 * privileged port and to connect to the same address, port 0 (connect doesn't
1652 * care). If it succeeds, we own the address. Note that non-inet addresses are
1653 * considered local since they're most likely AF_UNIX.
1654 */
1655int addr_is_local(const struct netns_entry *ns,
1656 const struct sockaddr_storage *orig)
1657{
1658 struct sockaddr_storage addr;
1659 int result;
1660 int fd;
1661
1662 if (!is_inet_addr(orig))
1663 return 1;
1664
1665 memcpy(&addr, orig, sizeof(addr));
1666 set_host_port(&addr, 0);
1667
1668 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1669 if (fd < 0)
1670 return -1;
1671
1672 result = -1;
1673 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1674 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1675 result = 0; // fail, non-local address
1676 else
1677 result = 1; // success, local address
1678 }
1679 else {
1680 if (errno == EADDRNOTAVAIL)
1681 result = 0; // definitely not local :-)
1682 }
1683 close(fd);
1684
1685 return result;
1686}
1687
Willy Tarreaubaaee002006-06-26 02:48:02 +02001688/* will try to encode the string <string> replacing all characters tagged in
1689 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1690 * prefixed by <escape>, and will store the result between <start> (included)
1691 * and <stop> (excluded), and will always terminate the string with a '\0'
1692 * before <stop>. The position of the '\0' is returned if the conversion
1693 * completes. If bytes are missing between <start> and <stop>, then the
1694 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1695 * cannot even be stored so we return <start> without writing the 0.
1696 * The input string must also be zero-terminated.
1697 */
1698const char hextab[16] = "0123456789ABCDEF";
1699char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001700 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001701 const char *string)
1702{
1703 if (start < stop) {
1704 stop--; /* reserve one byte for the final '\0' */
1705 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001706 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001707 *start++ = *string;
1708 else {
1709 if (start + 3 >= stop)
1710 break;
1711 *start++ = escape;
1712 *start++ = hextab[(*string >> 4) & 15];
1713 *start++ = hextab[*string & 15];
1714 }
1715 string++;
1716 }
1717 *start = '\0';
1718 }
1719 return start;
1720}
1721
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001722/*
1723 * Same behavior as encode_string() above, except that it encodes chunk
1724 * <chunk> instead of a string.
1725 */
1726char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001727 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001728 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001729{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001730 char *str = chunk->area;
1731 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001732
1733 if (start < stop) {
1734 stop--; /* reserve one byte for the final '\0' */
1735 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001736 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001737 *start++ = *str;
1738 else {
1739 if (start + 3 >= stop)
1740 break;
1741 *start++ = escape;
1742 *start++ = hextab[(*str >> 4) & 15];
1743 *start++ = hextab[*str & 15];
1744 }
1745 str++;
1746 }
1747 *start = '\0';
1748 }
1749 return start;
1750}
1751
Dragan Dosen0edd1092016-02-12 13:23:02 +01001752/*
1753 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001754 * character. The input <string> must be zero-terminated. The result will
1755 * be stored between <start> (included) and <stop> (excluded). This
1756 * function will always try to terminate the resulting string with a '\0'
1757 * before <stop>, and will return its position if the conversion
1758 * completes.
1759 */
1760char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001761 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001762 const char *string)
1763{
1764 if (start < stop) {
1765 stop--; /* reserve one byte for the final '\0' */
1766 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001767 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001768 *start++ = *string;
1769 else {
1770 if (start + 2 >= stop)
1771 break;
1772 *start++ = escape;
1773 *start++ = *string;
1774 }
1775 string++;
1776 }
1777 *start = '\0';
1778 }
1779 return start;
1780}
1781
1782/*
1783 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001784 * character. <chunk> contains the input to be escaped. The result will be
1785 * stored between <start> (included) and <stop> (excluded). The function
1786 * will always try to terminate the resulting string with a '\0' before
1787 * <stop>, and will return its position if the conversion completes.
1788 */
1789char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001790 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001791 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001792{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001793 char *str = chunk->area;
1794 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001795
1796 if (start < stop) {
1797 stop--; /* reserve one byte for the final '\0' */
1798 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001799 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001800 *start++ = *str;
1801 else {
1802 if (start + 2 >= stop)
1803 break;
1804 *start++ = escape;
1805 *start++ = *str;
1806 }
1807 str++;
1808 }
1809 *start = '\0';
1810 }
1811 return start;
1812}
1813
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001814/* Check a string for using it in a CSV output format. If the string contains
1815 * one of the following four char <">, <,>, CR or LF, the string is
1816 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1817 * <str> is the input string to be escaped. The function assumes that
1818 * the input string is null-terminated.
1819 *
1820 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001821 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001822 * format.
1823 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001824 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001825 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001826 * If <quote> is 1, the converter puts the quotes only if any reserved character
1827 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001828 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001829 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001830 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001831 * The function returns the converted string on its output. If an error
1832 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001833 * for using the function directly as printf() argument.
1834 *
1835 * If the output buffer is too short to contain the input string, the result
1836 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001837 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001838 * This function appends the encoding to the existing output chunk, and it
1839 * guarantees that it starts immediately at the first available character of
1840 * the chunk. Please use csv_enc() instead if you want to replace the output
1841 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001842 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001843const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001844{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001845 char *end = output->area + output->size;
1846 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001847 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001848
Willy Tarreaub631c292016-01-08 10:04:08 +01001849 if (quote == 1) {
1850 /* automatic quoting: first verify if we'll have to quote the string */
1851 if (!strpbrk(str, "\n\r,\""))
1852 quote = 0;
1853 }
1854
1855 if (quote)
1856 *ptr++ = '"';
1857
Willy Tarreau898529b2016-01-06 18:07:04 +01001858 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1859 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001860 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001861 ptr++;
1862 if (ptr >= end - 2) {
1863 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001864 break;
1865 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001866 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001867 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001868 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001869 str++;
1870 }
1871
Willy Tarreaub631c292016-01-08 10:04:08 +01001872 if (quote)
1873 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001874
Willy Tarreau898529b2016-01-06 18:07:04 +01001875 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001876 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001877 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001878}
1879
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001880/* Decode an URL-encoded string in-place. The resulting string might
1881 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001882 * aborted, the string is truncated before the issue and a negative value is
1883 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001884 * If the 'in_form' argument is non-nul the string is assumed to be part of
1885 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1886 * turned to a space. If it's zero, this will only be done after a question
1887 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001888 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001889int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001890{
1891 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001892 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001893
1894 in = string;
1895 out = string;
1896 while (*in) {
1897 switch (*in) {
1898 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001899 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001900 break;
1901 case '%' :
1902 if (!ishex(in[1]) || !ishex(in[2]))
1903 goto end;
1904 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1905 in += 2;
1906 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001907 case '?':
1908 in_form = 1;
1909 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001910 default:
1911 *out++ = *in;
1912 break;
1913 }
1914 in++;
1915 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001916 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001917 end:
1918 *out = 0;
1919 return ret;
1920}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001921
Willy Tarreau6911fa42007-03-04 18:06:08 +01001922unsigned int str2ui(const char *s)
1923{
1924 return __str2ui(s);
1925}
1926
1927unsigned int str2uic(const char *s)
1928{
1929 return __str2uic(s);
1930}
1931
1932unsigned int strl2ui(const char *s, int len)
1933{
1934 return __strl2ui(s, len);
1935}
1936
1937unsigned int strl2uic(const char *s, int len)
1938{
1939 return __strl2uic(s, len);
1940}
1941
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001942unsigned int read_uint(const char **s, const char *end)
1943{
1944 return __read_uint(s, end);
1945}
1946
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001947/* This function reads an unsigned integer from the string pointed to by <s> and
1948 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1949 * function automatically stops at <end>. If the number overflows, the 2^64-1
1950 * value is returned.
1951 */
1952unsigned long long int read_uint64(const char **s, const char *end)
1953{
1954 const char *ptr = *s;
1955 unsigned long long int i = 0, tmp;
1956 unsigned int j;
1957
1958 while (ptr < end) {
1959
1960 /* read next char */
1961 j = *ptr - '0';
1962 if (j > 9)
1963 goto read_uint64_end;
1964
1965 /* add char to the number and check overflow. */
1966 tmp = i * 10;
1967 if (tmp / 10 != i) {
1968 i = ULLONG_MAX;
1969 goto read_uint64_eat;
1970 }
1971 if (ULLONG_MAX - tmp < j) {
1972 i = ULLONG_MAX;
1973 goto read_uint64_eat;
1974 }
1975 i = tmp + j;
1976 ptr++;
1977 }
1978read_uint64_eat:
1979 /* eat each numeric char */
1980 while (ptr < end) {
1981 if ((unsigned int)(*ptr - '0') > 9)
1982 break;
1983 ptr++;
1984 }
1985read_uint64_end:
1986 *s = ptr;
1987 return i;
1988}
1989
1990/* This function reads an integer from the string pointed to by <s> and returns
1991 * it. The <s> pointer is adjusted to point to the first unread char. The function
1992 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1993 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1994 * returned.
1995 */
1996long long int read_int64(const char **s, const char *end)
1997{
1998 unsigned long long int i = 0;
1999 int neg = 0;
2000
2001 /* Look for minus char. */
2002 if (**s == '-') {
2003 neg = 1;
2004 (*s)++;
2005 }
2006 else if (**s == '+')
2007 (*s)++;
2008
2009 /* convert as positive number. */
2010 i = read_uint64(s, end);
2011
2012 if (neg) {
2013 if (i > 0x8000000000000000ULL)
2014 return LLONG_MIN;
2015 return -i;
2016 }
2017 if (i > 0x7fffffffffffffffULL)
2018 return LLONG_MAX;
2019 return i;
2020}
2021
Willy Tarreau6911fa42007-03-04 18:06:08 +01002022/* This one is 7 times faster than strtol() on athlon with checks.
2023 * It returns the value of the number composed of all valid digits read,
2024 * and can process negative numbers too.
2025 */
2026int strl2ic(const char *s, int len)
2027{
2028 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002029 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002030
2031 if (len > 0) {
2032 if (*s != '-') {
2033 /* positive number */
2034 while (len-- > 0) {
2035 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002036 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002037 if (j > 9)
2038 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002039 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002040 }
2041 } else {
2042 /* negative number */
2043 s++;
2044 while (--len > 0) {
2045 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002046 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002047 if (j > 9)
2048 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002049 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002050 }
2051 }
2052 }
2053 return i;
2054}
2055
2056
2057/* This function reads exactly <len> chars from <s> and converts them to a
2058 * signed integer which it stores into <ret>. It accurately detects any error
2059 * (truncated string, invalid chars, overflows). It is meant to be used in
2060 * applications designed for hostile environments. It returns zero when the
2061 * number has successfully been converted, non-zero otherwise. When an error
2062 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2063 * faster than strtol().
2064 */
2065int strl2irc(const char *s, int len, int *ret)
2066{
2067 int i = 0;
2068 int j;
2069
2070 if (!len)
2071 return 1;
2072
2073 if (*s != '-') {
2074 /* positive number */
2075 while (len-- > 0) {
2076 j = (*s++) - '0';
2077 if (j > 9) return 1; /* invalid char */
2078 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2079 i = i * 10;
2080 if (i + j < i) return 1; /* check for addition overflow */
2081 i = i + j;
2082 }
2083 } else {
2084 /* negative number */
2085 s++;
2086 while (--len > 0) {
2087 j = (*s++) - '0';
2088 if (j > 9) return 1; /* invalid char */
2089 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2090 i = i * 10;
2091 if (i - j > i) return 1; /* check for subtract overflow */
2092 i = i - j;
2093 }
2094 }
2095 *ret = i;
2096 return 0;
2097}
2098
2099
2100/* This function reads exactly <len> chars from <s> and converts them to a
2101 * signed integer which it stores into <ret>. It accurately detects any error
2102 * (truncated string, invalid chars, overflows). It is meant to be used in
2103 * applications designed for hostile environments. It returns zero when the
2104 * number has successfully been converted, non-zero otherwise. When an error
2105 * is returned, the <ret> value is left untouched. It is about 3 times slower
2106 * than str2irc().
2107 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002108
2109int strl2llrc(const char *s, int len, long long *ret)
2110{
2111 long long i = 0;
2112 int j;
2113
2114 if (!len)
2115 return 1;
2116
2117 if (*s != '-') {
2118 /* positive number */
2119 while (len-- > 0) {
2120 j = (*s++) - '0';
2121 if (j > 9) return 1; /* invalid char */
2122 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2123 i = i * 10LL;
2124 if (i + j < i) return 1; /* check for addition overflow */
2125 i = i + j;
2126 }
2127 } else {
2128 /* negative number */
2129 s++;
2130 while (--len > 0) {
2131 j = (*s++) - '0';
2132 if (j > 9) return 1; /* invalid char */
2133 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2134 i = i * 10LL;
2135 if (i - j > i) return 1; /* check for subtract overflow */
2136 i = i - j;
2137 }
2138 }
2139 *ret = i;
2140 return 0;
2141}
2142
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002143/* This function is used with pat_parse_dotted_ver(). It converts a string
2144 * composed by two number separated by a dot. Each part must contain in 16 bits
2145 * because internally they will be represented as a 32-bit quantity stored in
2146 * a 64-bit integer. It returns zero when the number has successfully been
2147 * converted, non-zero otherwise. When an error is returned, the <ret> value
2148 * is left untouched.
2149 *
2150 * "1.3" -> 0x0000000000010003
2151 * "65535.65535" -> 0x00000000ffffffff
2152 */
2153int strl2llrc_dotted(const char *text, int len, long long *ret)
2154{
2155 const char *end = &text[len];
2156 const char *p;
2157 long long major, minor;
2158
2159 /* Look for dot. */
2160 for (p = text; p < end; p++)
2161 if (*p == '.')
2162 break;
2163
2164 /* Convert major. */
2165 if (strl2llrc(text, p - text, &major) != 0)
2166 return 1;
2167
2168 /* Check major. */
2169 if (major >= 65536)
2170 return 1;
2171
2172 /* Convert minor. */
2173 minor = 0;
2174 if (p < end)
2175 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2176 return 1;
2177
2178 /* Check minor. */
2179 if (minor >= 65536)
2180 return 1;
2181
2182 /* Compose value. */
2183 *ret = (major << 16) | (minor & 0xffff);
2184 return 0;
2185}
2186
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002187/* This function parses a time value optionally followed by a unit suffix among
2188 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2189 * expected by the caller. The computation does its best to avoid overflows.
2190 * The value is returned in <ret> if everything is fine, and a NULL is returned
2191 * by the function. In case of error, a pointer to the error is returned and
2192 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002193 * Values resulting in values larger than or equal to 2^31 after conversion are
2194 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2195 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002196 */
2197const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2198{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002199 unsigned long long imult, idiv;
2200 unsigned long long omult, odiv;
2201 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002202
2203 omult = odiv = 1;
2204
2205 switch (unit_flags & TIME_UNIT_MASK) {
2206 case TIME_UNIT_US: omult = 1000000; break;
2207 case TIME_UNIT_MS: omult = 1000; break;
2208 case TIME_UNIT_S: break;
2209 case TIME_UNIT_MIN: odiv = 60; break;
2210 case TIME_UNIT_HOUR: odiv = 3600; break;
2211 case TIME_UNIT_DAY: odiv = 86400; break;
2212 default: break;
2213 }
2214
2215 value = 0;
2216
2217 while (1) {
2218 unsigned int j;
2219
2220 j = *text - '0';
2221 if (j > 9)
2222 break;
2223 text++;
2224 value *= 10;
2225 value += j;
2226 }
2227
2228 imult = idiv = 1;
2229 switch (*text) {
2230 case '\0': /* no unit = default unit */
2231 imult = omult = idiv = odiv = 1;
2232 break;
2233 case 's': /* second = unscaled unit */
2234 break;
2235 case 'u': /* microsecond : "us" */
2236 if (text[1] == 's') {
2237 idiv = 1000000;
2238 text++;
2239 }
2240 break;
2241 case 'm': /* millisecond : "ms" or minute: "m" */
2242 if (text[1] == 's') {
2243 idiv = 1000;
2244 text++;
2245 } else
2246 imult = 60;
2247 break;
2248 case 'h': /* hour : "h" */
2249 imult = 3600;
2250 break;
2251 case 'd': /* day : "d" */
2252 imult = 86400;
2253 break;
2254 default:
2255 return text;
2256 break;
2257 }
2258
2259 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2260 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2261 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2262 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2263
Willy Tarreau9faebe32019-06-07 19:00:37 +02002264 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2265 if (result >= 0x80000000)
2266 return PARSE_TIME_OVER;
2267 if (!result && value)
2268 return PARSE_TIME_UNDER;
2269 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002270 return NULL;
2271}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002272
Emeric Brun39132b22010-01-04 14:57:24 +01002273/* this function converts the string starting at <text> to an unsigned int
2274 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002275 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002276 */
2277const char *parse_size_err(const char *text, unsigned *ret) {
2278 unsigned value = 0;
2279
2280 while (1) {
2281 unsigned int j;
2282
2283 j = *text - '0';
2284 if (j > 9)
2285 break;
2286 if (value > ~0U / 10)
2287 return text;
2288 value *= 10;
2289 if (value > (value + j))
2290 return text;
2291 value += j;
2292 text++;
2293 }
2294
2295 switch (*text) {
2296 case '\0':
2297 break;
2298 case 'K':
2299 case 'k':
2300 if (value > ~0U >> 10)
2301 return text;
2302 value = value << 10;
2303 break;
2304 case 'M':
2305 case 'm':
2306 if (value > ~0U >> 20)
2307 return text;
2308 value = value << 20;
2309 break;
2310 case 'G':
2311 case 'g':
2312 if (value > ~0U >> 30)
2313 return text;
2314 value = value << 30;
2315 break;
2316 default:
2317 return text;
2318 }
2319
Godbach58048a22015-01-28 17:36:16 +08002320 if (*text != '\0' && *++text != '\0')
2321 return text;
2322
Emeric Brun39132b22010-01-04 14:57:24 +01002323 *ret = value;
2324 return NULL;
2325}
2326
Willy Tarreau126d4062013-12-03 17:50:47 +01002327/*
2328 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002329 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002330 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002331 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002332 */
2333int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2334{
2335 int len;
2336 const char *p = source;
2337 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002338 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002339
2340 len = strlen(source);
2341 if (len % 2) {
2342 memprintf(err, "an even number of hex digit is expected");
2343 return 0;
2344 }
2345
2346 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002347
Willy Tarreau126d4062013-12-03 17:50:47 +01002348 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002349 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002350 if (!*binstr) {
2351 memprintf(err, "out of memory while loading string pattern");
2352 return 0;
2353 }
2354 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002355 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002356 else {
2357 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002358 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002359 len, *binstrlen);
2360 return 0;
2361 }
2362 alloc = 0;
2363 }
2364 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002365
2366 i = j = 0;
2367 while (j < len) {
2368 if (!ishex(p[i++]))
2369 goto bad_input;
2370 if (!ishex(p[i++]))
2371 goto bad_input;
2372 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2373 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002374 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002375
2376bad_input:
2377 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002378 if (alloc) {
2379 free(*binstr);
2380 *binstr = NULL;
2381 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002382 return 0;
2383}
2384
Willy Tarreau946ba592009-05-10 15:41:18 +02002385/* copies at most <n> characters from <src> and always terminates with '\0' */
2386char *my_strndup(const char *src, int n)
2387{
2388 int len = 0;
2389 char *ret;
2390
2391 while (len < n && src[len])
2392 len++;
2393
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002394 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002395 if (!ret)
2396 return ret;
2397 memcpy(ret, src, len);
2398 ret[len] = '\0';
2399 return ret;
2400}
2401
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002402/*
2403 * search needle in haystack
2404 * returns the pointer if found, returns NULL otherwise
2405 */
2406const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2407{
2408 const void *c = NULL;
2409 unsigned char f;
2410
2411 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2412 return NULL;
2413
2414 f = *(char *)needle;
2415 c = haystack;
2416 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2417 if ((haystacklen - (c - haystack)) < needlelen)
2418 return NULL;
2419
2420 if (memcmp(c, needle, needlelen) == 0)
2421 return c;
2422 ++c;
2423 }
2424 return NULL;
2425}
2426
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002427/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002428size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2429{
2430 size_t ret = 0;
2431
2432 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2433 str++;
2434 ret++;
2435 }
2436 return ret;
2437}
2438
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002439/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002440size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2441{
2442 size_t ret = 0;
2443
2444 while (ret < len) {
2445 if(memchr(reject, *((int *)str), rejectlen))
2446 return ret;
2447 str++;
2448 ret++;
2449 }
2450 return ret;
2451}
2452
Willy Tarreau482b00d2009-10-04 22:48:42 +02002453/* This function returns the first unused key greater than or equal to <key> in
2454 * ID tree <root>. Zero is returned if no place is found.
2455 */
2456unsigned int get_next_id(struct eb_root *root, unsigned int key)
2457{
2458 struct eb32_node *used;
2459
2460 do {
2461 used = eb32_lookup_ge(root, key);
2462 if (!used || used->key > key)
2463 return key; /* key is available */
2464 key++;
2465 } while (key);
2466 return key;
2467}
2468
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002469/* dump the full tree to <file> in DOT format for debugging purposes. Will
2470 * optionally highlight node <subj> if found, depending on operation <op> :
2471 * 0 : nothing
2472 * >0 : insertion, node/leaf are surrounded in red
2473 * <0 : removal, node/leaf are dashed with no background
2474 * Will optionally add "desc" as a label on the graph if set and non-null.
2475 */
2476void 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 +01002477{
2478 struct eb32sc_node *node;
2479 unsigned long scope = -1;
2480
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002481 fprintf(file, "digraph ebtree {\n");
2482
2483 if (desc && *desc) {
2484 fprintf(file,
2485 " fontname=\"fixed\";\n"
2486 " fontsize=8;\n"
2487 " label=\"%s\";\n", desc);
2488 }
2489
Willy Tarreaued3cda02017-11-15 15:04:05 +01002490 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002491 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2492 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002493 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2494 );
2495
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002496 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002497 (long)eb_root_to_node(root),
2498 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002499 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2500
2501 node = eb32sc_first(root, scope);
2502 while (node) {
2503 if (node->node.node_p) {
2504 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002505 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2506 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2507 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002508
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002509 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002510 (long)node,
2511 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002512 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002513
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002514 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002515 (long)node,
2516 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002517 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2518
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002519 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002520 (long)node,
2521 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002522 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2523 }
2524
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002525 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2526 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2527 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002528
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002529 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002530 (long)node,
2531 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002532 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002533 node = eb32sc_next(node, scope);
2534 }
2535 fprintf(file, "}\n");
2536}
2537
Willy Tarreau348238b2010-01-18 15:05:57 +01002538/* This function compares a sample word possibly followed by blanks to another
2539 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2540 * otherwise zero. This intends to be used when checking HTTP headers for some
2541 * values. Note that it validates a word followed only by blanks but does not
2542 * validate a word followed by blanks then other chars.
2543 */
2544int word_match(const char *sample, int slen, const char *word, int wlen)
2545{
2546 if (slen < wlen)
2547 return 0;
2548
2549 while (wlen) {
2550 char c = *sample ^ *word;
2551 if (c && c != ('A' ^ 'a'))
2552 return 0;
2553 sample++;
2554 word++;
2555 slen--;
2556 wlen--;
2557 }
2558
2559 while (slen) {
2560 if (*sample != ' ' && *sample != '\t')
2561 return 0;
2562 sample++;
2563 slen--;
2564 }
2565 return 1;
2566}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002567
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002568/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2569 * is particularly fast because it avoids expensive operations such as
2570 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002571 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002572 */
2573unsigned int inetaddr_host(const char *text)
2574{
2575 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2576 register unsigned int dig100, dig10, dig1;
2577 int s;
2578 const char *p, *d;
2579
2580 dig1 = dig10 = dig100 = ascii_zero;
2581 s = 24;
2582
2583 p = text;
2584 while (1) {
2585 if (((unsigned)(*p - '0')) <= 9) {
2586 p++;
2587 continue;
2588 }
2589
2590 /* here, we have a complete byte between <text> and <p> (exclusive) */
2591 if (p == text)
2592 goto end;
2593
2594 d = p - 1;
2595 dig1 |= (unsigned int)(*d << s);
2596 if (d == text)
2597 goto end;
2598
2599 d--;
2600 dig10 |= (unsigned int)(*d << s);
2601 if (d == text)
2602 goto end;
2603
2604 d--;
2605 dig100 |= (unsigned int)(*d << s);
2606 end:
2607 if (!s || *p != '.')
2608 break;
2609
2610 s -= 8;
2611 text = ++p;
2612 }
2613
2614 dig100 -= ascii_zero;
2615 dig10 -= ascii_zero;
2616 dig1 -= ascii_zero;
2617 return ((dig100 * 10) + dig10) * 10 + dig1;
2618}
2619
2620/*
2621 * Idem except the first unparsed character has to be passed in <stop>.
2622 */
2623unsigned int inetaddr_host_lim(const char *text, const char *stop)
2624{
2625 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2626 register unsigned int dig100, dig10, dig1;
2627 int s;
2628 const char *p, *d;
2629
2630 dig1 = dig10 = dig100 = ascii_zero;
2631 s = 24;
2632
2633 p = text;
2634 while (1) {
2635 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2636 p++;
2637 continue;
2638 }
2639
2640 /* here, we have a complete byte between <text> and <p> (exclusive) */
2641 if (p == text)
2642 goto end;
2643
2644 d = p - 1;
2645 dig1 |= (unsigned int)(*d << s);
2646 if (d == text)
2647 goto end;
2648
2649 d--;
2650 dig10 |= (unsigned int)(*d << s);
2651 if (d == text)
2652 goto end;
2653
2654 d--;
2655 dig100 |= (unsigned int)(*d << s);
2656 end:
2657 if (!s || p == stop || *p != '.')
2658 break;
2659
2660 s -= 8;
2661 text = ++p;
2662 }
2663
2664 dig100 -= ascii_zero;
2665 dig10 -= ascii_zero;
2666 dig1 -= ascii_zero;
2667 return ((dig100 * 10) + dig10) * 10 + dig1;
2668}
2669
2670/*
2671 * Idem except the pointer to first unparsed byte is returned into <ret> which
2672 * must not be NULL.
2673 */
Willy Tarreau74172752010-10-15 23:21:42 +02002674unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002675{
2676 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2677 register unsigned int dig100, dig10, dig1;
2678 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002679 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002680
2681 dig1 = dig10 = dig100 = ascii_zero;
2682 s = 24;
2683
2684 p = text;
2685 while (1) {
2686 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2687 p++;
2688 continue;
2689 }
2690
2691 /* here, we have a complete byte between <text> and <p> (exclusive) */
2692 if (p == text)
2693 goto end;
2694
2695 d = p - 1;
2696 dig1 |= (unsigned int)(*d << s);
2697 if (d == text)
2698 goto end;
2699
2700 d--;
2701 dig10 |= (unsigned int)(*d << s);
2702 if (d == text)
2703 goto end;
2704
2705 d--;
2706 dig100 |= (unsigned int)(*d << s);
2707 end:
2708 if (!s || p == stop || *p != '.')
2709 break;
2710
2711 s -= 8;
2712 text = ++p;
2713 }
2714
2715 *ret = p;
2716 dig100 -= ascii_zero;
2717 dig10 -= ascii_zero;
2718 dig1 -= ascii_zero;
2719 return ((dig100 * 10) + dig10) * 10 + dig1;
2720}
2721
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002722/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2723 * or the number of chars read in case of success. Maybe this could be replaced
2724 * by one of the functions above. Also, apparently this function does not support
2725 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002726 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002727 */
2728int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2729{
2730 const char *addr;
2731 int saw_digit, octets, ch;
2732 u_char tmp[4], *tp;
2733 const char *cp = buf;
2734
2735 saw_digit = 0;
2736 octets = 0;
2737 *(tp = tmp) = 0;
2738
2739 for (addr = buf; addr - buf < len; addr++) {
2740 unsigned char digit = (ch = *addr) - '0';
2741
2742 if (digit > 9 && ch != '.')
2743 break;
2744
2745 if (digit <= 9) {
2746 u_int new = *tp * 10 + digit;
2747
2748 if (new > 255)
2749 return 0;
2750
2751 *tp = new;
2752
2753 if (!saw_digit) {
2754 if (++octets > 4)
2755 return 0;
2756 saw_digit = 1;
2757 }
2758 } else if (ch == '.' && saw_digit) {
2759 if (octets == 4)
2760 return 0;
2761
2762 *++tp = 0;
2763 saw_digit = 0;
2764 } else
2765 return 0;
2766 }
2767
2768 if (octets < 4)
2769 return 0;
2770
2771 memcpy(&dst->s_addr, tmp, 4);
2772 return addr - cp;
2773}
2774
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002775/* This function converts the string in <buf> of the len <len> to
2776 * struct in6_addr <dst> which must be allocated by the caller.
2777 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002778 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002779 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002780int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2781{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002782 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002783 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002784
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002785 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002786 return 0;
2787
2788 memcpy(null_term_ip6, buf, len);
2789 null_term_ip6[len] = '\0';
2790
Willy Tarreau075415a2013-12-12 11:29:39 +01002791 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002792 return 0;
2793
Willy Tarreau075415a2013-12-12 11:29:39 +01002794 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002795 return 1;
2796}
2797
Willy Tarreauacf95772010-06-14 19:09:21 +02002798/* To be used to quote config arg positions. Returns the short string at <ptr>
2799 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2800 * if ptr is NULL or empty. The string is locally allocated.
2801 */
2802const char *quote_arg(const char *ptr)
2803{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002804 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002805 int i;
2806
2807 if (!ptr || !*ptr)
2808 return "end of line";
2809 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002810 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002811 val[i] = *ptr++;
2812 val[i++] = '\'';
2813 val[i] = '\0';
2814 return val;
2815}
2816
Willy Tarreau5b180202010-07-18 10:40:48 +02002817/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2818int get_std_op(const char *str)
2819{
2820 int ret = -1;
2821
2822 if (*str == 'e' && str[1] == 'q')
2823 ret = STD_OP_EQ;
2824 else if (*str == 'n' && str[1] == 'e')
2825 ret = STD_OP_NE;
2826 else if (*str == 'l') {
2827 if (str[1] == 'e') ret = STD_OP_LE;
2828 else if (str[1] == 't') ret = STD_OP_LT;
2829 }
2830 else if (*str == 'g') {
2831 if (str[1] == 'e') ret = STD_OP_GE;
2832 else if (str[1] == 't') ret = STD_OP_GT;
2833 }
2834
2835 if (ret == -1 || str[2] != '\0')
2836 return -1;
2837 return ret;
2838}
2839
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002840/* hash a 32-bit integer to another 32-bit integer */
2841unsigned int full_hash(unsigned int a)
2842{
2843 return __full_hash(a);
2844}
2845
Willy Tarreauf3241112019-02-26 09:56:22 +01002846/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2847 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2848 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2849 * a popcount variant and is described here :
2850 * https://graphics.stanford.edu/~seander/bithacks.html
2851 */
2852unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2853{
2854 unsigned long a, b, c, d;
2855 unsigned int s;
2856 unsigned int t;
2857
2858 a = m - ((m >> 1) & ~0UL/3);
2859 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2860 c = (b + (b >> 4)) & ~0UL/0x11;
2861 d = (c + (c >> 8)) & ~0UL/0x101;
2862
2863 r++; // make r be 1..64
2864
2865 t = 0;
2866 s = LONGBITS;
2867 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002868 unsigned long d2 = (d >> 16) >> 16;
2869 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002870 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2871 }
2872
2873 t = (d >> (s - 16)) & 0xff;
2874 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2875 t = (c >> (s - 8)) & 0xf;
2876 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2877 t = (b >> (s - 4)) & 0x7;
2878 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2879 t = (a >> (s - 2)) & 0x3;
2880 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2881 t = (m >> (s - 1)) & 0x1;
2882 s -= ((t - r) & 256) >> 8;
2883
2884 return s - 1;
2885}
2886
2887/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2888 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2889 * using mask_prep_rank_map() below.
2890 */
2891unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2892 unsigned long a, unsigned long b,
2893 unsigned long c, unsigned long d)
2894{
2895 unsigned int s;
2896 unsigned int t;
2897
2898 r++; // make r be 1..64
2899
2900 t = 0;
2901 s = LONGBITS;
2902 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002903 unsigned long d2 = (d >> 16) >> 16;
2904 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002905 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2906 }
2907
2908 t = (d >> (s - 16)) & 0xff;
2909 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2910 t = (c >> (s - 8)) & 0xf;
2911 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2912 t = (b >> (s - 4)) & 0x7;
2913 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2914 t = (a >> (s - 2)) & 0x3;
2915 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2916 t = (m >> (s - 1)) & 0x1;
2917 s -= ((t - r) & 256) >> 8;
2918
2919 return s - 1;
2920}
2921
2922/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2923 * above.
2924 */
2925void mask_prep_rank_map(unsigned long m,
2926 unsigned long *a, unsigned long *b,
2927 unsigned long *c, unsigned long *d)
2928{
2929 *a = m - ((m >> 1) & ~0UL/3);
2930 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2931 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2932 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2933}
2934
David du Colombier4f92d322011-03-24 11:09:31 +01002935/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002936 * otherwise zero. Note that <addr> may not necessarily be aligned
2937 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002938 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002939int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002940{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002941 struct in_addr addr_copy;
2942
2943 memcpy(&addr_copy, addr, sizeof(addr_copy));
2944 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002945}
2946
2947/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002948 * otherwise zero. Note that <addr> may not necessarily be aligned
2949 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002950 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002951int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002952{
2953 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002954 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002955
Willy Tarreaueec1d382016-07-13 11:59:39 +02002956 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002957 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002958 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002959 (((int *)net)[i] & ((int *)mask)[i]))
2960 return 0;
2961 return 1;
2962}
2963
2964/* RFC 4291 prefix */
2965const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2966 0x00, 0x00, 0x00, 0x00,
2967 0x00, 0x00, 0xFF, 0xFF };
2968
Joseph Herlant32b83272018-11-15 11:58:28 -08002969/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002970 * Input and output may overlap.
2971 */
David du Colombier4f92d322011-03-24 11:09:31 +01002972void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2973{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002974 struct in_addr tmp_addr;
2975
2976 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002977 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002978 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002979}
2980
Joseph Herlant32b83272018-11-15 11:58:28 -08002981/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002982 * Return true if conversion is possible and false otherwise.
2983 */
2984int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2985{
2986 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2987 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2988 sizeof(struct in_addr));
2989 return 1;
2990 }
2991
2992 return 0;
2993}
2994
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002995/* compare two struct sockaddr_storage and return:
2996 * 0 (true) if the addr is the same in both
2997 * 1 (false) if the addr is not the same in both
2998 * -1 (unable) if one of the addr is not AF_INET*
2999 */
3000int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3001{
3002 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3003 return -1;
3004
3005 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3006 return -1;
3007
3008 if (ss1->ss_family != ss2->ss_family)
3009 return 1;
3010
3011 switch (ss1->ss_family) {
3012 case AF_INET:
3013 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3014 &((struct sockaddr_in *)ss2)->sin_addr,
3015 sizeof(struct in_addr)) != 0;
3016 case AF_INET6:
3017 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3018 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3019 sizeof(struct in6_addr)) != 0;
3020 }
3021
3022 return 1;
3023}
3024
Baptiste Assmann08396c82016-01-31 00:27:17 +01003025/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003026 * The caller must allocate and clear <dest> before calling.
3027 * The source must be in either AF_INET or AF_INET6 family, or the destination
3028 * address will be undefined. If the destination address used to hold a port,
3029 * it is preserved, so that this function can be used to switch to another
3030 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003031 */
3032struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3033{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003034 int prev_port;
3035
3036 prev_port = get_net_port(dest);
3037 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003038 dest->ss_family = source->ss_family;
3039
3040 /* copy new addr and apply it */
3041 switch (source->ss_family) {
3042 case AF_INET:
3043 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003044 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003045 break;
3046 case AF_INET6:
3047 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 +01003048 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003049 break;
3050 }
3051
3052 return dest;
3053}
3054
William Lallemand421f5b52012-02-06 18:15:57 +01003055char *human_time(int t, short hz_div) {
3056 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3057 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003058 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003059 int cnt=2; // print two numbers
3060
3061 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003062 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003063 return rv;
3064 }
3065
3066 if (unlikely(hz_div > 1))
3067 t /= hz_div;
3068
3069 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003070 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003071 cnt--;
3072 }
3073
3074 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003075 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003076 cnt--;
3077 }
3078
3079 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003080 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003081 cnt--;
3082 }
3083
3084 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003085 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003086
3087 return rv;
3088}
3089
3090const char *monthname[12] = {
3091 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3092 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3093};
3094
3095/* date2str_log: write a date in the format :
3096 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3097 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3098 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3099 *
3100 * without using sprintf. return a pointer to the last char written (\0) or
3101 * NULL if there isn't enough space.
3102 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003103char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003104{
3105
3106 if (size < 25) /* the size is fixed: 24 chars + \0 */
3107 return NULL;
3108
3109 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003110 if (!dst)
3111 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003112 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003113
William Lallemand421f5b52012-02-06 18:15:57 +01003114 memcpy(dst, monthname[tm->tm_mon], 3); // month
3115 dst += 3;
3116 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003117
William Lallemand421f5b52012-02-06 18:15:57 +01003118 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003119 if (!dst)
3120 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003121 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003122
William Lallemand421f5b52012-02-06 18:15:57 +01003123 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003124 if (!dst)
3125 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003126 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003127
William Lallemand421f5b52012-02-06 18:15:57 +01003128 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003129 if (!dst)
3130 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003131 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003132
William Lallemand421f5b52012-02-06 18:15:57 +01003133 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003134 if (!dst)
3135 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003136 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003137
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003138 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003139 if (!dst)
3140 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003141 *dst = '\0';
3142
3143 return dst;
3144}
3145
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003146/* Base year used to compute leap years */
3147#define TM_YEAR_BASE 1900
3148
3149/* Return the difference in seconds between two times (leap seconds are ignored).
3150 * Retrieved from glibc 2.18 source code.
3151 */
3152static int my_tm_diff(const struct tm *a, const struct tm *b)
3153{
3154 /* Compute intervening leap days correctly even if year is negative.
3155 * Take care to avoid int overflow in leap day calculations,
3156 * but it's OK to assume that A and B are close to each other.
3157 */
3158 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3159 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3160 int a100 = a4 / 25 - (a4 % 25 < 0);
3161 int b100 = b4 / 25 - (b4 % 25 < 0);
3162 int a400 = a100 >> 2;
3163 int b400 = b100 >> 2;
3164 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3165 int years = a->tm_year - b->tm_year;
3166 int days = (365 * years + intervening_leap_days
3167 + (a->tm_yday - b->tm_yday));
3168 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3169 + (a->tm_min - b->tm_min))
3170 + (a->tm_sec - b->tm_sec));
3171}
3172
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003173/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003174 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003175 * The string returned has the same format as returned by strftime(... "%z", tm).
3176 * Offsets are kept in an internal cache for better performances.
3177 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003178const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003179{
3180 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003181 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003182
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003183 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003184 struct tm tm_gmt;
3185 int diff;
3186 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003187
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003188 /* Pretend DST not active if its status is unknown */
3189 if (isdst < 0)
3190 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003191
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003192 /* Fetch the offset and initialize it if needed */
3193 gmt_offset = gmt_offsets[isdst & 0x01];
3194 if (unlikely(!*gmt_offset)) {
3195 get_gmtime(t, &tm_gmt);
3196 diff = my_tm_diff(tm, &tm_gmt);
3197 if (diff < 0) {
3198 diff = -diff;
3199 *gmt_offset = '-';
3200 } else {
3201 *gmt_offset = '+';
3202 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003203 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003204 diff /= 60; /* Convert to minutes */
3205 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3206 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003207
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003208 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003209}
3210
William Lallemand421f5b52012-02-06 18:15:57 +01003211/* gmt2str_log: write a date in the format :
3212 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3213 * return a pointer to the last char written (\0) or
3214 * NULL if there isn't enough space.
3215 */
3216char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3217{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003218 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003219 return NULL;
3220
3221 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003222 if (!dst)
3223 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003224 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003225
William Lallemand421f5b52012-02-06 18:15:57 +01003226 memcpy(dst, monthname[tm->tm_mon], 3); // month
3227 dst += 3;
3228 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003229
William Lallemand421f5b52012-02-06 18:15:57 +01003230 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003231 if (!dst)
3232 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003233 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003234
William Lallemand421f5b52012-02-06 18:15:57 +01003235 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003236 if (!dst)
3237 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003238 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003239
William Lallemand421f5b52012-02-06 18:15:57 +01003240 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003241 if (!dst)
3242 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003243 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003244
William Lallemand421f5b52012-02-06 18:15:57 +01003245 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003246 if (!dst)
3247 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003248 *dst++ = ' ';
3249 *dst++ = '+';
3250 *dst++ = '0';
3251 *dst++ = '0';
3252 *dst++ = '0';
3253 *dst++ = '0';
3254 *dst = '\0';
3255
3256 return dst;
3257}
3258
Yuxans Yao4e25b012012-10-19 10:36:09 +08003259/* localdate2str_log: write a date in the format :
3260 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003261 * Both t and tm must represent the same time.
3262 * return a pointer to the last char written (\0) or
3263 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003264 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003265char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003266{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003267 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003268 if (size < 27) /* the size is fixed: 26 chars + \0 */
3269 return NULL;
3270
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003271 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003272
Yuxans Yao4e25b012012-10-19 10:36:09 +08003273 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003274 if (!dst)
3275 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003276 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003277
Yuxans Yao4e25b012012-10-19 10:36:09 +08003278 memcpy(dst, monthname[tm->tm_mon], 3); // month
3279 dst += 3;
3280 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003281
Yuxans Yao4e25b012012-10-19 10:36:09 +08003282 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003283 if (!dst)
3284 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003285 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003286
Yuxans Yao4e25b012012-10-19 10:36:09 +08003287 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003288 if (!dst)
3289 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003290 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003291
Yuxans Yao4e25b012012-10-19 10:36:09 +08003292 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003293 if (!dst)
3294 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003295 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003296
Yuxans Yao4e25b012012-10-19 10:36:09 +08003297 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003298 if (!dst)
3299 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003300 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003301
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003302 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003303 dst += 5;
3304 *dst = '\0';
3305
3306 return dst;
3307}
3308
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003309/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3310 * It is meant as a portable replacement for timegm() for use with valid inputs.
3311 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3312 */
3313time_t my_timegm(const struct tm *tm)
3314{
3315 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3316 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3317 * sum of the extra N days for elapsed months. The sum of all these N
3318 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3319 * in a 5-bit word. This means that with 60 bits we can represent a
3320 * matrix of all these values at once, which is fast and efficient to
3321 * access. The extra February day for leap years is not counted here.
3322 *
3323 * Jan : none = 0 (0)
3324 * Feb : Jan = 3 (3)
3325 * Mar : Jan..Feb = 3 (3 + 0)
3326 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3327 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3328 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3329 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3330 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3331 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3332 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3333 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3334 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3335 */
3336 uint64_t extra =
3337 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3338 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3339 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3340 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3341
3342 unsigned int y = tm->tm_year + 1900;
3343 unsigned int m = tm->tm_mon;
3344 unsigned long days = 0;
3345
3346 /* days since 1/1/1970 for full years */
3347 days += days_since_zero(y) - days_since_zero(1970);
3348
3349 /* days for full months in the current year */
3350 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3351
3352 /* count + 1 after March for leap years. A leap year is a year multiple
3353 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3354 * is leap, 1900 isn't, 1904 is.
3355 */
3356 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3357 days++;
3358
3359 days += tm->tm_mday - 1;
3360 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3361}
3362
Thierry Fournier93127942016-01-20 18:49:45 +01003363/* This function check a char. It returns true and updates
3364 * <date> and <len> pointer to the new position if the
3365 * character is found.
3366 */
3367static inline int parse_expect_char(const char **date, int *len, char c)
3368{
3369 if (*len < 1 || **date != c)
3370 return 0;
3371 (*len)--;
3372 (*date)++;
3373 return 1;
3374}
3375
3376/* This function expects a string <str> of len <l>. It return true and updates.
3377 * <date> and <len> if the string matches, otherwise, it returns false.
3378 */
3379static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3380{
3381 if (*len < l || strncmp(*date, str, l) != 0)
3382 return 0;
3383 (*len) -= l;
3384 (*date) += l;
3385 return 1;
3386}
3387
3388/* This macro converts 3 chars name in integer. */
3389#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3390
3391/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3392 * / %x54.75.65 ; "Tue", case-sensitive
3393 * / %x57.65.64 ; "Wed", case-sensitive
3394 * / %x54.68.75 ; "Thu", case-sensitive
3395 * / %x46.72.69 ; "Fri", case-sensitive
3396 * / %x53.61.74 ; "Sat", case-sensitive
3397 * / %x53.75.6E ; "Sun", case-sensitive
3398 *
3399 * This array must be alphabetically sorted
3400 */
3401static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3402{
3403 if (*len < 3)
3404 return 0;
3405 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3406 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3407 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3408 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3409 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3410 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3411 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3412 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3413 default: return 0;
3414 }
3415 *len -= 3;
3416 *date += 3;
3417 return 1;
3418}
3419
3420/* month = %x4A.61.6E ; "Jan", case-sensitive
3421 * / %x46.65.62 ; "Feb", case-sensitive
3422 * / %x4D.61.72 ; "Mar", case-sensitive
3423 * / %x41.70.72 ; "Apr", case-sensitive
3424 * / %x4D.61.79 ; "May", case-sensitive
3425 * / %x4A.75.6E ; "Jun", case-sensitive
3426 * / %x4A.75.6C ; "Jul", case-sensitive
3427 * / %x41.75.67 ; "Aug", case-sensitive
3428 * / %x53.65.70 ; "Sep", case-sensitive
3429 * / %x4F.63.74 ; "Oct", case-sensitive
3430 * / %x4E.6F.76 ; "Nov", case-sensitive
3431 * / %x44.65.63 ; "Dec", case-sensitive
3432 *
3433 * This array must be alphabetically sorted
3434 */
3435static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3436{
3437 if (*len < 3)
3438 return 0;
3439 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3440 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3441 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3442 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3443 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3444 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3445 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3446 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3447 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3448 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3449 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3450 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3451 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3452 default: return 0;
3453 }
3454 *len -= 3;
3455 *date += 3;
3456 return 1;
3457}
3458
3459/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3460 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3461 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3462 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3463 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3464 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3465 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3466 *
3467 * This array must be alphabetically sorted
3468 */
3469static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3470{
3471 if (*len < 6) /* Minimum length. */
3472 return 0;
3473 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3474 case STR2I3('M','o','n'):
3475 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3476 tm->tm_wday = 1;
3477 return 1;
3478 case STR2I3('T','u','e'):
3479 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3480 tm->tm_wday = 2;
3481 return 1;
3482 case STR2I3('W','e','d'):
3483 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3484 tm->tm_wday = 3;
3485 return 1;
3486 case STR2I3('T','h','u'):
3487 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3488 tm->tm_wday = 4;
3489 return 1;
3490 case STR2I3('F','r','i'):
3491 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3492 tm->tm_wday = 5;
3493 return 1;
3494 case STR2I3('S','a','t'):
3495 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3496 tm->tm_wday = 6;
3497 return 1;
3498 case STR2I3('S','u','n'):
3499 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3500 tm->tm_wday = 7;
3501 return 1;
3502 }
3503 return 0;
3504}
3505
3506/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3507static inline int parse_digit(const char **date, int *len, int *digit)
3508{
3509 if (*len < 1 || **date < '0' || **date > '9')
3510 return 0;
3511 *digit = (**date - '0');
3512 (*date)++;
3513 (*len)--;
3514 return 1;
3515}
3516
3517/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3518static inline int parse_2digit(const char **date, int *len, int *digit)
3519{
3520 int value;
3521
3522 RET0_UNLESS(parse_digit(date, len, &value));
3523 (*digit) = value * 10;
3524 RET0_UNLESS(parse_digit(date, len, &value));
3525 (*digit) += value;
3526
3527 return 1;
3528}
3529
3530/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3531static inline int parse_4digit(const char **date, int *len, int *digit)
3532{
3533 int value;
3534
3535 RET0_UNLESS(parse_digit(date, len, &value));
3536 (*digit) = value * 1000;
3537
3538 RET0_UNLESS(parse_digit(date, len, &value));
3539 (*digit) += value * 100;
3540
3541 RET0_UNLESS(parse_digit(date, len, &value));
3542 (*digit) += value * 10;
3543
3544 RET0_UNLESS(parse_digit(date, len, &value));
3545 (*digit) += value;
3546
3547 return 1;
3548}
3549
3550/* time-of-day = hour ":" minute ":" second
3551 * ; 00:00:00 - 23:59:60 (leap second)
3552 *
3553 * hour = 2DIGIT
3554 * minute = 2DIGIT
3555 * second = 2DIGIT
3556 */
3557static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3558{
3559 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3560 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3561 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3562 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3563 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3564 return 1;
3565}
3566
3567/* From RFC7231
3568 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3569 *
3570 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3571 * ; fixed length/zone/capitalization subset of the format
3572 * ; see Section 3.3 of [RFC5322]
3573 *
3574 *
3575 * date1 = day SP month SP year
3576 * ; e.g., 02 Jun 1982
3577 *
3578 * day = 2DIGIT
3579 * year = 4DIGIT
3580 *
3581 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3582 *
3583 * time-of-day = hour ":" minute ":" second
3584 * ; 00:00:00 - 23:59:60 (leap second)
3585 *
3586 * hour = 2DIGIT
3587 * minute = 2DIGIT
3588 * second = 2DIGIT
3589 *
3590 * DIGIT = decimal 0-9
3591 */
3592int parse_imf_date(const char *date, int len, struct tm *tm)
3593{
David Carlier327298c2016-11-20 10:42:38 +00003594 /* tm_gmtoff, if present, ought to be zero'ed */
3595 memset(tm, 0, sizeof(*tm));
3596
Thierry Fournier93127942016-01-20 18:49:45 +01003597 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3598 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3599 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3600 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3601 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3602 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3603 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3604 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3605 tm->tm_year -= 1900;
3606 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3607 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3608 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3609 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3610 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003611 return 1;
3612}
3613
3614/* From RFC7231
3615 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3616 *
3617 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3618 * date2 = day "-" month "-" 2DIGIT
3619 * ; e.g., 02-Jun-82
3620 *
3621 * day = 2DIGIT
3622 */
3623int parse_rfc850_date(const char *date, int len, struct tm *tm)
3624{
3625 int year;
3626
David Carlier327298c2016-11-20 10:42:38 +00003627 /* tm_gmtoff, if present, ought to be zero'ed */
3628 memset(tm, 0, sizeof(*tm));
3629
Thierry Fournier93127942016-01-20 18:49:45 +01003630 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3631 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3632 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3633 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3634 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3635 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3636 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3637
3638 /* year = 2DIGIT
3639 *
3640 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3641 * two-digit year, MUST interpret a timestamp that appears to be more
3642 * than 50 years in the future as representing the most recent year in
3643 * the past that had the same last two digits.
3644 */
3645 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3646
3647 /* expect SP */
3648 if (!parse_expect_char(&date, &len, ' ')) {
3649 /* Maybe we have the date with 4 digits. */
3650 RET0_UNLESS(parse_2digit(&date, &len, &year));
3651 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3652 /* expect SP */
3653 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3654 } else {
3655 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3656 * tm_year is the number of year since 1900, so for +1900, we
3657 * do nothing, and for +2000, we add 100.
3658 */
3659 if (tm->tm_year <= 60)
3660 tm->tm_year += 100;
3661 }
3662
3663 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3664 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3665 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3666 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003667
3668 return 1;
3669}
3670
3671/* From RFC7231
3672 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3673 *
3674 * asctime-date = day-name SP date3 SP time-of-day SP year
3675 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3676 * ; e.g., Jun 2
3677 *
3678 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3679 * whitespace in an HTTP-date beyond that specifically included as SP in
3680 * the grammar.
3681 */
3682int parse_asctime_date(const char *date, int len, struct tm *tm)
3683{
David Carlier327298c2016-11-20 10:42:38 +00003684 /* tm_gmtoff, if present, ought to be zero'ed */
3685 memset(tm, 0, sizeof(*tm));
3686
Thierry Fournier93127942016-01-20 18:49:45 +01003687 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3688 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3689 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3690 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3691
3692 /* expect SP and 1DIGIT or 2DIGIT */
3693 if (parse_expect_char(&date, &len, ' '))
3694 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3695 else
3696 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3697
3698 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3699 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3700 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3701 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3702 tm->tm_year -= 1900;
3703 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003704 return 1;
3705}
3706
3707/* From RFC7231
3708 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3709 *
3710 * HTTP-date = IMF-fixdate / obs-date
3711 * obs-date = rfc850-date / asctime-date
3712 *
3713 * parses an HTTP date in the RFC format and is accepted
3714 * alternatives. <date> is the strinf containing the date,
3715 * len is the len of the string. <tm> is filled with the
3716 * parsed time. We must considers this time as GMT.
3717 */
3718int parse_http_date(const char *date, int len, struct tm *tm)
3719{
3720 if (parse_imf_date(date, len, tm))
3721 return 1;
3722
3723 if (parse_rfc850_date(date, len, tm))
3724 return 1;
3725
3726 if (parse_asctime_date(date, len, tm))
3727 return 1;
3728
3729 return 0;
3730}
3731
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003732/* Dynamically allocates a string of the proper length to hold the formatted
3733 * output. NULL is returned on error. The caller is responsible for freeing the
3734 * memory area using free(). The resulting string is returned in <out> if the
3735 * pointer is not NULL. A previous version of <out> might be used to build the
3736 * new string, and it will be freed before returning if it is not NULL, which
3737 * makes it possible to build complex strings from iterative calls without
3738 * having to care about freeing intermediate values, as in the example below :
3739 *
3740 * memprintf(&err, "invalid argument: '%s'", arg);
3741 * ...
3742 * memprintf(&err, "parser said : <%s>\n", *err);
3743 * ...
3744 * free(*err);
3745 *
3746 * This means that <err> must be initialized to NULL before first invocation.
3747 * The return value also holds the allocated string, which eases error checking
3748 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003749 * passed instead and it will be ignored. The returned message will then also
3750 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003751 *
3752 * It is also convenient to use it without any free except the last one :
3753 * err = NULL;
3754 * if (!fct1(err)) report(*err);
3755 * if (!fct2(err)) report(*err);
3756 * if (!fct3(err)) report(*err);
3757 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003758 *
3759 * memprintf relies on memvprintf. This last version can be called from any
3760 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003761 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003762char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003763{
3764 va_list args;
3765 char *ret = NULL;
3766 int allocated = 0;
3767 int needed = 0;
3768
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003769 if (!out)
3770 return NULL;
3771
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003772 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003773 char buf1;
3774
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003775 /* vsnprintf() will return the required length even when the
3776 * target buffer is NULL. We do this in a loop just in case
3777 * intermediate evaluations get wrong.
3778 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003779 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003780 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003781 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003782 if (needed < allocated) {
3783 /* Note: on Solaris 8, the first iteration always
3784 * returns -1 if allocated is zero, so we force a
3785 * retry.
3786 */
3787 if (!allocated)
3788 needed = 0;
3789 else
3790 break;
3791 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003792
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003793 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003794 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003795 } while (ret);
3796
3797 if (needed < 0) {
3798 /* an error was encountered */
3799 free(ret);
3800 ret = NULL;
3801 }
3802
3803 if (out) {
3804 free(*out);
3805 *out = ret;
3806 }
3807
3808 return ret;
3809}
William Lallemand421f5b52012-02-06 18:15:57 +01003810
Christopher Faulet93a518f2017-10-24 11:25:33 +02003811char *memprintf(char **out, const char *format, ...)
3812{
3813 va_list args;
3814 char *ret = NULL;
3815
3816 va_start(args, format);
3817 ret = memvprintf(out, format, args);
3818 va_end(args);
3819
3820 return ret;
3821}
3822
Willy Tarreau21c705b2012-09-14 11:40:36 +02003823/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3824 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003825 * freed by the caller. It also supports being passed a NULL which results in the same
3826 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003827 * Example of use :
3828 * parse(cmd, &err); (callee: memprintf(&err, ...))
3829 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3830 * free(err);
3831 */
3832char *indent_msg(char **out, int level)
3833{
3834 char *ret, *in, *p;
3835 int needed = 0;
3836 int lf = 0;
3837 int lastlf = 0;
3838 int len;
3839
Willy Tarreau70eec382012-10-10 08:56:47 +02003840 if (!out || !*out)
3841 return NULL;
3842
Willy Tarreau21c705b2012-09-14 11:40:36 +02003843 in = *out - 1;
3844 while ((in = strchr(in + 1, '\n')) != NULL) {
3845 lastlf = in - *out;
3846 lf++;
3847 }
3848
3849 if (!lf) /* single line, no LF, return it as-is */
3850 return *out;
3851
3852 len = strlen(*out);
3853
3854 if (lf == 1 && lastlf == len - 1) {
3855 /* single line, LF at end, strip it and return as-is */
3856 (*out)[lastlf] = 0;
3857 return *out;
3858 }
3859
3860 /* OK now we have at least one LF, we need to process the whole string
3861 * as a multi-line string. What we'll do :
3862 * - prefix with an LF if there is none
3863 * - add <level> spaces before each line
3864 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3865 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3866 */
3867
3868 needed = 1 + level * (lf + 1) + len + 1;
3869 p = ret = malloc(needed);
3870 in = *out;
3871
3872 /* skip initial LFs */
3873 while (*in == '\n')
3874 in++;
3875
3876 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3877 while (*in) {
3878 *p++ = '\n';
3879 memset(p, ' ', level);
3880 p += level;
3881 do {
3882 *p++ = *in++;
3883 } while (*in && *in != '\n');
3884 if (*in)
3885 in++;
3886 }
3887 *p = 0;
3888
3889 free(*out);
3890 *out = ret;
3891
3892 return ret;
3893}
3894
Willy Tarreaua2c99112019-08-21 13:17:37 +02003895/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3896 * and end of lines replaced with <eol> if not 0. The first line to indent has
3897 * to be indicated in <first> (starts at zero), so that it is possible to skip
3898 * indenting the first line if it has to be appended after an existing message.
3899 * Empty strings are never indented, and NULL strings are considered empty both
3900 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3901 * character, non-zero otherwise.
3902 */
3903int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3904{
3905 int bol, lf;
3906 int pfxlen = pfx ? strlen(pfx) : 0;
3907
3908 if (!in)
3909 return 0;
3910
3911 bol = 1;
3912 lf = 0;
3913 while (*in) {
3914 if (bol && pfxlen) {
3915 if (first > 0)
3916 first--;
3917 else
3918 b_putblk(out, pfx, pfxlen);
3919 bol = 0;
3920 }
3921
3922 lf = (*in == '\n');
3923 bol |= lf;
3924 b_putchr(out, (lf && eol) ? eol : *in);
3925 in++;
3926 }
3927 return lf;
3928}
3929
Willy Tarreau9d22e562019-03-29 18:49:09 +01003930/* removes environment variable <name> from the environment as found in
3931 * environ. This is only provided as an alternative for systems without
3932 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003933 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003934 * <name> and to replace the matching pointers with the last pointer of
3935 * the array (since variables are not ordered).
3936 * It always returns 0 (success).
3937 */
3938int my_unsetenv(const char *name)
3939{
3940 extern char **environ;
3941 char **p = environ;
3942 int vars;
3943 int next;
3944 int len;
3945
3946 len = strlen(name);
3947 for (vars = 0; p[vars]; vars++)
3948 ;
3949 next = 0;
3950 while (next < vars) {
3951 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3952 next++;
3953 continue;
3954 }
3955 if (next < vars - 1)
3956 p[next] = p[vars - 1];
3957 p[--vars] = NULL;
3958 }
3959 return 0;
3960}
3961
Willy Tarreaudad36a32013-03-11 01:20:04 +01003962/* Convert occurrences of environment variables in the input string to their
3963 * corresponding value. A variable is identified as a series of alphanumeric
3964 * characters or underscores following a '$' sign. The <in> string must be
3965 * free()able. NULL returns NULL. The resulting string might be reallocated if
3966 * some expansion is made. Variable names may also be enclosed into braces if
3967 * needed (eg: to concatenate alphanum characters).
3968 */
3969char *env_expand(char *in)
3970{
3971 char *txt_beg;
3972 char *out;
3973 char *txt_end;
3974 char *var_beg;
3975 char *var_end;
3976 char *value;
3977 char *next;
3978 int out_len;
3979 int val_len;
3980
3981 if (!in)
3982 return in;
3983
3984 value = out = NULL;
3985 out_len = 0;
3986
3987 txt_beg = in;
3988 do {
3989 /* look for next '$' sign in <in> */
3990 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3991
3992 if (!*txt_end && !out) /* end and no expansion performed */
3993 return in;
3994
3995 val_len = 0;
3996 next = txt_end;
3997 if (*txt_end == '$') {
3998 char save;
3999
4000 var_beg = txt_end + 1;
4001 if (*var_beg == '{')
4002 var_beg++;
4003
4004 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004005 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004006 var_end++;
4007 }
4008
4009 next = var_end;
4010 if (*var_end == '}' && (var_beg > txt_end + 1))
4011 next++;
4012
4013 /* get value of the variable name at this location */
4014 save = *var_end;
4015 *var_end = '\0';
4016 value = getenv(var_beg);
4017 *var_end = save;
4018 val_len = value ? strlen(value) : 0;
4019 }
4020
Hubert Verstraete831962e2016-06-28 22:44:26 +02004021 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004022 if (txt_end > txt_beg) {
4023 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4024 out_len += txt_end - txt_beg;
4025 }
4026 if (val_len) {
4027 memcpy(out + out_len, value, val_len);
4028 out_len += val_len;
4029 }
4030 out[out_len] = 0;
4031 txt_beg = next;
4032 } while (*txt_beg);
4033
4034 /* here we know that <out> was allocated and that we don't need <in> anymore */
4035 free(in);
4036 return out;
4037}
4038
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004039
4040/* same as strstr() but case-insensitive and with limit length */
4041const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4042{
4043 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004044 unsigned int slen, plen;
4045 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004046
4047 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4048 return NULL;
4049
4050 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4051 return str1;
4052
4053 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4054 return NULL;
4055
4056 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 +02004057 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004058 start++;
4059 slen--;
4060 tmp1++;
4061
4062 if (tmp1 >= len_str1)
4063 return NULL;
4064
4065 /* if pattern longer than string */
4066 if (slen < plen)
4067 return NULL;
4068 }
4069
4070 sptr = start;
4071 pptr = (char *)str2;
4072
4073 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004074 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004075 sptr++;
4076 pptr++;
4077 tmp2++;
4078
4079 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4080 return start;
4081 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4082 return NULL;
4083 }
4084 }
4085 return NULL;
4086}
4087
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004088/* This function read the next valid utf8 char.
4089 * <s> is the byte srray to be decode, <len> is its length.
4090 * The function returns decoded char encoded like this:
4091 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4092 * are the length read. The decoded character is stored in <c>.
4093 */
4094unsigned char utf8_next(const char *s, int len, unsigned int *c)
4095{
4096 const unsigned char *p = (unsigned char *)s;
4097 int dec;
4098 unsigned char code = UTF8_CODE_OK;
4099
4100 if (len < 1)
4101 return UTF8_CODE_OK;
4102
4103 /* Check the type of UTF8 sequence
4104 *
4105 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4106 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4107 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4108 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4109 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4110 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4111 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4112 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4113 */
4114 switch (*p) {
4115 case 0x00 ... 0x7f:
4116 *c = *p;
4117 return UTF8_CODE_OK | 1;
4118
4119 case 0x80 ... 0xbf:
4120 *c = *p;
4121 return UTF8_CODE_BADSEQ | 1;
4122
4123 case 0xc0 ... 0xdf:
4124 if (len < 2) {
4125 *c = *p;
4126 return UTF8_CODE_BADSEQ | 1;
4127 }
4128 *c = *p & 0x1f;
4129 dec = 1;
4130 break;
4131
4132 case 0xe0 ... 0xef:
4133 if (len < 3) {
4134 *c = *p;
4135 return UTF8_CODE_BADSEQ | 1;
4136 }
4137 *c = *p & 0x0f;
4138 dec = 2;
4139 break;
4140
4141 case 0xf0 ... 0xf7:
4142 if (len < 4) {
4143 *c = *p;
4144 return UTF8_CODE_BADSEQ | 1;
4145 }
4146 *c = *p & 0x07;
4147 dec = 3;
4148 break;
4149
4150 case 0xf8 ... 0xfb:
4151 if (len < 5) {
4152 *c = *p;
4153 return UTF8_CODE_BADSEQ | 1;
4154 }
4155 *c = *p & 0x03;
4156 dec = 4;
4157 break;
4158
4159 case 0xfc ... 0xfd:
4160 if (len < 6) {
4161 *c = *p;
4162 return UTF8_CODE_BADSEQ | 1;
4163 }
4164 *c = *p & 0x01;
4165 dec = 5;
4166 break;
4167
4168 case 0xfe ... 0xff:
4169 default:
4170 *c = *p;
4171 return UTF8_CODE_BADSEQ | 1;
4172 }
4173
4174 p++;
4175
4176 while (dec > 0) {
4177
4178 /* need 0x10 for the 2 first bits */
4179 if ( ( *p & 0xc0 ) != 0x80 )
4180 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4181
4182 /* add data at char */
4183 *c = ( *c << 6 ) | ( *p & 0x3f );
4184
4185 dec--;
4186 p++;
4187 }
4188
4189 /* Check ovelong encoding.
4190 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4191 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4192 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4193 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004194 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004195 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4196 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4197 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4198 code |= UTF8_CODE_OVERLONG;
4199
4200 /* Check invalid UTF8 range. */
4201 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4202 (*c >= 0xfffe && *c <= 0xffff))
4203 code |= UTF8_CODE_INVRANGE;
4204
4205 return code | ((p-(unsigned char *)s)&0x0f);
4206}
4207
Maxime de Roucydc887852016-05-13 23:52:54 +02004208/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4209 * On failure : return 0 and <err> filled with an error message.
4210 * The caller is responsible for freeing the <err> and <str> copy
4211 * memory area using free()
4212 */
4213int list_append_word(struct list *li, const char *str, char **err)
4214{
4215 struct wordlist *wl;
4216
4217 wl = calloc(1, sizeof(*wl));
4218 if (!wl) {
4219 memprintf(err, "out of memory");
4220 goto fail_wl;
4221 }
4222
4223 wl->s = strdup(str);
4224 if (!wl->s) {
4225 memprintf(err, "out of memory");
4226 goto fail_wl_s;
4227 }
4228
4229 LIST_ADDQ(li, &wl->list);
4230
4231 return 1;
4232
4233fail_wl_s:
4234 free(wl->s);
4235fail_wl:
4236 free(wl);
4237 return 0;
4238}
4239
Willy Tarreau37101052019-05-20 16:48:20 +02004240/* indicates if a memory location may safely be read or not. The trick consists
4241 * in performing a harmless syscall using this location as an input and letting
4242 * the operating system report whether it's OK or not. For this we have the
4243 * stat() syscall, which will return EFAULT when the memory location supposed
4244 * to contain the file name is not readable. If it is readable it will then
4245 * either return 0 if the area contains an existing file name, or -1 with
4246 * another code. This must not be abused, and some audit systems might detect
4247 * this as abnormal activity. It's used only for unsafe dumps.
4248 */
4249int may_access(const void *ptr)
4250{
4251 struct stat buf;
4252
4253 if (stat(ptr, &buf) == 0)
4254 return 1;
4255 if (errno == EFAULT)
4256 return 0;
4257 return 1;
4258}
4259
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004260/* print a string of text buffer to <out>. The format is :
4261 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4262 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4263 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4264 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004265int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004266{
4267 unsigned char c;
4268 int ptr = 0;
4269
4270 while (buf[ptr] && ptr < bsize) {
4271 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004272 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004273 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004274 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004275 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004276 }
4277 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004278 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004279 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004280 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004281 switch (c) {
4282 case ' ': c = ' '; break;
4283 case '\t': c = 't'; break;
4284 case '\n': c = 'n'; break;
4285 case '\r': c = 'r'; break;
4286 case '\e': c = 'e'; break;
4287 case '\\': c = '\\'; break;
4288 case '=': c = '='; break;
4289 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004290 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004291 }
4292 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004293 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004294 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004295 out->area[out->data++] = '\\';
4296 out->area[out->data++] = 'x';
4297 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4298 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004299 }
4300 ptr++;
4301 }
4302
4303 return ptr;
4304}
4305
4306/* print a buffer in hexa.
4307 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4308 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004309int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004310{
4311 unsigned char c;
4312 int ptr = 0;
4313
4314 while (ptr < bsize) {
4315 c = buf[ptr];
4316
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004317 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004318 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004319 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4320 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004321
4322 ptr++;
4323 }
4324 return ptr;
4325}
4326
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004327/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4328 * prepending each line with prefix <pfx>. The output is *not* initialized.
4329 * The output will not wrap pas the buffer's end so it is more optimal if the
4330 * caller makes sure the buffer is aligned first. A trailing zero will always
4331 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004332 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4333 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004334 */
Willy Tarreau37101052019-05-20 16:48:20 +02004335void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004336{
4337 const unsigned char *d = buf;
4338 int i, j, start;
4339
4340 d = (const unsigned char *)(((unsigned long)buf) & -16);
4341 start = ((unsigned long)buf) & 15;
4342
4343 for (i = 0; i < start + len; i += 16) {
4344 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4345
Willy Tarreau37101052019-05-20 16:48:20 +02004346 // 0: unchecked, 1: checked safe, 2: danger
4347 unsafe = !!unsafe;
4348 if (unsafe && !may_access(d + i))
4349 unsafe = 2;
4350
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004351 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004352 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004353 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004354 else if (unsafe > 1)
4355 chunk_strcat(out, "** ");
4356 else
4357 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004358
4359 if (j == 7)
4360 chunk_strcat(out, "- ");
4361 }
4362 chunk_strcat(out, " ");
4363 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004364 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004365 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004366 else if (unsafe > 1)
4367 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004368 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004369 chunk_appendf(out, "%c", d[i + j]);
4370 else
4371 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004372 }
4373 chunk_strcat(out, "\n");
4374 }
4375}
4376
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004377/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4378 * enclosed in brackets after the address itself, formatted on 14 chars
4379 * including the "0x" prefix. This is meant to be used as a prefix for code
4380 * areas. For example:
4381 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4382 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4383 * is emitted. A NULL <pfx> will be considered empty.
4384 */
4385void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4386{
4387 int ok = 0;
4388 int i;
4389
4390 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4391
4392 for (i = 0; i < n; i++) {
4393 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4394 ok = may_access(addr + i);
4395 if (ok)
4396 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4397 else
4398 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4399 }
4400}
4401
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004402/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4403 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4404 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4405 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4406 * lines are respected within the limit of 70 output chars. Lines that are
4407 * continuation of a previous truncated line begin with "+" instead of " "
4408 * after the offset. The new pointer is returned.
4409 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004410int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004411 int *line, int ptr)
4412{
4413 int end;
4414 unsigned char c;
4415
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004416 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004417 if (end > out->size)
4418 return ptr;
4419
4420 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4421
4422 while (ptr < len && ptr < bsize) {
4423 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004424 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004425 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004426 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004427 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004428 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004429 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004430 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004431 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004432 switch (c) {
4433 case '\t': c = 't'; break;
4434 case '\n': c = 'n'; break;
4435 case '\r': c = 'r'; break;
4436 case '\e': c = 'e'; break;
4437 case '\\': c = '\\'; break;
4438 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004439 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004440 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004441 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004442 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004443 out->area[out->data++] = '\\';
4444 out->area[out->data++] = 'x';
4445 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4446 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004447 }
4448 if (buf[ptr++] == '\n') {
4449 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004450 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004451 *line = ptr;
4452 return ptr;
4453 }
4454 }
4455 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004456 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004457 return ptr;
4458}
4459
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004460/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004461 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4462 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004463 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004464void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4465 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004466{
Willy Tarreau73459792017-04-11 07:58:08 +02004467 unsigned int i;
4468 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004469
4470 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4471 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004472 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004473 for (j = 0; j < 8; j++) {
4474 if (b + j >= 0 && b + j < len)
4475 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4476 else
4477 fprintf(out, " ");
4478 }
4479
4480 if (b + j >= 0 && b + j < len)
4481 fputc('-', out);
4482 else
4483 fputc(' ', out);
4484
4485 for (j = 8; j < 16; j++) {
4486 if (b + j >= 0 && b + j < len)
4487 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4488 else
4489 fprintf(out, " ");
4490 }
4491
4492 fprintf(out, " ");
4493 for (j = 0; j < 16; j++) {
4494 if (b + j >= 0 && b + j < len) {
4495 if (isprint((unsigned char)buf[b + j]))
4496 fputc((unsigned char)buf[b + j], out);
4497 else
4498 fputc('.', out);
4499 }
4500 else
4501 fputc(' ', out);
4502 }
4503 fputc('\n', out);
4504 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004505}
4506
Willy Tarreaubb869862020-04-16 10:52:41 +02004507/* Tries to report the executable path name on platforms supporting this. If
4508 * not found or not possible, returns NULL.
4509 */
4510const char *get_exec_path()
4511{
4512 const char *ret = NULL;
4513
4514#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4515 long execfn = getauxval(AT_EXECFN);
4516
4517 if (execfn && execfn != ENOENT)
4518 ret = (const char *)execfn;
4519#endif
4520 return ret;
4521}
4522
Baruch Siache1651b22020-07-24 07:52:20 +03004523#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004524/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4525 * also returns the symbol size in <size>, otherwise returns 0 there.
4526 */
4527static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4528{
4529 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004530#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004531 const ElfW(Sym) *sym;
4532
4533 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4534 if (ret)
4535 *size = sym ? sym->st_size : 0;
4536#else
4537 ret = dladdr(addr, dli);
4538 *size = 0;
4539#endif
4540 return ret;
4541}
4542#endif
4543
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004544/* Tries to append to buffer <buf> some indications about the symbol at address
4545 * <addr> using the following form:
4546 * lib:+0xoffset (unresolvable address from lib's base)
4547 * main+0xoffset (unresolvable address from main (+/-))
4548 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4549 * name (resolved exact exec address)
4550 * lib:name (resolved exact lib address)
4551 * name+0xoffset/0xsize (resolved address within exec symbol)
4552 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4553 *
4554 * The file name (lib or executable) is limited to what lies between the last
4555 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4556 * 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 +03004557 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004558 *
4559 * The symbol's base address is returned, or NULL when unresolved, in order to
4560 * allow the caller to match it against known ones.
4561 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004562const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004563{
4564 const struct {
4565 const void *func;
4566 const char *name;
4567 } fcts[] = {
4568 { .func = process_stream, .name = "process_stream" },
4569 { .func = task_run_applet, .name = "task_run_applet" },
4570 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4571 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4572 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4573 { .func = listener_accept, .name = "listener_accept" },
4574 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4575 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4576#ifdef USE_LUA
4577 { .func = hlua_process_task, .name = "hlua_process_task" },
4578#endif
4579#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4580 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4581 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4582#endif
4583 };
4584
Baruch Siache1651b22020-07-24 07:52:20 +03004585#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004586 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004587 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004588 const char *fname, *p;
4589#endif
4590 int i;
4591
4592 if (pfx)
4593 chunk_appendf(buf, "%s", pfx);
4594
4595 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4596 if (addr == fcts[i].func) {
4597 chunk_appendf(buf, "%s", fcts[i].name);
4598 return addr;
4599 }
4600 }
4601
Baruch Siache1651b22020-07-24 07:52:20 +03004602#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004603 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004604 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004605 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004606
4607 /* 1. prefix the library name if it's not the same object as the one
4608 * that contains the main function. The name is picked between last '/'
4609 * and first following '.'.
4610 */
4611 if (!dladdr(main, &dli_main))
4612 dli_main.dli_fbase = NULL;
4613
4614 if (dli_main.dli_fbase != dli.dli_fbase) {
4615 fname = dli.dli_fname;
4616 p = strrchr(fname, '/');
4617 if (p++)
4618 fname = p;
4619 p = strchr(fname, '.');
4620 if (!p)
4621 p = fname + strlen(fname);
4622
4623 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4624 }
4625
4626 /* 2. symbol name */
4627 if (dli.dli_sname) {
4628 /* known, dump it and return symbol's address (exact or relative) */
4629 chunk_appendf(buf, "%s", dli.dli_sname);
4630 if (addr != dli.dli_saddr) {
4631 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004632 if (size)
4633 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004634 }
4635 return dli.dli_saddr;
4636 }
4637 else if (dli_main.dli_fbase != dli.dli_fbase) {
4638 /* unresolved symbol from a known library, report relative offset */
4639 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4640 return NULL;
4641 }
Baruch Siache1651b22020-07-24 07:52:20 +03004642#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004643 unknown:
4644 /* unresolved symbol from the main file, report relative offset to main */
4645 if ((void*)addr < (void*)main)
4646 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4647 else
4648 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4649 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004650}
4651
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004652/*
4653 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004654 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004655 *
4656 * First, initializes the value with <sz> as address to 0 and initializes the
4657 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4658 * address updating <sz> pointed value to the size of this array.
4659 *
4660 * Returns 1 if succeeded, 0 if not.
4661 */
4662int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4663{
4664 unsigned int *n;
4665 const char *s, *end;
4666
4667 s = str;
4668 *sz = 0;
4669 end = str + strlen(str);
4670 *nums = n = NULL;
4671
4672 while (1) {
4673 unsigned int r;
4674
4675 if (s >= end)
4676 break;
4677
4678 r = read_uint(&s, end);
4679 /* Expected characters after having read an uint: '\0' or '.',
4680 * if '.', must not be terminal.
4681 */
4682 if (*s != '\0'&& (*s++ != '.' || s == end))
4683 return 0;
4684
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004685 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004686 if (!n)
4687 return 0;
4688
4689 n[(*sz)++] = r;
4690 }
4691 *nums = n;
4692
4693 return 1;
4694}
4695
Willy Tarreau4d589e72019-08-23 19:02:26 +02004696
4697/* returns the number of bytes needed to encode <v> as a varint. An inline
4698 * version exists for use with constants (__varint_bytes()).
4699 */
4700int varint_bytes(uint64_t v)
4701{
4702 int len = 1;
4703
4704 if (v >= 240) {
4705 v = (v - 240) >> 4;
4706 while (1) {
4707 len++;
4708 if (v < 128)
4709 break;
4710 v = (v - 128) >> 7;
4711 }
4712 }
4713 return len;
4714}
4715
Willy Tarreau52bf8392020-03-08 00:42:37 +01004716
4717/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004718static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004719
4720/* This is a thread-safe implementation of xoroshiro128** described below:
4721 * http://prng.di.unimi.it/
4722 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4723 * supports fast jumps and passes all common quality tests. It is thread-safe,
4724 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4725 * local lock on other ones.
4726 */
4727uint64_t ha_random64()
4728{
4729 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004730 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4731 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004732
4733#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4734 static HA_SPINLOCK_T rand_lock;
4735
4736 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4737#endif
4738
4739 old[0] = ha_random_state[0];
4740 old[1] = ha_random_state[1];
4741
4742#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4743 do {
4744#endif
4745 result = rotl64(old[0] * 5, 7) * 9;
4746 new[1] = old[0] ^ old[1];
4747 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4748 new[1] = rotl64(new[1], 37); // c
4749
4750#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4751 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4752#else
4753 ha_random_state[0] = new[0];
4754 ha_random_state[1] = new[1];
4755#if defined(USE_THREAD)
4756 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4757#endif
4758#endif
4759 return result;
4760}
4761
4762/* seeds the random state using up to <len> bytes from <seed>, starting with
4763 * the first non-zero byte.
4764 */
4765void ha_random_seed(const unsigned char *seed, size_t len)
4766{
4767 size_t pos;
4768
4769 /* the seed must not be all zeroes, so we pre-fill it with alternating
4770 * bits and overwrite part of them with the block starting at the first
4771 * non-zero byte from the seed.
4772 */
4773 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4774
4775 for (pos = 0; pos < len; pos++)
4776 if (seed[pos] != 0)
4777 break;
4778
4779 if (pos == len)
4780 return;
4781
4782 seed += pos;
4783 len -= pos;
4784
4785 if (len > sizeof(ha_random_state))
4786 len = sizeof(ha_random_state);
4787
4788 memcpy(ha_random_state, seed, len);
4789}
4790
4791/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4792 * and is equivalent to calling ha_random64() as many times. It is used to
4793 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4794 * different generators (i.e. different processes after a fork). The <dist>
4795 * argument is the distance to jump to and is used in a loop so it rather not
4796 * be too large if the processing time is a concern.
4797 *
4798 * BEWARE: this function is NOT thread-safe and must not be called during
4799 * concurrent accesses to ha_random64().
4800 */
4801void ha_random_jump96(uint32_t dist)
4802{
4803 while (dist--) {
4804 uint64_t s0 = 0;
4805 uint64_t s1 = 0;
4806 int b;
4807
4808 for (b = 0; b < 64; b++) {
4809 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4810 s0 ^= ha_random_state[0];
4811 s1 ^= ha_random_state[1];
4812 }
4813 ha_random64();
4814 }
4815
4816 for (b = 0; b < 64; b++) {
4817 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4818 s0 ^= ha_random_state[0];
4819 s1 ^= ha_random_state[1];
4820 }
4821 ha_random64();
4822 }
4823 ha_random_state[0] = s0;
4824 ha_random_state[1] = s1;
4825 }
4826}
4827
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004828/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4829 * bytes large.
4830 */
4831void ha_generate_uuid(struct buffer *output)
4832{
4833 uint32_t rnd[4];
4834 uint64_t last;
4835
4836 last = ha_random64();
4837 rnd[0] = last;
4838 rnd[1] = last >> 32;
4839
4840 last = ha_random64();
4841 rnd[2] = last;
4842 rnd[3] = last >> 32;
4843
4844 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4845 rnd[0],
4846 rnd[1] & 0xFFFF,
4847 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4848 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4849 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4850}
4851
4852
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004853/* only used by parse_line() below. It supports writing in place provided that
4854 * <in> is updated to the next location before calling it. In that case, the
4855 * char at <in> may be overwritten.
4856 */
4857#define EMIT_CHAR(x) \
4858 do { \
4859 char __c = (char)(x); \
4860 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4861 err |= PARSE_ERR_OVERLAP; \
4862 if (outpos >= outmax) \
4863 err |= PARSE_ERR_TOOLARGE; \
4864 if (!err) \
4865 out[outpos] = __c; \
4866 outpos++; \
4867 } while (0)
4868
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004869/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004870 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4871 * extraneous ones are not emitted but <outlen> is updated so that the caller
4872 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4873 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004874 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4875 * it is guaranteed that at least one arg will point to the zero. It is safe
4876 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004877 *
4878 * <out> may overlap with <in> provided that it never goes further, in which
4879 * case the parser will accept to perform in-place parsing and unquoting/
4880 * unescaping but only if environment variables do not lead to expansion that
4881 * causes overlapping, otherwise the input string being destroyed, the error
4882 * will not be recoverable. Note that even during out-of-place <in> will
4883 * experience temporary modifications in-place for variable resolution and must
4884 * be writable, and will also receive zeroes to delimit words when using
4885 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4886 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4887 * starting point of the first invalid character sequence or unmatched
4888 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4889 * error reporting might be difficult since zeroes will have been inserted into
4890 * the string. One solution for the caller may consist in replacing all args
4891 * delimiters with spaces in this case.
4892 */
4893uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4894{
4895 char *quote = NULL;
4896 char *brace = NULL;
4897 unsigned char hex1, hex2;
4898 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004899 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004900 size_t outpos = 0;
4901 int squote = 0;
4902 int dquote = 0;
4903 int arg = 0;
4904 uint32_t err = 0;
4905
4906 *nbargs = 0;
4907 *outlen = 0;
4908
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004909 /* argsmax may be -1 here, protecting args[] from any write */
4910 if (arg < argsmax)
4911 args[arg] = out;
4912
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004913 while (1) {
4914 if (*in >= '-' && *in != '\\') {
4915 /* speedup: directly send all regular chars starting
4916 * with '-', '.', '/', alnum etc...
4917 */
4918 EMIT_CHAR(*in++);
4919 continue;
4920 }
4921 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4922 /* end of line */
4923 break;
4924 }
4925 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4926 /* comment */
4927 break;
4928 }
4929 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4930 if (dquote) {
4931 dquote = 0;
4932 quote = NULL;
4933 }
4934 else {
4935 dquote = 1;
4936 quote = in;
4937 }
4938 in++;
4939 continue;
4940 }
4941 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4942 if (squote) {
4943 squote = 0;
4944 quote = NULL;
4945 }
4946 else {
4947 squote = 1;
4948 quote = in;
4949 }
4950 in++;
4951 continue;
4952 }
4953 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4954 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4955 * C equivalent value but only when they have a special meaning and within
4956 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4957 */
4958 char tosend = *in;
4959
4960 switch (in[1]) {
4961 case ' ':
4962 case '\\':
4963 tosend = in[1];
4964 in++;
4965 break;
4966
4967 case 't':
4968 tosend = '\t';
4969 in++;
4970 break;
4971
4972 case 'n':
4973 tosend = '\n';
4974 in++;
4975 break;
4976
4977 case 'r':
4978 tosend = '\r';
4979 in++;
4980 break;
4981
4982 case '#':
4983 /* escaping of "#" only if comments are supported */
4984 if (opts & PARSE_OPT_SHARP)
4985 in++;
4986 tosend = *in;
4987 break;
4988
4989 case '\'':
4990 /* escaping of "'" only outside single quotes and only if single quotes are supported */
4991 if (opts & PARSE_OPT_SQUOTE && !squote)
4992 in++;
4993 tosend = *in;
4994 break;
4995
4996 case '"':
4997 /* escaping of '"' only outside single quotes and only if double quotes are supported */
4998 if (opts & PARSE_OPT_DQUOTE && !squote)
4999 in++;
5000 tosend = *in;
5001 break;
5002
5003 case '$':
5004 /* escaping of '$' only inside double quotes and only if env supported */
5005 if (opts & PARSE_OPT_ENV && dquote)
5006 in++;
5007 tosend = *in;
5008 break;
5009
5010 case 'x':
5011 if (!ishex(in[2]) || !ishex(in[3])) {
5012 /* invalid or incomplete hex sequence */
5013 err |= PARSE_ERR_HEX;
5014 if (errptr)
5015 *errptr = in;
5016 goto leave;
5017 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005018 hex1 = toupper((unsigned char)in[2]) - '0';
5019 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005020 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5021 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5022 tosend = (hex1 << 4) + hex2;
5023 in += 3;
5024 break;
5025
5026 default:
5027 /* other combinations are not escape sequences */
5028 break;
5029 }
5030
5031 in++;
5032 EMIT_CHAR(tosend);
5033 }
5034 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5035 /* a non-escaped space is an argument separator */
5036 while (isspace((unsigned char)*in))
5037 in++;
5038 EMIT_CHAR(0);
5039 arg++;
5040 if (arg < argsmax)
5041 args[arg] = out + outpos;
5042 else
5043 err |= PARSE_ERR_TOOMANY;
5044 }
5045 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5046 /* environment variables are evaluated anywhere, or only
5047 * inside double quotes if they are supported.
5048 */
5049 char *var_name;
5050 char save_char;
5051 char *value;
5052
5053 in++;
5054
5055 if (*in == '{')
5056 brace = in++;
5057
5058 if (!isalpha((unsigned char)*in) && *in != '_') {
5059 /* unacceptable character in variable name */
5060 err |= PARSE_ERR_VARNAME;
5061 if (errptr)
5062 *errptr = in;
5063 goto leave;
5064 }
5065
5066 var_name = in;
5067 while (isalnum((unsigned char)*in) || *in == '_')
5068 in++;
5069
5070 save_char = *in;
5071 *in = '\0';
5072 value = getenv(var_name);
5073 *in = save_char;
5074
5075 if (brace) {
5076 if (*in != '}') {
5077 /* unmatched brace */
5078 err |= PARSE_ERR_BRACE;
5079 if (errptr)
5080 *errptr = brace;
5081 goto leave;
5082 }
5083 in++;
5084 brace = NULL;
5085 }
5086
5087 if (value) {
5088 while (*value)
5089 EMIT_CHAR(*value++);
5090 }
5091 }
5092 else {
5093 /* any other regular char */
5094 EMIT_CHAR(*in++);
5095 }
5096 }
5097
5098 /* end of output string */
5099 EMIT_CHAR(0);
5100 arg++;
5101
5102 if (quote) {
5103 /* unmatched quote */
5104 err |= PARSE_ERR_QUOTE;
5105 if (errptr)
5106 *errptr = quote;
5107 goto leave;
5108 }
5109 leave:
5110 *nbargs = arg;
5111 *outlen = outpos;
5112
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005113 /* empty all trailing args by making them point to the trailing zero,
5114 * at least the last one in any case.
5115 */
5116 if (arg > argsmax)
5117 arg = argsmax;
5118
5119 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005120 args[arg++] = out + outpos - 1;
5121
5122 return err;
5123}
5124#undef EMIT_CHAR
5125
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005126/* This is used to sanitize an input line that's about to be used for error reporting.
5127 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5128 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5129 * If non-printable chars are present in the output. It returns the new offset <pos>
5130 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5131 * be at least 6 to support two "..." otherwise the result is undefined. The line
5132 * itself must have at least 7 chars allocated for the same reason.
5133 */
5134size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5135{
5136 size_t shift = 0;
5137 char *out = line;
5138 char *in = line;
5139 char *end = line + width;
5140
5141 if (pos >= width) {
5142 /* if we have to shift, we'll be out of context, so let's
5143 * try to put <pos> at the center of width.
5144 */
5145 shift = pos - width / 2;
5146 in += shift + 3;
5147 end = out + width - 3;
5148 out[0] = out[1] = out[2] = '.';
5149 out += 3;
5150 }
5151
5152 while (out < end && *in) {
5153 if (isspace((unsigned char)*in))
5154 *out++ = ' ';
5155 else if (isprint((unsigned char)*in))
5156 *out++ = *in;
5157 else
5158 *out++ = '?';
5159 in++;
5160 }
5161
5162 if (end < line + width) {
5163 out[0] = out[1] = out[2] = '.';
5164 out += 3;
5165 }
5166
5167 *out++ = 0;
5168 return pos - shift;
5169}
5170
Willy Tarreaubaaee002006-06-26 02:48:02 +02005171/*
5172 * Local variables:
5173 * c-indent-level: 8
5174 * c-basic-offset: 8
5175 * End:
5176 */