blob: 34b1ab099cf051e2ce0ad2d44c7fa6b0462a19c5 [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
devnexen@gmail.comc4e52322021-08-17 12:55:49 +010019#if defined(__FreeBSD__)
20#include <elf.h>
21#include <dlfcn.h>
22extern void *__elf_aux_vector;
23#endif
24
David Carlierbd2cced2021-08-17 08:44:25 +010025#if defined(__NetBSD__)
26#include <sys/exec_elf.h>
27#include <dlfcn.h>
28#endif
29
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010030#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020033#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020034#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035#include <stdlib.h>
36#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010037#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020038#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010039#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020040#include <sys/stat.h>
41#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010042#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020043#include <netinet/in.h>
44#include <arpa/inet.h>
45
David Carlier43a56852022-03-04 15:50:48 +000046#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreau30053062020-08-20 16:39:14 +020047#include <sys/auxv.h>
48#endif
49
Willy Tarreau48fbcae2020-06-03 18:09:46 +020050#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <import/eb32tree.h>
Willy Tarreau0dc9e6d2022-08-01 11:55:57 +020052#include <import/ebmbtree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020053
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020054#include <haproxy/api.h>
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +020055#include <haproxy/applet.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020056#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020057#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020058#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020059#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020060#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020061#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010062#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020063#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010064#include <haproxy/resolvers.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020065#include <haproxy/sc_strm.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010066#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020067#include <haproxy/ssl_sock.h>
William Lallemand3aeb3f92021-08-21 23:59:56 +020068#include <haproxy/ssl_utils.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020069#include <haproxy/stconn.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020070#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020071#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010072
Thierry Fournier93127942016-01-20 18:49:45 +010073/* This macro returns false if the test __x is false. Many
74 * of the following parsing function must be abort the processing
75 * if it returns 0, so this macro is useful for writing light code.
76 */
77#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
78
Erwan Le Goas9c766372022-09-14 17:40:24 +020079/* Define the number of line of hash_word */
80#define NB_L_HASH_WORD 7
81
Willy Tarreau56adcf22012-12-23 18:00:29 +010082/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020083 * 2^64-1 = 18446744073709551615 or
84 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020085 *
86 * The HTML version needs room for adding the 25 characters
87 * '<span class="rls"></span>' around digits at positions 3N+1 in order
88 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020089 */
Christopher Faulet99bca652017-11-14 16:47:26 +010090THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
91THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020092
Willy Tarreau588297f2014-06-16 15:16:40 +020093/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
94 * to quote strings larger than a max configuration line.
95 */
Christopher Faulet99bca652017-11-14 16:47:26 +010096THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
97THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020098
Willy Tarreau06e69b52021-03-02 14:01:35 +010099/* thread-local PRNG state. It's modified to start from a different sequence
100 * on all threads upon startup. It must not be used or anything beyond getting
101 * statistical values as it's 100% predictable.
102 */
103THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
104
Willy Tarreau5b3cd952022-07-18 13:58:17 +0200105/* set to true if this is a static build */
106int build_is_static = 0;
107
Erwan Le Goas9c766372022-09-14 17:40:24 +0200108/* A global static table to store hashed words */
109static THREAD_LOCAL char hash_word[NB_L_HASH_WORD][20];
110static THREAD_LOCAL int index_hash = 0;
111
Willy Tarreaubaaee002006-06-26 02:48:02 +0200112/*
William Lallemande7340ec2012-01-24 11:15:39 +0100113 * unsigned long long ASCII representation
114 *
115 * return the last char '\0' or NULL if no enough
116 * space in dst
117 */
118char *ulltoa(unsigned long long n, char *dst, size_t size)
119{
120 int i = 0;
121 char *res;
122
123 switch(n) {
124 case 1ULL ... 9ULL:
125 i = 0;
126 break;
127
128 case 10ULL ... 99ULL:
129 i = 1;
130 break;
131
132 case 100ULL ... 999ULL:
133 i = 2;
134 break;
135
136 case 1000ULL ... 9999ULL:
137 i = 3;
138 break;
139
140 case 10000ULL ... 99999ULL:
141 i = 4;
142 break;
143
144 case 100000ULL ... 999999ULL:
145 i = 5;
146 break;
147
148 case 1000000ULL ... 9999999ULL:
149 i = 6;
150 break;
151
152 case 10000000ULL ... 99999999ULL:
153 i = 7;
154 break;
155
156 case 100000000ULL ... 999999999ULL:
157 i = 8;
158 break;
159
160 case 1000000000ULL ... 9999999999ULL:
161 i = 9;
162 break;
163
164 case 10000000000ULL ... 99999999999ULL:
165 i = 10;
166 break;
167
168 case 100000000000ULL ... 999999999999ULL:
169 i = 11;
170 break;
171
172 case 1000000000000ULL ... 9999999999999ULL:
173 i = 12;
174 break;
175
176 case 10000000000000ULL ... 99999999999999ULL:
177 i = 13;
178 break;
179
180 case 100000000000000ULL ... 999999999999999ULL:
181 i = 14;
182 break;
183
184 case 1000000000000000ULL ... 9999999999999999ULL:
185 i = 15;
186 break;
187
188 case 10000000000000000ULL ... 99999999999999999ULL:
189 i = 16;
190 break;
191
192 case 100000000000000000ULL ... 999999999999999999ULL:
193 i = 17;
194 break;
195
196 case 1000000000000000000ULL ... 9999999999999999999ULL:
197 i = 18;
198 break;
199
200 case 10000000000000000000ULL ... ULLONG_MAX:
201 i = 19;
202 break;
203 }
204 if (i + 2 > size) // (i + 1) + '\0'
205 return NULL; // too long
206 res = dst + i + 1;
207 *res = '\0';
208 for (; i >= 0; i--) {
209 dst[i] = n % 10ULL + '0';
210 n /= 10ULL;
211 }
212 return res;
213}
214
215/*
216 * unsigned long ASCII representation
217 *
218 * return the last char '\0' or NULL if no enough
219 * space in dst
220 */
221char *ultoa_o(unsigned long n, char *dst, size_t size)
222{
223 int i = 0;
224 char *res;
225
226 switch (n) {
227 case 0U ... 9UL:
228 i = 0;
229 break;
230
231 case 10U ... 99UL:
232 i = 1;
233 break;
234
235 case 100U ... 999UL:
236 i = 2;
237 break;
238
239 case 1000U ... 9999UL:
240 i = 3;
241 break;
242
243 case 10000U ... 99999UL:
244 i = 4;
245 break;
246
247 case 100000U ... 999999UL:
248 i = 5;
249 break;
250
251 case 1000000U ... 9999999UL:
252 i = 6;
253 break;
254
255 case 10000000U ... 99999999UL:
256 i = 7;
257 break;
258
259 case 100000000U ... 999999999UL:
260 i = 8;
261 break;
262#if __WORDSIZE == 32
263
264 case 1000000000ULL ... ULONG_MAX:
265 i = 9;
266 break;
267
268#elif __WORDSIZE == 64
269
270 case 1000000000ULL ... 9999999999UL:
271 i = 9;
272 break;
273
274 case 10000000000ULL ... 99999999999UL:
275 i = 10;
276 break;
277
278 case 100000000000ULL ... 999999999999UL:
279 i = 11;
280 break;
281
282 case 1000000000000ULL ... 9999999999999UL:
283 i = 12;
284 break;
285
286 case 10000000000000ULL ... 99999999999999UL:
287 i = 13;
288 break;
289
290 case 100000000000000ULL ... 999999999999999UL:
291 i = 14;
292 break;
293
294 case 1000000000000000ULL ... 9999999999999999UL:
295 i = 15;
296 break;
297
298 case 10000000000000000ULL ... 99999999999999999UL:
299 i = 16;
300 break;
301
302 case 100000000000000000ULL ... 999999999999999999UL:
303 i = 17;
304 break;
305
306 case 1000000000000000000ULL ... 9999999999999999999UL:
307 i = 18;
308 break;
309
310 case 10000000000000000000ULL ... ULONG_MAX:
311 i = 19;
312 break;
313
314#endif
315 }
316 if (i + 2 > size) // (i + 1) + '\0'
317 return NULL; // too long
318 res = dst + i + 1;
319 *res = '\0';
320 for (; i >= 0; i--) {
321 dst[i] = n % 10U + '0';
322 n /= 10U;
323 }
324 return res;
325}
326
327/*
328 * signed long ASCII representation
329 *
330 * return the last char '\0' or NULL if no enough
331 * space in dst
332 */
333char *ltoa_o(long int n, char *dst, size_t size)
334{
335 char *pos = dst;
336
337 if (n < 0) {
338 if (size < 3)
339 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
340 *pos = '-';
341 pos++;
342 dst = ultoa_o(-n, pos, size - 1);
343 } else {
344 dst = ultoa_o(n, dst, size);
345 }
346 return dst;
347}
348
349/*
350 * signed long long ASCII representation
351 *
352 * return the last char '\0' or NULL if no enough
353 * space in dst
354 */
355char *lltoa(long long n, char *dst, size_t size)
356{
357 char *pos = dst;
358
359 if (n < 0) {
360 if (size < 3)
361 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
362 *pos = '-';
363 pos++;
364 dst = ulltoa(-n, pos, size - 1);
365 } else {
366 dst = ulltoa(n, dst, size);
367 }
368 return dst;
369}
370
371/*
372 * write a ascii representation of a unsigned into dst,
373 * return a pointer to the last character
374 * Pad the ascii representation with '0', using size.
375 */
376char *utoa_pad(unsigned int n, char *dst, size_t size)
377{
378 int i = 0;
379 char *ret;
380
381 switch(n) {
382 case 0U ... 9U:
383 i = 0;
384 break;
385
386 case 10U ... 99U:
387 i = 1;
388 break;
389
390 case 100U ... 999U:
391 i = 2;
392 break;
393
394 case 1000U ... 9999U:
395 i = 3;
396 break;
397
398 case 10000U ... 99999U:
399 i = 4;
400 break;
401
402 case 100000U ... 999999U:
403 i = 5;
404 break;
405
406 case 1000000U ... 9999999U:
407 i = 6;
408 break;
409
410 case 10000000U ... 99999999U:
411 i = 7;
412 break;
413
414 case 100000000U ... 999999999U:
415 i = 8;
416 break;
417
418 case 1000000000U ... 4294967295U:
419 i = 9;
420 break;
421 }
422 if (i + 2 > size) // (i + 1) + '\0'
423 return NULL; // too long
424 if (i < size)
425 i = size - 2; // padding - '\0'
426
427 ret = dst + i + 1;
428 *ret = '\0';
429 for (; i >= 0; i--) {
430 dst[i] = n % 10U + '0';
431 n /= 10U;
432 }
433 return ret;
434}
435
436/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200437 * copies at most <size-1> chars from <src> to <dst>. Last char is always
438 * set to 0, unless <size> is 0. The number of chars copied is returned
439 * (excluding the terminating zero).
440 * This code has been optimized for size and speed : on x86, it's 45 bytes
441 * long, uses only registers, and consumes only 4 cycles per char.
442 */
443int strlcpy2(char *dst, const char *src, int size)
444{
445 char *orig = dst;
446 if (size) {
447 while (--size && (*dst = *src)) {
448 src++; dst++;
449 }
450 *dst = 0;
451 }
452 return dst - orig;
453}
454
455/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200456 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200457 * the ascii representation for number 'n' in decimal.
458 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100459char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200460{
461 char *pos;
462
Willy Tarreau72d759c2007-10-25 12:14:10 +0200463 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200464 *pos-- = '\0';
465
466 do {
467 *pos-- = '0' + n % 10;
468 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200469 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200470 return pos + 1;
471}
472
Willy Tarreau91092e52007-10-25 16:58:42 +0200473/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200474 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200475 * the ascii representation for number 'n' in decimal.
476 */
477char *lltoa_r(long long int in, char *buffer, int size)
478{
479 char *pos;
480 int neg = 0;
481 unsigned long long int n;
482
483 pos = buffer + size - 1;
484 *pos-- = '\0';
485
486 if (in < 0) {
487 neg = 1;
488 n = -in;
489 }
490 else
491 n = in;
492
493 do {
494 *pos-- = '0' + n % 10;
495 n /= 10;
496 } while (n && pos >= buffer);
497 if (neg && pos > buffer)
498 *pos-- = '-';
499 return pos + 1;
500}
501
502/*
503 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200504 * the ascii representation for signed number 'n' in decimal.
505 */
506char *sltoa_r(long n, char *buffer, int size)
507{
508 char *pos;
509
510 if (n >= 0)
511 return ultoa_r(n, buffer, size);
512
513 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
514 *pos = '-';
515 return pos;
516}
517
518/*
519 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200520 * the ascii representation for number 'n' in decimal, formatted for
521 * HTML output with tags to create visual grouping by 3 digits. The
522 * output needs to support at least 171 characters.
523 */
524const char *ulltoh_r(unsigned long long n, char *buffer, int size)
525{
526 char *start;
527 int digit = 0;
528
529 start = buffer + size;
530 *--start = '\0';
531
532 do {
533 if (digit == 3 && start >= buffer + 7)
534 memcpy(start -= 7, "</span>", 7);
535
536 if (start >= buffer + 1) {
537 *--start = '0' + n % 10;
538 n /= 10;
539 }
540
541 if (digit == 3 && start >= buffer + 18)
542 memcpy(start -= 18, "<span class=\"rls\">", 18);
543
544 if (digit++ == 3)
545 digit = 1;
546 } while (n && start > buffer);
547 return start;
548}
549
550/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200551 * This function simply returns a locally allocated string containing the ascii
552 * representation for number 'n' in decimal, unless n is 0 in which case it
553 * returns the alternate string (or an empty string if the alternate string is
554 * NULL). It use is intended for limits reported in reports, where it's
555 * desirable not to display anything if there is no limit. Warning! it shares
556 * the same vector as ultoa_r().
557 */
558const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
559{
560 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
561}
562
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200563/* Trims the first "%f" float in a string to its minimum number of digits after
564 * the decimal point by trimming trailing zeroes, even dropping the decimal
565 * point if not needed. The string is in <buffer> of length <len>, and the
566 * number is expected to start at or after position <num_start> (the first
567 * point appearing there is considered). A NUL character is always placed at
568 * the end if some trimming occurs. The new buffer length is returned.
569 */
570size_t flt_trim(char *buffer, size_t num_start, size_t len)
571{
572 char *end = buffer + len;
573 char *p = buffer + num_start;
574 char *trim;
575
576 do {
577 if (p >= end)
578 return len;
579 trim = p++;
580 } while (*trim != '.');
581
582 /* For now <trim> is on the decimal point. Let's look for any other
583 * meaningful digit after it.
584 */
585 while (p < end) {
586 if (*p++ != '0')
587 trim = p;
588 }
589
590 if (trim < end)
591 *trim = 0;
592
593 return trim - buffer;
594}
595
Willy Tarreauae03d262021-05-08 07:35:00 +0200596/*
597 * This function simply returns a locally allocated string containing
598 * the ascii representation for number 'n' in decimal with useless trailing
599 * zeroes trimmed.
600 */
601char *ftoa_r(double n, char *buffer, int size)
602{
603 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
604 return buffer;
605}
606
Willy Tarreau588297f2014-06-16 15:16:40 +0200607/* returns a locally allocated string containing the quoted encoding of the
608 * input string. The output may be truncated to QSTR_SIZE chars, but it is
609 * guaranteed that the string will always be properly terminated. Quotes are
610 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
611 * always be at least 4 chars.
612 */
613const char *qstr(const char *str)
614{
615 char *ret = quoted_str[quoted_idx];
616 char *p, *end;
617
618 if (++quoted_idx >= NB_QSTR)
619 quoted_idx = 0;
620
621 p = ret;
622 end = ret + QSTR_SIZE;
623
624 *p++ = '"';
625
626 /* always keep 3 chars to support passing "" and the ending " */
627 while (*str && p < end - 3) {
628 if (*str == '"') {
629 *p++ = '"';
630 *p++ = '"';
631 }
632 else
633 *p++ = *str;
634 str++;
635 }
636 *p++ = '"';
637 return ret;
638}
639
Robert Tsai81ae1952007-12-05 10:47:29 +0100640/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200641 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
642 *
643 * It looks like this one would be a good candidate for inlining, but this is
644 * not interesting because it around 35 bytes long and often called multiple
645 * times within the same function.
646 */
647int ishex(char s)
648{
649 s -= '0';
650 if ((unsigned char)s <= 9)
651 return 1;
652 s -= 'A' - '0';
653 if ((unsigned char)s <= 5)
654 return 1;
655 s -= 'a' - 'A';
656 if ((unsigned char)s <= 5)
657 return 1;
658 return 0;
659}
660
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100661/* rounds <i> down to the closest value having max 2 digits */
662unsigned int round_2dig(unsigned int i)
663{
664 unsigned int mul = 1;
665
666 while (i >= 100) {
667 i /= 10;
668 mul *= 10;
669 }
670 return i * mul;
671}
672
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100673/*
674 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
675 * invalid character is found, a pointer to it is returned. If everything is
676 * fine, NULL is returned.
677 */
678const char *invalid_char(const char *name)
679{
680 if (!*name)
681 return name;
682
683 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100684 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100685 *name != '_' && *name != '-')
686 return name;
687 name++;
688 }
689 return NULL;
690}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200691
692/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200693 * Checks <name> for invalid characters. Valid chars are [_.-] and those
694 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200695 * If an invalid character is found, a pointer to it is returned.
696 * If everything is fine, NULL is returned.
697 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200698static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200699
700 if (!*name)
701 return name;
702
703 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100704 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200705 *name != '_' && *name != '-')
706 return name;
707
708 name++;
709 }
710
711 return NULL;
712}
713
714/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200715 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
716 * If an invalid character is found, a pointer to it is returned.
717 * If everything is fine, NULL is returned.
718 */
719const char *invalid_domainchar(const char *name) {
720 return __invalid_char(name, isalnum);
721}
722
723/*
724 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
725 * If an invalid character is found, a pointer to it is returned.
726 * If everything is fine, NULL is returned.
727 */
728const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200729 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200730}
731
732/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100733 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100734 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
735 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
736 * the function tries to guess the address family from the syntax. If the
737 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100738 * string is assumed to contain only an address, no port. The address can be a
739 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
740 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
741 * The return address will only have the address family and the address set,
742 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100743 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
744 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100745 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200746 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100747struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200748{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100749 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100750 /* max IPv6 length, including brackets and terminating NULL */
751 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100752 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100753
754 /* check IPv6 with square brackets */
755 if (str[0] == '[') {
756 size_t iplength = strlen(str);
757
758 if (iplength < 4) {
759 /* minimal size is 4 when using brackets "[::]" */
760 goto fail;
761 }
762 else if (iplength >= sizeof(tmpip)) {
763 /* IPv6 literal can not be larger than tmpip */
764 goto fail;
765 }
766 else {
767 if (str[iplength - 1] != ']') {
768 /* if address started with bracket, it should end with bracket */
769 goto fail;
770 }
771 else {
772 memcpy(tmpip, str + 1, iplength - 2);
773 tmpip[iplength - 2] = '\0';
774 str = tmpip;
775 }
776 }
777 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100778
Willy Tarreaufab5a432011-03-04 15:31:53 +0100779 /* Any IPv6 address */
780 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100781 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
782 sa->ss_family = AF_INET6;
783 else if (sa->ss_family != AF_INET6)
784 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100785 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100786 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100787 }
788
Willy Tarreau24709282013-03-10 21:32:12 +0100789 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100790 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100791 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
792 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100793 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100794 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100795 }
796
797 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100798 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
799 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100800 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100801 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100802 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100803 }
804
805 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100806 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
807 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100808 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100809 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100810 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100811 }
812
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100813 if (!resolve)
814 return NULL;
815
Emeric Brund30e9a12020-12-23 18:49:16 +0100816 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200817 return NULL;
818
David du Colombierd5f43282011-03-17 10:40:16 +0100819#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200820 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100821 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100822 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100823
824 memset(&result, 0, sizeof(result));
825 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100826 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100827 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200828 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100829 hints.ai_protocol = 0;
830
831 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100832 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
833 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100834 else if (sa->ss_family != result->ai_family) {
835 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100836 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100837 }
Willy Tarreau24709282013-03-10 21:32:12 +0100838
David du Colombierd5f43282011-03-17 10:40:16 +0100839 switch (result->ai_family) {
840 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100841 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100842 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100843 success = 1;
844 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100845 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100846 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100847 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100848 success = 1;
849 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100850 }
851 }
852
Sean Carey58ea0392013-02-15 23:39:18 +0100853 if (result)
854 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100855
856 if (success)
857 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100858 }
David du Colombierd5f43282011-03-17 10:40:16 +0100859#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200860 /* try to resolve an IPv4/IPv6 hostname */
861 he = gethostbyname(str);
862 if (he) {
863 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
864 sa->ss_family = he->h_addrtype;
865 else if (sa->ss_family != he->h_addrtype)
866 goto fail;
867
868 switch (sa->ss_family) {
869 case AF_INET:
870 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100871 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200872 return sa;
873 case AF_INET6:
874 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100875 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200876 return sa;
877 }
878 }
879
David du Colombierd5f43282011-03-17 10:40:16 +0100880 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100881 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100882 return NULL;
883}
884
885/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100886 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
887 * range or offset consisting in two integers that the caller will have to
888 * check to find the relevant input format. The following format are supported :
889 *
890 * String format | address | port | low | high
891 * addr | <addr> | 0 | 0 | 0
892 * addr: | <addr> | 0 | 0 | 0
893 * addr:port | <addr> | <port> | <port> | <port>
894 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
895 * addr:+port | <addr> | <port> | 0 | <port>
896 * addr:-port | <addr> |-<port> | <port> | 0
897 *
898 * The detection of a port range or increment by the caller is made by
899 * comparing <low> and <high>. If both are equal, then port 0 means no port
900 * was specified. The caller may pass NULL for <low> and <high> if it is not
901 * interested in retrieving port ranges.
902 *
903 * Note that <addr> above may also be :
904 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
905 * - "*" => family will be AF_INET and address will be INADDR_ANY
906 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
907 * - a host name => family and address will depend on host name resolving.
908 *
Willy Tarreau24709282013-03-10 21:32:12 +0100909 * A prefix may be passed in before the address above to force the family :
910 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
911 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
912 * - "unix@" => force address to be a path to a UNIX socket even if the
913 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200914 * - 'abns@' -> force address to belong to the abstract namespace (Linux
915 * only). These sockets are just like Unix sockets but without
916 * the need for an underlying file system. The address is a
917 * string. Technically it's like a Unix socket with a zero in
918 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100919 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100920 *
mildisff5d5102015-10-26 18:50:08 +0100921 * IPv6 addresses can be declared with or without square brackets. When using
922 * square brackets for IPv6 addresses, the port separator (colon) is optional.
923 * If not using square brackets, and in order to avoid any ambiguity with
924 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
925 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
926 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100927 *
928 * If <pfx> is non-null, it is used as a string prefix before any path-based
929 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100930 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200931 * if <fqdn> is non-null, it will be filled with :
932 * - a pointer to the FQDN of the server name to resolve if there's one, and
933 * that the caller will have to free(),
934 * - NULL if there was an explicit address that doesn't require resolution.
935 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200936 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
937 * still honored so it is possible for the caller to know whether a resolution
938 * failed by clearing this flag and checking if <fqdn> was filled, indicating
939 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200940 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100941 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200942 * the address when cast to sockaddr_in and the address family is
943 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200944 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200945 * The matching protocol will be set into <proto> if non-null.
946 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200947 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
948 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100949 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200950struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
951 struct protocol **proto, char **err,
952 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100953{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100954 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100955 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200956 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100957 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100958 char *port1, *port2;
959 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200960 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200961 int new_fd = -1;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200962 enum proto_type proto_type;
963 int ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100964
965 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200966 if (fqdn)
967 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200968
Willy Tarreaudad36a32013-03-11 01:20:04 +0100969 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100970 if (str2 == NULL) {
971 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100972 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100973 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200974
Willy Tarreau9f69f462015-09-08 16:01:25 +0200975 if (!*str2) {
976 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
977 goto out;
978 }
979
Willy Tarreau24709282013-03-10 21:32:12 +0100980 memset(&ss, 0, sizeof(ss));
981
Willy Tarreaue835bd82020-09-16 11:35:47 +0200982 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100983 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
Willy Tarreaue3b45182021-10-27 17:28:55 +0200984 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM))) {
985 proto_type = PROTO_TYPE_DGRAM;
986 ctrl_type = SOCK_DGRAM;
987 } else {
988 proto_type = PROTO_TYPE_STREAM;
989 ctrl_type = SOCK_STREAM;
990 }
Willy Tarreaue835bd82020-09-16 11:35:47 +0200991
992 if (strncmp(str2, "stream+", 7) == 0) {
993 str2 += 7;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200994 proto_type = PROTO_TYPE_STREAM;
995 ctrl_type = SOCK_STREAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200996 }
997 else if (strncmp(str2, "dgram+", 6) == 0) {
998 str2 += 6;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200999 proto_type = PROTO_TYPE_DGRAM;
1000 ctrl_type = SOCK_DGRAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001001 }
1002
Willy Tarreau24709282013-03-10 21:32:12 +01001003 if (strncmp(str2, "unix@", 5) == 0) {
1004 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +02001005 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +01001006 ss.ss_family = AF_UNIX;
1007 }
Emeric Brunce325c42021-04-02 17:05:09 +02001008 else if (strncmp(str2, "uxdg@", 5) == 0) {
1009 str2 += 5;
1010 abstract = 0;
1011 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001012 proto_type = PROTO_TYPE_DGRAM;
1013 ctrl_type = SOCK_DGRAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001014 }
1015 else if (strncmp(str2, "uxst@", 5) == 0) {
1016 str2 += 5;
1017 abstract = 0;
1018 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001019 proto_type = PROTO_TYPE_STREAM;
1020 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001021 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001022 else if (strncmp(str2, "abns@", 5) == 0) {
1023 str2 += 5;
1024 abstract = 1;
1025 ss.ss_family = AF_UNIX;
1026 }
Emeric Brunce325c42021-04-02 17:05:09 +02001027 else if (strncmp(str2, "ip@", 3) == 0) {
1028 str2 += 3;
1029 ss.ss_family = AF_UNSPEC;
1030 }
Willy Tarreau24709282013-03-10 21:32:12 +01001031 else if (strncmp(str2, "ipv4@", 5) == 0) {
1032 str2 += 5;
1033 ss.ss_family = AF_INET;
1034 }
1035 else if (strncmp(str2, "ipv6@", 5) == 0) {
1036 str2 += 5;
1037 ss.ss_family = AF_INET6;
1038 }
Emeric Brunce325c42021-04-02 17:05:09 +02001039 else if (strncmp(str2, "tcp4@", 5) == 0) {
1040 str2 += 5;
1041 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001042 proto_type = PROTO_TYPE_STREAM;
1043 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001044 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001045 else if (strncmp(str2, "udp4@", 5) == 0) {
1046 str2 += 5;
1047 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001048 proto_type = PROTO_TYPE_DGRAM;
1049 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001050 }
Emeric Brunce325c42021-04-02 17:05:09 +02001051 else if (strncmp(str2, "tcp6@", 5) == 0) {
1052 str2 += 5;
1053 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001054 proto_type = PROTO_TYPE_STREAM;
1055 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001056 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001057 else if (strncmp(str2, "udp6@", 5) == 0) {
1058 str2 += 5;
1059 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001060 proto_type = PROTO_TYPE_DGRAM;
1061 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001062 }
Emeric Brunce325c42021-04-02 17:05:09 +02001063 else if (strncmp(str2, "tcp@", 4) == 0) {
1064 str2 += 4;
1065 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001066 proto_type = PROTO_TYPE_STREAM;
1067 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001068 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001069 else if (strncmp(str2, "udp@", 4) == 0) {
1070 str2 += 4;
1071 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001072 proto_type = PROTO_TYPE_DGRAM;
1073 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001074 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001075 else if (strncmp(str2, "quic4@", 6) == 0) {
1076 str2 += 6;
1077 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001078 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001079 ctrl_type = SOCK_STREAM;
1080 }
1081 else if (strncmp(str2, "quic6@", 6) == 0) {
1082 str2 += 6;
1083 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001084 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001085 ctrl_type = SOCK_STREAM;
1086 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001087 else if (strncmp(str2, "fd@", 3) == 0) {
1088 str2 += 3;
1089 ss.ss_family = AF_CUST_EXISTING_FD;
1090 }
1091 else if (strncmp(str2, "sockpair@", 9) == 0) {
1092 str2 += 9;
1093 ss.ss_family = AF_CUST_SOCKPAIR;
1094 }
Willy Tarreau24709282013-03-10 21:32:12 +01001095 else if (*str2 == '/') {
1096 ss.ss_family = AF_UNIX;
1097 }
1098 else
1099 ss.ss_family = AF_UNSPEC;
1100
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001101 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001102 struct sockaddr_storage ss2;
1103 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001104 char *endptr;
1105
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001106 new_fd = strtol(str2, &endptr, 10);
1107 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001108 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1109 goto out;
1110 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001111
Willy Tarreaua215be22020-09-16 10:14:16 +02001112 /* just verify that it's a socket */
1113 addr_len = sizeof(ss2);
1114 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1115 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1116 goto out;
1117 }
1118
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001119 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1120 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001121 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001122 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001123 char *endptr;
1124
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001125 new_fd = strtol(str2, &endptr, 10);
1126 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001127 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001128 goto out;
1129 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001130
Willy Tarreau6edc7222020-09-15 17:41:56 +02001131 if (opts & PA_O_SOCKET_FD) {
1132 socklen_t addr_len;
1133 int type;
1134
1135 addr_len = sizeof(ss);
1136 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1137 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1138 goto out;
1139 }
1140
1141 addr_len = sizeof(type);
1142 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue3b45182021-10-27 17:28:55 +02001143 (type == SOCK_STREAM) != (proto_type == PROTO_TYPE_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001144 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1145 goto out;
1146 }
1147
1148 porta = portl = porth = get_host_port(&ss);
1149 } else if (opts & PA_O_RAW_FD) {
1150 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1151 ((struct sockaddr_in *)&ss)->sin_port = 0;
1152 } else {
1153 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1154 goto out;
1155 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001156 }
1157 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001158 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001159 int prefix_path_len;
1160 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001161 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001162
1163 /* complete unix socket path name during startup or soft-restart is
1164 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1165 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001166 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001167 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001168 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001169
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001170 adr_len = strlen(str2);
1171 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001172 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1173 goto out;
1174 }
1175
Willy Tarreauccfccef2014-05-10 01:49:15 +02001176 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001177 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001178 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001179 memcpy(un->sun_path, pfx, prefix_path_len);
1180 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001181 }
Willy Tarreau24709282013-03-10 21:32:12 +01001182 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001183 char *end = str2 + strlen(str2);
1184 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001185
mildisff5d5102015-10-26 18:50:08 +01001186 /* search for : or ] whatever comes first */
1187 for (chr = end-1; chr > str2; chr--) {
1188 if (*chr == ']' || *chr == ':')
1189 break;
1190 }
1191
1192 if (*chr == ':') {
1193 /* Found a colon before a closing-bracket, must be a port separator.
1194 * This guarantee backward compatibility.
1195 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001196 if (!(opts & PA_O_PORT_OK)) {
1197 memprintf(err, "port specification not permitted here in '%s'", str);
1198 goto out;
1199 }
mildisff5d5102015-10-26 18:50:08 +01001200 *chr++ = '\0';
1201 port1 = chr;
1202 }
1203 else {
1204 /* Either no colon and no closing-bracket
1205 * or directly ending with a closing-bracket.
1206 * However, no port.
1207 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001208 if (opts & PA_O_PORT_MAND) {
1209 memprintf(err, "missing port specification in '%s'", str);
1210 goto out;
1211 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001212 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001213 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001214
Willy Tarreau90807112020-02-25 08:16:33 +01001215 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001216 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001217 if (port2) {
1218 if (!(opts & PA_O_PORT_RANGE)) {
1219 memprintf(err, "port range not permitted here in '%s'", str);
1220 goto out;
1221 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001222 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001223 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001224 else
1225 port2 = port1;
1226 portl = atoi(port1);
1227 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001228
1229 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1230 memprintf(err, "invalid port '%s'", port1);
1231 goto out;
1232 }
1233
1234 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1235 memprintf(err, "invalid port '%s'", port2);
1236 goto out;
1237 }
1238
1239 if (portl > porth) {
1240 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1241 goto out;
1242 }
1243
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001244 porta = portl;
1245 }
1246 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001247 if (!(opts & PA_O_PORT_OFS)) {
1248 memprintf(err, "port offset not permitted here in '%s'", str);
1249 goto out;
1250 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001251 portl = atoi(port1 + 1);
1252 porta = -portl;
1253 }
1254 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001255 if (!(opts & PA_O_PORT_OFS)) {
1256 memprintf(err, "port offset not permitted here in '%s'", str);
1257 goto out;
1258 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001259 porth = atoi(port1 + 1);
1260 porta = porth;
1261 }
1262 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001263 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001264 goto out;
1265 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001266 else if (opts & PA_O_PORT_MAND) {
1267 memprintf(err, "missing port specification in '%s'", str);
1268 goto out;
1269 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001270
1271 /* first try to parse the IP without resolving. If it fails, it
1272 * tells us we need to keep a copy of the FQDN to resolve later
1273 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001274 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001275 */
1276 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001277 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1278 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001279 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1280 goto out;
1281 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001282
Willy Tarreauceccdd72016-11-02 22:27:10 +01001283 if (fqdn) {
1284 if (str2 != back)
1285 memmove(back, str2, strlen(str2) + 1);
1286 *fqdn = back;
1287 back = NULL;
1288 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001289 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001290 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001291 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001292
Willy Tarreaue835bd82020-09-16 11:35:47 +02001293 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001294 memprintf(err, "stream-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001295 goto out;
1296 }
1297 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001298 memprintf(err, "dgram-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001299 goto out;
1300 }
1301
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001302 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001303 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001304 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1305 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001306 * in which case the address is not known yet (this is only
1307 * for servers actually).
1308 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001309 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreaue3b45182021-10-27 17:28:55 +02001310 proto_type,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001311 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001312
Emeric Brun26754902021-04-07 14:26:44 +02001313 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001314 memprintf(err, "unsupported %s protocol for %s family %d address '%s'%s",
Willy Tarreau2b049b82022-05-20 17:28:30 +02001315 (ctrl_type == SOCK_DGRAM) ? "datagram" : "stream",
1316 (proto_type == PROTO_TYPE_DGRAM) ? "datagram" : "stream",
1317 ss.ss_family,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001318 str,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001319#ifndef USE_QUIC
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001320 (ctrl_type == SOCK_STREAM && proto_type == PROTO_TYPE_DGRAM)
1321 ? "; QUIC is not compiled in if this is what you were looking for."
1322 : ""
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001323#else
1324 ""
1325#endif
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001326 );
Willy Tarreau5fc93282020-09-16 18:25:03 +02001327 goto out;
1328 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001329
1330 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1331 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1332 goto out;
1333 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001334 }
1335
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001336 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001337 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001338 if (port)
1339 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001340 if (low)
1341 *low = portl;
1342 if (high)
1343 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001344 if (fd)
1345 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001346 if (proto)
1347 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001348 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001349 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001350}
1351
Thayne McCombs92149f92020-11-20 01:28:26 -07001352/* converts <addr> and <port> into a string representation of the address and port. This is sort
1353 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1354 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1355 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1356 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1357 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1358 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1359 *
1360 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1361 */
1362char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1363{
1364 char buffer[INET6_ADDRSTRLEN];
1365 char *out = NULL;
1366 const void *ptr;
1367 const char *path;
1368
1369 switch (addr->ss_family) {
1370 case AF_INET:
1371 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1372 break;
1373 case AF_INET6:
1374 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1375 break;
1376 case AF_UNIX:
1377 path = ((struct sockaddr_un *)addr)->sun_path;
1378 if (path[0] == '\0') {
1379 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1380 return memprintf(&out, "abns@%.*s", max_length, path+1);
1381 } else {
1382 return strdup(path);
1383 }
1384 case AF_CUST_SOCKPAIR:
1385 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1386 default:
1387 return NULL;
1388 }
Tim Duesterhus22535a52022-05-23 09:30:49 +02001389 if (inet_ntop(addr->ss_family, ptr, buffer, sizeof(buffer)) == NULL) {
1390 BUG_ON(errno == ENOSPC);
1391 return NULL;
1392 }
Thayne McCombs92149f92020-11-20 01:28:26 -07001393 if (map_ports)
1394 return memprintf(&out, "%s:%+d", buffer, port);
1395 else
1396 return memprintf(&out, "%s:%d", buffer, port);
1397}
1398
1399
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001400/* converts <str> to a struct in_addr containing a network mask. It can be
1401 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001402 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001403 */
1404int str2mask(const char *str, struct in_addr *mask)
1405{
1406 if (strchr(str, '.') != NULL) { /* dotted notation */
1407 if (!inet_pton(AF_INET, str, mask))
1408 return 0;
1409 }
1410 else { /* mask length */
1411 char *err;
1412 unsigned long len = strtol(str, &err, 10);
1413
1414 if (!*str || (err && *err) || (unsigned)len > 32)
1415 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001416
1417 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001418 }
1419 return 1;
1420}
1421
Tim Duesterhus47185172018-01-25 16:24:49 +01001422/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001423 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001424 * if the conversion succeeds otherwise zero.
1425 */
1426int str2mask6(const char *str, struct in6_addr *mask)
1427{
1428 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1429 if (!inet_pton(AF_INET6, str, mask))
1430 return 0;
1431 }
1432 else { /* mask length */
1433 char *err;
1434 unsigned long len = strtol(str, &err, 10);
1435
1436 if (!*str || (err && *err) || (unsigned)len > 128)
1437 return 0;
1438
1439 len2mask6(len, mask);
1440 }
1441 return 1;
1442}
1443
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001444/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1445 * succeeds otherwise zero.
1446 */
1447int cidr2dotted(int cidr, struct in_addr *mask) {
1448
1449 if (cidr < 0 || cidr > 32)
1450 return 0;
1451
1452 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1453 return 1;
1454}
1455
Thierry Fournier70473a52016-02-17 17:12:14 +01001456/* Convert mask from bit length form to in_addr form.
1457 * This function never fails.
1458 */
1459void len2mask4(int len, struct in_addr *addr)
1460{
1461 if (len >= 32) {
1462 addr->s_addr = 0xffffffff;
1463 return;
1464 }
1465 if (len <= 0) {
1466 addr->s_addr = 0x00000000;
1467 return;
1468 }
1469 addr->s_addr = 0xffffffff << (32 - len);
1470 addr->s_addr = htonl(addr->s_addr);
1471}
1472
1473/* Convert mask from bit length form to in6_addr form.
1474 * This function never fails.
1475 */
1476void len2mask6(int len, struct in6_addr *addr)
1477{
1478 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1479 len -= 32;
1480 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1481 len -= 32;
1482 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1483 len -= 32;
1484 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1485}
1486
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001487/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001488 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001489 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001490 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001491 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1492 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001493int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001494{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001495 __label__ out_free, out_err;
1496 char *c, *s;
1497 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001498
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001499 s = strdup(str);
1500 if (!s)
1501 return 0;
1502
Willy Tarreaubaaee002006-06-26 02:48:02 +02001503 memset(mask, 0, sizeof(*mask));
1504 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001505
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001506 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001507 *c++ = '\0';
1508 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001509 if (!str2mask(c, mask))
1510 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001511 }
1512 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001513 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001514 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001515 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001516 struct hostent *he;
1517
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001518 if (!resolve)
1519 goto out_err;
1520
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001521 if ((he = gethostbyname(s)) == NULL) {
1522 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001523 }
1524 else
1525 *addr = *(struct in_addr *) *(he->h_addr_list);
1526 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001527
1528 ret_val = 1;
1529 out_free:
1530 free(s);
1531 return ret_val;
1532 out_err:
1533 ret_val = 0;
1534 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001535}
1536
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001537
1538/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001539 * converts <str> to two struct in6_addr* which must be pre-allocated.
1540 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001541 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001542 * Returns 1 if OK, 0 if error.
1543 */
1544int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1545{
1546 char *c, *s;
1547 int ret_val = 0;
1548 char *err;
1549 unsigned long len = 128;
1550
1551 s = strdup(str);
1552 if (!s)
1553 return 0;
1554
1555 memset(mask, 0, sizeof(*mask));
1556 memset(addr, 0, sizeof(*addr));
1557
1558 if ((c = strrchr(s, '/')) != NULL) {
1559 *c++ = '\0'; /* c points to the mask */
1560 if (!*c)
1561 goto out_free;
1562
1563 len = strtoul(c, &err, 10);
1564 if ((err && *err) || (unsigned)len > 128)
1565 goto out_free;
1566 }
1567 *mask = len; /* OK we have a valid mask in <len> */
1568
1569 if (!inet_pton(AF_INET6, s, addr))
1570 goto out_free;
1571
1572 ret_val = 1;
1573 out_free:
1574 free(s);
1575 return ret_val;
1576}
1577
1578
1579/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001580 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1581 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1582 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001583 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001584int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001585{
1586 int saw_digit, octets, ch;
1587 u_char tmp[4], *tp;
1588 const char *cp = addr;
1589
1590 saw_digit = 0;
1591 octets = 0;
1592 *(tp = tmp) = 0;
1593
1594 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001595 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001596 if (digit > 9 && ch != '.')
1597 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001598 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001599 if (digit <= 9) {
1600 u_int new = *tp * 10 + digit;
1601 if (new > 255)
1602 return 0;
1603 *tp = new;
1604 if (!saw_digit) {
1605 if (++octets > 4)
1606 return 0;
1607 saw_digit = 1;
1608 }
1609 } else if (ch == '.' && saw_digit) {
1610 if (octets == 4)
1611 return 0;
1612 *++tp = 0;
1613 saw_digit = 0;
1614 } else
1615 return 0;
1616 }
1617
1618 if (octets < 4)
1619 return 0;
1620
1621 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001622 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001623}
1624
1625/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001626 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001627 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001628 * the hostname. Actually only http and https are supported. <out> can be NULL.
1629 * This function returns the consumed length. It is useful if you parse complete
1630 * url like http://host:port/path, because the consumed length corresponds to
1631 * the first character of the path. If the conversion fails, it returns -1.
1632 *
1633 * This function tries to resolve the DNS name if haproxy is in starting mode.
1634 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001635 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001636int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001637{
1638 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001639 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001640 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001641 unsigned long long int http_code = 0;
1642 int default_port;
1643 struct hostent *he;
1644 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001645
1646 /* Firstly, try to find :// pattern */
1647 while (curr < url+ulen && url_code != 0x3a2f2f) {
1648 url_code = ((url_code & 0xffff) << 8);
1649 url_code += (unsigned char)*curr++;
1650 }
1651
1652 /* Secondly, if :// pattern is found, verify parsed stuff
1653 * before pattern is matching our http pattern.
1654 * If so parse ip address and port in uri.
1655 *
1656 * WARNING: Current code doesn't support dynamic async dns resolver.
1657 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001658 if (url_code != 0x3a2f2f)
1659 return -1;
1660
1661 /* Copy scheme, and utrn to lower case. */
1662 while (cp < curr - 3)
1663 http_code = (http_code << 8) + *cp++;
1664 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001665
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001666 /* HTTP or HTTPS url matching */
1667 if (http_code == 0x2020202068747470ULL) {
1668 default_port = 80;
1669 if (out)
1670 out->scheme = SCH_HTTP;
1671 }
1672 else if (http_code == 0x2020206874747073ULL) {
1673 default_port = 443;
1674 if (out)
1675 out->scheme = SCH_HTTPS;
1676 }
1677 else
1678 return -1;
1679
1680 /* If the next char is '[', the host address is IPv6. */
1681 if (*curr == '[') {
1682 curr++;
1683
1684 /* Check trash size */
1685 if (trash.size < ulen)
1686 return -1;
1687
1688 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001689 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001690 for (end = curr;
1691 end < url + ulen && *end != ']';
1692 end++, p++)
1693 *p = *end;
1694 if (*end != ']')
1695 return -1;
1696 *p = '\0';
1697
1698 /* Update out. */
1699 if (out) {
1700 out->host = curr;
1701 out->host_len = end - curr;
1702 }
1703
1704 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001705 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001706 return -1;
1707 end++;
1708
1709 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001710 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001711 end++;
1712 default_port = read_uint(&end, url + ulen);
1713 }
1714 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1715 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1716 return end - url;
1717 }
1718 else {
William Lallemand8a913742022-02-18 16:13:12 +01001719 /* we need to copy the string into the trash because url2ipv4
1720 * needs a \0 at the end of the string */
1721 if (trash.size < ulen)
1722 return -1;
1723
1724 memcpy(trash.area, curr, ulen - (curr - url));
1725 trash.area[ulen - (curr - url)] = '\0';
1726
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001727 /* We are looking for IP address. If you want to parse and
1728 * resolve hostname found in url, you can use str2sa_range(), but
1729 * be warned this can slow down global daemon performances
1730 * while handling lagging dns responses.
1731 */
William Lallemand8a913742022-02-18 16:13:12 +01001732 ret = url2ipv4(trash.area, &((struct sockaddr_in *)addr)->sin_addr);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001733 if (ret) {
1734 /* Update out. */
1735 if (out) {
1736 out->host = curr;
1737 out->host_len = ret;
1738 }
1739
William Lallemandb938b772022-03-24 21:59:03 +01001740 curr += ret;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001741
1742 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001743 if (curr < url + ulen && *curr == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001744 curr++;
1745 default_port = read_uint(&curr, url + ulen);
1746 }
1747 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1748
1749 /* Set family. */
1750 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1751 return curr - url;
1752 }
1753 else if (global.mode & MODE_STARTING) {
1754 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1755 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001756 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001757
1758 /* look for : or / or end */
1759 for (end = curr;
1760 end < url + ulen && *end != '/' && *end != ':';
1761 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001762 memcpy(trash.area, curr, end - curr);
1763 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001764
1765 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001766 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001767 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001768 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001769
1770 /* Update out. */
1771 if (out) {
1772 out->host = curr;
1773 out->host_len = end - curr;
1774 }
1775
1776 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001777 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001778 end++;
1779 default_port = read_uint(&end, url + ulen);
1780 }
1781
1782 /* Copy IP address, set port and family. */
1783 switch (he->h_addrtype) {
1784 case AF_INET:
1785 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1786 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1787 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1788 return end - url;
1789
1790 case AF_INET6:
1791 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1792 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1793 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1794 return end - url;
1795 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001796 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001797 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001798 return -1;
1799}
1800
Willy Tarreau631f01c2011-09-05 00:36:48 +02001801/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1802 * address family is returned so that it's easy for the caller to adapt to the
1803 * output format. Zero is returned if the address family is not supported. -1
1804 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1805 * supported.
1806 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001807int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001808{
1809
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001810 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001811
1812 if (size < 5)
1813 return 0;
1814 *str = '\0';
1815
1816 switch (addr->ss_family) {
1817 case AF_INET:
1818 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1819 break;
1820 case AF_INET6:
1821 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1822 break;
1823 case AF_UNIX:
1824 memcpy(str, "unix", 5);
1825 return addr->ss_family;
1826 default:
1827 return 0;
1828 }
1829
1830 if (inet_ntop(addr->ss_family, ptr, str, size))
1831 return addr->ss_family;
1832
1833 /* failed */
1834 return -1;
1835}
1836
Simon Horman75ab8bd2014-06-16 09:39:41 +09001837/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1838 * address family is returned so that it's easy for the caller to adapt to the
1839 * output format. Zero is returned if the address family is not supported. -1
1840 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1841 * supported.
1842 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001843int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001844{
1845
1846 uint16_t port;
1847
1848
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001849 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001850 return 0;
1851 *str = '\0';
1852
1853 switch (addr->ss_family) {
1854 case AF_INET:
1855 port = ((struct sockaddr_in *)addr)->sin_port;
1856 break;
1857 case AF_INET6:
1858 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1859 break;
1860 case AF_UNIX:
1861 memcpy(str, "unix", 5);
1862 return addr->ss_family;
1863 default:
1864 return 0;
1865 }
1866
1867 snprintf(str, size, "%u", ntohs(port));
1868 return addr->ss_family;
1869}
1870
Willy Tarreau16e01562016-08-09 16:46:18 +02001871/* check if the given address is local to the system or not. It will return
1872 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1873 * it is. We don't want to iterate over all interfaces for this (and it is not
1874 * portable). So instead we try to bind in UDP to this address on a free non
1875 * privileged port and to connect to the same address, port 0 (connect doesn't
1876 * care). If it succeeds, we own the address. Note that non-inet addresses are
1877 * considered local since they're most likely AF_UNIX.
1878 */
1879int addr_is_local(const struct netns_entry *ns,
1880 const struct sockaddr_storage *orig)
1881{
1882 struct sockaddr_storage addr;
1883 int result;
1884 int fd;
1885
1886 if (!is_inet_addr(orig))
1887 return 1;
1888
1889 memcpy(&addr, orig, sizeof(addr));
1890 set_host_port(&addr, 0);
1891
1892 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1893 if (fd < 0)
1894 return -1;
1895
1896 result = -1;
1897 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1898 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1899 result = 0; // fail, non-local address
1900 else
1901 result = 1; // success, local address
1902 }
1903 else {
1904 if (errno == EADDRNOTAVAIL)
1905 result = 0; // definitely not local :-)
1906 }
1907 close(fd);
1908
1909 return result;
1910}
1911
Willy Tarreaubaaee002006-06-26 02:48:02 +02001912/* will try to encode the string <string> replacing all characters tagged in
1913 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1914 * prefixed by <escape>, and will store the result between <start> (included)
1915 * and <stop> (excluded), and will always terminate the string with a '\0'
1916 * before <stop>. The position of the '\0' is returned if the conversion
1917 * completes. If bytes are missing between <start> and <stop>, then the
1918 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1919 * cannot even be stored so we return <start> without writing the 0.
1920 * The input string must also be zero-terminated.
1921 */
1922const char hextab[16] = "0123456789ABCDEF";
1923char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001924 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001925 const char *string)
1926{
1927 if (start < stop) {
1928 stop--; /* reserve one byte for the final '\0' */
1929 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001930 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001931 *start++ = *string;
1932 else {
1933 if (start + 3 >= stop)
1934 break;
1935 *start++ = escape;
1936 *start++ = hextab[(*string >> 4) & 15];
1937 *start++ = hextab[*string & 15];
1938 }
1939 string++;
1940 }
1941 *start = '\0';
1942 }
1943 return start;
1944}
1945
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001946/*
1947 * Same behavior as encode_string() above, except that it encodes chunk
1948 * <chunk> instead of a string.
1949 */
1950char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001951 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001952 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001953{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001954 char *str = chunk->area;
1955 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001956
1957 if (start < stop) {
1958 stop--; /* reserve one byte for the final '\0' */
1959 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001960 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001961 *start++ = *str;
1962 else {
1963 if (start + 3 >= stop)
1964 break;
1965 *start++ = escape;
1966 *start++ = hextab[(*str >> 4) & 15];
1967 *start++ = hextab[*str & 15];
1968 }
1969 str++;
1970 }
1971 *start = '\0';
1972 }
1973 return start;
1974}
1975
Dragan Dosen0edd1092016-02-12 13:23:02 +01001976/*
1977 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001978 * character. The input <string> must be zero-terminated. The result will
1979 * be stored between <start> (included) and <stop> (excluded). This
1980 * function will always try to terminate the resulting string with a '\0'
1981 * before <stop>, and will return its position if the conversion
1982 * completes.
1983 */
1984char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001985 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001986 const char *string)
1987{
1988 if (start < stop) {
1989 stop--; /* reserve one byte for the final '\0' */
1990 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001991 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001992 *start++ = *string;
1993 else {
1994 if (start + 2 >= stop)
1995 break;
1996 *start++ = escape;
1997 *start++ = *string;
1998 }
1999 string++;
2000 }
2001 *start = '\0';
2002 }
2003 return start;
2004}
2005
2006/*
2007 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01002008 * character. <chunk> contains the input to be escaped. The result will be
2009 * stored between <start> (included) and <stop> (excluded). The function
2010 * will always try to terminate the resulting string with a '\0' before
2011 * <stop>, and will return its position if the conversion completes.
2012 */
2013char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02002014 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02002015 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01002016{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002017 char *str = chunk->area;
2018 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01002019
2020 if (start < stop) {
2021 stop--; /* reserve one byte for the final '\0' */
2022 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02002023 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01002024 *start++ = *str;
2025 else {
2026 if (start + 2 >= stop)
2027 break;
2028 *start++ = escape;
2029 *start++ = *str;
2030 }
2031 str++;
2032 }
2033 *start = '\0';
2034 }
2035 return start;
2036}
2037
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002038/* Check a string for using it in a CSV output format. If the string contains
2039 * one of the following four char <">, <,>, CR or LF, the string is
2040 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2041 * <str> is the input string to be escaped. The function assumes that
2042 * the input string is null-terminated.
2043 *
2044 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002045 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002046 * format.
2047 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002048 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002049 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002050 * If <quote> is 1, the converter puts the quotes only if any reserved character
2051 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002052 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002053 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002054 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002055 * The function returns the converted string on its output. If an error
2056 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002057 * for using the function directly as printf() argument.
2058 *
2059 * If the output buffer is too short to contain the input string, the result
2060 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002061 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002062 * This function appends the encoding to the existing output chunk, and it
2063 * guarantees that it starts immediately at the first available character of
2064 * the chunk. Please use csv_enc() instead if you want to replace the output
2065 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002066 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002067const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002068{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002069 char *end = output->area + output->size;
2070 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002071 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002072
Willy Tarreaub631c292016-01-08 10:04:08 +01002073 if (quote == 1) {
2074 /* automatic quoting: first verify if we'll have to quote the string */
2075 if (!strpbrk(str, "\n\r,\""))
2076 quote = 0;
2077 }
2078
2079 if (quote)
2080 *ptr++ = '"';
2081
Willy Tarreau898529b2016-01-06 18:07:04 +01002082 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2083 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002084 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002085 ptr++;
2086 if (ptr >= end - 2) {
2087 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002088 break;
2089 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002090 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002091 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002092 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002093 str++;
2094 }
2095
Willy Tarreaub631c292016-01-08 10:04:08 +01002096 if (quote)
2097 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002098
Willy Tarreau898529b2016-01-06 18:07:04 +01002099 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002100 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002101 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002102}
2103
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002104/* Decode an URL-encoded string in-place. The resulting string might
2105 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002106 * aborted, the string is truncated before the issue and a negative value is
2107 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002108 * If the 'in_form' argument is non-nul the string is assumed to be part of
2109 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2110 * turned to a space. If it's zero, this will only be done after a question
2111 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002112 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002113int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002114{
2115 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002116 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002117
2118 in = string;
2119 out = string;
2120 while (*in) {
2121 switch (*in) {
2122 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002123 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002124 break;
2125 case '%' :
2126 if (!ishex(in[1]) || !ishex(in[2]))
2127 goto end;
2128 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2129 in += 2;
2130 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002131 case '?':
2132 in_form = 1;
2133 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002134 default:
2135 *out++ = *in;
2136 break;
2137 }
2138 in++;
2139 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002140 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002141 end:
2142 *out = 0;
2143 return ret;
2144}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002145
Willy Tarreau6911fa42007-03-04 18:06:08 +01002146unsigned int str2ui(const char *s)
2147{
2148 return __str2ui(s);
2149}
2150
2151unsigned int str2uic(const char *s)
2152{
2153 return __str2uic(s);
2154}
2155
2156unsigned int strl2ui(const char *s, int len)
2157{
2158 return __strl2ui(s, len);
2159}
2160
2161unsigned int strl2uic(const char *s, int len)
2162{
2163 return __strl2uic(s, len);
2164}
2165
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002166unsigned int read_uint(const char **s, const char *end)
2167{
2168 return __read_uint(s, end);
2169}
2170
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002171/* This function reads an unsigned integer from the string pointed to by <s> and
2172 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2173 * function automatically stops at <end>. If the number overflows, the 2^64-1
2174 * value is returned.
2175 */
2176unsigned long long int read_uint64(const char **s, const char *end)
2177{
2178 const char *ptr = *s;
2179 unsigned long long int i = 0, tmp;
2180 unsigned int j;
2181
2182 while (ptr < end) {
2183
2184 /* read next char */
2185 j = *ptr - '0';
2186 if (j > 9)
2187 goto read_uint64_end;
2188
2189 /* add char to the number and check overflow. */
2190 tmp = i * 10;
2191 if (tmp / 10 != i) {
2192 i = ULLONG_MAX;
2193 goto read_uint64_eat;
2194 }
2195 if (ULLONG_MAX - tmp < j) {
2196 i = ULLONG_MAX;
2197 goto read_uint64_eat;
2198 }
2199 i = tmp + j;
2200 ptr++;
2201 }
2202read_uint64_eat:
2203 /* eat each numeric char */
2204 while (ptr < end) {
2205 if ((unsigned int)(*ptr - '0') > 9)
2206 break;
2207 ptr++;
2208 }
2209read_uint64_end:
2210 *s = ptr;
2211 return i;
2212}
2213
2214/* This function reads an integer from the string pointed to by <s> and returns
2215 * it. The <s> pointer is adjusted to point to the first unread char. The function
2216 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2217 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2218 * returned.
2219 */
2220long long int read_int64(const char **s, const char *end)
2221{
2222 unsigned long long int i = 0;
2223 int neg = 0;
2224
2225 /* Look for minus char. */
2226 if (**s == '-') {
2227 neg = 1;
2228 (*s)++;
2229 }
2230 else if (**s == '+')
2231 (*s)++;
2232
2233 /* convert as positive number. */
2234 i = read_uint64(s, end);
2235
2236 if (neg) {
2237 if (i > 0x8000000000000000ULL)
2238 return LLONG_MIN;
2239 return -i;
2240 }
2241 if (i > 0x7fffffffffffffffULL)
2242 return LLONG_MAX;
2243 return i;
2244}
2245
Willy Tarreau6911fa42007-03-04 18:06:08 +01002246/* This one is 7 times faster than strtol() on athlon with checks.
2247 * It returns the value of the number composed of all valid digits read,
2248 * and can process negative numbers too.
2249 */
2250int strl2ic(const char *s, int len)
2251{
2252 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002253 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002254
2255 if (len > 0) {
2256 if (*s != '-') {
2257 /* positive number */
2258 while (len-- > 0) {
2259 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002260 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002261 if (j > 9)
2262 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002263 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002264 }
2265 } else {
2266 /* negative number */
2267 s++;
2268 while (--len > 0) {
2269 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002270 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002271 if (j > 9)
2272 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002273 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002274 }
2275 }
2276 }
2277 return i;
2278}
2279
2280
2281/* This function reads exactly <len> chars from <s> and converts them to a
2282 * signed integer which it stores into <ret>. It accurately detects any error
2283 * (truncated string, invalid chars, overflows). It is meant to be used in
2284 * applications designed for hostile environments. It returns zero when the
2285 * number has successfully been converted, non-zero otherwise. When an error
2286 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2287 * faster than strtol().
2288 */
2289int strl2irc(const char *s, int len, int *ret)
2290{
2291 int i = 0;
2292 int j;
2293
2294 if (!len)
2295 return 1;
2296
2297 if (*s != '-') {
2298 /* positive number */
2299 while (len-- > 0) {
2300 j = (*s++) - '0';
2301 if (j > 9) return 1; /* invalid char */
2302 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2303 i = i * 10;
2304 if (i + j < i) return 1; /* check for addition overflow */
2305 i = i + j;
2306 }
2307 } else {
2308 /* negative number */
2309 s++;
2310 while (--len > 0) {
2311 j = (*s++) - '0';
2312 if (j > 9) return 1; /* invalid char */
2313 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2314 i = i * 10;
2315 if (i - j > i) return 1; /* check for subtract overflow */
2316 i = i - j;
2317 }
2318 }
2319 *ret = i;
2320 return 0;
2321}
2322
2323
2324/* This function reads exactly <len> chars from <s> and converts them to a
2325 * signed integer which it stores into <ret>. It accurately detects any error
2326 * (truncated string, invalid chars, overflows). It is meant to be used in
2327 * applications designed for hostile environments. It returns zero when the
2328 * number has successfully been converted, non-zero otherwise. When an error
2329 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002330 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002331 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002332
2333int strl2llrc(const char *s, int len, long long *ret)
2334{
2335 long long i = 0;
2336 int j;
2337
2338 if (!len)
2339 return 1;
2340
2341 if (*s != '-') {
2342 /* positive number */
2343 while (len-- > 0) {
2344 j = (*s++) - '0';
2345 if (j > 9) return 1; /* invalid char */
2346 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2347 i = i * 10LL;
2348 if (i + j < i) return 1; /* check for addition overflow */
2349 i = i + j;
2350 }
2351 } else {
2352 /* negative number */
2353 s++;
2354 while (--len > 0) {
2355 j = (*s++) - '0';
2356 if (j > 9) return 1; /* invalid char */
2357 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2358 i = i * 10LL;
2359 if (i - j > i) return 1; /* check for subtract overflow */
2360 i = i - j;
2361 }
2362 }
2363 *ret = i;
2364 return 0;
2365}
2366
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002367/* This function is used with pat_parse_dotted_ver(). It converts a string
2368 * composed by two number separated by a dot. Each part must contain in 16 bits
2369 * because internally they will be represented as a 32-bit quantity stored in
2370 * a 64-bit integer. It returns zero when the number has successfully been
2371 * converted, non-zero otherwise. When an error is returned, the <ret> value
2372 * is left untouched.
2373 *
2374 * "1.3" -> 0x0000000000010003
2375 * "65535.65535" -> 0x00000000ffffffff
2376 */
2377int strl2llrc_dotted(const char *text, int len, long long *ret)
2378{
2379 const char *end = &text[len];
2380 const char *p;
2381 long long major, minor;
2382
2383 /* Look for dot. */
2384 for (p = text; p < end; p++)
2385 if (*p == '.')
2386 break;
2387
2388 /* Convert major. */
2389 if (strl2llrc(text, p - text, &major) != 0)
2390 return 1;
2391
2392 /* Check major. */
2393 if (major >= 65536)
2394 return 1;
2395
2396 /* Convert minor. */
2397 minor = 0;
2398 if (p < end)
2399 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2400 return 1;
2401
2402 /* Check minor. */
2403 if (minor >= 65536)
2404 return 1;
2405
2406 /* Compose value. */
2407 *ret = (major << 16) | (minor & 0xffff);
2408 return 0;
2409}
2410
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002411/* This function parses a time value optionally followed by a unit suffix among
2412 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2413 * expected by the caller. The computation does its best to avoid overflows.
2414 * The value is returned in <ret> if everything is fine, and a NULL is returned
2415 * by the function. In case of error, a pointer to the error is returned and
2416 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002417 * Values resulting in values larger than or equal to 2^31 after conversion are
2418 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2419 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002420 */
2421const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2422{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002423 unsigned long long imult, idiv;
2424 unsigned long long omult, odiv;
2425 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002426 const char *str = text;
2427
2428 if (!isdigit((unsigned char)*text))
2429 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002430
2431 omult = odiv = 1;
2432
2433 switch (unit_flags & TIME_UNIT_MASK) {
2434 case TIME_UNIT_US: omult = 1000000; break;
2435 case TIME_UNIT_MS: omult = 1000; break;
2436 case TIME_UNIT_S: break;
2437 case TIME_UNIT_MIN: odiv = 60; break;
2438 case TIME_UNIT_HOUR: odiv = 3600; break;
2439 case TIME_UNIT_DAY: odiv = 86400; break;
2440 default: break;
2441 }
2442
2443 value = 0;
2444
2445 while (1) {
2446 unsigned int j;
2447
2448 j = *text - '0';
2449 if (j > 9)
2450 break;
2451 text++;
2452 value *= 10;
2453 value += j;
2454 }
2455
2456 imult = idiv = 1;
2457 switch (*text) {
2458 case '\0': /* no unit = default unit */
2459 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002460 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002461 case 's': /* second = unscaled unit */
2462 break;
2463 case 'u': /* microsecond : "us" */
2464 if (text[1] == 's') {
2465 idiv = 1000000;
2466 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002467 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002468 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002469 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002470 case 'm': /* millisecond : "ms" or minute: "m" */
2471 if (text[1] == 's') {
2472 idiv = 1000;
2473 text++;
2474 } else
2475 imult = 60;
2476 break;
2477 case 'h': /* hour : "h" */
2478 imult = 3600;
2479 break;
2480 case 'd': /* day : "d" */
2481 imult = 86400;
2482 break;
2483 default:
2484 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002485 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002486 if (*(++text) != '\0') {
2487 ha_warning("unexpected character '%c' after the timer value '%s', only "
2488 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2489 " This will be reported as an error in next versions.\n", *text, str);
2490 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002491
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002492 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002493 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2494 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2495 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2496 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2497
Willy Tarreau9faebe32019-06-07 19:00:37 +02002498 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2499 if (result >= 0x80000000)
2500 return PARSE_TIME_OVER;
2501 if (!result && value)
2502 return PARSE_TIME_UNDER;
2503 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002504 return NULL;
2505}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002506
Emeric Brun39132b22010-01-04 14:57:24 +01002507/* this function converts the string starting at <text> to an unsigned int
2508 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002509 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002510 */
2511const char *parse_size_err(const char *text, unsigned *ret) {
2512 unsigned value = 0;
2513
Christopher Faulet82635a02020-12-11 09:30:45 +01002514 if (!isdigit((unsigned char)*text))
2515 return text;
2516
Emeric Brun39132b22010-01-04 14:57:24 +01002517 while (1) {
2518 unsigned int j;
2519
2520 j = *text - '0';
2521 if (j > 9)
2522 break;
2523 if (value > ~0U / 10)
2524 return text;
2525 value *= 10;
2526 if (value > (value + j))
2527 return text;
2528 value += j;
2529 text++;
2530 }
2531
2532 switch (*text) {
2533 case '\0':
2534 break;
2535 case 'K':
2536 case 'k':
2537 if (value > ~0U >> 10)
2538 return text;
2539 value = value << 10;
2540 break;
2541 case 'M':
2542 case 'm':
2543 if (value > ~0U >> 20)
2544 return text;
2545 value = value << 20;
2546 break;
2547 case 'G':
2548 case 'g':
2549 if (value > ~0U >> 30)
2550 return text;
2551 value = value << 30;
2552 break;
2553 default:
2554 return text;
2555 }
2556
Godbach58048a22015-01-28 17:36:16 +08002557 if (*text != '\0' && *++text != '\0')
2558 return text;
2559
Emeric Brun39132b22010-01-04 14:57:24 +01002560 *ret = value;
2561 return NULL;
2562}
2563
Willy Tarreau126d4062013-12-03 17:50:47 +01002564/*
2565 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002566 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002567 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002568 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002569 */
2570int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2571{
2572 int len;
2573 const char *p = source;
2574 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002575 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002576
2577 len = strlen(source);
2578 if (len % 2) {
2579 memprintf(err, "an even number of hex digit is expected");
2580 return 0;
2581 }
2582
2583 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002584
Willy Tarreau126d4062013-12-03 17:50:47 +01002585 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002586 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002587 if (!*binstr) {
2588 memprintf(err, "out of memory while loading string pattern");
2589 return 0;
2590 }
2591 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002592 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002593 else {
2594 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002595 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002596 len, *binstrlen);
2597 return 0;
2598 }
2599 alloc = 0;
2600 }
2601 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002602
2603 i = j = 0;
2604 while (j < len) {
2605 if (!ishex(p[i++]))
2606 goto bad_input;
2607 if (!ishex(p[i++]))
2608 goto bad_input;
2609 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2610 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002611 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002612
2613bad_input:
2614 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002615 if (alloc)
2616 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002617 return 0;
2618}
2619
Willy Tarreau946ba592009-05-10 15:41:18 +02002620/* copies at most <n> characters from <src> and always terminates with '\0' */
2621char *my_strndup(const char *src, int n)
2622{
2623 int len = 0;
2624 char *ret;
2625
2626 while (len < n && src[len])
2627 len++;
2628
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002629 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002630 if (!ret)
2631 return ret;
2632 memcpy(ret, src, len);
2633 ret[len] = '\0';
2634 return ret;
2635}
2636
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002637/*
2638 * search needle in haystack
2639 * returns the pointer if found, returns NULL otherwise
2640 */
2641const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2642{
2643 const void *c = NULL;
2644 unsigned char f;
2645
2646 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2647 return NULL;
2648
2649 f = *(char *)needle;
2650 c = haystack;
2651 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2652 if ((haystacklen - (c - haystack)) < needlelen)
2653 return NULL;
2654
2655 if (memcmp(c, needle, needlelen) == 0)
2656 return c;
2657 ++c;
2658 }
2659 return NULL;
2660}
2661
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002662/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002663size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2664{
2665 size_t ret = 0;
2666
2667 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2668 str++;
2669 ret++;
2670 }
2671 return ret;
2672}
2673
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002674/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002675size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2676{
2677 size_t ret = 0;
2678
2679 while (ret < len) {
2680 if(memchr(reject, *((int *)str), rejectlen))
2681 return ret;
2682 str++;
2683 ret++;
2684 }
2685 return ret;
2686}
2687
Willy Tarreau482b00d2009-10-04 22:48:42 +02002688/* This function returns the first unused key greater than or equal to <key> in
2689 * ID tree <root>. Zero is returned if no place is found.
2690 */
2691unsigned int get_next_id(struct eb_root *root, unsigned int key)
2692{
2693 struct eb32_node *used;
2694
2695 do {
2696 used = eb32_lookup_ge(root, key);
2697 if (!used || used->key > key)
2698 return key; /* key is available */
2699 key++;
2700 } while (key);
2701 return key;
2702}
2703
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002704/* dump the full tree to <file> in DOT format for debugging purposes. Will
2705 * optionally highlight node <subj> if found, depending on operation <op> :
2706 * 0 : nothing
2707 * >0 : insertion, node/leaf are surrounded in red
2708 * <0 : removal, node/leaf are dashed with no background
2709 * Will optionally add "desc" as a label on the graph if set and non-null.
2710 */
2711void 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 +01002712{
2713 struct eb32sc_node *node;
2714 unsigned long scope = -1;
2715
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002716 fprintf(file, "digraph ebtree {\n");
2717
2718 if (desc && *desc) {
2719 fprintf(file,
2720 " fontname=\"fixed\";\n"
2721 " fontsize=8;\n"
2722 " label=\"%s\";\n", desc);
2723 }
2724
Willy Tarreaued3cda02017-11-15 15:04:05 +01002725 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002726 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2727 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002728 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2729 );
2730
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002731 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002732 (long)eb_root_to_node(root),
2733 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002734 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2735
2736 node = eb32sc_first(root, scope);
2737 while (node) {
2738 if (node->node.node_p) {
2739 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002740 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2741 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2742 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002743
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002744 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002745 (long)node,
2746 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002747 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002748
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002749 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002750 (long)node,
2751 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002752 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2753
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002754 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002755 (long)node,
2756 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002757 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2758 }
2759
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002760 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2761 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2762 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002763
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002764 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002765 (long)node,
2766 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002767 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002768 node = eb32sc_next(node, scope);
2769 }
2770 fprintf(file, "}\n");
2771}
2772
Willy Tarreau0dc9e6d2022-08-01 11:55:57 +02002773/* dump the full tree to <file> in DOT format for debugging purposes. Will
2774 * optionally highlight node <subj> if found, depending on operation <op> :
2775 * 0 : nothing
2776 * >0 : insertion, node/leaf are surrounded in red
2777 * <0 : removal, node/leaf are dashed with no background
2778 * Will optionally add "desc" as a label on the graph if set and non-null. The
2779 * key is printed as a u32 hex value. A full-sized hex dump would be better but
2780 * is left to be implemented.
2781 */
2782void ebmb_to_file(FILE *file, struct eb_root *root, const struct ebmb_node *subj, int op, const char *desc)
2783{
2784 struct ebmb_node *node;
2785
2786 fprintf(file, "digraph ebtree {\n");
2787
2788 if (desc && *desc) {
2789 fprintf(file,
2790 " fontname=\"fixed\";\n"
2791 " fontsize=8;\n"
2792 " label=\"%s\";\n", desc);
2793 }
2794
2795 fprintf(file,
2796 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2797 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
2798 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2799 );
2800
2801 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2802 (long)eb_root_to_node(root),
2803 (long)eb_root_to_node(eb_clrtag(root->b[0])),
2804 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2805
2806 node = ebmb_first(root);
2807 while (node) {
2808 if (node->node.node_p) {
2809 /* node part is used */
2810 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%#x\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2811 (long)node, (long)node, read_u32(node->key), node->node.bit,
2812 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2813
2814 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2815 (long)node,
2816 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
2817 eb_gettag(node->node.node_p) ? 'R' : 'L');
2818
2819 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2820 (long)node,
2821 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
2822 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2823
2824 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
2825 (long)node,
2826 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
2827 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2828 }
2829
2830 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%#x\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2831 (long)node, (long)node, read_u32(node->key), node->node.pfx,
2832 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2833
2834 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2835 (long)node,
2836 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
2837 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
2838 node = ebmb_next(node);
2839 }
2840 fprintf(file, "}\n");
2841}
2842
Willy Tarreau348238b2010-01-18 15:05:57 +01002843/* This function compares a sample word possibly followed by blanks to another
2844 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2845 * otherwise zero. This intends to be used when checking HTTP headers for some
2846 * values. Note that it validates a word followed only by blanks but does not
2847 * validate a word followed by blanks then other chars.
2848 */
2849int word_match(const char *sample, int slen, const char *word, int wlen)
2850{
2851 if (slen < wlen)
2852 return 0;
2853
2854 while (wlen) {
2855 char c = *sample ^ *word;
2856 if (c && c != ('A' ^ 'a'))
2857 return 0;
2858 sample++;
2859 word++;
2860 slen--;
2861 wlen--;
2862 }
2863
2864 while (slen) {
2865 if (*sample != ' ' && *sample != '\t')
2866 return 0;
2867 sample++;
2868 slen--;
2869 }
2870 return 1;
2871}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002872
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002873/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2874 * is particularly fast because it avoids expensive operations such as
2875 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002876 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002877 */
2878unsigned int inetaddr_host(const char *text)
2879{
2880 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2881 register unsigned int dig100, dig10, dig1;
2882 int s;
2883 const char *p, *d;
2884
2885 dig1 = dig10 = dig100 = ascii_zero;
2886 s = 24;
2887
2888 p = text;
2889 while (1) {
2890 if (((unsigned)(*p - '0')) <= 9) {
2891 p++;
2892 continue;
2893 }
2894
2895 /* here, we have a complete byte between <text> and <p> (exclusive) */
2896 if (p == text)
2897 goto end;
2898
2899 d = p - 1;
2900 dig1 |= (unsigned int)(*d << s);
2901 if (d == text)
2902 goto end;
2903
2904 d--;
2905 dig10 |= (unsigned int)(*d << s);
2906 if (d == text)
2907 goto end;
2908
2909 d--;
2910 dig100 |= (unsigned int)(*d << s);
2911 end:
2912 if (!s || *p != '.')
2913 break;
2914
2915 s -= 8;
2916 text = ++p;
2917 }
2918
2919 dig100 -= ascii_zero;
2920 dig10 -= ascii_zero;
2921 dig1 -= ascii_zero;
2922 return ((dig100 * 10) + dig10) * 10 + dig1;
2923}
2924
2925/*
2926 * Idem except the first unparsed character has to be passed in <stop>.
2927 */
2928unsigned int inetaddr_host_lim(const char *text, const char *stop)
2929{
2930 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2931 register unsigned int dig100, dig10, dig1;
2932 int s;
2933 const char *p, *d;
2934
2935 dig1 = dig10 = dig100 = ascii_zero;
2936 s = 24;
2937
2938 p = text;
2939 while (1) {
2940 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2941 p++;
2942 continue;
2943 }
2944
2945 /* here, we have a complete byte between <text> and <p> (exclusive) */
2946 if (p == text)
2947 goto end;
2948
2949 d = p - 1;
2950 dig1 |= (unsigned int)(*d << s);
2951 if (d == text)
2952 goto end;
2953
2954 d--;
2955 dig10 |= (unsigned int)(*d << s);
2956 if (d == text)
2957 goto end;
2958
2959 d--;
2960 dig100 |= (unsigned int)(*d << s);
2961 end:
2962 if (!s || p == stop || *p != '.')
2963 break;
2964
2965 s -= 8;
2966 text = ++p;
2967 }
2968
2969 dig100 -= ascii_zero;
2970 dig10 -= ascii_zero;
2971 dig1 -= ascii_zero;
2972 return ((dig100 * 10) + dig10) * 10 + dig1;
2973}
2974
2975/*
2976 * Idem except the pointer to first unparsed byte is returned into <ret> which
2977 * must not be NULL.
2978 */
Willy Tarreau74172752010-10-15 23:21:42 +02002979unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002980{
2981 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2982 register unsigned int dig100, dig10, dig1;
2983 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002984 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002985
2986 dig1 = dig10 = dig100 = ascii_zero;
2987 s = 24;
2988
2989 p = text;
2990 while (1) {
2991 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2992 p++;
2993 continue;
2994 }
2995
2996 /* here, we have a complete byte between <text> and <p> (exclusive) */
2997 if (p == text)
2998 goto end;
2999
3000 d = p - 1;
3001 dig1 |= (unsigned int)(*d << s);
3002 if (d == text)
3003 goto end;
3004
3005 d--;
3006 dig10 |= (unsigned int)(*d << s);
3007 if (d == text)
3008 goto end;
3009
3010 d--;
3011 dig100 |= (unsigned int)(*d << s);
3012 end:
3013 if (!s || p == stop || *p != '.')
3014 break;
3015
3016 s -= 8;
3017 text = ++p;
3018 }
3019
3020 *ret = p;
3021 dig100 -= ascii_zero;
3022 dig10 -= ascii_zero;
3023 dig1 -= ascii_zero;
3024 return ((dig100 * 10) + dig10) * 10 + dig1;
3025}
3026
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02003027/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
3028 * or the number of chars read in case of success. Maybe this could be replaced
3029 * by one of the functions above. Also, apparently this function does not support
3030 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01003031 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02003032 */
3033int buf2ip(const char *buf, size_t len, struct in_addr *dst)
3034{
3035 const char *addr;
3036 int saw_digit, octets, ch;
3037 u_char tmp[4], *tp;
3038 const char *cp = buf;
3039
3040 saw_digit = 0;
3041 octets = 0;
3042 *(tp = tmp) = 0;
3043
3044 for (addr = buf; addr - buf < len; addr++) {
3045 unsigned char digit = (ch = *addr) - '0';
3046
3047 if (digit > 9 && ch != '.')
3048 break;
3049
3050 if (digit <= 9) {
3051 u_int new = *tp * 10 + digit;
3052
3053 if (new > 255)
3054 return 0;
3055
3056 *tp = new;
3057
3058 if (!saw_digit) {
3059 if (++octets > 4)
3060 return 0;
3061 saw_digit = 1;
3062 }
3063 } else if (ch == '.' && saw_digit) {
3064 if (octets == 4)
3065 return 0;
3066
3067 *++tp = 0;
3068 saw_digit = 0;
3069 } else
3070 return 0;
3071 }
3072
3073 if (octets < 4)
3074 return 0;
3075
3076 memcpy(&dst->s_addr, tmp, 4);
3077 return addr - cp;
3078}
3079
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003080/* This function converts the string in <buf> of the len <len> to
3081 * struct in6_addr <dst> which must be allocated by the caller.
3082 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01003083 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003084 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003085int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
3086{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003087 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01003088 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003089
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003090 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003091 return 0;
3092
3093 memcpy(null_term_ip6, buf, len);
3094 null_term_ip6[len] = '\0';
3095
Willy Tarreau075415a2013-12-12 11:29:39 +01003096 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003097 return 0;
3098
Willy Tarreau075415a2013-12-12 11:29:39 +01003099 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003100 return 1;
3101}
3102
Willy Tarreauacf95772010-06-14 19:09:21 +02003103/* To be used to quote config arg positions. Returns the short string at <ptr>
3104 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
3105 * if ptr is NULL or empty. The string is locally allocated.
3106 */
3107const char *quote_arg(const char *ptr)
3108{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003109 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003110 int i;
3111
3112 if (!ptr || !*ptr)
3113 return "end of line";
3114 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003115 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003116 val[i] = *ptr++;
3117 val[i++] = '\'';
3118 val[i] = '\0';
3119 return val;
3120}
3121
Willy Tarreau5b180202010-07-18 10:40:48 +02003122/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3123int get_std_op(const char *str)
3124{
3125 int ret = -1;
3126
3127 if (*str == 'e' && str[1] == 'q')
3128 ret = STD_OP_EQ;
3129 else if (*str == 'n' && str[1] == 'e')
3130 ret = STD_OP_NE;
3131 else if (*str == 'l') {
3132 if (str[1] == 'e') ret = STD_OP_LE;
3133 else if (str[1] == 't') ret = STD_OP_LT;
3134 }
3135 else if (*str == 'g') {
3136 if (str[1] == 'e') ret = STD_OP_GE;
3137 else if (str[1] == 't') ret = STD_OP_GT;
3138 }
3139
3140 if (ret == -1 || str[2] != '\0')
3141 return -1;
3142 return ret;
3143}
3144
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003145/* hash a 32-bit integer to another 32-bit integer */
3146unsigned int full_hash(unsigned int a)
3147{
3148 return __full_hash(a);
3149}
3150
Willy Tarreauf3241112019-02-26 09:56:22 +01003151/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3152 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3153 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3154 * a popcount variant and is described here :
3155 * https://graphics.stanford.edu/~seander/bithacks.html
3156 */
3157unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3158{
3159 unsigned long a, b, c, d;
3160 unsigned int s;
3161 unsigned int t;
3162
3163 a = m - ((m >> 1) & ~0UL/3);
3164 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3165 c = (b + (b >> 4)) & ~0UL/0x11;
3166 d = (c + (c >> 8)) & ~0UL/0x101;
3167
3168 r++; // make r be 1..64
3169
3170 t = 0;
3171 s = LONGBITS;
3172 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003173 unsigned long d2 = (d >> 16) >> 16;
3174 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003175 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3176 }
3177
3178 t = (d >> (s - 16)) & 0xff;
3179 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3180 t = (c >> (s - 8)) & 0xf;
3181 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3182 t = (b >> (s - 4)) & 0x7;
3183 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3184 t = (a >> (s - 2)) & 0x3;
3185 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3186 t = (m >> (s - 1)) & 0x1;
3187 s -= ((t - r) & 256) >> 8;
3188
3189 return s - 1;
3190}
3191
3192/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3193 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3194 * using mask_prep_rank_map() below.
3195 */
3196unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3197 unsigned long a, unsigned long b,
3198 unsigned long c, unsigned long d)
3199{
3200 unsigned int s;
3201 unsigned int t;
3202
3203 r++; // make r be 1..64
3204
3205 t = 0;
3206 s = LONGBITS;
3207 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003208 unsigned long d2 = (d >> 16) >> 16;
3209 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003210 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3211 }
3212
3213 t = (d >> (s - 16)) & 0xff;
3214 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3215 t = (c >> (s - 8)) & 0xf;
3216 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3217 t = (b >> (s - 4)) & 0x7;
3218 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3219 t = (a >> (s - 2)) & 0x3;
3220 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3221 t = (m >> (s - 1)) & 0x1;
3222 s -= ((t - r) & 256) >> 8;
3223
3224 return s - 1;
3225}
3226
3227/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3228 * above.
3229 */
3230void mask_prep_rank_map(unsigned long m,
3231 unsigned long *a, unsigned long *b,
3232 unsigned long *c, unsigned long *d)
3233{
3234 *a = m - ((m >> 1) & ~0UL/3);
3235 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3236 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3237 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3238}
3239
Willy Tarreauc7a8a3c2022-06-21 20:19:54 +02003240/* Returns the position of one bit set in <v>, starting at position <bit>, and
3241 * searching in other halves if not found. This is intended to be used to
3242 * report the position of one bit set among several based on a counter or a
3243 * random generator while preserving a relatively good distribution so that
3244 * values made of holes in the middle do not see one of the bits around the
3245 * hole being returned much more often than the other one. It can be seen as a
3246 * disturbed ffsl() where the initial search starts at bit <bit>. The look up
3247 * is performed in O(logN) time for N bit words, yielding a bit among 64 in
3248 * about 16 cycles. Its usage differs from the rank find function in that the
3249 * bit passed doesn't need to be limited to the value's popcount, making the
3250 * function easier to use for random picking, and twice as fast. Passing value
3251 * 0 for <v> makes no sense and -1 is returned in this case.
3252 */
3253int one_among_mask(unsigned long v, int bit)
3254{
3255 /* note, these masks may be produced by ~0UL/((1UL<<scale)+1) but
3256 * that's more expensive.
3257 */
3258 static const unsigned long halves[] = {
3259 (unsigned long)0x5555555555555555ULL,
3260 (unsigned long)0x3333333333333333ULL,
3261 (unsigned long)0x0F0F0F0F0F0F0F0FULL,
3262 (unsigned long)0x00FF00FF00FF00FFULL,
3263 (unsigned long)0x0000FFFF0000FFFFULL,
3264 (unsigned long)0x00000000FFFFFFFFULL
3265 };
3266 unsigned long halfword = ~0UL;
3267 int scope = 0;
3268 int mirror;
3269 int scale;
3270
3271 if (!v)
3272 return -1;
3273
3274 /* we check if the exact bit is set or if it's present in a mirror
3275 * position based on the current scale we're checking, in which case
3276 * it's returned with its current (or mirrored) value. Otherwise we'll
3277 * make sure there's at least one bit in the half we're in, and will
3278 * scale down to a smaller scope and try again, until we find the
3279 * closest bit.
3280 */
3281 for (scale = (sizeof(long) > 4) ? 5 : 4; scale >= 0; scale--) {
3282 halfword >>= (1UL << scale);
3283 scope |= (1UL << scale);
3284 mirror = bit ^ (1UL << scale);
3285 if (v & ((1UL << bit) | (1UL << mirror)))
3286 return (v & (1UL << bit)) ? bit : mirror;
3287
3288 if (!((v >> (bit & scope)) & halves[scale] & halfword))
3289 bit = mirror;
3290 }
3291 return bit;
3292}
3293
David du Colombier4f92d322011-03-24 11:09:31 +01003294/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003295 * otherwise zero. Note that <addr> may not necessarily be aligned
3296 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003297 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003298int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003299{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003300 struct in_addr addr_copy;
3301
3302 memcpy(&addr_copy, addr, sizeof(addr_copy));
3303 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003304}
3305
3306/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003307 * otherwise zero. Note that <addr> may not necessarily be aligned
3308 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003309 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003310int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003311{
3312 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003313 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003314
Willy Tarreaueec1d382016-07-13 11:59:39 +02003315 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003316 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003317 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003318 (((int *)net)[i] & ((int *)mask)[i]))
3319 return 0;
3320 return 1;
3321}
3322
3323/* RFC 4291 prefix */
3324const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3325 0x00, 0x00, 0x00, 0x00,
3326 0x00, 0x00, 0xFF, 0xFF };
3327
Joseph Herlant32b83272018-11-15 11:58:28 -08003328/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003329 * Input and output may overlap.
3330 */
David du Colombier4f92d322011-03-24 11:09:31 +01003331void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3332{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003333 struct in_addr tmp_addr;
3334
3335 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003336 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003337 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003338}
3339
Joseph Herlant32b83272018-11-15 11:58:28 -08003340/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003341 * Return true if conversion is possible and false otherwise.
3342 */
3343int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3344{
3345 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3346 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3347 sizeof(struct in_addr));
3348 return 1;
3349 }
3350
3351 return 0;
3352}
3353
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003354/* compare two struct sockaddr_storage and return:
3355 * 0 (true) if the addr is the same in both
3356 * 1 (false) if the addr is not the same in both
3357 * -1 (unable) if one of the addr is not AF_INET*
3358 */
3359int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3360{
3361 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3362 return -1;
3363
3364 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3365 return -1;
3366
3367 if (ss1->ss_family != ss2->ss_family)
3368 return 1;
3369
3370 switch (ss1->ss_family) {
3371 case AF_INET:
3372 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3373 &((struct sockaddr_in *)ss2)->sin_addr,
3374 sizeof(struct in_addr)) != 0;
3375 case AF_INET6:
3376 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3377 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3378 sizeof(struct in6_addr)) != 0;
3379 }
3380
3381 return 1;
3382}
3383
Christopher Faulet9553de72021-02-26 09:12:50 +01003384/* compare a struct sockaddr_storage to a struct net_addr and return :
3385 * 0 (true) if <addr> is matching <net>
3386 * 1 (false) if <addr> is not matching <net>
3387 * -1 (unable) if <addr> or <net> is not AF_INET*
3388 */
3389int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3390{
3391 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3392 return -1;
3393
3394 if ((net->family != AF_INET) && (net->family != AF_INET6))
3395 return -1;
3396
3397 if (addr->ss_family != net->family)
3398 return 1;
3399
3400 if (addr->ss_family == AF_INET &&
3401 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3402 return 0;
3403 else {
3404 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3405 const struct in6_addr *nip6 = &net->addr.v6.ip;
3406 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3407
3408 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3409 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3410 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3411 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3412 return 0;
3413 }
3414
3415 return 1;
3416}
3417
Baptiste Assmann08396c82016-01-31 00:27:17 +01003418/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003419 * The caller must allocate and clear <dest> before calling.
3420 * The source must be in either AF_INET or AF_INET6 family, or the destination
3421 * address will be undefined. If the destination address used to hold a port,
3422 * it is preserved, so that this function can be used to switch to another
3423 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003424 */
3425struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3426{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003427 int prev_port;
3428
3429 prev_port = get_net_port(dest);
3430 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003431 dest->ss_family = source->ss_family;
3432
3433 /* copy new addr and apply it */
3434 switch (source->ss_family) {
3435 case AF_INET:
3436 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003437 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003438 break;
3439 case AF_INET6:
3440 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 +01003441 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003442 break;
3443 }
3444
3445 return dest;
3446}
3447
William Lallemand421f5b52012-02-06 18:15:57 +01003448char *human_time(int t, short hz_div) {
3449 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3450 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003451 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003452 int cnt=2; // print two numbers
3453
3454 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003455 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003456 return rv;
3457 }
3458
3459 if (unlikely(hz_div > 1))
3460 t /= hz_div;
3461
3462 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003463 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003464 cnt--;
3465 }
3466
3467 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003468 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003469 cnt--;
3470 }
3471
3472 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003473 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003474 cnt--;
3475 }
3476
3477 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003478 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003479
3480 return rv;
3481}
3482
3483const char *monthname[12] = {
3484 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3485 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3486};
3487
3488/* date2str_log: write a date in the format :
3489 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3490 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3491 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3492 *
3493 * without using sprintf. return a pointer to the last char written (\0) or
3494 * NULL if there isn't enough space.
3495 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003496char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003497{
3498
3499 if (size < 25) /* the size is fixed: 24 chars + \0 */
3500 return NULL;
3501
3502 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003503 if (!dst)
3504 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003505 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003506
William Lallemand421f5b52012-02-06 18:15:57 +01003507 memcpy(dst, monthname[tm->tm_mon], 3); // month
3508 dst += 3;
3509 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003510
William Lallemand421f5b52012-02-06 18:15:57 +01003511 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003512 if (!dst)
3513 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003514 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003515
William Lallemand421f5b52012-02-06 18:15:57 +01003516 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003517 if (!dst)
3518 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003519 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003520
William Lallemand421f5b52012-02-06 18:15:57 +01003521 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003522 if (!dst)
3523 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003524 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003525
William Lallemand421f5b52012-02-06 18:15:57 +01003526 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003527 if (!dst)
3528 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003529 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003530
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003531 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003532 if (!dst)
3533 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003534 *dst = '\0';
3535
3536 return dst;
3537}
3538
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003539/* Base year used to compute leap years */
3540#define TM_YEAR_BASE 1900
3541
3542/* Return the difference in seconds between two times (leap seconds are ignored).
3543 * Retrieved from glibc 2.18 source code.
3544 */
3545static int my_tm_diff(const struct tm *a, const struct tm *b)
3546{
3547 /* Compute intervening leap days correctly even if year is negative.
3548 * Take care to avoid int overflow in leap day calculations,
3549 * but it's OK to assume that A and B are close to each other.
3550 */
3551 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3552 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3553 int a100 = a4 / 25 - (a4 % 25 < 0);
3554 int b100 = b4 / 25 - (b4 % 25 < 0);
3555 int a400 = a100 >> 2;
3556 int b400 = b100 >> 2;
3557 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3558 int years = a->tm_year - b->tm_year;
3559 int days = (365 * years + intervening_leap_days
3560 + (a->tm_yday - b->tm_yday));
3561 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3562 + (a->tm_min - b->tm_min))
3563 + (a->tm_sec - b->tm_sec));
3564}
3565
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003566/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003567 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003568 * The string returned has the same format as returned by strftime(... "%z", tm).
3569 * Offsets are kept in an internal cache for better performances.
3570 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003571const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003572{
3573 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003574 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003575
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003576 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003577 struct tm tm_gmt;
3578 int diff;
3579 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003580
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003581 /* Pretend DST not active if its status is unknown */
3582 if (isdst < 0)
3583 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003584
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003585 /* Fetch the offset and initialize it if needed */
3586 gmt_offset = gmt_offsets[isdst & 0x01];
3587 if (unlikely(!*gmt_offset)) {
3588 get_gmtime(t, &tm_gmt);
3589 diff = my_tm_diff(tm, &tm_gmt);
3590 if (diff < 0) {
3591 diff = -diff;
3592 *gmt_offset = '-';
3593 } else {
3594 *gmt_offset = '+';
3595 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003596 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003597 diff /= 60; /* Convert to minutes */
3598 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3599 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003600
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003601 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003602}
3603
William Lallemand421f5b52012-02-06 18:15:57 +01003604/* gmt2str_log: write a date in the format :
3605 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3606 * return a pointer to the last char written (\0) or
3607 * NULL if there isn't enough space.
3608 */
3609char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3610{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003611 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003612 return NULL;
3613
3614 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003615 if (!dst)
3616 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003617 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003618
William Lallemand421f5b52012-02-06 18:15:57 +01003619 memcpy(dst, monthname[tm->tm_mon], 3); // month
3620 dst += 3;
3621 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003622
William Lallemand421f5b52012-02-06 18:15:57 +01003623 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003624 if (!dst)
3625 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003626 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003627
William Lallemand421f5b52012-02-06 18:15:57 +01003628 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003629 if (!dst)
3630 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003631 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003632
William Lallemand421f5b52012-02-06 18:15:57 +01003633 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003634 if (!dst)
3635 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003636 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003637
William Lallemand421f5b52012-02-06 18:15:57 +01003638 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003639 if (!dst)
3640 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003641 *dst++ = ' ';
3642 *dst++ = '+';
3643 *dst++ = '0';
3644 *dst++ = '0';
3645 *dst++ = '0';
3646 *dst++ = '0';
3647 *dst = '\0';
3648
3649 return dst;
3650}
3651
Yuxans Yao4e25b012012-10-19 10:36:09 +08003652/* localdate2str_log: write a date in the format :
3653 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003654 * Both t and tm must represent the same time.
3655 * return a pointer to the last char written (\0) or
3656 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003657 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003658char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003659{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003660 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003661 if (size < 27) /* the size is fixed: 26 chars + \0 */
3662 return NULL;
3663
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003664 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003665
Yuxans Yao4e25b012012-10-19 10:36:09 +08003666 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003667 if (!dst)
3668 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003669 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003670
Yuxans Yao4e25b012012-10-19 10:36:09 +08003671 memcpy(dst, monthname[tm->tm_mon], 3); // month
3672 dst += 3;
3673 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003674
Yuxans Yao4e25b012012-10-19 10:36:09 +08003675 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003676 if (!dst)
3677 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003678 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003679
Yuxans Yao4e25b012012-10-19 10:36:09 +08003680 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003681 if (!dst)
3682 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003683 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003684
Yuxans Yao4e25b012012-10-19 10:36:09 +08003685 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003686 if (!dst)
3687 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003688 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003689
Yuxans Yao4e25b012012-10-19 10:36:09 +08003690 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003691 if (!dst)
3692 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003693 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003694
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003695 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003696 dst += 5;
3697 *dst = '\0';
3698
3699 return dst;
3700}
3701
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003702/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3703 * It is meant as a portable replacement for timegm() for use with valid inputs.
3704 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3705 */
3706time_t my_timegm(const struct tm *tm)
3707{
3708 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3709 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3710 * sum of the extra N days for elapsed months. The sum of all these N
3711 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3712 * in a 5-bit word. This means that with 60 bits we can represent a
3713 * matrix of all these values at once, which is fast and efficient to
3714 * access. The extra February day for leap years is not counted here.
3715 *
3716 * Jan : none = 0 (0)
3717 * Feb : Jan = 3 (3)
3718 * Mar : Jan..Feb = 3 (3 + 0)
3719 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3720 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3721 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3722 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3723 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3724 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3725 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3726 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3727 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3728 */
3729 uint64_t extra =
3730 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3731 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3732 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3733 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3734
3735 unsigned int y = tm->tm_year + 1900;
3736 unsigned int m = tm->tm_mon;
3737 unsigned long days = 0;
3738
3739 /* days since 1/1/1970 for full years */
3740 days += days_since_zero(y) - days_since_zero(1970);
3741
3742 /* days for full months in the current year */
3743 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3744
3745 /* count + 1 after March for leap years. A leap year is a year multiple
3746 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3747 * is leap, 1900 isn't, 1904 is.
3748 */
3749 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3750 days++;
3751
3752 days += tm->tm_mday - 1;
3753 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3754}
3755
Thierry Fournier93127942016-01-20 18:49:45 +01003756/* This function check a char. It returns true and updates
3757 * <date> and <len> pointer to the new position if the
3758 * character is found.
3759 */
3760static inline int parse_expect_char(const char **date, int *len, char c)
3761{
3762 if (*len < 1 || **date != c)
3763 return 0;
3764 (*len)--;
3765 (*date)++;
3766 return 1;
3767}
3768
3769/* This function expects a string <str> of len <l>. It return true and updates.
3770 * <date> and <len> if the string matches, otherwise, it returns false.
3771 */
3772static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3773{
3774 if (*len < l || strncmp(*date, str, l) != 0)
3775 return 0;
3776 (*len) -= l;
3777 (*date) += l;
3778 return 1;
3779}
3780
3781/* This macro converts 3 chars name in integer. */
3782#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3783
3784/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3785 * / %x54.75.65 ; "Tue", case-sensitive
3786 * / %x57.65.64 ; "Wed", case-sensitive
3787 * / %x54.68.75 ; "Thu", case-sensitive
3788 * / %x46.72.69 ; "Fri", case-sensitive
3789 * / %x53.61.74 ; "Sat", case-sensitive
3790 * / %x53.75.6E ; "Sun", case-sensitive
3791 *
3792 * This array must be alphabetically sorted
3793 */
3794static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3795{
3796 if (*len < 3)
3797 return 0;
3798 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3799 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3800 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3801 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3802 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3803 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3804 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3805 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3806 default: return 0;
3807 }
3808 *len -= 3;
3809 *date += 3;
3810 return 1;
3811}
3812
3813/* month = %x4A.61.6E ; "Jan", case-sensitive
3814 * / %x46.65.62 ; "Feb", case-sensitive
3815 * / %x4D.61.72 ; "Mar", case-sensitive
3816 * / %x41.70.72 ; "Apr", case-sensitive
3817 * / %x4D.61.79 ; "May", case-sensitive
3818 * / %x4A.75.6E ; "Jun", case-sensitive
3819 * / %x4A.75.6C ; "Jul", case-sensitive
3820 * / %x41.75.67 ; "Aug", case-sensitive
3821 * / %x53.65.70 ; "Sep", case-sensitive
3822 * / %x4F.63.74 ; "Oct", case-sensitive
3823 * / %x4E.6F.76 ; "Nov", case-sensitive
3824 * / %x44.65.63 ; "Dec", case-sensitive
3825 *
3826 * This array must be alphabetically sorted
3827 */
3828static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3829{
3830 if (*len < 3)
3831 return 0;
3832 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3833 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3834 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3835 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3836 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3837 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3838 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3839 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3840 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3841 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3842 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3843 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3844 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3845 default: return 0;
3846 }
3847 *len -= 3;
3848 *date += 3;
3849 return 1;
3850}
3851
3852/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3853 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3854 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3855 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3856 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3857 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3858 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3859 *
3860 * This array must be alphabetically sorted
3861 */
3862static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3863{
3864 if (*len < 6) /* Minimum length. */
3865 return 0;
3866 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3867 case STR2I3('M','o','n'):
3868 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3869 tm->tm_wday = 1;
3870 return 1;
3871 case STR2I3('T','u','e'):
3872 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3873 tm->tm_wday = 2;
3874 return 1;
3875 case STR2I3('W','e','d'):
3876 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3877 tm->tm_wday = 3;
3878 return 1;
3879 case STR2I3('T','h','u'):
3880 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3881 tm->tm_wday = 4;
3882 return 1;
3883 case STR2I3('F','r','i'):
3884 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3885 tm->tm_wday = 5;
3886 return 1;
3887 case STR2I3('S','a','t'):
3888 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3889 tm->tm_wday = 6;
3890 return 1;
3891 case STR2I3('S','u','n'):
3892 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3893 tm->tm_wday = 7;
3894 return 1;
3895 }
3896 return 0;
3897}
3898
3899/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3900static inline int parse_digit(const char **date, int *len, int *digit)
3901{
3902 if (*len < 1 || **date < '0' || **date > '9')
3903 return 0;
3904 *digit = (**date - '0');
3905 (*date)++;
3906 (*len)--;
3907 return 1;
3908}
3909
3910/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3911static inline int parse_2digit(const char **date, int *len, int *digit)
3912{
3913 int value;
3914
3915 RET0_UNLESS(parse_digit(date, len, &value));
3916 (*digit) = value * 10;
3917 RET0_UNLESS(parse_digit(date, len, &value));
3918 (*digit) += value;
3919
3920 return 1;
3921}
3922
3923/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3924static inline int parse_4digit(const char **date, int *len, int *digit)
3925{
3926 int value;
3927
3928 RET0_UNLESS(parse_digit(date, len, &value));
3929 (*digit) = value * 1000;
3930
3931 RET0_UNLESS(parse_digit(date, len, &value));
3932 (*digit) += value * 100;
3933
3934 RET0_UNLESS(parse_digit(date, len, &value));
3935 (*digit) += value * 10;
3936
3937 RET0_UNLESS(parse_digit(date, len, &value));
3938 (*digit) += value;
3939
3940 return 1;
3941}
3942
3943/* time-of-day = hour ":" minute ":" second
3944 * ; 00:00:00 - 23:59:60 (leap second)
3945 *
3946 * hour = 2DIGIT
3947 * minute = 2DIGIT
3948 * second = 2DIGIT
3949 */
3950static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3951{
3952 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3953 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3954 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3955 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3956 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3957 return 1;
3958}
3959
3960/* From RFC7231
3961 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3962 *
3963 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3964 * ; fixed length/zone/capitalization subset of the format
3965 * ; see Section 3.3 of [RFC5322]
3966 *
3967 *
3968 * date1 = day SP month SP year
3969 * ; e.g., 02 Jun 1982
3970 *
3971 * day = 2DIGIT
3972 * year = 4DIGIT
3973 *
3974 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3975 *
3976 * time-of-day = hour ":" minute ":" second
3977 * ; 00:00:00 - 23:59:60 (leap second)
3978 *
3979 * hour = 2DIGIT
3980 * minute = 2DIGIT
3981 * second = 2DIGIT
3982 *
3983 * DIGIT = decimal 0-9
3984 */
3985int parse_imf_date(const char *date, int len, struct tm *tm)
3986{
David Carlier327298c2016-11-20 10:42:38 +00003987 /* tm_gmtoff, if present, ought to be zero'ed */
3988 memset(tm, 0, sizeof(*tm));
3989
Thierry Fournier93127942016-01-20 18:49:45 +01003990 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3991 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3992 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3993 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3994 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3995 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3996 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3997 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3998 tm->tm_year -= 1900;
3999 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4000 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4001 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4002 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
4003 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004004 return 1;
4005}
4006
4007/* From RFC7231
4008 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4009 *
4010 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
4011 * date2 = day "-" month "-" 2DIGIT
4012 * ; e.g., 02-Jun-82
4013 *
4014 * day = 2DIGIT
4015 */
4016int parse_rfc850_date(const char *date, int len, struct tm *tm)
4017{
4018 int year;
4019
David Carlier327298c2016-11-20 10:42:38 +00004020 /* tm_gmtoff, if present, ought to be zero'ed */
4021 memset(tm, 0, sizeof(*tm));
4022
Thierry Fournier93127942016-01-20 18:49:45 +01004023 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
4024 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
4025 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4026 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
4027 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
4028 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
4029 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
4030
4031 /* year = 2DIGIT
4032 *
4033 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
4034 * two-digit year, MUST interpret a timestamp that appears to be more
4035 * than 50 years in the future as representing the most recent year in
4036 * the past that had the same last two digits.
4037 */
4038 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
4039
4040 /* expect SP */
4041 if (!parse_expect_char(&date, &len, ' ')) {
4042 /* Maybe we have the date with 4 digits. */
4043 RET0_UNLESS(parse_2digit(&date, &len, &year));
4044 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
4045 /* expect SP */
4046 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
4047 } else {
4048 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
4049 * tm_year is the number of year since 1900, so for +1900, we
4050 * do nothing, and for +2000, we add 100.
4051 */
4052 if (tm->tm_year <= 60)
4053 tm->tm_year += 100;
4054 }
4055
4056 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4057 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4058 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
4059 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004060
4061 return 1;
4062}
4063
4064/* From RFC7231
4065 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4066 *
4067 * asctime-date = day-name SP date3 SP time-of-day SP year
4068 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
4069 * ; e.g., Jun 2
4070 *
4071 * HTTP-date is case sensitive. A sender MUST NOT generate additional
4072 * whitespace in an HTTP-date beyond that specifically included as SP in
4073 * the grammar.
4074 */
4075int parse_asctime_date(const char *date, int len, struct tm *tm)
4076{
David Carlier327298c2016-11-20 10:42:38 +00004077 /* tm_gmtoff, if present, ought to be zero'ed */
4078 memset(tm, 0, sizeof(*tm));
4079
Thierry Fournier93127942016-01-20 18:49:45 +01004080 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
4081 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4082 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
4083 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4084
4085 /* expect SP and 1DIGIT or 2DIGIT */
4086 if (parse_expect_char(&date, &len, ' '))
4087 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
4088 else
4089 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
4090
4091 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4092 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4093 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4094 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
4095 tm->tm_year -= 1900;
4096 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004097 return 1;
4098}
4099
4100/* From RFC7231
4101 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4102 *
4103 * HTTP-date = IMF-fixdate / obs-date
4104 * obs-date = rfc850-date / asctime-date
4105 *
4106 * parses an HTTP date in the RFC format and is accepted
4107 * alternatives. <date> is the strinf containing the date,
4108 * len is the len of the string. <tm> is filled with the
4109 * parsed time. We must considers this time as GMT.
4110 */
4111int parse_http_date(const char *date, int len, struct tm *tm)
4112{
4113 if (parse_imf_date(date, len, tm))
4114 return 1;
4115
4116 if (parse_rfc850_date(date, len, tm))
4117 return 1;
4118
4119 if (parse_asctime_date(date, len, tm))
4120 return 1;
4121
4122 return 0;
4123}
4124
Willy Tarreau4deeb102021-01-29 10:47:52 +01004125/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
4126 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
4127 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
4128 * surrounded by <pfx> and <sfx> respectively if not NULL.
4129 */
4130int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
4131{
4132 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
4133 const char *unit;
4134
4135 if (!pfx)
4136 pfx = "";
4137 if (!sfx)
4138 sfx = "";
4139
4140 do {
4141 unit = " - "; if (val <= 0.0) break;
4142 unit = "ns"; if (val < 1000.0) break;
4143 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
4144 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
4145 unit = "s "; val /= 1000.0; if (val < 60.0) break;
4146 unit = "m "; val /= 60.0; if (val < 60.0) break;
4147 unit = "h "; val /= 60.0; if (val < 24.0) break;
4148 unit = "d "; val /= 24.0; if (val < 365.0) break;
4149 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
4150 unit = " inf "; val = 0.0; break;
4151 } while (0);
4152
4153 if (val <= 0.0)
4154 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
4155 else if (val < 10.0)
4156 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
4157 else if (val < 100.0)
4158 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
4159 else
4160 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4161}
4162
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004163/* Dynamically allocates a string of the proper length to hold the formatted
4164 * output. NULL is returned on error. The caller is responsible for freeing the
4165 * memory area using free(). The resulting string is returned in <out> if the
4166 * pointer is not NULL. A previous version of <out> might be used to build the
4167 * new string, and it will be freed before returning if it is not NULL, which
4168 * makes it possible to build complex strings from iterative calls without
4169 * having to care about freeing intermediate values, as in the example below :
4170 *
4171 * memprintf(&err, "invalid argument: '%s'", arg);
4172 * ...
4173 * memprintf(&err, "parser said : <%s>\n", *err);
4174 * ...
4175 * free(*err);
4176 *
4177 * This means that <err> must be initialized to NULL before first invocation.
4178 * The return value also holds the allocated string, which eases error checking
4179 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004180 * passed instead and it will be ignored. The returned message will then also
4181 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004182 *
4183 * It is also convenient to use it without any free except the last one :
4184 * err = NULL;
4185 * if (!fct1(err)) report(*err);
4186 * if (!fct2(err)) report(*err);
4187 * if (!fct3(err)) report(*err);
4188 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004189 *
4190 * memprintf relies on memvprintf. This last version can be called from any
4191 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004192 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004193char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004194{
4195 va_list args;
4196 char *ret = NULL;
4197 int allocated = 0;
4198 int needed = 0;
4199
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004200 if (!out)
4201 return NULL;
4202
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004203 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004204 char buf1;
4205
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004206 /* vsnprintf() will return the required length even when the
4207 * target buffer is NULL. We do this in a loop just in case
4208 * intermediate evaluations get wrong.
4209 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004210 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004211 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004212 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004213 if (needed < allocated) {
4214 /* Note: on Solaris 8, the first iteration always
4215 * returns -1 if allocated is zero, so we force a
4216 * retry.
4217 */
4218 if (!allocated)
4219 needed = 0;
4220 else
4221 break;
4222 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004223
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004224 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004225 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004226 } while (ret);
4227
4228 if (needed < 0) {
4229 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004230 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004231 }
4232
4233 if (out) {
4234 free(*out);
4235 *out = ret;
4236 }
4237
4238 return ret;
4239}
William Lallemand421f5b52012-02-06 18:15:57 +01004240
Christopher Faulet93a518f2017-10-24 11:25:33 +02004241char *memprintf(char **out, const char *format, ...)
4242{
4243 va_list args;
4244 char *ret = NULL;
4245
4246 va_start(args, format);
4247 ret = memvprintf(out, format, args);
4248 va_end(args);
4249
4250 return ret;
4251}
4252
Willy Tarreau21c705b2012-09-14 11:40:36 +02004253/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4254 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004255 * freed by the caller. It also supports being passed a NULL which results in the same
4256 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004257 * Example of use :
4258 * parse(cmd, &err); (callee: memprintf(&err, ...))
4259 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4260 * free(err);
4261 */
4262char *indent_msg(char **out, int level)
4263{
4264 char *ret, *in, *p;
4265 int needed = 0;
4266 int lf = 0;
4267 int lastlf = 0;
4268 int len;
4269
Willy Tarreau70eec382012-10-10 08:56:47 +02004270 if (!out || !*out)
4271 return NULL;
4272
Willy Tarreau21c705b2012-09-14 11:40:36 +02004273 in = *out - 1;
4274 while ((in = strchr(in + 1, '\n')) != NULL) {
4275 lastlf = in - *out;
4276 lf++;
4277 }
4278
4279 if (!lf) /* single line, no LF, return it as-is */
4280 return *out;
4281
4282 len = strlen(*out);
4283
4284 if (lf == 1 && lastlf == len - 1) {
4285 /* single line, LF at end, strip it and return as-is */
4286 (*out)[lastlf] = 0;
4287 return *out;
4288 }
4289
4290 /* OK now we have at least one LF, we need to process the whole string
4291 * as a multi-line string. What we'll do :
4292 * - prefix with an LF if there is none
4293 * - add <level> spaces before each line
4294 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4295 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4296 */
4297
4298 needed = 1 + level * (lf + 1) + len + 1;
4299 p = ret = malloc(needed);
4300 in = *out;
4301
4302 /* skip initial LFs */
4303 while (*in == '\n')
4304 in++;
4305
4306 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4307 while (*in) {
4308 *p++ = '\n';
4309 memset(p, ' ', level);
4310 p += level;
4311 do {
4312 *p++ = *in++;
4313 } while (*in && *in != '\n');
4314 if (*in)
4315 in++;
4316 }
4317 *p = 0;
4318
4319 free(*out);
4320 *out = ret;
4321
4322 return ret;
4323}
4324
Willy Tarreaua2c99112019-08-21 13:17:37 +02004325/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4326 * and end of lines replaced with <eol> if not 0. The first line to indent has
4327 * to be indicated in <first> (starts at zero), so that it is possible to skip
4328 * indenting the first line if it has to be appended after an existing message.
4329 * Empty strings are never indented, and NULL strings are considered empty both
4330 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4331 * character, non-zero otherwise.
4332 */
4333int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4334{
4335 int bol, lf;
4336 int pfxlen = pfx ? strlen(pfx) : 0;
4337
4338 if (!in)
4339 return 0;
4340
4341 bol = 1;
4342 lf = 0;
4343 while (*in) {
4344 if (bol && pfxlen) {
4345 if (first > 0)
4346 first--;
4347 else
4348 b_putblk(out, pfx, pfxlen);
4349 bol = 0;
4350 }
4351
4352 lf = (*in == '\n');
4353 bol |= lf;
4354 b_putchr(out, (lf && eol) ? eol : *in);
4355 in++;
4356 }
4357 return lf;
4358}
4359
Willy Tarreau9d22e562019-03-29 18:49:09 +01004360/* removes environment variable <name> from the environment as found in
4361 * environ. This is only provided as an alternative for systems without
4362 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004363 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004364 * <name> and to replace the matching pointers with the last pointer of
4365 * the array (since variables are not ordered).
4366 * It always returns 0 (success).
4367 */
4368int my_unsetenv(const char *name)
4369{
4370 extern char **environ;
4371 char **p = environ;
4372 int vars;
4373 int next;
4374 int len;
4375
4376 len = strlen(name);
4377 for (vars = 0; p[vars]; vars++)
4378 ;
4379 next = 0;
4380 while (next < vars) {
4381 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4382 next++;
4383 continue;
4384 }
4385 if (next < vars - 1)
4386 p[next] = p[vars - 1];
4387 p[--vars] = NULL;
4388 }
4389 return 0;
4390}
4391
Willy Tarreaudad36a32013-03-11 01:20:04 +01004392/* Convert occurrences of environment variables in the input string to their
4393 * corresponding value. A variable is identified as a series of alphanumeric
4394 * characters or underscores following a '$' sign. The <in> string must be
4395 * free()able. NULL returns NULL. The resulting string might be reallocated if
4396 * some expansion is made. Variable names may also be enclosed into braces if
4397 * needed (eg: to concatenate alphanum characters).
4398 */
4399char *env_expand(char *in)
4400{
4401 char *txt_beg;
4402 char *out;
4403 char *txt_end;
4404 char *var_beg;
4405 char *var_end;
4406 char *value;
4407 char *next;
4408 int out_len;
4409 int val_len;
4410
4411 if (!in)
4412 return in;
4413
4414 value = out = NULL;
4415 out_len = 0;
4416
4417 txt_beg = in;
4418 do {
4419 /* look for next '$' sign in <in> */
4420 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4421
4422 if (!*txt_end && !out) /* end and no expansion performed */
4423 return in;
4424
4425 val_len = 0;
4426 next = txt_end;
4427 if (*txt_end == '$') {
4428 char save;
4429
4430 var_beg = txt_end + 1;
4431 if (*var_beg == '{')
4432 var_beg++;
4433
4434 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004435 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004436 var_end++;
4437 }
4438
4439 next = var_end;
4440 if (*var_end == '}' && (var_beg > txt_end + 1))
4441 next++;
4442
4443 /* get value of the variable name at this location */
4444 save = *var_end;
4445 *var_end = '\0';
4446 value = getenv(var_beg);
4447 *var_end = save;
4448 val_len = value ? strlen(value) : 0;
4449 }
4450
Hubert Verstraete831962e2016-06-28 22:44:26 +02004451 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004452 if (txt_end > txt_beg) {
4453 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4454 out_len += txt_end - txt_beg;
4455 }
4456 if (val_len) {
4457 memcpy(out + out_len, value, val_len);
4458 out_len += val_len;
4459 }
4460 out[out_len] = 0;
4461 txt_beg = next;
4462 } while (*txt_beg);
4463
4464 /* here we know that <out> was allocated and that we don't need <in> anymore */
4465 free(in);
4466 return out;
4467}
4468
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004469
4470/* same as strstr() but case-insensitive and with limit length */
4471const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4472{
4473 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004474 unsigned int slen, plen;
4475 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004476
4477 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4478 return NULL;
4479
4480 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4481 return str1;
4482
4483 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4484 return NULL;
4485
4486 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 +02004487 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004488 start++;
4489 slen--;
4490 tmp1++;
4491
4492 if (tmp1 >= len_str1)
4493 return NULL;
4494
4495 /* if pattern longer than string */
4496 if (slen < plen)
4497 return NULL;
4498 }
4499
4500 sptr = start;
4501 pptr = (char *)str2;
4502
4503 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004504 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004505 sptr++;
4506 pptr++;
4507 tmp2++;
4508
4509 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4510 return start;
4511 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4512 return NULL;
4513 }
4514 }
4515 return NULL;
4516}
4517
Willy Tarreau3ff476e2022-03-30 10:02:56 +02004518/* Returns true if s1 < s2 < s3 otherwise zero. Both s1 and s3 may be NULL and
4519 * in this case only non-null strings are compared. This allows to pass initial
4520 * values in iterators and in sort functions.
4521 */
4522int strordered(const char *s1, const char *s2, const char *s3)
4523{
4524 return (!s1 || strcmp(s1, s2) < 0) && (!s3 || strcmp(s2, s3) < 0);
4525}
4526
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004527/* This function read the next valid utf8 char.
4528 * <s> is the byte srray to be decode, <len> is its length.
4529 * The function returns decoded char encoded like this:
4530 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4531 * are the length read. The decoded character is stored in <c>.
4532 */
4533unsigned char utf8_next(const char *s, int len, unsigned int *c)
4534{
4535 const unsigned char *p = (unsigned char *)s;
4536 int dec;
4537 unsigned char code = UTF8_CODE_OK;
4538
4539 if (len < 1)
4540 return UTF8_CODE_OK;
4541
4542 /* Check the type of UTF8 sequence
4543 *
4544 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4545 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4546 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4547 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4548 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4549 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4550 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4551 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4552 */
4553 switch (*p) {
4554 case 0x00 ... 0x7f:
4555 *c = *p;
4556 return UTF8_CODE_OK | 1;
4557
4558 case 0x80 ... 0xbf:
4559 *c = *p;
4560 return UTF8_CODE_BADSEQ | 1;
4561
4562 case 0xc0 ... 0xdf:
4563 if (len < 2) {
4564 *c = *p;
4565 return UTF8_CODE_BADSEQ | 1;
4566 }
4567 *c = *p & 0x1f;
4568 dec = 1;
4569 break;
4570
4571 case 0xe0 ... 0xef:
4572 if (len < 3) {
4573 *c = *p;
4574 return UTF8_CODE_BADSEQ | 1;
4575 }
4576 *c = *p & 0x0f;
4577 dec = 2;
4578 break;
4579
4580 case 0xf0 ... 0xf7:
4581 if (len < 4) {
4582 *c = *p;
4583 return UTF8_CODE_BADSEQ | 1;
4584 }
4585 *c = *p & 0x07;
4586 dec = 3;
4587 break;
4588
4589 case 0xf8 ... 0xfb:
4590 if (len < 5) {
4591 *c = *p;
4592 return UTF8_CODE_BADSEQ | 1;
4593 }
4594 *c = *p & 0x03;
4595 dec = 4;
4596 break;
4597
4598 case 0xfc ... 0xfd:
4599 if (len < 6) {
4600 *c = *p;
4601 return UTF8_CODE_BADSEQ | 1;
4602 }
4603 *c = *p & 0x01;
4604 dec = 5;
4605 break;
4606
4607 case 0xfe ... 0xff:
4608 default:
4609 *c = *p;
4610 return UTF8_CODE_BADSEQ | 1;
4611 }
4612
4613 p++;
4614
4615 while (dec > 0) {
4616
4617 /* need 0x10 for the 2 first bits */
4618 if ( ( *p & 0xc0 ) != 0x80 )
4619 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4620
4621 /* add data at char */
4622 *c = ( *c << 6 ) | ( *p & 0x3f );
4623
4624 dec--;
4625 p++;
4626 }
4627
4628 /* Check ovelong encoding.
4629 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4630 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4631 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4632 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004633 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004634 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4635 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4636 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4637 code |= UTF8_CODE_OVERLONG;
4638
4639 /* Check invalid UTF8 range. */
4640 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4641 (*c >= 0xfffe && *c <= 0xffff))
4642 code |= UTF8_CODE_INVRANGE;
4643
4644 return code | ((p-(unsigned char *)s)&0x0f);
4645}
4646
Maxime de Roucydc887852016-05-13 23:52:54 +02004647/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4648 * On failure : return 0 and <err> filled with an error message.
4649 * The caller is responsible for freeing the <err> and <str> copy
4650 * memory area using free()
4651 */
4652int list_append_word(struct list *li, const char *str, char **err)
4653{
4654 struct wordlist *wl;
4655
4656 wl = calloc(1, sizeof(*wl));
4657 if (!wl) {
4658 memprintf(err, "out of memory");
4659 goto fail_wl;
4660 }
4661
4662 wl->s = strdup(str);
4663 if (!wl->s) {
4664 memprintf(err, "out of memory");
4665 goto fail_wl_s;
4666 }
4667
Willy Tarreau2b718102021-04-21 07:32:39 +02004668 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004669
4670 return 1;
4671
4672fail_wl_s:
4673 free(wl->s);
4674fail_wl:
4675 free(wl);
4676 return 0;
4677}
4678
Willy Tarreau37101052019-05-20 16:48:20 +02004679/* indicates if a memory location may safely be read or not. The trick consists
4680 * in performing a harmless syscall using this location as an input and letting
4681 * the operating system report whether it's OK or not. For this we have the
4682 * stat() syscall, which will return EFAULT when the memory location supposed
4683 * to contain the file name is not readable. If it is readable it will then
4684 * either return 0 if the area contains an existing file name, or -1 with
4685 * another code. This must not be abused, and some audit systems might detect
4686 * this as abnormal activity. It's used only for unsafe dumps.
4687 */
4688int may_access(const void *ptr)
4689{
4690 struct stat buf;
4691
4692 if (stat(ptr, &buf) == 0)
4693 return 1;
4694 if (errno == EFAULT)
4695 return 0;
4696 return 1;
4697}
4698
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004699/* print a string of text buffer to <out>. The format is :
4700 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4701 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4702 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4703 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004704int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004705{
4706 unsigned char c;
Tim Duesterhus18795d42021-08-29 00:58:22 +02004707 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004708
Tim Duesterhus18795d42021-08-29 00:58:22 +02004709 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004710 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004711 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004712 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004713 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004714 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004715 }
4716 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004717 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004718 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004719 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004720 switch (c) {
4721 case ' ': c = ' '; break;
4722 case '\t': c = 't'; break;
4723 case '\n': c = 'n'; break;
4724 case '\r': c = 'r'; break;
4725 case '\e': c = 'e'; break;
4726 case '\\': c = '\\'; break;
4727 case '=': c = '='; break;
4728 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004729 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004730 }
4731 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004732 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004733 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004734 out->area[out->data++] = '\\';
4735 out->area[out->data++] = 'x';
4736 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4737 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004738 }
4739 ptr++;
4740 }
4741
4742 return ptr;
4743}
4744
4745/* print a buffer in hexa.
4746 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4747 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004748int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004749{
4750 unsigned char c;
4751 int ptr = 0;
4752
4753 while (ptr < bsize) {
4754 c = buf[ptr];
4755
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004756 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004757 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004758 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4759 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004760
4761 ptr++;
4762 }
4763 return ptr;
4764}
4765
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004766/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4767 * prepending each line with prefix <pfx>. The output is *not* initialized.
4768 * The output will not wrap pas the buffer's end so it is more optimal if the
4769 * caller makes sure the buffer is aligned first. A trailing zero will always
4770 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004771 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4772 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004773 */
Willy Tarreau37101052019-05-20 16:48:20 +02004774void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004775{
4776 const unsigned char *d = buf;
4777 int i, j, start;
4778
4779 d = (const unsigned char *)(((unsigned long)buf) & -16);
4780 start = ((unsigned long)buf) & 15;
4781
4782 for (i = 0; i < start + len; i += 16) {
4783 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4784
Willy Tarreau37101052019-05-20 16:48:20 +02004785 // 0: unchecked, 1: checked safe, 2: danger
4786 unsafe = !!unsafe;
4787 if (unsafe && !may_access(d + i))
4788 unsafe = 2;
4789
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004790 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004791 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004792 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004793 else if (unsafe > 1)
4794 chunk_strcat(out, "** ");
4795 else
4796 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004797
4798 if (j == 7)
4799 chunk_strcat(out, "- ");
4800 }
4801 chunk_strcat(out, " ");
4802 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004803 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004804 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004805 else if (unsafe > 1)
4806 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004807 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004808 chunk_appendf(out, "%c", d[i + j]);
4809 else
4810 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004811 }
4812 chunk_strcat(out, "\n");
4813 }
4814}
4815
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004816/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4817 * enclosed in brackets after the address itself, formatted on 14 chars
4818 * including the "0x" prefix. This is meant to be used as a prefix for code
4819 * areas. For example:
4820 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4821 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4822 * is emitted. A NULL <pfx> will be considered empty.
4823 */
4824void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4825{
4826 int ok = 0;
4827 int i;
4828
4829 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4830
4831 for (i = 0; i < n; i++) {
4832 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4833 ok = may_access(addr + i);
4834 if (ok)
4835 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4836 else
4837 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4838 }
4839}
4840
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004841/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4842 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4843 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4844 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4845 * lines are respected within the limit of 70 output chars. Lines that are
4846 * continuation of a previous truncated line begin with "+" instead of " "
4847 * after the offset. The new pointer is returned.
4848 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004849int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004850 int *line, int ptr)
4851{
4852 int end;
4853 unsigned char c;
4854
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004855 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004856 if (end > out->size)
4857 return ptr;
4858
4859 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4860
4861 while (ptr < len && ptr < bsize) {
4862 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004863 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004864 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004865 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004866 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004867 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004868 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004869 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004870 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004871 switch (c) {
4872 case '\t': c = 't'; break;
4873 case '\n': c = 'n'; break;
4874 case '\r': c = 'r'; break;
4875 case '\e': c = 'e'; break;
4876 case '\\': c = '\\'; break;
4877 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004878 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004879 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004880 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004881 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004882 out->area[out->data++] = '\\';
4883 out->area[out->data++] = 'x';
4884 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4885 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004886 }
4887 if (buf[ptr++] == '\n') {
4888 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004889 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004890 *line = ptr;
4891 return ptr;
4892 }
4893 }
4894 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004895 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004896 return ptr;
4897}
4898
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004899/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004900 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4901 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004902 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004903void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4904 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004905{
Willy Tarreau73459792017-04-11 07:58:08 +02004906 unsigned int i;
4907 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004908
4909 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4910 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004911 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004912 for (j = 0; j < 8; j++) {
4913 if (b + j >= 0 && b + j < len)
4914 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4915 else
4916 fprintf(out, " ");
4917 }
4918
4919 if (b + j >= 0 && b + j < len)
4920 fputc('-', out);
4921 else
4922 fputc(' ', out);
4923
4924 for (j = 8; j < 16; j++) {
4925 if (b + j >= 0 && b + j < len)
4926 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4927 else
4928 fprintf(out, " ");
4929 }
4930
4931 fprintf(out, " ");
4932 for (j = 0; j < 16; j++) {
4933 if (b + j >= 0 && b + j < len) {
4934 if (isprint((unsigned char)buf[b + j]))
4935 fputc((unsigned char)buf[b + j], out);
4936 else
4937 fputc('.', out);
4938 }
4939 else
4940 fputc(' ', out);
4941 }
4942 fputc('\n', out);
4943 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004944}
4945
Willy Tarreaubb869862020-04-16 10:52:41 +02004946/* Tries to report the executable path name on platforms supporting this. If
4947 * not found or not possible, returns NULL.
4948 */
4949const char *get_exec_path()
4950{
4951 const char *ret = NULL;
4952
David Carlier43a56852022-03-04 15:50:48 +00004953#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004954 long execfn = getauxval(AT_EXECFN);
4955
4956 if (execfn && execfn != ENOENT)
4957 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004958#elif defined(__FreeBSD__)
4959 Elf_Auxinfo *auxv;
4960 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4961 if (auxv->a_type == AT_EXECPATH) {
4962 ret = (const char *)auxv->a_un.a_ptr;
4963 break;
4964 }
4965 }
David Carlierbd2cced2021-08-17 08:44:25 +01004966#elif defined(__NetBSD__)
4967 AuxInfo *auxv;
4968 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4969 if (auxv->a_type == AT_SUN_EXECNAME) {
4970 ret = (const char *)auxv->a_v;
4971 break;
4972 }
4973 }
David Carlier7198c702022-05-14 17:15:49 +01004974#elif defined(__sun)
4975 ret = getexecname();
Willy Tarreaubb869862020-04-16 10:52:41 +02004976#endif
4977 return ret;
4978}
4979
Baruch Siache1651b22020-07-24 07:52:20 +03004980#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004981/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4982 * also returns the symbol size in <size>, otherwise returns 0 there.
4983 */
4984static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4985{
4986 int ret;
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004987#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreauf3d5c4b2022-01-28 09:42:29 +01004988 const ElfW(Sym) *sym __attribute__((may_alias));
Willy Tarreau9133e482020-03-04 10:19:36 +01004989
4990 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4991 if (ret)
4992 *size = sym ? sym->st_size : 0;
4993#else
David Carlierae5c42f2021-12-31 08:15:29 +00004994#if defined(__sun)
4995 ret = dladdr((void *)addr, dli);
4996#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004997 ret = dladdr(addr, dli);
David Carlierae5c42f2021-12-31 08:15:29 +00004998#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004999 *size = 0;
5000#endif
5001 return ret;
5002}
Willy Tarreau64192392021-05-05 09:06:21 +02005003
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005004/* Sets build_is_static to true if we detect a static build. Some older glibcs
5005 * tend to crash inside dlsym() in static builds, but tests show that at least
5006 * dladdr() still works (and will fail to resolve anything of course). Thus we
5007 * try to determine if we're on a static build to avoid calling dlsym() in this
5008 * case.
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005009 */
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005010void check_if_static_build()
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005011{
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005012 Dl_info dli = { };
5013 size_t size = 0;
5014
5015 /* Now let's try to be smarter */
5016 if (!dladdr_and_size(&main, &dli, &size))
5017 build_is_static = 1;
5018 else
5019 build_is_static = 0;
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005020}
5021
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005022INITCALL0(STG_PREPARE, check_if_static_build);
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005023
Willy Tarreau64192392021-05-05 09:06:21 +02005024/* Tries to retrieve the address of the first occurrence symbol <name>.
5025 * Note that NULL in return is not always an error as a symbol may have that
5026 * address in special situations.
5027 */
5028void *get_sym_curr_addr(const char *name)
5029{
5030 void *ptr = NULL;
5031
5032#ifdef RTLD_DEFAULT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005033 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005034 ptr = dlsym(RTLD_DEFAULT, name);
Willy Tarreau64192392021-05-05 09:06:21 +02005035#endif
5036 return ptr;
5037}
5038
5039
5040/* Tries to retrieve the address of the next occurrence of symbol <name>
5041 * Note that NULL in return is not always an error as a symbol may have that
5042 * address in special situations.
5043 */
5044void *get_sym_next_addr(const char *name)
5045{
5046 void *ptr = NULL;
5047
5048#ifdef RTLD_NEXT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005049 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005050 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01005051#endif
Willy Tarreau64192392021-05-05 09:06:21 +02005052 return ptr;
5053}
5054
5055#else /* elf & linux & dl */
5056
5057/* no possible resolving on other platforms at the moment */
5058void *get_sym_curr_addr(const char *name)
5059{
5060 return NULL;
5061}
5062
5063void *get_sym_next_addr(const char *name)
5064{
5065 return NULL;
5066}
5067
5068#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01005069
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005070/* Tries to append to buffer <buf> some indications about the symbol at address
5071 * <addr> using the following form:
5072 * lib:+0xoffset (unresolvable address from lib's base)
5073 * main+0xoffset (unresolvable address from main (+/-))
5074 * lib:main+0xoffset (unresolvable lib address from main (+/-))
5075 * name (resolved exact exec address)
5076 * lib:name (resolved exact lib address)
5077 * name+0xoffset/0xsize (resolved address within exec symbol)
5078 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
5079 *
5080 * The file name (lib or executable) is limited to what lies between the last
5081 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
5082 * 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 +03005083 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005084 *
5085 * The symbol's base address is returned, or NULL when unresolved, in order to
5086 * allow the caller to match it against known ones.
5087 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01005088const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005089{
5090 const struct {
5091 const void *func;
5092 const char *name;
5093 } fcts[] = {
5094 { .func = process_stream, .name = "process_stream" },
5095 { .func = task_run_applet, .name = "task_run_applet" },
Willy Tarreau462b9892022-05-18 18:06:53 +02005096 { .func = sc_conn_io_cb, .name = "sc_conn_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01005097 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005098 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
5099 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01005100 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005101 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
5102 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01005103 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01005104#ifdef USE_THREAD
5105 { .func = accept_queue_process, .name = "accept_queue_process" },
5106#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005107#ifdef USE_LUA
5108 { .func = hlua_process_task, .name = "hlua_process_task" },
5109#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005110#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005111 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
5112 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
5113#endif
5114 };
5115
Baruch Siache1651b22020-07-24 07:52:20 +03005116#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005117 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01005118 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005119 const char *fname, *p;
5120#endif
5121 int i;
5122
5123 if (pfx)
5124 chunk_appendf(buf, "%s", pfx);
5125
5126 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
5127 if (addr == fcts[i].func) {
5128 chunk_appendf(buf, "%s", fcts[i].name);
5129 return addr;
5130 }
5131 }
5132
Baruch Siache1651b22020-07-24 07:52:20 +03005133#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005134 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01005135 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005136 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005137
5138 /* 1. prefix the library name if it's not the same object as the one
5139 * that contains the main function. The name is picked between last '/'
5140 * and first following '.'.
5141 */
5142 if (!dladdr(main, &dli_main))
5143 dli_main.dli_fbase = NULL;
5144
5145 if (dli_main.dli_fbase != dli.dli_fbase) {
5146 fname = dli.dli_fname;
5147 p = strrchr(fname, '/');
5148 if (p++)
5149 fname = p;
5150 p = strchr(fname, '.');
5151 if (!p)
5152 p = fname + strlen(fname);
5153
5154 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
5155 }
5156
5157 /* 2. symbol name */
5158 if (dli.dli_sname) {
5159 /* known, dump it and return symbol's address (exact or relative) */
5160 chunk_appendf(buf, "%s", dli.dli_sname);
5161 if (addr != dli.dli_saddr) {
5162 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01005163 if (size)
5164 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005165 }
5166 return dli.dli_saddr;
5167 }
5168 else if (dli_main.dli_fbase != dli.dli_fbase) {
5169 /* unresolved symbol from a known library, report relative offset */
5170 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
5171 return NULL;
5172 }
Baruch Siache1651b22020-07-24 07:52:20 +03005173#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005174 unknown:
5175 /* unresolved symbol from the main file, report relative offset to main */
5176 if ((void*)addr < (void*)main)
5177 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
5178 else
5179 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
5180 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01005181}
5182
Willy Tarreau6ab7b212021-12-28 09:57:10 +01005183/* On systems where this is supported, let's provide a possibility to enumerate
5184 * the list of object files. The output is appended to a buffer initialized by
5185 * the caller, with one name per line. A trailing zero is always emitted if data
5186 * are written. Only real objects are dumped (executable and .so libs). The
5187 * function returns non-zero if it dumps anything. These functions do not make
5188 * use of the trash so that it is possible for the caller to call them with the
5189 * trash on input. The output format may be platform-specific but at least one
5190 * version must emit raw object file names when argument is zero.
5191 */
5192#if defined(HA_HAVE_DUMP_LIBS)
5193# if defined(HA_HAVE_DL_ITERATE_PHDR)
5194/* the private <data> we pass below is a dump context initialized like this */
5195struct dl_dump_ctx {
5196 struct buffer *buf;
5197 int with_addr;
5198};
5199
5200static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5201{
5202 struct dl_dump_ctx *ctx = data;
5203 const char *fname;
5204 size_t p1, p2, beg, end;
5205 int idx;
5206
5207 if (!info || !info->dlpi_name)
5208 goto leave;
5209
5210 if (!*info->dlpi_name)
5211 fname = get_exec_path();
5212 else if (strchr(info->dlpi_name, '/'))
5213 fname = info->dlpi_name;
5214 else
5215 /* else it's a VDSO or similar and we're not interested */
5216 goto leave;
5217
5218 if (!ctx->with_addr)
5219 goto dump_name;
5220
5221 /* virtual addresses are relative to the load address and are per
5222 * pseudo-header, so we have to scan them all to find the furthest
5223 * one from the beginning. In this case we only dump entries if
5224 * they have at least one section.
5225 */
5226 beg = ~0; end = 0;
5227 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5228 if (!info->dlpi_phdr[idx].p_memsz)
5229 continue;
5230 p1 = info->dlpi_phdr[idx].p_vaddr;
5231 if (p1 < beg)
5232 beg = p1;
5233 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5234 if (p2 > end)
5235 end = p2;
5236 }
5237
5238 if (!idx)
5239 goto leave;
5240
5241 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5242 (ullong)info->dlpi_addr + beg,
5243 (ullong)info->dlpi_addr + end,
5244 (ullong)(end - beg + 1));
5245 dump_name:
5246 chunk_appendf(ctx->buf, "%s\n", fname);
5247 leave:
5248 return 0;
5249}
5250
5251/* dumps lib names and optionally address ranges */
5252int dump_libs(struct buffer *output, int with_addr)
5253{
5254 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5255 size_t old_data = output->data;
5256
5257 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5258 return output->data != old_data;
5259}
5260# else // no DL_ITERATE_PHDR
5261# error "No dump_libs() function for this platform"
5262# endif
5263#else // no HA_HAVE_DUMP_LIBS
5264
5265/* unsupported platform: do not dump anything */
5266int dump_libs(struct buffer *output, int with_addr)
5267{
5268 return 0;
5269}
5270
5271#endif // HA_HAVE_DUMP_LIBS
5272
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005273/*
5274 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005275 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005276 *
5277 * First, initializes the value with <sz> as address to 0 and initializes the
5278 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5279 * address updating <sz> pointed value to the size of this array.
5280 *
5281 * Returns 1 if succeeded, 0 if not.
5282 */
5283int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5284{
5285 unsigned int *n;
5286 const char *s, *end;
5287
5288 s = str;
5289 *sz = 0;
5290 end = str + strlen(str);
5291 *nums = n = NULL;
5292
5293 while (1) {
5294 unsigned int r;
5295
5296 if (s >= end)
5297 break;
5298
5299 r = read_uint(&s, end);
5300 /* Expected characters after having read an uint: '\0' or '.',
5301 * if '.', must not be terminal.
5302 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005303 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5304 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005305 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005306 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005307
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005308 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005309 if (!n)
5310 return 0;
5311
5312 n[(*sz)++] = r;
5313 }
5314 *nums = n;
5315
5316 return 1;
5317}
5318
Willy Tarreau4d589e72019-08-23 19:02:26 +02005319
5320/* returns the number of bytes needed to encode <v> as a varint. An inline
5321 * version exists for use with constants (__varint_bytes()).
5322 */
5323int varint_bytes(uint64_t v)
5324{
5325 int len = 1;
5326
5327 if (v >= 240) {
5328 v = (v - 240) >> 4;
5329 while (1) {
5330 len++;
5331 if (v < 128)
5332 break;
5333 v = (v - 128) >> 7;
5334 }
5335 }
5336 return len;
5337}
5338
Willy Tarreau52bf8392020-03-08 00:42:37 +01005339
5340/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005341static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005342
5343/* This is a thread-safe implementation of xoroshiro128** described below:
5344 * http://prng.di.unimi.it/
5345 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5346 * supports fast jumps and passes all common quality tests. It is thread-safe,
5347 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5348 * local lock on other ones.
5349 */
5350uint64_t ha_random64()
5351{
Willy Tarreau1544c142020-03-12 00:31:18 +01005352 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5353 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005354
5355#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5356 static HA_SPINLOCK_T rand_lock;
5357
5358 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5359#endif
5360
5361 old[0] = ha_random_state[0];
5362 old[1] = ha_random_state[1];
5363
5364#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5365 do {
5366#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005367 new[1] = old[0] ^ old[1];
5368 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5369 new[1] = rotl64(new[1], 37); // c
5370
5371#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5372 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5373#else
5374 ha_random_state[0] = new[0];
5375 ha_random_state[1] = new[1];
5376#if defined(USE_THREAD)
5377 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5378#endif
5379#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005380 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005381}
5382
5383/* seeds the random state using up to <len> bytes from <seed>, starting with
5384 * the first non-zero byte.
5385 */
5386void ha_random_seed(const unsigned char *seed, size_t len)
5387{
5388 size_t pos;
5389
5390 /* the seed must not be all zeroes, so we pre-fill it with alternating
5391 * bits and overwrite part of them with the block starting at the first
5392 * non-zero byte from the seed.
5393 */
5394 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5395
5396 for (pos = 0; pos < len; pos++)
5397 if (seed[pos] != 0)
5398 break;
5399
5400 if (pos == len)
5401 return;
5402
5403 seed += pos;
5404 len -= pos;
5405
5406 if (len > sizeof(ha_random_state))
5407 len = sizeof(ha_random_state);
5408
5409 memcpy(ha_random_state, seed, len);
5410}
5411
5412/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5413 * and is equivalent to calling ha_random64() as many times. It is used to
5414 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5415 * different generators (i.e. different processes after a fork). The <dist>
5416 * argument is the distance to jump to and is used in a loop so it rather not
5417 * be too large if the processing time is a concern.
5418 *
5419 * BEWARE: this function is NOT thread-safe and must not be called during
5420 * concurrent accesses to ha_random64().
5421 */
5422void ha_random_jump96(uint32_t dist)
5423{
5424 while (dist--) {
5425 uint64_t s0 = 0;
5426 uint64_t s1 = 0;
5427 int b;
5428
5429 for (b = 0; b < 64; b++) {
5430 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5431 s0 ^= ha_random_state[0];
5432 s1 ^= ha_random_state[1];
5433 }
5434 ha_random64();
5435 }
5436
5437 for (b = 0; b < 64; b++) {
5438 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5439 s0 ^= ha_random_state[0];
5440 s1 ^= ha_random_state[1];
5441 }
5442 ha_random64();
5443 }
5444 ha_random_state[0] = s0;
5445 ha_random_state[1] = s1;
5446 }
5447}
5448
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005449/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5450 * bytes large.
5451 */
5452void ha_generate_uuid(struct buffer *output)
5453{
5454 uint32_t rnd[4];
5455 uint64_t last;
5456
5457 last = ha_random64();
5458 rnd[0] = last;
5459 rnd[1] = last >> 32;
5460
5461 last = ha_random64();
5462 rnd[2] = last;
5463 rnd[3] = last >> 32;
5464
5465 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5466 rnd[0],
5467 rnd[1] & 0xFFFF,
5468 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5469 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5470 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5471}
5472
5473
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005474/* only used by parse_line() below. It supports writing in place provided that
5475 * <in> is updated to the next location before calling it. In that case, the
5476 * char at <in> may be overwritten.
5477 */
5478#define EMIT_CHAR(x) \
5479 do { \
5480 char __c = (char)(x); \
5481 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5482 err |= PARSE_ERR_OVERLAP; \
5483 if (outpos >= outmax) \
5484 err |= PARSE_ERR_TOOLARGE; \
5485 if (!err) \
5486 out[outpos] = __c; \
5487 outpos++; \
5488 } while (0)
5489
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005490/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005491 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5492 * extraneous ones are not emitted but <outlen> is updated so that the caller
5493 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5494 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005495 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5496 * it is guaranteed that at least one arg will point to the zero. It is safe
5497 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005498 *
5499 * <out> may overlap with <in> provided that it never goes further, in which
5500 * case the parser will accept to perform in-place parsing and unquoting/
5501 * unescaping but only if environment variables do not lead to expansion that
5502 * causes overlapping, otherwise the input string being destroyed, the error
5503 * will not be recoverable. Note that even during out-of-place <in> will
5504 * experience temporary modifications in-place for variable resolution and must
5505 * be writable, and will also receive zeroes to delimit words when using
5506 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5507 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5508 * starting point of the first invalid character sequence or unmatched
5509 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5510 * error reporting might be difficult since zeroes will have been inserted into
5511 * the string. One solution for the caller may consist in replacing all args
5512 * delimiters with spaces in this case.
5513 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005514uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, const char **errptr)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005515{
5516 char *quote = NULL;
5517 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005518 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005519 unsigned char hex1, hex2;
5520 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005521 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005522 size_t outpos = 0;
5523 int squote = 0;
5524 int dquote = 0;
5525 int arg = 0;
5526 uint32_t err = 0;
5527
5528 *nbargs = 0;
5529 *outlen = 0;
5530
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005531 /* argsmax may be -1 here, protecting args[] from any write */
5532 if (arg < argsmax)
5533 args[arg] = out;
5534
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005535 while (1) {
5536 if (*in >= '-' && *in != '\\') {
5537 /* speedup: directly send all regular chars starting
5538 * with '-', '.', '/', alnum etc...
5539 */
5540 EMIT_CHAR(*in++);
5541 continue;
5542 }
5543 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5544 /* end of line */
5545 break;
5546 }
5547 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5548 /* comment */
5549 break;
5550 }
5551 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5552 if (dquote) {
5553 dquote = 0;
5554 quote = NULL;
5555 }
5556 else {
5557 dquote = 1;
5558 quote = in;
5559 }
5560 in++;
5561 continue;
5562 }
5563 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5564 if (squote) {
5565 squote = 0;
5566 quote = NULL;
5567 }
5568 else {
5569 squote = 1;
5570 quote = in;
5571 }
5572 in++;
5573 continue;
5574 }
5575 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5576 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5577 * C equivalent value but only when they have a special meaning and within
5578 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5579 */
5580 char tosend = *in;
5581
5582 switch (in[1]) {
5583 case ' ':
5584 case '\\':
5585 tosend = in[1];
5586 in++;
5587 break;
5588
5589 case 't':
5590 tosend = '\t';
5591 in++;
5592 break;
5593
5594 case 'n':
5595 tosend = '\n';
5596 in++;
5597 break;
5598
5599 case 'r':
5600 tosend = '\r';
5601 in++;
5602 break;
5603
5604 case '#':
5605 /* escaping of "#" only if comments are supported */
5606 if (opts & PARSE_OPT_SHARP)
5607 in++;
5608 tosend = *in;
5609 break;
5610
5611 case '\'':
5612 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5613 if (opts & PARSE_OPT_SQUOTE && !squote)
5614 in++;
5615 tosend = *in;
5616 break;
5617
5618 case '"':
5619 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5620 if (opts & PARSE_OPT_DQUOTE && !squote)
5621 in++;
5622 tosend = *in;
5623 break;
5624
5625 case '$':
5626 /* escaping of '$' only inside double quotes and only if env supported */
5627 if (opts & PARSE_OPT_ENV && dquote)
5628 in++;
5629 tosend = *in;
5630 break;
5631
5632 case 'x':
5633 if (!ishex(in[2]) || !ishex(in[3])) {
5634 /* invalid or incomplete hex sequence */
5635 err |= PARSE_ERR_HEX;
5636 if (errptr)
5637 *errptr = in;
5638 goto leave;
5639 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005640 hex1 = toupper((unsigned char)in[2]) - '0';
5641 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005642 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5643 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5644 tosend = (hex1 << 4) + hex2;
5645 in += 3;
5646 break;
5647
5648 default:
5649 /* other combinations are not escape sequences */
5650 break;
5651 }
5652
5653 in++;
5654 EMIT_CHAR(tosend);
5655 }
5656 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5657 /* a non-escaped space is an argument separator */
5658 while (isspace((unsigned char)*in))
5659 in++;
5660 EMIT_CHAR(0);
5661 arg++;
5662 if (arg < argsmax)
5663 args[arg] = out + outpos;
5664 else
5665 err |= PARSE_ERR_TOOMANY;
5666 }
5667 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5668 /* environment variables are evaluated anywhere, or only
5669 * inside double quotes if they are supported.
5670 */
5671 char *var_name;
5672 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005673 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005674
5675 in++;
5676
5677 if (*in == '{')
5678 brace = in++;
5679
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005680 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005681 /* unacceptable character in variable name */
5682 err |= PARSE_ERR_VARNAME;
5683 if (errptr)
5684 *errptr = in;
5685 goto leave;
5686 }
5687
5688 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005689 if (*in == '.')
5690 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005691 while (isalnum((unsigned char)*in) || *in == '_')
5692 in++;
5693
5694 save_char = *in;
5695 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005696 if (unlikely(*var_name == '.')) {
5697 /* internal pseudo-variables */
5698 if (strcmp(var_name, ".LINE") == 0)
5699 value = ultoa(global.cfg_curr_line);
5700 else if (strcmp(var_name, ".FILE") == 0)
5701 value = global.cfg_curr_file;
5702 else if (strcmp(var_name, ".SECTION") == 0)
5703 value = global.cfg_curr_section;
5704 else {
5705 /* unsupported internal variable name */
5706 err |= PARSE_ERR_VARNAME;
5707 if (errptr)
5708 *errptr = var_name;
5709 goto leave;
5710 }
5711 } else {
5712 value = getenv(var_name);
5713 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005714 *in = save_char;
5715
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005716 /* support for '[*]' sequence to force word expansion,
5717 * only available inside braces */
5718 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5719 word_expand = in++;
5720
5721 if (*in++ != '*' || *in++ != ']') {
5722 err |= PARSE_ERR_WRONG_EXPAND;
5723 if (errptr)
5724 *errptr = word_expand;
5725 goto leave;
5726 }
5727 }
5728
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005729 if (brace) {
Willy Tarreauec347b12021-11-18 17:42:50 +01005730 if (*in == '-') {
5731 /* default value starts just after the '-' */
5732 if (!value)
5733 value = in + 1;
5734
5735 while (*in && *in != '}')
5736 in++;
5737 if (!*in)
5738 goto no_brace;
5739 *in = 0; // terminate the default value
5740 }
5741 else if (*in != '}') {
5742 no_brace:
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005743 /* unmatched brace */
5744 err |= PARSE_ERR_BRACE;
5745 if (errptr)
5746 *errptr = brace;
5747 goto leave;
5748 }
Willy Tarreauec347b12021-11-18 17:42:50 +01005749
5750 /* brace found, skip it */
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005751 in++;
5752 brace = NULL;
5753 }
5754
5755 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005756 while (*value) {
5757 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005758 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005759 EMIT_CHAR(0);
5760 ++arg;
5761 if (arg < argsmax)
5762 args[arg] = out + outpos;
5763 else
5764 err |= PARSE_ERR_TOOMANY;
5765
5766 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005767 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005768 ;
5769 } else {
5770 EMIT_CHAR(*value++);
5771 }
5772 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005773 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005774 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005775 }
5776 else {
5777 /* any other regular char */
5778 EMIT_CHAR(*in++);
5779 }
5780 }
5781
5782 /* end of output string */
5783 EMIT_CHAR(0);
5784 arg++;
5785
5786 if (quote) {
5787 /* unmatched quote */
5788 err |= PARSE_ERR_QUOTE;
5789 if (errptr)
5790 *errptr = quote;
5791 goto leave;
5792 }
5793 leave:
5794 *nbargs = arg;
5795 *outlen = outpos;
5796
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005797 /* empty all trailing args by making them point to the trailing zero,
5798 * at least the last one in any case.
5799 */
5800 if (arg > argsmax)
5801 arg = argsmax;
5802
5803 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005804 args[arg++] = out + outpos - 1;
5805
5806 return err;
5807}
5808#undef EMIT_CHAR
5809
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005810/* This is used to sanitize an input line that's about to be used for error reporting.
5811 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5812 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5813 * If non-printable chars are present in the output. It returns the new offset <pos>
5814 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5815 * be at least 6 to support two "..." otherwise the result is undefined. The line
5816 * itself must have at least 7 chars allocated for the same reason.
5817 */
5818size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5819{
5820 size_t shift = 0;
5821 char *out = line;
5822 char *in = line;
5823 char *end = line + width;
5824
5825 if (pos >= width) {
5826 /* if we have to shift, we'll be out of context, so let's
5827 * try to put <pos> at the center of width.
5828 */
5829 shift = pos - width / 2;
5830 in += shift + 3;
5831 end = out + width - 3;
5832 out[0] = out[1] = out[2] = '.';
5833 out += 3;
5834 }
5835
5836 while (out < end && *in) {
5837 if (isspace((unsigned char)*in))
5838 *out++ = ' ';
5839 else if (isprint((unsigned char)*in))
5840 *out++ = *in;
5841 else
5842 *out++ = '?';
5843 in++;
5844 }
5845
5846 if (end < line + width) {
5847 out[0] = out[1] = out[2] = '.';
5848 out += 3;
5849 }
5850
5851 *out++ = 0;
5852 return pos - shift;
5853}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005854
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005855/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005856 * transitions between characters. <fp> is a 1024-entries array indexed as
5857 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005858 * 1..26=letter, 27=digit, 28=other/begin/end.
5859 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005860 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005861void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005862{
5863 const char *p;
5864 int from, to;
5865 int c;
5866
Willy Tarreauba2c4452021-03-12 09:01:52 +01005867 from = 28; // begin
5868 for (p = word; *p; p++) {
5869 c = tolower(*p);
5870 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005871 case 'a'...'z': to = c - 'a' + 1; break;
5872 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5873 case '0'...'9': to = 27; break;
5874 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005875 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005876 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005877 fp[32 * from + to]++;
5878 from = to;
5879 }
5880 to = 28; // end
5881 fp[32 * from + to]++;
5882}
5883
Erwan Le Goas9c766372022-09-14 17:40:24 +02005884/* This function hashes a word, scramble is the anonymizing key, returns
5885 * the hashed word when the key (scramble) != 0, else returns the word.
5886 * This function can be called NB_L_HASH_WORD times in a row, don't call
5887 * it if you called it more than NB_L_HASH_WORD.
5888 */
5889const char *hash_anon(uint32_t scramble, const char *string2hash, const char *prefix, const char *suffix)
5890{
5891 index_hash++;
5892 if (index_hash > NB_L_HASH_WORD)
5893 index_hash = 0;
5894
5895 /* don't hash empty strings */
5896 if (!string2hash[0] || (string2hash[0] == ' ' && string2hash[1] == 0))
5897 return string2hash;
5898
5899 if (scramble != 0) {
5900 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "%s%06x%s",
5901 prefix, HA_ANON(scramble, string2hash, strlen(string2hash)), suffix);
5902 return hash_word[index_hash];
5903 }
5904 else
5905 return string2hash;
5906}
5907
5908/* This function hashes or not an ip address ipstring, scramble is the anonymizing
5909 * key, returns the hashed ip with his port or ipstring when there is nothing to hash.
5910 */
5911const char *hash_ipanon(uint32_t scramble, char *ipstring)
5912{
5913 char *errmsg = NULL;
5914 struct sockaddr_storage *sa;
5915 char addr[46];
5916 int port;
5917
5918 index_hash++;
5919 if (index_hash > NB_L_HASH_WORD) {
5920 index_hash = 0;
5921 }
5922
5923 if (strncmp(ipstring, "localhost", 1) == 0) {
5924 return ipstring;
5925 }
5926 else {
5927 sa = str2sa_range(ipstring, NULL, NULL, NULL, NULL, NULL, &errmsg, NULL, NULL,
5928 PA_O_PORT_OK | PA_O_STREAM | PA_O_XPRT | PA_O_CONNECT | PA_O_PORT_RANGE);
5929 if (sa == NULL) {
5930 return ipstring;
5931 }
5932 else {
5933 addr_to_str(sa, addr, sizeof(addr));
5934 port = get_host_port(sa);
5935
5936 switch(sa->ss_family) {
5937 case AF_INET:
5938 if (strncmp(addr, "127", 3) == 0 || strncmp(addr, "255", 3) == 0 || strncmp(addr, "0", 1) == 0) {
5939 return ipstring;
5940 }
5941 else {
5942 if (port != 0) {
5943 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV4(%06x):%d", HA_ANON(scramble, addr, strlen(addr)), port);
5944 return hash_word[index_hash];
5945 }
5946 else {
5947 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV4(%06x)", HA_ANON(scramble, addr, strlen(addr)));
5948 return hash_word[index_hash];
5949 }
5950 }
5951 break;
5952
5953 case AF_INET6:
5954 if (strcmp(addr, "::1") == 0) {
5955 return ipstring;
5956 }
5957 else {
5958 if (port != 0) {
5959 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV6(%06x):%d", HA_ANON(scramble, addr, strlen(addr)), port);
5960 return hash_word[index_hash];
5961 }
5962 else {
5963 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV6(%06x)", HA_ANON(scramble, addr, strlen(addr)));
5964 return hash_word[index_hash];
5965 }
5966 }
5967 break;
5968
5969 default:
5970 return ipstring;
5971 break;
5972 };
5973 }
5974 }
5975 return ipstring;
5976}
5977
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005978/* Initialize array <fp> with the fingerprint of word <word> by counting the
5979 * transitions between characters. <fp> is a 1024-entries array indexed as
5980 * 32*from+to. Positions for 'from' and 'to' are:
5981 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5982 */
5983void make_word_fingerprint(uint8_t *fp, const char *word)
5984{
5985 memset(fp, 0, 1024);
5986 update_word_fingerprint(fp, word);
5987}
5988
Willy Tarreauba2c4452021-03-12 09:01:52 +01005989/* Return the distance between two word fingerprints created by function
5990 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005991 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005992 */
5993int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5994{
5995 int i, k, dist = 0;
5996
5997 for (i = 0; i < 1024; i++) {
5998 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005999 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01006000 }
6001 return dist;
6002}
6003
William Lallemand3aeb3f92021-08-21 23:59:56 +02006004/*
6005 * This function compares the loaded openssl version with a string <version>
6006 * This function use the same return code as compare_current_version:
6007 *
6008 * -1 : the version in argument is older than the current openssl version
6009 * 0 : the version in argument is the same as the current openssl version
6010 * 1 : the version in argument is newer than the current openssl version
6011 *
6012 * Or some errors:
6013 * -2 : openssl is not available on this process
6014 * -3 : the version in argument is not parsable
6015 */
6016int openssl_compare_current_version(const char *version)
6017{
6018#ifdef USE_OPENSSL
6019 int numversion;
6020
6021 numversion = openssl_version_parser(version);
6022 if (numversion == 0)
6023 return -3;
6024
6025 if (numversion < OPENSSL_VERSION_NUMBER)
6026 return -1;
6027 else if (numversion > OPENSSL_VERSION_NUMBER)
6028 return 1;
6029 else
6030 return 0;
6031#else
6032 return -2;
6033#endif
6034}
6035
Remi Tricot-Le Bretonb01179a2021-10-11 15:34:12 +02006036/*
6037 * This function compares the loaded openssl name with a string <name>
6038 * This function returns 0 if the OpenSSL name starts like the passed parameter,
6039 * 1 otherwise.
6040 */
6041int openssl_compare_current_name(const char *name)
6042{
6043#ifdef USE_OPENSSL
6044 int name_len = 0;
6045 const char *openssl_version = OpenSSL_version(OPENSSL_VERSION);
6046
6047 if (name) {
6048 name_len = strlen(name);
6049 if (strlen(name) <= strlen(openssl_version))
6050 return strncmp(openssl_version, name, name_len);
6051 }
6052#endif
6053 return 1;
6054}
6055
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006056#if defined(RTLD_DEFAULT) || defined(RTLD_NEXT)
6057/* redefine dlopen() so that we can detect unexpected replacement of some
6058 * critical symbols, typically init/alloc/free functions coming from alternate
6059 * libraries. When called, a tainted flag is set (TAINTED_SHARED_LIBS).
6060 */
6061void *dlopen(const char *filename, int flags)
6062{
6063 static void *(*_dlopen)(const char *filename, int flags);
Willy Tarreau177aed52022-06-19 16:49:51 +02006064 struct {
6065 const char *name;
6066 void *curr, *next;
6067 } check_syms[] = {
6068 { .name = "malloc", },
6069 { .name = "free", },
6070 { .name = "SSL_library_init", },
6071 { .name = "X509_free", },
6072 /* insert only above, 0 must be the last one */
6073 { 0 },
6074 };
6075 const char *trace;
6076 void *addr;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006077 void *ret;
Willy Tarreau177aed52022-06-19 16:49:51 +02006078 int sym = 0;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006079
6080 if (!_dlopen) {
6081 _dlopen = get_sym_next_addr("dlopen");
6082 if (!_dlopen || _dlopen == dlopen) {
6083 _dlopen = NULL;
6084 return NULL;
6085 }
6086 }
6087
Willy Tarreau177aed52022-06-19 16:49:51 +02006088 /* save a few pointers to critical symbols. We keep a copy of both the
6089 * current and the next value, because we might already have replaced
6090 * some of them (e.g. malloc/free with DEBUG_MEM_STATS), and we're only
6091 * interested in verifying that a loaded library doesn't come with a
6092 * completely different definition that would be incompatible.
6093 */
6094 for (sym = 0; check_syms[sym].name; sym++) {
6095 check_syms[sym].curr = get_sym_curr_addr(check_syms[sym].name);
6096 check_syms[sym].next = get_sym_next_addr(check_syms[sym].name);
6097 }
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006098
6099 /* now open the requested lib */
6100 ret = _dlopen(filename, flags);
6101 if (!ret)
6102 return ret;
6103
6104 mark_tainted(TAINTED_SHARED_LIBS);
6105
Willy Tarreau177aed52022-06-19 16:49:51 +02006106 /* and check that critical symbols didn't change */
6107 for (sym = 0; check_syms[sym].name; sym++) {
6108 if (!check_syms[sym].curr && !check_syms[sym].next)
6109 continue;
6110
6111 addr = dlsym(ret, check_syms[sym].name);
6112 if (!addr || addr == check_syms[sym].curr || addr == check_syms[sym].next)
6113 continue;
6114
6115 /* OK it's clear that this symbol was redefined */
6116 mark_tainted(TAINTED_REDEFINITION);
6117
6118 trace = hlua_show_current_location("\n ");
6119 ha_warning("dlopen(): shared library '%s' brings a different definition of symbol '%s'. The process cannot be trusted anymore!%s%s\n",
6120 filename, check_syms[sym].name,
6121 trace ? " Suspected call location: \n " : "",
6122 trace ? trace : "");
6123 }
6124
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006125 return ret;
6126}
6127#endif
6128
Willy Tarreau06e69b52021-03-02 14:01:35 +01006129static int init_tools_per_thread()
6130{
6131 /* Let's make each thread start from a different position */
6132 statistical_prng_state += tid * MAX_THREADS;
6133 if (!statistical_prng_state)
6134 statistical_prng_state++;
6135 return 1;
6136}
6137REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02006138
Willy Tarreaubaaee002006-06-26 02:48:02 +02006139/*
6140 * Local variables:
6141 * c-indent-level: 8
6142 * c-basic-offset: 8
6143 * End:
6144 */