blob: 3796c98b11b1f63bc3cc5619f4311da0342c4674 [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 */
Erwan Le Goas5eef1582022-09-29 10:25:31 +020080#define NB_L_HASH_WORD 15
Erwan Le Goas9c766372022-09-14 17:40:24 +020081
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>
Aurelien DARRAGONc5bff8e2022-09-20 14:33:18 +02001978 * character. The input <string> is processed until string_stop
1979 * is reached or NULL-byte is encountered. The result will
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001980 * be stored between <start> (included) and <stop> (excluded). This
1981 * function will always try to terminate the resulting string with a '\0'
1982 * before <stop>, and will return its position if the conversion
1983 * completes.
1984 */
1985char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001986 const char escape, const long *map,
Aurelien DARRAGONc5bff8e2022-09-20 14:33:18 +02001987 const char *string, const char *string_stop)
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001988{
1989 if (start < stop) {
1990 stop--; /* reserve one byte for the final '\0' */
Aurelien DARRAGONc5bff8e2022-09-20 14:33:18 +02001991 while (start < stop && string < string_stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001992 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001993 *start++ = *string;
1994 else {
1995 if (start + 2 >= stop)
1996 break;
1997 *start++ = escape;
1998 *start++ = *string;
1999 }
2000 string++;
2001 }
2002 *start = '\0';
2003 }
2004 return start;
2005}
2006
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002007/* Check a string for using it in a CSV output format. If the string contains
2008 * one of the following four char <">, <,>, CR or LF, the string is
2009 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2010 * <str> is the input string to be escaped. The function assumes that
2011 * the input string is null-terminated.
2012 *
2013 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002014 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002015 * format.
2016 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002017 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002018 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002019 * If <quote> is 1, the converter puts the quotes only if any reserved character
2020 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002021 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002022 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002023 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002024 * The function returns the converted string on its output. If an error
2025 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002026 * for using the function directly as printf() argument.
2027 *
2028 * If the output buffer is too short to contain the input string, the result
2029 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002030 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002031 * This function appends the encoding to the existing output chunk, and it
2032 * guarantees that it starts immediately at the first available character of
2033 * the chunk. Please use csv_enc() instead if you want to replace the output
2034 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002035 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002036const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002037{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002038 char *end = output->area + output->size;
2039 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002040 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002041
Willy Tarreaub631c292016-01-08 10:04:08 +01002042 if (quote == 1) {
2043 /* automatic quoting: first verify if we'll have to quote the string */
2044 if (!strpbrk(str, "\n\r,\""))
2045 quote = 0;
2046 }
2047
2048 if (quote)
2049 *ptr++ = '"';
2050
Willy Tarreau898529b2016-01-06 18:07:04 +01002051 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2052 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002053 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002054 ptr++;
2055 if (ptr >= end - 2) {
2056 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002057 break;
2058 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002059 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002060 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002061 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002062 str++;
2063 }
2064
Willy Tarreaub631c292016-01-08 10:04:08 +01002065 if (quote)
2066 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002067
Willy Tarreau898529b2016-01-06 18:07:04 +01002068 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002069 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002070 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002071}
2072
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002073/* Decode an URL-encoded string in-place. The resulting string might
2074 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002075 * aborted, the string is truncated before the issue and a negative value is
2076 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002077 * If the 'in_form' argument is non-nul the string is assumed to be part of
2078 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2079 * turned to a space. If it's zero, this will only be done after a question
2080 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002081 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002082int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002083{
2084 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002085 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002086
2087 in = string;
2088 out = string;
2089 while (*in) {
2090 switch (*in) {
2091 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002092 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002093 break;
2094 case '%' :
2095 if (!ishex(in[1]) || !ishex(in[2]))
2096 goto end;
2097 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2098 in += 2;
2099 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002100 case '?':
2101 in_form = 1;
2102 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002103 default:
2104 *out++ = *in;
2105 break;
2106 }
2107 in++;
2108 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002109 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002110 end:
2111 *out = 0;
2112 return ret;
2113}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002114
Willy Tarreau6911fa42007-03-04 18:06:08 +01002115unsigned int str2ui(const char *s)
2116{
2117 return __str2ui(s);
2118}
2119
2120unsigned int str2uic(const char *s)
2121{
2122 return __str2uic(s);
2123}
2124
2125unsigned int strl2ui(const char *s, int len)
2126{
2127 return __strl2ui(s, len);
2128}
2129
2130unsigned int strl2uic(const char *s, int len)
2131{
2132 return __strl2uic(s, len);
2133}
2134
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002135unsigned int read_uint(const char **s, const char *end)
2136{
2137 return __read_uint(s, end);
2138}
2139
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002140/* This function reads an unsigned integer from the string pointed to by <s> and
2141 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2142 * function automatically stops at <end>. If the number overflows, the 2^64-1
2143 * value is returned.
2144 */
2145unsigned long long int read_uint64(const char **s, const char *end)
2146{
2147 const char *ptr = *s;
2148 unsigned long long int i = 0, tmp;
2149 unsigned int j;
2150
2151 while (ptr < end) {
2152
2153 /* read next char */
2154 j = *ptr - '0';
2155 if (j > 9)
2156 goto read_uint64_end;
2157
2158 /* add char to the number and check overflow. */
2159 tmp = i * 10;
2160 if (tmp / 10 != i) {
2161 i = ULLONG_MAX;
2162 goto read_uint64_eat;
2163 }
2164 if (ULLONG_MAX - tmp < j) {
2165 i = ULLONG_MAX;
2166 goto read_uint64_eat;
2167 }
2168 i = tmp + j;
2169 ptr++;
2170 }
2171read_uint64_eat:
2172 /* eat each numeric char */
2173 while (ptr < end) {
2174 if ((unsigned int)(*ptr - '0') > 9)
2175 break;
2176 ptr++;
2177 }
2178read_uint64_end:
2179 *s = ptr;
2180 return i;
2181}
2182
2183/* This function reads an integer from the string pointed to by <s> and returns
2184 * it. The <s> pointer is adjusted to point to the first unread char. The function
2185 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2186 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2187 * returned.
2188 */
2189long long int read_int64(const char **s, const char *end)
2190{
2191 unsigned long long int i = 0;
2192 int neg = 0;
2193
2194 /* Look for minus char. */
2195 if (**s == '-') {
2196 neg = 1;
2197 (*s)++;
2198 }
2199 else if (**s == '+')
2200 (*s)++;
2201
2202 /* convert as positive number. */
2203 i = read_uint64(s, end);
2204
2205 if (neg) {
2206 if (i > 0x8000000000000000ULL)
2207 return LLONG_MIN;
2208 return -i;
2209 }
2210 if (i > 0x7fffffffffffffffULL)
2211 return LLONG_MAX;
2212 return i;
2213}
2214
Willy Tarreau6911fa42007-03-04 18:06:08 +01002215/* This one is 7 times faster than strtol() on athlon with checks.
2216 * It returns the value of the number composed of all valid digits read,
2217 * and can process negative numbers too.
2218 */
2219int strl2ic(const char *s, int len)
2220{
2221 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002222 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002223
2224 if (len > 0) {
2225 if (*s != '-') {
2226 /* positive number */
2227 while (len-- > 0) {
2228 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002229 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002230 if (j > 9)
2231 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002232 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002233 }
2234 } else {
2235 /* negative number */
2236 s++;
2237 while (--len > 0) {
2238 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002239 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002240 if (j > 9)
2241 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002242 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002243 }
2244 }
2245 }
2246 return i;
2247}
2248
2249
2250/* This function reads exactly <len> chars from <s> and converts them to a
2251 * signed integer which it stores into <ret>. It accurately detects any error
2252 * (truncated string, invalid chars, overflows). It is meant to be used in
2253 * applications designed for hostile environments. It returns zero when the
2254 * number has successfully been converted, non-zero otherwise. When an error
2255 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2256 * faster than strtol().
2257 */
2258int strl2irc(const char *s, int len, int *ret)
2259{
2260 int i = 0;
2261 int j;
2262
2263 if (!len)
2264 return 1;
2265
2266 if (*s != '-') {
2267 /* positive number */
2268 while (len-- > 0) {
2269 j = (*s++) - '0';
2270 if (j > 9) return 1; /* invalid char */
2271 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2272 i = i * 10;
2273 if (i + j < i) return 1; /* check for addition overflow */
2274 i = i + j;
2275 }
2276 } else {
2277 /* negative number */
2278 s++;
2279 while (--len > 0) {
2280 j = (*s++) - '0';
2281 if (j > 9) return 1; /* invalid char */
2282 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2283 i = i * 10;
2284 if (i - j > i) return 1; /* check for subtract overflow */
2285 i = i - j;
2286 }
2287 }
2288 *ret = i;
2289 return 0;
2290}
2291
2292
2293/* This function reads exactly <len> chars from <s> and converts them to a
2294 * signed integer which it stores into <ret>. It accurately detects any error
2295 * (truncated string, invalid chars, overflows). It is meant to be used in
2296 * applications designed for hostile environments. It returns zero when the
2297 * number has successfully been converted, non-zero otherwise. When an error
2298 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002299 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002300 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002301
2302int strl2llrc(const char *s, int len, long long *ret)
2303{
2304 long long i = 0;
2305 int j;
2306
2307 if (!len)
2308 return 1;
2309
2310 if (*s != '-') {
2311 /* positive number */
2312 while (len-- > 0) {
2313 j = (*s++) - '0';
2314 if (j > 9) return 1; /* invalid char */
2315 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2316 i = i * 10LL;
2317 if (i + j < i) return 1; /* check for addition overflow */
2318 i = i + j;
2319 }
2320 } else {
2321 /* negative number */
2322 s++;
2323 while (--len > 0) {
2324 j = (*s++) - '0';
2325 if (j > 9) return 1; /* invalid char */
2326 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2327 i = i * 10LL;
2328 if (i - j > i) return 1; /* check for subtract overflow */
2329 i = i - j;
2330 }
2331 }
2332 *ret = i;
2333 return 0;
2334}
2335
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002336/* This function is used with pat_parse_dotted_ver(). It converts a string
2337 * composed by two number separated by a dot. Each part must contain in 16 bits
2338 * because internally they will be represented as a 32-bit quantity stored in
2339 * a 64-bit integer. It returns zero when the number has successfully been
2340 * converted, non-zero otherwise. When an error is returned, the <ret> value
2341 * is left untouched.
2342 *
2343 * "1.3" -> 0x0000000000010003
2344 * "65535.65535" -> 0x00000000ffffffff
2345 */
2346int strl2llrc_dotted(const char *text, int len, long long *ret)
2347{
2348 const char *end = &text[len];
2349 const char *p;
2350 long long major, minor;
2351
2352 /* Look for dot. */
2353 for (p = text; p < end; p++)
2354 if (*p == '.')
2355 break;
2356
2357 /* Convert major. */
2358 if (strl2llrc(text, p - text, &major) != 0)
2359 return 1;
2360
2361 /* Check major. */
2362 if (major >= 65536)
2363 return 1;
2364
2365 /* Convert minor. */
2366 minor = 0;
2367 if (p < end)
2368 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2369 return 1;
2370
2371 /* Check minor. */
2372 if (minor >= 65536)
2373 return 1;
2374
2375 /* Compose value. */
2376 *ret = (major << 16) | (minor & 0xffff);
2377 return 0;
2378}
2379
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002380/* This function parses a time value optionally followed by a unit suffix among
2381 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2382 * expected by the caller. The computation does its best to avoid overflows.
2383 * The value is returned in <ret> if everything is fine, and a NULL is returned
2384 * by the function. In case of error, a pointer to the error is returned and
2385 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002386 * Values resulting in values larger than or equal to 2^31 after conversion are
2387 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2388 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002389 */
2390const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2391{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002392 unsigned long long imult, idiv;
2393 unsigned long long omult, odiv;
2394 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002395 const char *str = text;
2396
2397 if (!isdigit((unsigned char)*text))
2398 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002399
2400 omult = odiv = 1;
2401
2402 switch (unit_flags & TIME_UNIT_MASK) {
2403 case TIME_UNIT_US: omult = 1000000; break;
2404 case TIME_UNIT_MS: omult = 1000; break;
2405 case TIME_UNIT_S: break;
2406 case TIME_UNIT_MIN: odiv = 60; break;
2407 case TIME_UNIT_HOUR: odiv = 3600; break;
2408 case TIME_UNIT_DAY: odiv = 86400; break;
2409 default: break;
2410 }
2411
2412 value = 0;
2413
2414 while (1) {
2415 unsigned int j;
2416
2417 j = *text - '0';
2418 if (j > 9)
2419 break;
2420 text++;
2421 value *= 10;
2422 value += j;
2423 }
2424
2425 imult = idiv = 1;
2426 switch (*text) {
2427 case '\0': /* no unit = default unit */
2428 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002429 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002430 case 's': /* second = unscaled unit */
2431 break;
2432 case 'u': /* microsecond : "us" */
2433 if (text[1] == 's') {
2434 idiv = 1000000;
2435 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002436 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002437 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002438 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002439 case 'm': /* millisecond : "ms" or minute: "m" */
2440 if (text[1] == 's') {
2441 idiv = 1000;
2442 text++;
2443 } else
2444 imult = 60;
2445 break;
2446 case 'h': /* hour : "h" */
2447 imult = 3600;
2448 break;
2449 case 'd': /* day : "d" */
2450 imult = 86400;
2451 break;
2452 default:
2453 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002454 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002455 if (*(++text) != '\0') {
2456 ha_warning("unexpected character '%c' after the timer value '%s', only "
2457 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2458 " This will be reported as an error in next versions.\n", *text, str);
2459 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002460
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002461 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002462 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2463 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2464 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2465 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2466
Willy Tarreau9faebe32019-06-07 19:00:37 +02002467 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2468 if (result >= 0x80000000)
2469 return PARSE_TIME_OVER;
2470 if (!result && value)
2471 return PARSE_TIME_UNDER;
2472 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002473 return NULL;
2474}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002475
Emeric Brun39132b22010-01-04 14:57:24 +01002476/* this function converts the string starting at <text> to an unsigned int
2477 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002478 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002479 */
2480const char *parse_size_err(const char *text, unsigned *ret) {
2481 unsigned value = 0;
2482
Christopher Faulet82635a02020-12-11 09:30:45 +01002483 if (!isdigit((unsigned char)*text))
2484 return text;
2485
Emeric Brun39132b22010-01-04 14:57:24 +01002486 while (1) {
2487 unsigned int j;
2488
2489 j = *text - '0';
2490 if (j > 9)
2491 break;
2492 if (value > ~0U / 10)
2493 return text;
2494 value *= 10;
2495 if (value > (value + j))
2496 return text;
2497 value += j;
2498 text++;
2499 }
2500
2501 switch (*text) {
2502 case '\0':
2503 break;
2504 case 'K':
2505 case 'k':
2506 if (value > ~0U >> 10)
2507 return text;
2508 value = value << 10;
2509 break;
2510 case 'M':
2511 case 'm':
2512 if (value > ~0U >> 20)
2513 return text;
2514 value = value << 20;
2515 break;
2516 case 'G':
2517 case 'g':
2518 if (value > ~0U >> 30)
2519 return text;
2520 value = value << 30;
2521 break;
2522 default:
2523 return text;
2524 }
2525
Godbach58048a22015-01-28 17:36:16 +08002526 if (*text != '\0' && *++text != '\0')
2527 return text;
2528
Emeric Brun39132b22010-01-04 14:57:24 +01002529 *ret = value;
2530 return NULL;
2531}
2532
Willy Tarreau126d4062013-12-03 17:50:47 +01002533/*
2534 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002535 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002536 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002537 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002538 */
2539int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2540{
2541 int len;
2542 const char *p = source;
2543 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002544 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002545
2546 len = strlen(source);
2547 if (len % 2) {
2548 memprintf(err, "an even number of hex digit is expected");
2549 return 0;
2550 }
2551
2552 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002553
Willy Tarreau126d4062013-12-03 17:50:47 +01002554 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002555 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002556 if (!*binstr) {
2557 memprintf(err, "out of memory while loading string pattern");
2558 return 0;
2559 }
2560 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002561 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002562 else {
2563 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002564 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002565 len, *binstrlen);
2566 return 0;
2567 }
2568 alloc = 0;
2569 }
2570 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002571
2572 i = j = 0;
2573 while (j < len) {
2574 if (!ishex(p[i++]))
2575 goto bad_input;
2576 if (!ishex(p[i++]))
2577 goto bad_input;
2578 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2579 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002580 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002581
2582bad_input:
2583 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002584 if (alloc)
2585 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002586 return 0;
2587}
2588
Willy Tarreau946ba592009-05-10 15:41:18 +02002589/* copies at most <n> characters from <src> and always terminates with '\0' */
2590char *my_strndup(const char *src, int n)
2591{
2592 int len = 0;
2593 char *ret;
2594
2595 while (len < n && src[len])
2596 len++;
2597
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002598 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002599 if (!ret)
2600 return ret;
2601 memcpy(ret, src, len);
2602 ret[len] = '\0';
2603 return ret;
2604}
2605
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002606/*
2607 * search needle in haystack
2608 * returns the pointer if found, returns NULL otherwise
2609 */
2610const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2611{
2612 const void *c = NULL;
2613 unsigned char f;
2614
2615 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2616 return NULL;
2617
2618 f = *(char *)needle;
2619 c = haystack;
2620 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2621 if ((haystacklen - (c - haystack)) < needlelen)
2622 return NULL;
2623
2624 if (memcmp(c, needle, needlelen) == 0)
2625 return c;
2626 ++c;
2627 }
2628 return NULL;
2629}
2630
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002631/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002632size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2633{
2634 size_t ret = 0;
2635
2636 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2637 str++;
2638 ret++;
2639 }
2640 return ret;
2641}
2642
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002643/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002644size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2645{
2646 size_t ret = 0;
2647
2648 while (ret < len) {
2649 if(memchr(reject, *((int *)str), rejectlen))
2650 return ret;
2651 str++;
2652 ret++;
2653 }
2654 return ret;
2655}
2656
Willy Tarreau482b00d2009-10-04 22:48:42 +02002657/* This function returns the first unused key greater than or equal to <key> in
2658 * ID tree <root>. Zero is returned if no place is found.
2659 */
2660unsigned int get_next_id(struct eb_root *root, unsigned int key)
2661{
2662 struct eb32_node *used;
2663
2664 do {
2665 used = eb32_lookup_ge(root, key);
2666 if (!used || used->key > key)
2667 return key; /* key is available */
2668 key++;
2669 } while (key);
2670 return key;
2671}
2672
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002673/* dump the full tree to <file> in DOT format for debugging purposes. Will
2674 * optionally highlight node <subj> if found, depending on operation <op> :
2675 * 0 : nothing
2676 * >0 : insertion, node/leaf are surrounded in red
2677 * <0 : removal, node/leaf are dashed with no background
2678 * Will optionally add "desc" as a label on the graph if set and non-null.
2679 */
2680void 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 +01002681{
2682 struct eb32sc_node *node;
2683 unsigned long scope = -1;
2684
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002685 fprintf(file, "digraph ebtree {\n");
2686
2687 if (desc && *desc) {
2688 fprintf(file,
2689 " fontname=\"fixed\";\n"
2690 " fontsize=8;\n"
2691 " label=\"%s\";\n", desc);
2692 }
2693
Willy Tarreaued3cda02017-11-15 15:04:05 +01002694 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002695 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2696 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002697 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2698 );
2699
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002700 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002701 (long)eb_root_to_node(root),
2702 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002703 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2704
2705 node = eb32sc_first(root, scope);
2706 while (node) {
2707 if (node->node.node_p) {
2708 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002709 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2710 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2711 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002712
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002713 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002714 (long)node,
2715 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002716 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002717
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002718 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002719 (long)node,
2720 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002721 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2722
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002723 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002724 (long)node,
2725 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002726 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2727 }
2728
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002729 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2730 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2731 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002732
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002733 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002734 (long)node,
2735 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002736 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002737 node = eb32sc_next(node, scope);
2738 }
2739 fprintf(file, "}\n");
2740}
2741
Willy Tarreau0dc9e6d2022-08-01 11:55:57 +02002742/* dump the full tree to <file> in DOT format for debugging purposes. Will
2743 * optionally highlight node <subj> if found, depending on operation <op> :
2744 * 0 : nothing
2745 * >0 : insertion, node/leaf are surrounded in red
2746 * <0 : removal, node/leaf are dashed with no background
2747 * Will optionally add "desc" as a label on the graph if set and non-null. The
2748 * key is printed as a u32 hex value. A full-sized hex dump would be better but
2749 * is left to be implemented.
2750 */
2751void ebmb_to_file(FILE *file, struct eb_root *root, const struct ebmb_node *subj, int op, const char *desc)
2752{
2753 struct ebmb_node *node;
2754
2755 fprintf(file, "digraph ebtree {\n");
2756
2757 if (desc && *desc) {
2758 fprintf(file,
2759 " fontname=\"fixed\";\n"
2760 " fontsize=8;\n"
2761 " label=\"%s\";\n", desc);
2762 }
2763
2764 fprintf(file,
2765 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2766 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
2767 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2768 );
2769
2770 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2771 (long)eb_root_to_node(root),
2772 (long)eb_root_to_node(eb_clrtag(root->b[0])),
2773 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2774
2775 node = ebmb_first(root);
2776 while (node) {
2777 if (node->node.node_p) {
2778 /* node part is used */
2779 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%#x\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2780 (long)node, (long)node, read_u32(node->key), node->node.bit,
2781 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2782
2783 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2784 (long)node,
2785 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
2786 eb_gettag(node->node.node_p) ? 'R' : 'L');
2787
2788 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2789 (long)node,
2790 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
2791 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2792
2793 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
2794 (long)node,
2795 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
2796 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2797 }
2798
2799 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%#x\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2800 (long)node, (long)node, read_u32(node->key), node->node.pfx,
2801 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2802
2803 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2804 (long)node,
2805 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
2806 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
2807 node = ebmb_next(node);
2808 }
2809 fprintf(file, "}\n");
2810}
2811
Willy Tarreau348238b2010-01-18 15:05:57 +01002812/* This function compares a sample word possibly followed by blanks to another
2813 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2814 * otherwise zero. This intends to be used when checking HTTP headers for some
2815 * values. Note that it validates a word followed only by blanks but does not
2816 * validate a word followed by blanks then other chars.
2817 */
2818int word_match(const char *sample, int slen, const char *word, int wlen)
2819{
2820 if (slen < wlen)
2821 return 0;
2822
2823 while (wlen) {
2824 char c = *sample ^ *word;
2825 if (c && c != ('A' ^ 'a'))
2826 return 0;
2827 sample++;
2828 word++;
2829 slen--;
2830 wlen--;
2831 }
2832
2833 while (slen) {
2834 if (*sample != ' ' && *sample != '\t')
2835 return 0;
2836 sample++;
2837 slen--;
2838 }
2839 return 1;
2840}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002841
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002842/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2843 * is particularly fast because it avoids expensive operations such as
2844 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002845 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002846 */
2847unsigned int inetaddr_host(const char *text)
2848{
2849 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2850 register unsigned int dig100, dig10, dig1;
2851 int s;
2852 const char *p, *d;
2853
2854 dig1 = dig10 = dig100 = ascii_zero;
2855 s = 24;
2856
2857 p = text;
2858 while (1) {
2859 if (((unsigned)(*p - '0')) <= 9) {
2860 p++;
2861 continue;
2862 }
2863
2864 /* here, we have a complete byte between <text> and <p> (exclusive) */
2865 if (p == text)
2866 goto end;
2867
2868 d = p - 1;
2869 dig1 |= (unsigned int)(*d << s);
2870 if (d == text)
2871 goto end;
2872
2873 d--;
2874 dig10 |= (unsigned int)(*d << s);
2875 if (d == text)
2876 goto end;
2877
2878 d--;
2879 dig100 |= (unsigned int)(*d << s);
2880 end:
2881 if (!s || *p != '.')
2882 break;
2883
2884 s -= 8;
2885 text = ++p;
2886 }
2887
2888 dig100 -= ascii_zero;
2889 dig10 -= ascii_zero;
2890 dig1 -= ascii_zero;
2891 return ((dig100 * 10) + dig10) * 10 + dig1;
2892}
2893
2894/*
2895 * Idem except the first unparsed character has to be passed in <stop>.
2896 */
2897unsigned int inetaddr_host_lim(const char *text, const char *stop)
2898{
2899 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2900 register unsigned int dig100, dig10, dig1;
2901 int s;
2902 const char *p, *d;
2903
2904 dig1 = dig10 = dig100 = ascii_zero;
2905 s = 24;
2906
2907 p = text;
2908 while (1) {
2909 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2910 p++;
2911 continue;
2912 }
2913
2914 /* here, we have a complete byte between <text> and <p> (exclusive) */
2915 if (p == text)
2916 goto end;
2917
2918 d = p - 1;
2919 dig1 |= (unsigned int)(*d << s);
2920 if (d == text)
2921 goto end;
2922
2923 d--;
2924 dig10 |= (unsigned int)(*d << s);
2925 if (d == text)
2926 goto end;
2927
2928 d--;
2929 dig100 |= (unsigned int)(*d << s);
2930 end:
2931 if (!s || p == stop || *p != '.')
2932 break;
2933
2934 s -= 8;
2935 text = ++p;
2936 }
2937
2938 dig100 -= ascii_zero;
2939 dig10 -= ascii_zero;
2940 dig1 -= ascii_zero;
2941 return ((dig100 * 10) + dig10) * 10 + dig1;
2942}
2943
2944/*
2945 * Idem except the pointer to first unparsed byte is returned into <ret> which
2946 * must not be NULL.
2947 */
Willy Tarreau74172752010-10-15 23:21:42 +02002948unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002949{
2950 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2951 register unsigned int dig100, dig10, dig1;
2952 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002953 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002954
2955 dig1 = dig10 = dig100 = ascii_zero;
2956 s = 24;
2957
2958 p = text;
2959 while (1) {
2960 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2961 p++;
2962 continue;
2963 }
2964
2965 /* here, we have a complete byte between <text> and <p> (exclusive) */
2966 if (p == text)
2967 goto end;
2968
2969 d = p - 1;
2970 dig1 |= (unsigned int)(*d << s);
2971 if (d == text)
2972 goto end;
2973
2974 d--;
2975 dig10 |= (unsigned int)(*d << s);
2976 if (d == text)
2977 goto end;
2978
2979 d--;
2980 dig100 |= (unsigned int)(*d << s);
2981 end:
2982 if (!s || p == stop || *p != '.')
2983 break;
2984
2985 s -= 8;
2986 text = ++p;
2987 }
2988
2989 *ret = p;
2990 dig100 -= ascii_zero;
2991 dig10 -= ascii_zero;
2992 dig1 -= ascii_zero;
2993 return ((dig100 * 10) + dig10) * 10 + dig1;
2994}
2995
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002996/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2997 * or the number of chars read in case of success. Maybe this could be replaced
2998 * by one of the functions above. Also, apparently this function does not support
2999 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01003000 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02003001 */
3002int buf2ip(const char *buf, size_t len, struct in_addr *dst)
3003{
3004 const char *addr;
3005 int saw_digit, octets, ch;
3006 u_char tmp[4], *tp;
3007 const char *cp = buf;
3008
3009 saw_digit = 0;
3010 octets = 0;
3011 *(tp = tmp) = 0;
3012
3013 for (addr = buf; addr - buf < len; addr++) {
3014 unsigned char digit = (ch = *addr) - '0';
3015
3016 if (digit > 9 && ch != '.')
3017 break;
3018
3019 if (digit <= 9) {
3020 u_int new = *tp * 10 + digit;
3021
3022 if (new > 255)
3023 return 0;
3024
3025 *tp = new;
3026
3027 if (!saw_digit) {
3028 if (++octets > 4)
3029 return 0;
3030 saw_digit = 1;
3031 }
3032 } else if (ch == '.' && saw_digit) {
3033 if (octets == 4)
3034 return 0;
3035
3036 *++tp = 0;
3037 saw_digit = 0;
3038 } else
3039 return 0;
3040 }
3041
3042 if (octets < 4)
3043 return 0;
3044
3045 memcpy(&dst->s_addr, tmp, 4);
3046 return addr - cp;
3047}
3048
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003049/* This function converts the string in <buf> of the len <len> to
3050 * struct in6_addr <dst> which must be allocated by the caller.
3051 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01003052 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003053 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003054int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
3055{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003056 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01003057 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003058
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003059 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003060 return 0;
3061
3062 memcpy(null_term_ip6, buf, len);
3063 null_term_ip6[len] = '\0';
3064
Willy Tarreau075415a2013-12-12 11:29:39 +01003065 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003066 return 0;
3067
Willy Tarreau075415a2013-12-12 11:29:39 +01003068 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003069 return 1;
3070}
3071
Willy Tarreauacf95772010-06-14 19:09:21 +02003072/* To be used to quote config arg positions. Returns the short string at <ptr>
3073 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
3074 * if ptr is NULL or empty. The string is locally allocated.
3075 */
3076const char *quote_arg(const char *ptr)
3077{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003078 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003079 int i;
3080
3081 if (!ptr || !*ptr)
3082 return "end of line";
3083 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003084 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003085 val[i] = *ptr++;
3086 val[i++] = '\'';
3087 val[i] = '\0';
3088 return val;
3089}
3090
Willy Tarreau5b180202010-07-18 10:40:48 +02003091/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3092int get_std_op(const char *str)
3093{
3094 int ret = -1;
3095
3096 if (*str == 'e' && str[1] == 'q')
3097 ret = STD_OP_EQ;
3098 else if (*str == 'n' && str[1] == 'e')
3099 ret = STD_OP_NE;
3100 else if (*str == 'l') {
3101 if (str[1] == 'e') ret = STD_OP_LE;
3102 else if (str[1] == 't') ret = STD_OP_LT;
3103 }
3104 else if (*str == 'g') {
3105 if (str[1] == 'e') ret = STD_OP_GE;
3106 else if (str[1] == 't') ret = STD_OP_GT;
3107 }
3108
3109 if (ret == -1 || str[2] != '\0')
3110 return -1;
3111 return ret;
3112}
3113
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003114/* hash a 32-bit integer to another 32-bit integer */
3115unsigned int full_hash(unsigned int a)
3116{
3117 return __full_hash(a);
3118}
3119
Willy Tarreauf3241112019-02-26 09:56:22 +01003120/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3121 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3122 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3123 * a popcount variant and is described here :
3124 * https://graphics.stanford.edu/~seander/bithacks.html
3125 */
3126unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3127{
3128 unsigned long a, b, c, d;
3129 unsigned int s;
3130 unsigned int t;
3131
3132 a = m - ((m >> 1) & ~0UL/3);
3133 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3134 c = (b + (b >> 4)) & ~0UL/0x11;
3135 d = (c + (c >> 8)) & ~0UL/0x101;
3136
3137 r++; // make r be 1..64
3138
3139 t = 0;
3140 s = LONGBITS;
3141 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003142 unsigned long d2 = (d >> 16) >> 16;
3143 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003144 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3145 }
3146
3147 t = (d >> (s - 16)) & 0xff;
3148 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3149 t = (c >> (s - 8)) & 0xf;
3150 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3151 t = (b >> (s - 4)) & 0x7;
3152 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3153 t = (a >> (s - 2)) & 0x3;
3154 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3155 t = (m >> (s - 1)) & 0x1;
3156 s -= ((t - r) & 256) >> 8;
3157
3158 return s - 1;
3159}
3160
3161/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3162 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3163 * using mask_prep_rank_map() below.
3164 */
3165unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3166 unsigned long a, unsigned long b,
3167 unsigned long c, unsigned long d)
3168{
3169 unsigned int s;
3170 unsigned int t;
3171
3172 r++; // make r be 1..64
3173
3174 t = 0;
3175 s = LONGBITS;
3176 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003177 unsigned long d2 = (d >> 16) >> 16;
3178 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003179 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3180 }
3181
3182 t = (d >> (s - 16)) & 0xff;
3183 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3184 t = (c >> (s - 8)) & 0xf;
3185 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3186 t = (b >> (s - 4)) & 0x7;
3187 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3188 t = (a >> (s - 2)) & 0x3;
3189 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3190 t = (m >> (s - 1)) & 0x1;
3191 s -= ((t - r) & 256) >> 8;
3192
3193 return s - 1;
3194}
3195
3196/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3197 * above.
3198 */
3199void mask_prep_rank_map(unsigned long m,
3200 unsigned long *a, unsigned long *b,
3201 unsigned long *c, unsigned long *d)
3202{
3203 *a = m - ((m >> 1) & ~0UL/3);
3204 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3205 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3206 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3207}
3208
Willy Tarreauc7a8a3c2022-06-21 20:19:54 +02003209/* Returns the position of one bit set in <v>, starting at position <bit>, and
3210 * searching in other halves if not found. This is intended to be used to
3211 * report the position of one bit set among several based on a counter or a
3212 * random generator while preserving a relatively good distribution so that
3213 * values made of holes in the middle do not see one of the bits around the
3214 * hole being returned much more often than the other one. It can be seen as a
3215 * disturbed ffsl() where the initial search starts at bit <bit>. The look up
3216 * is performed in O(logN) time for N bit words, yielding a bit among 64 in
3217 * about 16 cycles. Its usage differs from the rank find function in that the
3218 * bit passed doesn't need to be limited to the value's popcount, making the
3219 * function easier to use for random picking, and twice as fast. Passing value
3220 * 0 for <v> makes no sense and -1 is returned in this case.
3221 */
3222int one_among_mask(unsigned long v, int bit)
3223{
3224 /* note, these masks may be produced by ~0UL/((1UL<<scale)+1) but
3225 * that's more expensive.
3226 */
3227 static const unsigned long halves[] = {
3228 (unsigned long)0x5555555555555555ULL,
3229 (unsigned long)0x3333333333333333ULL,
3230 (unsigned long)0x0F0F0F0F0F0F0F0FULL,
3231 (unsigned long)0x00FF00FF00FF00FFULL,
3232 (unsigned long)0x0000FFFF0000FFFFULL,
3233 (unsigned long)0x00000000FFFFFFFFULL
3234 };
3235 unsigned long halfword = ~0UL;
3236 int scope = 0;
3237 int mirror;
3238 int scale;
3239
3240 if (!v)
3241 return -1;
3242
3243 /* we check if the exact bit is set or if it's present in a mirror
3244 * position based on the current scale we're checking, in which case
3245 * it's returned with its current (or mirrored) value. Otherwise we'll
3246 * make sure there's at least one bit in the half we're in, and will
3247 * scale down to a smaller scope and try again, until we find the
3248 * closest bit.
3249 */
3250 for (scale = (sizeof(long) > 4) ? 5 : 4; scale >= 0; scale--) {
3251 halfword >>= (1UL << scale);
3252 scope |= (1UL << scale);
3253 mirror = bit ^ (1UL << scale);
3254 if (v & ((1UL << bit) | (1UL << mirror)))
3255 return (v & (1UL << bit)) ? bit : mirror;
3256
3257 if (!((v >> (bit & scope)) & halves[scale] & halfword))
3258 bit = mirror;
3259 }
3260 return bit;
3261}
3262
David du Colombier4f92d322011-03-24 11:09:31 +01003263/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003264 * otherwise zero. Note that <addr> may not necessarily be aligned
3265 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003266 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003267int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003268{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003269 struct in_addr addr_copy;
3270
3271 memcpy(&addr_copy, addr, sizeof(addr_copy));
3272 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003273}
3274
3275/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003276 * otherwise zero. Note that <addr> may not necessarily be aligned
3277 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003278 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003279int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003280{
3281 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003282 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003283
Willy Tarreaueec1d382016-07-13 11:59:39 +02003284 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003285 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003286 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003287 (((int *)net)[i] & ((int *)mask)[i]))
3288 return 0;
3289 return 1;
3290}
3291
3292/* RFC 4291 prefix */
3293const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3294 0x00, 0x00, 0x00, 0x00,
3295 0x00, 0x00, 0xFF, 0xFF };
3296
Joseph Herlant32b83272018-11-15 11:58:28 -08003297/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003298 * Input and output may overlap.
3299 */
David du Colombier4f92d322011-03-24 11:09:31 +01003300void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3301{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003302 struct in_addr tmp_addr;
3303
3304 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003305 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003306 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003307}
3308
Joseph Herlant32b83272018-11-15 11:58:28 -08003309/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003310 * Return true if conversion is possible and false otherwise.
3311 */
3312int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3313{
3314 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3315 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3316 sizeof(struct in_addr));
3317 return 1;
3318 }
3319
3320 return 0;
3321}
3322
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003323/* compare two struct sockaddr_storage and return:
3324 * 0 (true) if the addr is the same in both
3325 * 1 (false) if the addr is not the same in both
3326 * -1 (unable) if one of the addr is not AF_INET*
3327 */
3328int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3329{
3330 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3331 return -1;
3332
3333 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3334 return -1;
3335
3336 if (ss1->ss_family != ss2->ss_family)
3337 return 1;
3338
3339 switch (ss1->ss_family) {
3340 case AF_INET:
3341 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3342 &((struct sockaddr_in *)ss2)->sin_addr,
3343 sizeof(struct in_addr)) != 0;
3344 case AF_INET6:
3345 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3346 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3347 sizeof(struct in6_addr)) != 0;
3348 }
3349
3350 return 1;
3351}
3352
Christopher Faulet9553de72021-02-26 09:12:50 +01003353/* compare a struct sockaddr_storage to a struct net_addr and return :
3354 * 0 (true) if <addr> is matching <net>
3355 * 1 (false) if <addr> is not matching <net>
3356 * -1 (unable) if <addr> or <net> is not AF_INET*
3357 */
3358int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3359{
3360 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3361 return -1;
3362
3363 if ((net->family != AF_INET) && (net->family != AF_INET6))
3364 return -1;
3365
3366 if (addr->ss_family != net->family)
3367 return 1;
3368
3369 if (addr->ss_family == AF_INET &&
3370 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3371 return 0;
3372 else {
3373 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3374 const struct in6_addr *nip6 = &net->addr.v6.ip;
3375 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3376
3377 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3378 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3379 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3380 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3381 return 0;
3382 }
3383
3384 return 1;
3385}
3386
Baptiste Assmann08396c82016-01-31 00:27:17 +01003387/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003388 * The caller must allocate and clear <dest> before calling.
3389 * The source must be in either AF_INET or AF_INET6 family, or the destination
3390 * address will be undefined. If the destination address used to hold a port,
3391 * it is preserved, so that this function can be used to switch to another
3392 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003393 */
3394struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3395{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003396 int prev_port;
3397
3398 prev_port = get_net_port(dest);
3399 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003400 dest->ss_family = source->ss_family;
3401
3402 /* copy new addr and apply it */
3403 switch (source->ss_family) {
3404 case AF_INET:
3405 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003406 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003407 break;
3408 case AF_INET6:
3409 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 +01003410 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003411 break;
3412 }
3413
3414 return dest;
3415}
3416
William Lallemand421f5b52012-02-06 18:15:57 +01003417char *human_time(int t, short hz_div) {
3418 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3419 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003420 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003421 int cnt=2; // print two numbers
3422
3423 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003424 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003425 return rv;
3426 }
3427
3428 if (unlikely(hz_div > 1))
3429 t /= hz_div;
3430
3431 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003432 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003433 cnt--;
3434 }
3435
3436 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003437 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003438 cnt--;
3439 }
3440
3441 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003442 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003443 cnt--;
3444 }
3445
3446 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003447 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003448
3449 return rv;
3450}
3451
3452const char *monthname[12] = {
3453 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3454 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3455};
3456
3457/* date2str_log: write a date in the format :
3458 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3459 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3460 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3461 *
3462 * without using sprintf. return a pointer to the last char written (\0) or
3463 * NULL if there isn't enough space.
3464 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003465char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003466{
3467
3468 if (size < 25) /* the size is fixed: 24 chars + \0 */
3469 return NULL;
3470
3471 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003472 if (!dst)
3473 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003474 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003475
William Lallemand421f5b52012-02-06 18:15:57 +01003476 memcpy(dst, monthname[tm->tm_mon], 3); // month
3477 dst += 3;
3478 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003479
William Lallemand421f5b52012-02-06 18:15:57 +01003480 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003481 if (!dst)
3482 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003483 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003484
William Lallemand421f5b52012-02-06 18:15:57 +01003485 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003486 if (!dst)
3487 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003488 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003489
William Lallemand421f5b52012-02-06 18:15:57 +01003490 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003491 if (!dst)
3492 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003493 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003494
William Lallemand421f5b52012-02-06 18:15:57 +01003495 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003496 if (!dst)
3497 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003498 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003499
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003500 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003501 if (!dst)
3502 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003503 *dst = '\0';
3504
3505 return dst;
3506}
3507
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003508/* Base year used to compute leap years */
3509#define TM_YEAR_BASE 1900
3510
3511/* Return the difference in seconds between two times (leap seconds are ignored).
3512 * Retrieved from glibc 2.18 source code.
3513 */
3514static int my_tm_diff(const struct tm *a, const struct tm *b)
3515{
3516 /* Compute intervening leap days correctly even if year is negative.
3517 * Take care to avoid int overflow in leap day calculations,
3518 * but it's OK to assume that A and B are close to each other.
3519 */
3520 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3521 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3522 int a100 = a4 / 25 - (a4 % 25 < 0);
3523 int b100 = b4 / 25 - (b4 % 25 < 0);
3524 int a400 = a100 >> 2;
3525 int b400 = b100 >> 2;
3526 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3527 int years = a->tm_year - b->tm_year;
3528 int days = (365 * years + intervening_leap_days
3529 + (a->tm_yday - b->tm_yday));
3530 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3531 + (a->tm_min - b->tm_min))
3532 + (a->tm_sec - b->tm_sec));
3533}
3534
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003535/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003536 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003537 * The string returned has the same format as returned by strftime(... "%z", tm).
3538 * Offsets are kept in an internal cache for better performances.
3539 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003540const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003541{
3542 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003543 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003544
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003545 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003546 struct tm tm_gmt;
3547 int diff;
3548 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003549
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003550 /* Pretend DST not active if its status is unknown */
3551 if (isdst < 0)
3552 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003553
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003554 /* Fetch the offset and initialize it if needed */
3555 gmt_offset = gmt_offsets[isdst & 0x01];
3556 if (unlikely(!*gmt_offset)) {
3557 get_gmtime(t, &tm_gmt);
3558 diff = my_tm_diff(tm, &tm_gmt);
3559 if (diff < 0) {
3560 diff = -diff;
3561 *gmt_offset = '-';
3562 } else {
3563 *gmt_offset = '+';
3564 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003565 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003566 diff /= 60; /* Convert to minutes */
3567 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3568 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003569
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003570 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003571}
3572
William Lallemand421f5b52012-02-06 18:15:57 +01003573/* gmt2str_log: write a date in the format :
3574 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3575 * return a pointer to the last char written (\0) or
3576 * NULL if there isn't enough space.
3577 */
3578char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3579{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003580 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003581 return NULL;
3582
3583 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003584 if (!dst)
3585 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003586 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003587
William Lallemand421f5b52012-02-06 18:15:57 +01003588 memcpy(dst, monthname[tm->tm_mon], 3); // month
3589 dst += 3;
3590 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003591
William Lallemand421f5b52012-02-06 18:15:57 +01003592 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003593 if (!dst)
3594 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003595 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003596
William Lallemand421f5b52012-02-06 18:15:57 +01003597 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003598 if (!dst)
3599 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003600 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003601
William Lallemand421f5b52012-02-06 18:15:57 +01003602 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003603 if (!dst)
3604 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003605 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003606
William Lallemand421f5b52012-02-06 18:15:57 +01003607 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003608 if (!dst)
3609 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003610 *dst++ = ' ';
3611 *dst++ = '+';
3612 *dst++ = '0';
3613 *dst++ = '0';
3614 *dst++ = '0';
3615 *dst++ = '0';
3616 *dst = '\0';
3617
3618 return dst;
3619}
3620
Yuxans Yao4e25b012012-10-19 10:36:09 +08003621/* localdate2str_log: write a date in the format :
3622 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003623 * Both t and tm must represent the same time.
3624 * return a pointer to the last char written (\0) or
3625 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003626 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003627char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003628{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003629 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003630 if (size < 27) /* the size is fixed: 26 chars + \0 */
3631 return NULL;
3632
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003633 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003634
Yuxans Yao4e25b012012-10-19 10:36:09 +08003635 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003636 if (!dst)
3637 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003638 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003639
Yuxans Yao4e25b012012-10-19 10:36:09 +08003640 memcpy(dst, monthname[tm->tm_mon], 3); // month
3641 dst += 3;
3642 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003643
Yuxans Yao4e25b012012-10-19 10:36:09 +08003644 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003645 if (!dst)
3646 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003647 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003648
Yuxans Yao4e25b012012-10-19 10:36:09 +08003649 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003650 if (!dst)
3651 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003652 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003653
Yuxans Yao4e25b012012-10-19 10:36:09 +08003654 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003655 if (!dst)
3656 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003657 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003658
Yuxans Yao4e25b012012-10-19 10:36:09 +08003659 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003660 if (!dst)
3661 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003662 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003663
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003664 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003665 dst += 5;
3666 *dst = '\0';
3667
3668 return dst;
3669}
3670
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003671/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3672 * It is meant as a portable replacement for timegm() for use with valid inputs.
3673 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3674 */
3675time_t my_timegm(const struct tm *tm)
3676{
3677 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3678 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3679 * sum of the extra N days for elapsed months. The sum of all these N
3680 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3681 * in a 5-bit word. This means that with 60 bits we can represent a
3682 * matrix of all these values at once, which is fast and efficient to
3683 * access. The extra February day for leap years is not counted here.
3684 *
3685 * Jan : none = 0 (0)
3686 * Feb : Jan = 3 (3)
3687 * Mar : Jan..Feb = 3 (3 + 0)
3688 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3689 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3690 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3691 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3692 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3693 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3694 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3695 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3696 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3697 */
3698 uint64_t extra =
3699 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3700 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3701 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3702 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3703
3704 unsigned int y = tm->tm_year + 1900;
3705 unsigned int m = tm->tm_mon;
3706 unsigned long days = 0;
3707
3708 /* days since 1/1/1970 for full years */
3709 days += days_since_zero(y) - days_since_zero(1970);
3710
3711 /* days for full months in the current year */
3712 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3713
3714 /* count + 1 after March for leap years. A leap year is a year multiple
3715 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3716 * is leap, 1900 isn't, 1904 is.
3717 */
3718 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3719 days++;
3720
3721 days += tm->tm_mday - 1;
3722 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3723}
3724
Thierry Fournier93127942016-01-20 18:49:45 +01003725/* This function check a char. It returns true and updates
3726 * <date> and <len> pointer to the new position if the
3727 * character is found.
3728 */
3729static inline int parse_expect_char(const char **date, int *len, char c)
3730{
3731 if (*len < 1 || **date != c)
3732 return 0;
3733 (*len)--;
3734 (*date)++;
3735 return 1;
3736}
3737
3738/* This function expects a string <str> of len <l>. It return true and updates.
3739 * <date> and <len> if the string matches, otherwise, it returns false.
3740 */
3741static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3742{
3743 if (*len < l || strncmp(*date, str, l) != 0)
3744 return 0;
3745 (*len) -= l;
3746 (*date) += l;
3747 return 1;
3748}
3749
3750/* This macro converts 3 chars name in integer. */
3751#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3752
3753/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3754 * / %x54.75.65 ; "Tue", case-sensitive
3755 * / %x57.65.64 ; "Wed", case-sensitive
3756 * / %x54.68.75 ; "Thu", case-sensitive
3757 * / %x46.72.69 ; "Fri", case-sensitive
3758 * / %x53.61.74 ; "Sat", case-sensitive
3759 * / %x53.75.6E ; "Sun", case-sensitive
3760 *
3761 * This array must be alphabetically sorted
3762 */
3763static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3764{
3765 if (*len < 3)
3766 return 0;
3767 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3768 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3769 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3770 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3771 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3772 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3773 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3774 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3775 default: return 0;
3776 }
3777 *len -= 3;
3778 *date += 3;
3779 return 1;
3780}
3781
3782/* month = %x4A.61.6E ; "Jan", case-sensitive
3783 * / %x46.65.62 ; "Feb", case-sensitive
3784 * / %x4D.61.72 ; "Mar", case-sensitive
3785 * / %x41.70.72 ; "Apr", case-sensitive
3786 * / %x4D.61.79 ; "May", case-sensitive
3787 * / %x4A.75.6E ; "Jun", case-sensitive
3788 * / %x4A.75.6C ; "Jul", case-sensitive
3789 * / %x41.75.67 ; "Aug", case-sensitive
3790 * / %x53.65.70 ; "Sep", case-sensitive
3791 * / %x4F.63.74 ; "Oct", case-sensitive
3792 * / %x4E.6F.76 ; "Nov", case-sensitive
3793 * / %x44.65.63 ; "Dec", case-sensitive
3794 *
3795 * This array must be alphabetically sorted
3796 */
3797static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3798{
3799 if (*len < 3)
3800 return 0;
3801 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3802 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3803 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3804 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3805 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3806 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3807 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3808 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3809 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3810 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3811 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3812 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3813 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3814 default: return 0;
3815 }
3816 *len -= 3;
3817 *date += 3;
3818 return 1;
3819}
3820
3821/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3822 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3823 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3824 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3825 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3826 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3827 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3828 *
3829 * This array must be alphabetically sorted
3830 */
3831static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3832{
3833 if (*len < 6) /* Minimum length. */
3834 return 0;
3835 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3836 case STR2I3('M','o','n'):
3837 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3838 tm->tm_wday = 1;
3839 return 1;
3840 case STR2I3('T','u','e'):
3841 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3842 tm->tm_wday = 2;
3843 return 1;
3844 case STR2I3('W','e','d'):
3845 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3846 tm->tm_wday = 3;
3847 return 1;
3848 case STR2I3('T','h','u'):
3849 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3850 tm->tm_wday = 4;
3851 return 1;
3852 case STR2I3('F','r','i'):
3853 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3854 tm->tm_wday = 5;
3855 return 1;
3856 case STR2I3('S','a','t'):
3857 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3858 tm->tm_wday = 6;
3859 return 1;
3860 case STR2I3('S','u','n'):
3861 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3862 tm->tm_wday = 7;
3863 return 1;
3864 }
3865 return 0;
3866}
3867
3868/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3869static inline int parse_digit(const char **date, int *len, int *digit)
3870{
3871 if (*len < 1 || **date < '0' || **date > '9')
3872 return 0;
3873 *digit = (**date - '0');
3874 (*date)++;
3875 (*len)--;
3876 return 1;
3877}
3878
3879/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3880static inline int parse_2digit(const char **date, int *len, int *digit)
3881{
3882 int value;
3883
3884 RET0_UNLESS(parse_digit(date, len, &value));
3885 (*digit) = value * 10;
3886 RET0_UNLESS(parse_digit(date, len, &value));
3887 (*digit) += value;
3888
3889 return 1;
3890}
3891
3892/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3893static inline int parse_4digit(const char **date, int *len, int *digit)
3894{
3895 int value;
3896
3897 RET0_UNLESS(parse_digit(date, len, &value));
3898 (*digit) = value * 1000;
3899
3900 RET0_UNLESS(parse_digit(date, len, &value));
3901 (*digit) += value * 100;
3902
3903 RET0_UNLESS(parse_digit(date, len, &value));
3904 (*digit) += value * 10;
3905
3906 RET0_UNLESS(parse_digit(date, len, &value));
3907 (*digit) += value;
3908
3909 return 1;
3910}
3911
3912/* time-of-day = hour ":" minute ":" second
3913 * ; 00:00:00 - 23:59:60 (leap second)
3914 *
3915 * hour = 2DIGIT
3916 * minute = 2DIGIT
3917 * second = 2DIGIT
3918 */
3919static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3920{
3921 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3922 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3923 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3924 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3925 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3926 return 1;
3927}
3928
3929/* From RFC7231
3930 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3931 *
3932 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3933 * ; fixed length/zone/capitalization subset of the format
3934 * ; see Section 3.3 of [RFC5322]
3935 *
3936 *
3937 * date1 = day SP month SP year
3938 * ; e.g., 02 Jun 1982
3939 *
3940 * day = 2DIGIT
3941 * year = 4DIGIT
3942 *
3943 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3944 *
3945 * time-of-day = hour ":" minute ":" second
3946 * ; 00:00:00 - 23:59:60 (leap second)
3947 *
3948 * hour = 2DIGIT
3949 * minute = 2DIGIT
3950 * second = 2DIGIT
3951 *
3952 * DIGIT = decimal 0-9
3953 */
3954int parse_imf_date(const char *date, int len, struct tm *tm)
3955{
David Carlier327298c2016-11-20 10:42:38 +00003956 /* tm_gmtoff, if present, ought to be zero'ed */
3957 memset(tm, 0, sizeof(*tm));
3958
Thierry Fournier93127942016-01-20 18:49:45 +01003959 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3960 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3961 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3962 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3963 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3964 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3965 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3966 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3967 tm->tm_year -= 1900;
3968 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3969 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3970 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3971 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3972 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003973 return 1;
3974}
3975
3976/* From RFC7231
3977 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3978 *
3979 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3980 * date2 = day "-" month "-" 2DIGIT
3981 * ; e.g., 02-Jun-82
3982 *
3983 * day = 2DIGIT
3984 */
3985int parse_rfc850_date(const char *date, int len, struct tm *tm)
3986{
3987 int year;
3988
David Carlier327298c2016-11-20 10:42:38 +00003989 /* tm_gmtoff, if present, ought to be zero'ed */
3990 memset(tm, 0, sizeof(*tm));
3991
Thierry Fournier93127942016-01-20 18:49:45 +01003992 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3993 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3994 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3995 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3996 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3997 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3998 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3999
4000 /* year = 2DIGIT
4001 *
4002 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
4003 * two-digit year, MUST interpret a timestamp that appears to be more
4004 * than 50 years in the future as representing the most recent year in
4005 * the past that had the same last two digits.
4006 */
4007 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
4008
4009 /* expect SP */
4010 if (!parse_expect_char(&date, &len, ' ')) {
4011 /* Maybe we have the date with 4 digits. */
4012 RET0_UNLESS(parse_2digit(&date, &len, &year));
4013 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
4014 /* expect SP */
4015 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
4016 } else {
4017 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
4018 * tm_year is the number of year since 1900, so for +1900, we
4019 * do nothing, and for +2000, we add 100.
4020 */
4021 if (tm->tm_year <= 60)
4022 tm->tm_year += 100;
4023 }
4024
4025 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4026 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4027 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
4028 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004029
4030 return 1;
4031}
4032
4033/* From RFC7231
4034 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4035 *
4036 * asctime-date = day-name SP date3 SP time-of-day SP year
4037 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
4038 * ; e.g., Jun 2
4039 *
4040 * HTTP-date is case sensitive. A sender MUST NOT generate additional
4041 * whitespace in an HTTP-date beyond that specifically included as SP in
4042 * the grammar.
4043 */
4044int parse_asctime_date(const char *date, int len, struct tm *tm)
4045{
David Carlier327298c2016-11-20 10:42:38 +00004046 /* tm_gmtoff, if present, ought to be zero'ed */
4047 memset(tm, 0, sizeof(*tm));
4048
Thierry Fournier93127942016-01-20 18:49:45 +01004049 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
4050 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4051 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
4052 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4053
4054 /* expect SP and 1DIGIT or 2DIGIT */
4055 if (parse_expect_char(&date, &len, ' '))
4056 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
4057 else
4058 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
4059
4060 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4061 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4062 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4063 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
4064 tm->tm_year -= 1900;
4065 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004066 return 1;
4067}
4068
4069/* From RFC7231
4070 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4071 *
4072 * HTTP-date = IMF-fixdate / obs-date
4073 * obs-date = rfc850-date / asctime-date
4074 *
4075 * parses an HTTP date in the RFC format and is accepted
4076 * alternatives. <date> is the strinf containing the date,
4077 * len is the len of the string. <tm> is filled with the
4078 * parsed time. We must considers this time as GMT.
4079 */
4080int parse_http_date(const char *date, int len, struct tm *tm)
4081{
4082 if (parse_imf_date(date, len, tm))
4083 return 1;
4084
4085 if (parse_rfc850_date(date, len, tm))
4086 return 1;
4087
4088 if (parse_asctime_date(date, len, tm))
4089 return 1;
4090
4091 return 0;
4092}
4093
Willy Tarreau4deeb102021-01-29 10:47:52 +01004094/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
4095 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
4096 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
4097 * surrounded by <pfx> and <sfx> respectively if not NULL.
4098 */
4099int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
4100{
4101 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
4102 const char *unit;
4103
4104 if (!pfx)
4105 pfx = "";
4106 if (!sfx)
4107 sfx = "";
4108
4109 do {
4110 unit = " - "; if (val <= 0.0) break;
4111 unit = "ns"; if (val < 1000.0) break;
4112 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
4113 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
4114 unit = "s "; val /= 1000.0; if (val < 60.0) break;
4115 unit = "m "; val /= 60.0; if (val < 60.0) break;
4116 unit = "h "; val /= 60.0; if (val < 24.0) break;
4117 unit = "d "; val /= 24.0; if (val < 365.0) break;
4118 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
4119 unit = " inf "; val = 0.0; break;
4120 } while (0);
4121
4122 if (val <= 0.0)
4123 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
4124 else if (val < 10.0)
4125 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
4126 else if (val < 100.0)
4127 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
4128 else
4129 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4130}
4131
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004132/* Dynamically allocates a string of the proper length to hold the formatted
4133 * output. NULL is returned on error. The caller is responsible for freeing the
4134 * memory area using free(). The resulting string is returned in <out> if the
4135 * pointer is not NULL. A previous version of <out> might be used to build the
4136 * new string, and it will be freed before returning if it is not NULL, which
4137 * makes it possible to build complex strings from iterative calls without
4138 * having to care about freeing intermediate values, as in the example below :
4139 *
4140 * memprintf(&err, "invalid argument: '%s'", arg);
4141 * ...
4142 * memprintf(&err, "parser said : <%s>\n", *err);
4143 * ...
4144 * free(*err);
4145 *
4146 * This means that <err> must be initialized to NULL before first invocation.
4147 * The return value also holds the allocated string, which eases error checking
4148 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004149 * passed instead and it will be ignored. The returned message will then also
4150 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004151 *
4152 * It is also convenient to use it without any free except the last one :
4153 * err = NULL;
4154 * if (!fct1(err)) report(*err);
4155 * if (!fct2(err)) report(*err);
4156 * if (!fct3(err)) report(*err);
4157 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004158 *
4159 * memprintf relies on memvprintf. This last version can be called from any
4160 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004161 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004162char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004163{
4164 va_list args;
4165 char *ret = NULL;
4166 int allocated = 0;
4167 int needed = 0;
4168
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004169 if (!out)
4170 return NULL;
4171
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004172 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004173 char buf1;
4174
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004175 /* vsnprintf() will return the required length even when the
4176 * target buffer is NULL. We do this in a loop just in case
4177 * intermediate evaluations get wrong.
4178 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004179 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004180 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004181 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004182 if (needed < allocated) {
4183 /* Note: on Solaris 8, the first iteration always
4184 * returns -1 if allocated is zero, so we force a
4185 * retry.
4186 */
4187 if (!allocated)
4188 needed = 0;
4189 else
4190 break;
4191 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004192
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004193 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004194 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004195 } while (ret);
4196
4197 if (needed < 0) {
4198 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004199 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004200 }
4201
4202 if (out) {
4203 free(*out);
4204 *out = ret;
4205 }
4206
4207 return ret;
4208}
William Lallemand421f5b52012-02-06 18:15:57 +01004209
Christopher Faulet93a518f2017-10-24 11:25:33 +02004210char *memprintf(char **out, const char *format, ...)
4211{
4212 va_list args;
4213 char *ret = NULL;
4214
4215 va_start(args, format);
4216 ret = memvprintf(out, format, args);
4217 va_end(args);
4218
4219 return ret;
4220}
4221
Willy Tarreau21c705b2012-09-14 11:40:36 +02004222/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4223 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004224 * freed by the caller. It also supports being passed a NULL which results in the same
4225 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004226 * Example of use :
4227 * parse(cmd, &err); (callee: memprintf(&err, ...))
4228 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4229 * free(err);
4230 */
4231char *indent_msg(char **out, int level)
4232{
4233 char *ret, *in, *p;
4234 int needed = 0;
4235 int lf = 0;
4236 int lastlf = 0;
4237 int len;
4238
Willy Tarreau70eec382012-10-10 08:56:47 +02004239 if (!out || !*out)
4240 return NULL;
4241
Willy Tarreau21c705b2012-09-14 11:40:36 +02004242 in = *out - 1;
4243 while ((in = strchr(in + 1, '\n')) != NULL) {
4244 lastlf = in - *out;
4245 lf++;
4246 }
4247
4248 if (!lf) /* single line, no LF, return it as-is */
4249 return *out;
4250
4251 len = strlen(*out);
4252
4253 if (lf == 1 && lastlf == len - 1) {
4254 /* single line, LF at end, strip it and return as-is */
4255 (*out)[lastlf] = 0;
4256 return *out;
4257 }
4258
4259 /* OK now we have at least one LF, we need to process the whole string
4260 * as a multi-line string. What we'll do :
4261 * - prefix with an LF if there is none
4262 * - add <level> spaces before each line
4263 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4264 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4265 */
4266
4267 needed = 1 + level * (lf + 1) + len + 1;
4268 p = ret = malloc(needed);
4269 in = *out;
4270
4271 /* skip initial LFs */
4272 while (*in == '\n')
4273 in++;
4274
4275 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4276 while (*in) {
4277 *p++ = '\n';
4278 memset(p, ' ', level);
4279 p += level;
4280 do {
4281 *p++ = *in++;
4282 } while (*in && *in != '\n');
4283 if (*in)
4284 in++;
4285 }
4286 *p = 0;
4287
4288 free(*out);
4289 *out = ret;
4290
4291 return ret;
4292}
4293
Willy Tarreaua2c99112019-08-21 13:17:37 +02004294/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4295 * and end of lines replaced with <eol> if not 0. The first line to indent has
4296 * to be indicated in <first> (starts at zero), so that it is possible to skip
4297 * indenting the first line if it has to be appended after an existing message.
4298 * Empty strings are never indented, and NULL strings are considered empty both
4299 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4300 * character, non-zero otherwise.
4301 */
4302int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4303{
4304 int bol, lf;
4305 int pfxlen = pfx ? strlen(pfx) : 0;
4306
4307 if (!in)
4308 return 0;
4309
4310 bol = 1;
4311 lf = 0;
4312 while (*in) {
4313 if (bol && pfxlen) {
4314 if (first > 0)
4315 first--;
4316 else
4317 b_putblk(out, pfx, pfxlen);
4318 bol = 0;
4319 }
4320
4321 lf = (*in == '\n');
4322 bol |= lf;
4323 b_putchr(out, (lf && eol) ? eol : *in);
4324 in++;
4325 }
4326 return lf;
4327}
4328
Willy Tarreau9d22e562019-03-29 18:49:09 +01004329/* removes environment variable <name> from the environment as found in
4330 * environ. This is only provided as an alternative for systems without
4331 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004332 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004333 * <name> and to replace the matching pointers with the last pointer of
4334 * the array (since variables are not ordered).
4335 * It always returns 0 (success).
4336 */
4337int my_unsetenv(const char *name)
4338{
4339 extern char **environ;
4340 char **p = environ;
4341 int vars;
4342 int next;
4343 int len;
4344
4345 len = strlen(name);
4346 for (vars = 0; p[vars]; vars++)
4347 ;
4348 next = 0;
4349 while (next < vars) {
4350 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4351 next++;
4352 continue;
4353 }
4354 if (next < vars - 1)
4355 p[next] = p[vars - 1];
4356 p[--vars] = NULL;
4357 }
4358 return 0;
4359}
4360
Willy Tarreaudad36a32013-03-11 01:20:04 +01004361/* Convert occurrences of environment variables in the input string to their
4362 * corresponding value. A variable is identified as a series of alphanumeric
4363 * characters or underscores following a '$' sign. The <in> string must be
4364 * free()able. NULL returns NULL. The resulting string might be reallocated if
4365 * some expansion is made. Variable names may also be enclosed into braces if
4366 * needed (eg: to concatenate alphanum characters).
4367 */
4368char *env_expand(char *in)
4369{
4370 char *txt_beg;
4371 char *out;
4372 char *txt_end;
4373 char *var_beg;
4374 char *var_end;
4375 char *value;
4376 char *next;
4377 int out_len;
4378 int val_len;
4379
4380 if (!in)
4381 return in;
4382
4383 value = out = NULL;
4384 out_len = 0;
4385
4386 txt_beg = in;
4387 do {
4388 /* look for next '$' sign in <in> */
4389 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4390
4391 if (!*txt_end && !out) /* end and no expansion performed */
4392 return in;
4393
4394 val_len = 0;
4395 next = txt_end;
4396 if (*txt_end == '$') {
4397 char save;
4398
4399 var_beg = txt_end + 1;
4400 if (*var_beg == '{')
4401 var_beg++;
4402
4403 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004404 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004405 var_end++;
4406 }
4407
4408 next = var_end;
4409 if (*var_end == '}' && (var_beg > txt_end + 1))
4410 next++;
4411
4412 /* get value of the variable name at this location */
4413 save = *var_end;
4414 *var_end = '\0';
4415 value = getenv(var_beg);
4416 *var_end = save;
4417 val_len = value ? strlen(value) : 0;
4418 }
4419
Hubert Verstraete831962e2016-06-28 22:44:26 +02004420 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004421 if (txt_end > txt_beg) {
4422 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4423 out_len += txt_end - txt_beg;
4424 }
4425 if (val_len) {
4426 memcpy(out + out_len, value, val_len);
4427 out_len += val_len;
4428 }
4429 out[out_len] = 0;
4430 txt_beg = next;
4431 } while (*txt_beg);
4432
4433 /* here we know that <out> was allocated and that we don't need <in> anymore */
4434 free(in);
4435 return out;
4436}
4437
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004438
4439/* same as strstr() but case-insensitive and with limit length */
4440const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4441{
4442 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004443 unsigned int slen, plen;
4444 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004445
4446 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4447 return NULL;
4448
4449 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4450 return str1;
4451
4452 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4453 return NULL;
4454
4455 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 +02004456 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004457 start++;
4458 slen--;
4459 tmp1++;
4460
4461 if (tmp1 >= len_str1)
4462 return NULL;
4463
4464 /* if pattern longer than string */
4465 if (slen < plen)
4466 return NULL;
4467 }
4468
4469 sptr = start;
4470 pptr = (char *)str2;
4471
4472 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004473 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004474 sptr++;
4475 pptr++;
4476 tmp2++;
4477
4478 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4479 return start;
4480 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4481 return NULL;
4482 }
4483 }
4484 return NULL;
4485}
4486
Willy Tarreau3ff476e2022-03-30 10:02:56 +02004487/* Returns true if s1 < s2 < s3 otherwise zero. Both s1 and s3 may be NULL and
4488 * in this case only non-null strings are compared. This allows to pass initial
4489 * values in iterators and in sort functions.
4490 */
4491int strordered(const char *s1, const char *s2, const char *s3)
4492{
4493 return (!s1 || strcmp(s1, s2) < 0) && (!s3 || strcmp(s2, s3) < 0);
4494}
4495
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004496/* This function read the next valid utf8 char.
4497 * <s> is the byte srray to be decode, <len> is its length.
4498 * The function returns decoded char encoded like this:
4499 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4500 * are the length read. The decoded character is stored in <c>.
4501 */
4502unsigned char utf8_next(const char *s, int len, unsigned int *c)
4503{
4504 const unsigned char *p = (unsigned char *)s;
4505 int dec;
4506 unsigned char code = UTF8_CODE_OK;
4507
4508 if (len < 1)
4509 return UTF8_CODE_OK;
4510
4511 /* Check the type of UTF8 sequence
4512 *
4513 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4514 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4515 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4516 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4517 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4518 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4519 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4520 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4521 */
4522 switch (*p) {
4523 case 0x00 ... 0x7f:
4524 *c = *p;
4525 return UTF8_CODE_OK | 1;
4526
4527 case 0x80 ... 0xbf:
4528 *c = *p;
4529 return UTF8_CODE_BADSEQ | 1;
4530
4531 case 0xc0 ... 0xdf:
4532 if (len < 2) {
4533 *c = *p;
4534 return UTF8_CODE_BADSEQ | 1;
4535 }
4536 *c = *p & 0x1f;
4537 dec = 1;
4538 break;
4539
4540 case 0xe0 ... 0xef:
4541 if (len < 3) {
4542 *c = *p;
4543 return UTF8_CODE_BADSEQ | 1;
4544 }
4545 *c = *p & 0x0f;
4546 dec = 2;
4547 break;
4548
4549 case 0xf0 ... 0xf7:
4550 if (len < 4) {
4551 *c = *p;
4552 return UTF8_CODE_BADSEQ | 1;
4553 }
4554 *c = *p & 0x07;
4555 dec = 3;
4556 break;
4557
4558 case 0xf8 ... 0xfb:
4559 if (len < 5) {
4560 *c = *p;
4561 return UTF8_CODE_BADSEQ | 1;
4562 }
4563 *c = *p & 0x03;
4564 dec = 4;
4565 break;
4566
4567 case 0xfc ... 0xfd:
4568 if (len < 6) {
4569 *c = *p;
4570 return UTF8_CODE_BADSEQ | 1;
4571 }
4572 *c = *p & 0x01;
4573 dec = 5;
4574 break;
4575
4576 case 0xfe ... 0xff:
4577 default:
4578 *c = *p;
4579 return UTF8_CODE_BADSEQ | 1;
4580 }
4581
4582 p++;
4583
4584 while (dec > 0) {
4585
4586 /* need 0x10 for the 2 first bits */
4587 if ( ( *p & 0xc0 ) != 0x80 )
4588 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4589
4590 /* add data at char */
4591 *c = ( *c << 6 ) | ( *p & 0x3f );
4592
4593 dec--;
4594 p++;
4595 }
4596
4597 /* Check ovelong encoding.
4598 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4599 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4600 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4601 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004602 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004603 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4604 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4605 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4606 code |= UTF8_CODE_OVERLONG;
4607
4608 /* Check invalid UTF8 range. */
4609 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4610 (*c >= 0xfffe && *c <= 0xffff))
4611 code |= UTF8_CODE_INVRANGE;
4612
4613 return code | ((p-(unsigned char *)s)&0x0f);
4614}
4615
Maxime de Roucydc887852016-05-13 23:52:54 +02004616/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4617 * On failure : return 0 and <err> filled with an error message.
4618 * The caller is responsible for freeing the <err> and <str> copy
4619 * memory area using free()
4620 */
4621int list_append_word(struct list *li, const char *str, char **err)
4622{
4623 struct wordlist *wl;
4624
4625 wl = calloc(1, sizeof(*wl));
4626 if (!wl) {
4627 memprintf(err, "out of memory");
4628 goto fail_wl;
4629 }
4630
4631 wl->s = strdup(str);
4632 if (!wl->s) {
4633 memprintf(err, "out of memory");
4634 goto fail_wl_s;
4635 }
4636
Willy Tarreau2b718102021-04-21 07:32:39 +02004637 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004638
4639 return 1;
4640
4641fail_wl_s:
4642 free(wl->s);
4643fail_wl:
4644 free(wl);
4645 return 0;
4646}
4647
Willy Tarreau37101052019-05-20 16:48:20 +02004648/* indicates if a memory location may safely be read or not. The trick consists
4649 * in performing a harmless syscall using this location as an input and letting
4650 * the operating system report whether it's OK or not. For this we have the
4651 * stat() syscall, which will return EFAULT when the memory location supposed
4652 * to contain the file name is not readable. If it is readable it will then
4653 * either return 0 if the area contains an existing file name, or -1 with
4654 * another code. This must not be abused, and some audit systems might detect
4655 * this as abnormal activity. It's used only for unsafe dumps.
4656 */
4657int may_access(const void *ptr)
4658{
4659 struct stat buf;
4660
4661 if (stat(ptr, &buf) == 0)
4662 return 1;
4663 if (errno == EFAULT)
4664 return 0;
4665 return 1;
4666}
4667
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004668/* print a string of text buffer to <out>. The format is :
4669 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4670 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4671 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4672 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004673int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004674{
4675 unsigned char c;
Tim Duesterhus18795d42021-08-29 00:58:22 +02004676 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004677
Tim Duesterhus18795d42021-08-29 00:58:22 +02004678 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004679 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004680 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004681 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004682 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004683 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004684 }
4685 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004686 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004687 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004688 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004689 switch (c) {
4690 case ' ': c = ' '; break;
4691 case '\t': c = 't'; break;
4692 case '\n': c = 'n'; break;
4693 case '\r': c = 'r'; break;
4694 case '\e': c = 'e'; break;
4695 case '\\': c = '\\'; break;
4696 case '=': c = '='; break;
4697 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004698 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004699 }
4700 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004701 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004702 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004703 out->area[out->data++] = '\\';
4704 out->area[out->data++] = 'x';
4705 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4706 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004707 }
4708 ptr++;
4709 }
4710
4711 return ptr;
4712}
4713
4714/* print a buffer in hexa.
4715 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4716 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004717int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004718{
4719 unsigned char c;
4720 int ptr = 0;
4721
4722 while (ptr < bsize) {
4723 c = buf[ptr];
4724
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004725 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004726 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004727 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4728 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004729
4730 ptr++;
4731 }
4732 return ptr;
4733}
4734
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004735/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4736 * prepending each line with prefix <pfx>. The output is *not* initialized.
4737 * The output will not wrap pas the buffer's end so it is more optimal if the
4738 * caller makes sure the buffer is aligned first. A trailing zero will always
4739 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004740 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4741 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004742 */
Willy Tarreau37101052019-05-20 16:48:20 +02004743void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004744{
4745 const unsigned char *d = buf;
4746 int i, j, start;
4747
4748 d = (const unsigned char *)(((unsigned long)buf) & -16);
4749 start = ((unsigned long)buf) & 15;
4750
4751 for (i = 0; i < start + len; i += 16) {
4752 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4753
Willy Tarreau37101052019-05-20 16:48:20 +02004754 // 0: unchecked, 1: checked safe, 2: danger
4755 unsafe = !!unsafe;
4756 if (unsafe && !may_access(d + i))
4757 unsafe = 2;
4758
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004759 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004760 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004761 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004762 else if (unsafe > 1)
4763 chunk_strcat(out, "** ");
4764 else
4765 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004766
4767 if (j == 7)
4768 chunk_strcat(out, "- ");
4769 }
4770 chunk_strcat(out, " ");
4771 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004772 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004773 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004774 else if (unsafe > 1)
4775 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004776 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004777 chunk_appendf(out, "%c", d[i + j]);
4778 else
4779 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004780 }
4781 chunk_strcat(out, "\n");
4782 }
4783}
4784
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004785/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4786 * enclosed in brackets after the address itself, formatted on 14 chars
4787 * including the "0x" prefix. This is meant to be used as a prefix for code
4788 * areas. For example:
4789 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4790 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4791 * is emitted. A NULL <pfx> will be considered empty.
4792 */
4793void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4794{
4795 int ok = 0;
4796 int i;
4797
4798 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4799
4800 for (i = 0; i < n; i++) {
4801 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4802 ok = may_access(addr + i);
4803 if (ok)
4804 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4805 else
4806 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4807 }
4808}
4809
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004810/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4811 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4812 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4813 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4814 * lines are respected within the limit of 70 output chars. Lines that are
4815 * continuation of a previous truncated line begin with "+" instead of " "
4816 * after the offset. The new pointer is returned.
4817 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004818int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004819 int *line, int ptr)
4820{
4821 int end;
4822 unsigned char c;
4823
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004824 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004825 if (end > out->size)
4826 return ptr;
4827
4828 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4829
4830 while (ptr < len && ptr < bsize) {
4831 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004832 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004833 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004834 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004835 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004836 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004837 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004838 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004839 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004840 switch (c) {
4841 case '\t': c = 't'; break;
4842 case '\n': c = 'n'; break;
4843 case '\r': c = 'r'; break;
4844 case '\e': c = 'e'; break;
4845 case '\\': c = '\\'; break;
4846 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004847 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004848 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004849 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004850 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004851 out->area[out->data++] = '\\';
4852 out->area[out->data++] = 'x';
4853 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4854 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004855 }
4856 if (buf[ptr++] == '\n') {
4857 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004858 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004859 *line = ptr;
4860 return ptr;
4861 }
4862 }
4863 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004864 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004865 return ptr;
4866}
4867
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004868/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004869 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4870 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004871 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004872void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4873 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004874{
Willy Tarreau73459792017-04-11 07:58:08 +02004875 unsigned int i;
4876 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004877
4878 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4879 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004880 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004881 for (j = 0; j < 8; j++) {
4882 if (b + j >= 0 && b + j < len)
4883 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4884 else
4885 fprintf(out, " ");
4886 }
4887
4888 if (b + j >= 0 && b + j < len)
4889 fputc('-', out);
4890 else
4891 fputc(' ', out);
4892
4893 for (j = 8; j < 16; j++) {
4894 if (b + j >= 0 && b + j < len)
4895 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4896 else
4897 fprintf(out, " ");
4898 }
4899
4900 fprintf(out, " ");
4901 for (j = 0; j < 16; j++) {
4902 if (b + j >= 0 && b + j < len) {
4903 if (isprint((unsigned char)buf[b + j]))
4904 fputc((unsigned char)buf[b + j], out);
4905 else
4906 fputc('.', out);
4907 }
4908 else
4909 fputc(' ', out);
4910 }
4911 fputc('\n', out);
4912 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004913}
4914
Willy Tarreaubb869862020-04-16 10:52:41 +02004915/* Tries to report the executable path name on platforms supporting this. If
4916 * not found or not possible, returns NULL.
4917 */
4918const char *get_exec_path()
4919{
4920 const char *ret = NULL;
4921
David Carlier43a56852022-03-04 15:50:48 +00004922#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004923 long execfn = getauxval(AT_EXECFN);
4924
4925 if (execfn && execfn != ENOENT)
4926 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004927#elif defined(__FreeBSD__)
4928 Elf_Auxinfo *auxv;
4929 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4930 if (auxv->a_type == AT_EXECPATH) {
4931 ret = (const char *)auxv->a_un.a_ptr;
4932 break;
4933 }
4934 }
David Carlierbd2cced2021-08-17 08:44:25 +01004935#elif defined(__NetBSD__)
4936 AuxInfo *auxv;
4937 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4938 if (auxv->a_type == AT_SUN_EXECNAME) {
4939 ret = (const char *)auxv->a_v;
4940 break;
4941 }
4942 }
David Carlier7198c702022-05-14 17:15:49 +01004943#elif defined(__sun)
4944 ret = getexecname();
Willy Tarreaubb869862020-04-16 10:52:41 +02004945#endif
4946 return ret;
4947}
4948
Baruch Siache1651b22020-07-24 07:52:20 +03004949#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004950/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4951 * also returns the symbol size in <size>, otherwise returns 0 there.
4952 */
4953static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4954{
4955 int ret;
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004956#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreauf3d5c4b2022-01-28 09:42:29 +01004957 const ElfW(Sym) *sym __attribute__((may_alias));
Willy Tarreau9133e482020-03-04 10:19:36 +01004958
4959 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4960 if (ret)
4961 *size = sym ? sym->st_size : 0;
4962#else
David Carlierae5c42f2021-12-31 08:15:29 +00004963#if defined(__sun)
4964 ret = dladdr((void *)addr, dli);
4965#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004966 ret = dladdr(addr, dli);
David Carlierae5c42f2021-12-31 08:15:29 +00004967#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004968 *size = 0;
4969#endif
4970 return ret;
4971}
Willy Tarreau64192392021-05-05 09:06:21 +02004972
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004973/* Sets build_is_static to true if we detect a static build. Some older glibcs
4974 * tend to crash inside dlsym() in static builds, but tests show that at least
4975 * dladdr() still works (and will fail to resolve anything of course). Thus we
4976 * try to determine if we're on a static build to avoid calling dlsym() in this
4977 * case.
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004978 */
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004979void check_if_static_build()
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004980{
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004981 Dl_info dli = { };
4982 size_t size = 0;
4983
4984 /* Now let's try to be smarter */
4985 if (!dladdr_and_size(&main, &dli, &size))
4986 build_is_static = 1;
4987 else
4988 build_is_static = 0;
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004989}
4990
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004991INITCALL0(STG_PREPARE, check_if_static_build);
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004992
Willy Tarreau64192392021-05-05 09:06:21 +02004993/* Tries to retrieve the address of the first occurrence symbol <name>.
4994 * Note that NULL in return is not always an error as a symbol may have that
4995 * address in special situations.
4996 */
4997void *get_sym_curr_addr(const char *name)
4998{
4999 void *ptr = NULL;
5000
5001#ifdef RTLD_DEFAULT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005002 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005003 ptr = dlsym(RTLD_DEFAULT, name);
Willy Tarreau64192392021-05-05 09:06:21 +02005004#endif
5005 return ptr;
5006}
5007
5008
5009/* Tries to retrieve the address of the next occurrence of symbol <name>
5010 * Note that NULL in return is not always an error as a symbol may have that
5011 * address in special situations.
5012 */
5013void *get_sym_next_addr(const char *name)
5014{
5015 void *ptr = NULL;
5016
5017#ifdef RTLD_NEXT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005018 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005019 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01005020#endif
Willy Tarreau64192392021-05-05 09:06:21 +02005021 return ptr;
5022}
5023
5024#else /* elf & linux & dl */
5025
5026/* no possible resolving on other platforms at the moment */
5027void *get_sym_curr_addr(const char *name)
5028{
5029 return NULL;
5030}
5031
5032void *get_sym_next_addr(const char *name)
5033{
5034 return NULL;
5035}
5036
5037#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01005038
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005039/* Tries to append to buffer <buf> some indications about the symbol at address
5040 * <addr> using the following form:
5041 * lib:+0xoffset (unresolvable address from lib's base)
5042 * main+0xoffset (unresolvable address from main (+/-))
5043 * lib:main+0xoffset (unresolvable lib address from main (+/-))
5044 * name (resolved exact exec address)
5045 * lib:name (resolved exact lib address)
5046 * name+0xoffset/0xsize (resolved address within exec symbol)
5047 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
5048 *
5049 * The file name (lib or executable) is limited to what lies between the last
5050 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
5051 * 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 +03005052 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005053 *
5054 * The symbol's base address is returned, or NULL when unresolved, in order to
5055 * allow the caller to match it against known ones.
5056 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01005057const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005058{
5059 const struct {
5060 const void *func;
5061 const char *name;
5062 } fcts[] = {
5063 { .func = process_stream, .name = "process_stream" },
5064 { .func = task_run_applet, .name = "task_run_applet" },
Willy Tarreau462b9892022-05-18 18:06:53 +02005065 { .func = sc_conn_io_cb, .name = "sc_conn_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01005066 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005067 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
5068 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01005069 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005070 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
5071 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01005072 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01005073#ifdef USE_THREAD
5074 { .func = accept_queue_process, .name = "accept_queue_process" },
5075#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005076#ifdef USE_LUA
5077 { .func = hlua_process_task, .name = "hlua_process_task" },
5078#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005079#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005080 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
5081 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
5082#endif
5083 };
5084
Baruch Siache1651b22020-07-24 07:52:20 +03005085#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005086 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01005087 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005088 const char *fname, *p;
5089#endif
5090 int i;
5091
5092 if (pfx)
5093 chunk_appendf(buf, "%s", pfx);
5094
5095 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
5096 if (addr == fcts[i].func) {
5097 chunk_appendf(buf, "%s", fcts[i].name);
5098 return addr;
5099 }
5100 }
5101
Baruch Siache1651b22020-07-24 07:52:20 +03005102#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005103 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01005104 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005105 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005106
5107 /* 1. prefix the library name if it's not the same object as the one
5108 * that contains the main function. The name is picked between last '/'
5109 * and first following '.'.
5110 */
5111 if (!dladdr(main, &dli_main))
5112 dli_main.dli_fbase = NULL;
5113
5114 if (dli_main.dli_fbase != dli.dli_fbase) {
5115 fname = dli.dli_fname;
5116 p = strrchr(fname, '/');
5117 if (p++)
5118 fname = p;
5119 p = strchr(fname, '.');
5120 if (!p)
5121 p = fname + strlen(fname);
5122
5123 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
5124 }
5125
5126 /* 2. symbol name */
5127 if (dli.dli_sname) {
5128 /* known, dump it and return symbol's address (exact or relative) */
5129 chunk_appendf(buf, "%s", dli.dli_sname);
5130 if (addr != dli.dli_saddr) {
5131 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01005132 if (size)
5133 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005134 }
5135 return dli.dli_saddr;
5136 }
5137 else if (dli_main.dli_fbase != dli.dli_fbase) {
5138 /* unresolved symbol from a known library, report relative offset */
5139 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
5140 return NULL;
5141 }
Baruch Siache1651b22020-07-24 07:52:20 +03005142#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005143 unknown:
5144 /* unresolved symbol from the main file, report relative offset to main */
5145 if ((void*)addr < (void*)main)
5146 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
5147 else
5148 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
5149 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01005150}
5151
Willy Tarreau6ab7b212021-12-28 09:57:10 +01005152/* On systems where this is supported, let's provide a possibility to enumerate
5153 * the list of object files. The output is appended to a buffer initialized by
5154 * the caller, with one name per line. A trailing zero is always emitted if data
5155 * are written. Only real objects are dumped (executable and .so libs). The
5156 * function returns non-zero if it dumps anything. These functions do not make
5157 * use of the trash so that it is possible for the caller to call them with the
5158 * trash on input. The output format may be platform-specific but at least one
5159 * version must emit raw object file names when argument is zero.
5160 */
5161#if defined(HA_HAVE_DUMP_LIBS)
5162# if defined(HA_HAVE_DL_ITERATE_PHDR)
5163/* the private <data> we pass below is a dump context initialized like this */
5164struct dl_dump_ctx {
5165 struct buffer *buf;
5166 int with_addr;
5167};
5168
5169static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5170{
5171 struct dl_dump_ctx *ctx = data;
5172 const char *fname;
5173 size_t p1, p2, beg, end;
5174 int idx;
5175
5176 if (!info || !info->dlpi_name)
5177 goto leave;
5178
5179 if (!*info->dlpi_name)
5180 fname = get_exec_path();
5181 else if (strchr(info->dlpi_name, '/'))
5182 fname = info->dlpi_name;
5183 else
5184 /* else it's a VDSO or similar and we're not interested */
5185 goto leave;
5186
5187 if (!ctx->with_addr)
5188 goto dump_name;
5189
5190 /* virtual addresses are relative to the load address and are per
5191 * pseudo-header, so we have to scan them all to find the furthest
5192 * one from the beginning. In this case we only dump entries if
5193 * they have at least one section.
5194 */
5195 beg = ~0; end = 0;
5196 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5197 if (!info->dlpi_phdr[idx].p_memsz)
5198 continue;
5199 p1 = info->dlpi_phdr[idx].p_vaddr;
5200 if (p1 < beg)
5201 beg = p1;
5202 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5203 if (p2 > end)
5204 end = p2;
5205 }
5206
5207 if (!idx)
5208 goto leave;
5209
5210 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5211 (ullong)info->dlpi_addr + beg,
5212 (ullong)info->dlpi_addr + end,
5213 (ullong)(end - beg + 1));
5214 dump_name:
5215 chunk_appendf(ctx->buf, "%s\n", fname);
5216 leave:
5217 return 0;
5218}
5219
5220/* dumps lib names and optionally address ranges */
5221int dump_libs(struct buffer *output, int with_addr)
5222{
5223 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5224 size_t old_data = output->data;
5225
5226 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5227 return output->data != old_data;
5228}
5229# else // no DL_ITERATE_PHDR
5230# error "No dump_libs() function for this platform"
5231# endif
5232#else // no HA_HAVE_DUMP_LIBS
5233
5234/* unsupported platform: do not dump anything */
5235int dump_libs(struct buffer *output, int with_addr)
5236{
5237 return 0;
5238}
5239
5240#endif // HA_HAVE_DUMP_LIBS
5241
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005242/*
5243 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005244 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005245 *
5246 * First, initializes the value with <sz> as address to 0 and initializes the
5247 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5248 * address updating <sz> pointed value to the size of this array.
5249 *
5250 * Returns 1 if succeeded, 0 if not.
5251 */
5252int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5253{
5254 unsigned int *n;
5255 const char *s, *end;
5256
5257 s = str;
5258 *sz = 0;
5259 end = str + strlen(str);
5260 *nums = n = NULL;
5261
5262 while (1) {
5263 unsigned int r;
5264
5265 if (s >= end)
5266 break;
5267
5268 r = read_uint(&s, end);
5269 /* Expected characters after having read an uint: '\0' or '.',
5270 * if '.', must not be terminal.
5271 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005272 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5273 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005274 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005275 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005276
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005277 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005278 if (!n)
5279 return 0;
5280
5281 n[(*sz)++] = r;
5282 }
5283 *nums = n;
5284
5285 return 1;
5286}
5287
Willy Tarreau4d589e72019-08-23 19:02:26 +02005288
5289/* returns the number of bytes needed to encode <v> as a varint. An inline
5290 * version exists for use with constants (__varint_bytes()).
5291 */
5292int varint_bytes(uint64_t v)
5293{
5294 int len = 1;
5295
5296 if (v >= 240) {
5297 v = (v - 240) >> 4;
5298 while (1) {
5299 len++;
5300 if (v < 128)
5301 break;
5302 v = (v - 128) >> 7;
5303 }
5304 }
5305 return len;
5306}
5307
Willy Tarreau52bf8392020-03-08 00:42:37 +01005308
5309/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005310static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005311
5312/* This is a thread-safe implementation of xoroshiro128** described below:
5313 * http://prng.di.unimi.it/
5314 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5315 * supports fast jumps and passes all common quality tests. It is thread-safe,
5316 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5317 * local lock on other ones.
5318 */
5319uint64_t ha_random64()
5320{
Willy Tarreau1544c142020-03-12 00:31:18 +01005321 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5322 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005323
5324#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5325 static HA_SPINLOCK_T rand_lock;
5326
5327 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5328#endif
5329
5330 old[0] = ha_random_state[0];
5331 old[1] = ha_random_state[1];
5332
5333#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5334 do {
5335#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005336 new[1] = old[0] ^ old[1];
5337 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5338 new[1] = rotl64(new[1], 37); // c
5339
5340#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5341 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5342#else
5343 ha_random_state[0] = new[0];
5344 ha_random_state[1] = new[1];
5345#if defined(USE_THREAD)
5346 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5347#endif
5348#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005349 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005350}
5351
5352/* seeds the random state using up to <len> bytes from <seed>, starting with
5353 * the first non-zero byte.
5354 */
5355void ha_random_seed(const unsigned char *seed, size_t len)
5356{
5357 size_t pos;
5358
5359 /* the seed must not be all zeroes, so we pre-fill it with alternating
5360 * bits and overwrite part of them with the block starting at the first
5361 * non-zero byte from the seed.
5362 */
5363 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5364
5365 for (pos = 0; pos < len; pos++)
5366 if (seed[pos] != 0)
5367 break;
5368
5369 if (pos == len)
5370 return;
5371
5372 seed += pos;
5373 len -= pos;
5374
5375 if (len > sizeof(ha_random_state))
5376 len = sizeof(ha_random_state);
5377
5378 memcpy(ha_random_state, seed, len);
5379}
5380
5381/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5382 * and is equivalent to calling ha_random64() as many times. It is used to
5383 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5384 * different generators (i.e. different processes after a fork). The <dist>
5385 * argument is the distance to jump to and is used in a loop so it rather not
5386 * be too large if the processing time is a concern.
5387 *
5388 * BEWARE: this function is NOT thread-safe and must not be called during
5389 * concurrent accesses to ha_random64().
5390 */
5391void ha_random_jump96(uint32_t dist)
5392{
5393 while (dist--) {
5394 uint64_t s0 = 0;
5395 uint64_t s1 = 0;
5396 int b;
5397
5398 for (b = 0; b < 64; b++) {
5399 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5400 s0 ^= ha_random_state[0];
5401 s1 ^= ha_random_state[1];
5402 }
5403 ha_random64();
5404 }
5405
5406 for (b = 0; b < 64; b++) {
5407 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5408 s0 ^= ha_random_state[0];
5409 s1 ^= ha_random_state[1];
5410 }
5411 ha_random64();
5412 }
5413 ha_random_state[0] = s0;
5414 ha_random_state[1] = s1;
5415 }
5416}
5417
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005418/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5419 * bytes large.
5420 */
5421void ha_generate_uuid(struct buffer *output)
5422{
5423 uint32_t rnd[4];
5424 uint64_t last;
5425
5426 last = ha_random64();
5427 rnd[0] = last;
5428 rnd[1] = last >> 32;
5429
5430 last = ha_random64();
5431 rnd[2] = last;
5432 rnd[3] = last >> 32;
5433
5434 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5435 rnd[0],
5436 rnd[1] & 0xFFFF,
5437 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5438 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5439 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5440}
5441
5442
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005443/* only used by parse_line() below. It supports writing in place provided that
5444 * <in> is updated to the next location before calling it. In that case, the
5445 * char at <in> may be overwritten.
5446 */
5447#define EMIT_CHAR(x) \
5448 do { \
5449 char __c = (char)(x); \
5450 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5451 err |= PARSE_ERR_OVERLAP; \
5452 if (outpos >= outmax) \
5453 err |= PARSE_ERR_TOOLARGE; \
5454 if (!err) \
5455 out[outpos] = __c; \
5456 outpos++; \
5457 } while (0)
5458
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005459/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005460 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5461 * extraneous ones are not emitted but <outlen> is updated so that the caller
5462 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5463 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005464 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5465 * it is guaranteed that at least one arg will point to the zero. It is safe
5466 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005467 *
5468 * <out> may overlap with <in> provided that it never goes further, in which
5469 * case the parser will accept to perform in-place parsing and unquoting/
5470 * unescaping but only if environment variables do not lead to expansion that
5471 * causes overlapping, otherwise the input string being destroyed, the error
5472 * will not be recoverable. Note that even during out-of-place <in> will
5473 * experience temporary modifications in-place for variable resolution and must
5474 * be writable, and will also receive zeroes to delimit words when using
5475 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5476 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5477 * starting point of the first invalid character sequence or unmatched
5478 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5479 * error reporting might be difficult since zeroes will have been inserted into
5480 * the string. One solution for the caller may consist in replacing all args
5481 * delimiters with spaces in this case.
5482 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005483uint32_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 +02005484{
5485 char *quote = NULL;
5486 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005487 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005488 unsigned char hex1, hex2;
5489 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005490 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005491 size_t outpos = 0;
5492 int squote = 0;
5493 int dquote = 0;
5494 int arg = 0;
5495 uint32_t err = 0;
5496
5497 *nbargs = 0;
5498 *outlen = 0;
5499
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005500 /* argsmax may be -1 here, protecting args[] from any write */
5501 if (arg < argsmax)
5502 args[arg] = out;
5503
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005504 while (1) {
5505 if (*in >= '-' && *in != '\\') {
5506 /* speedup: directly send all regular chars starting
5507 * with '-', '.', '/', alnum etc...
5508 */
5509 EMIT_CHAR(*in++);
5510 continue;
5511 }
5512 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5513 /* end of line */
5514 break;
5515 }
5516 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5517 /* comment */
5518 break;
5519 }
5520 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5521 if (dquote) {
5522 dquote = 0;
5523 quote = NULL;
5524 }
5525 else {
5526 dquote = 1;
5527 quote = in;
5528 }
5529 in++;
5530 continue;
5531 }
5532 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5533 if (squote) {
5534 squote = 0;
5535 quote = NULL;
5536 }
5537 else {
5538 squote = 1;
5539 quote = in;
5540 }
5541 in++;
5542 continue;
5543 }
5544 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5545 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5546 * C equivalent value but only when they have a special meaning and within
5547 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5548 */
5549 char tosend = *in;
5550
5551 switch (in[1]) {
5552 case ' ':
5553 case '\\':
5554 tosend = in[1];
5555 in++;
5556 break;
5557
5558 case 't':
5559 tosend = '\t';
5560 in++;
5561 break;
5562
5563 case 'n':
5564 tosend = '\n';
5565 in++;
5566 break;
5567
5568 case 'r':
5569 tosend = '\r';
5570 in++;
5571 break;
5572
5573 case '#':
5574 /* escaping of "#" only if comments are supported */
5575 if (opts & PARSE_OPT_SHARP)
5576 in++;
5577 tosend = *in;
5578 break;
5579
5580 case '\'':
5581 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5582 if (opts & PARSE_OPT_SQUOTE && !squote)
5583 in++;
5584 tosend = *in;
5585 break;
5586
5587 case '"':
5588 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5589 if (opts & PARSE_OPT_DQUOTE && !squote)
5590 in++;
5591 tosend = *in;
5592 break;
5593
5594 case '$':
5595 /* escaping of '$' only inside double quotes and only if env supported */
5596 if (opts & PARSE_OPT_ENV && dquote)
5597 in++;
5598 tosend = *in;
5599 break;
5600
5601 case 'x':
5602 if (!ishex(in[2]) || !ishex(in[3])) {
5603 /* invalid or incomplete hex sequence */
5604 err |= PARSE_ERR_HEX;
5605 if (errptr)
5606 *errptr = in;
5607 goto leave;
5608 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005609 hex1 = toupper((unsigned char)in[2]) - '0';
5610 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005611 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5612 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5613 tosend = (hex1 << 4) + hex2;
5614 in += 3;
5615 break;
5616
5617 default:
5618 /* other combinations are not escape sequences */
5619 break;
5620 }
5621
5622 in++;
5623 EMIT_CHAR(tosend);
5624 }
5625 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5626 /* a non-escaped space is an argument separator */
5627 while (isspace((unsigned char)*in))
5628 in++;
5629 EMIT_CHAR(0);
5630 arg++;
5631 if (arg < argsmax)
5632 args[arg] = out + outpos;
5633 else
5634 err |= PARSE_ERR_TOOMANY;
5635 }
5636 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5637 /* environment variables are evaluated anywhere, or only
5638 * inside double quotes if they are supported.
5639 */
5640 char *var_name;
5641 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005642 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005643
5644 in++;
5645
5646 if (*in == '{')
5647 brace = in++;
5648
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005649 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005650 /* unacceptable character in variable name */
5651 err |= PARSE_ERR_VARNAME;
5652 if (errptr)
5653 *errptr = in;
5654 goto leave;
5655 }
5656
5657 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005658 if (*in == '.')
5659 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005660 while (isalnum((unsigned char)*in) || *in == '_')
5661 in++;
5662
5663 save_char = *in;
5664 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005665 if (unlikely(*var_name == '.')) {
5666 /* internal pseudo-variables */
5667 if (strcmp(var_name, ".LINE") == 0)
5668 value = ultoa(global.cfg_curr_line);
5669 else if (strcmp(var_name, ".FILE") == 0)
5670 value = global.cfg_curr_file;
5671 else if (strcmp(var_name, ".SECTION") == 0)
5672 value = global.cfg_curr_section;
5673 else {
5674 /* unsupported internal variable name */
5675 err |= PARSE_ERR_VARNAME;
5676 if (errptr)
5677 *errptr = var_name;
5678 goto leave;
5679 }
5680 } else {
5681 value = getenv(var_name);
5682 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005683 *in = save_char;
5684
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005685 /* support for '[*]' sequence to force word expansion,
5686 * only available inside braces */
5687 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5688 word_expand = in++;
5689
5690 if (*in++ != '*' || *in++ != ']') {
5691 err |= PARSE_ERR_WRONG_EXPAND;
5692 if (errptr)
5693 *errptr = word_expand;
5694 goto leave;
5695 }
5696 }
5697
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005698 if (brace) {
Willy Tarreauec347b12021-11-18 17:42:50 +01005699 if (*in == '-') {
5700 /* default value starts just after the '-' */
5701 if (!value)
5702 value = in + 1;
5703
5704 while (*in && *in != '}')
5705 in++;
5706 if (!*in)
5707 goto no_brace;
5708 *in = 0; // terminate the default value
5709 }
5710 else if (*in != '}') {
5711 no_brace:
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005712 /* unmatched brace */
5713 err |= PARSE_ERR_BRACE;
5714 if (errptr)
5715 *errptr = brace;
5716 goto leave;
5717 }
Willy Tarreauec347b12021-11-18 17:42:50 +01005718
5719 /* brace found, skip it */
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005720 in++;
5721 brace = NULL;
5722 }
5723
5724 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005725 while (*value) {
5726 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005727 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005728 EMIT_CHAR(0);
5729 ++arg;
5730 if (arg < argsmax)
5731 args[arg] = out + outpos;
5732 else
5733 err |= PARSE_ERR_TOOMANY;
5734
5735 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005736 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005737 ;
5738 } else {
5739 EMIT_CHAR(*value++);
5740 }
5741 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005742 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005743 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005744 }
5745 else {
5746 /* any other regular char */
5747 EMIT_CHAR(*in++);
5748 }
5749 }
5750
5751 /* end of output string */
5752 EMIT_CHAR(0);
Erwan Le Goas8a6767d2022-09-23 15:06:34 +02005753
5754 /* don't add empty arg after trailing spaces. Note that args[arg]
5755 * may contain some distances relative to NULL if <out> was NULL,
5756 * so we test <out> instead of args[arg].
5757 */
5758 if (arg < argsmax && out && *(args[arg]))
5759 arg++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005760
5761 if (quote) {
5762 /* unmatched quote */
5763 err |= PARSE_ERR_QUOTE;
5764 if (errptr)
5765 *errptr = quote;
5766 goto leave;
5767 }
5768 leave:
5769 *nbargs = arg;
5770 *outlen = outpos;
5771
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005772 /* empty all trailing args by making them point to the trailing zero,
5773 * at least the last one in any case.
5774 */
5775 if (arg > argsmax)
5776 arg = argsmax;
5777
5778 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005779 args[arg++] = out + outpos - 1;
5780
5781 return err;
5782}
5783#undef EMIT_CHAR
5784
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005785/* This is used to sanitize an input line that's about to be used for error reporting.
5786 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5787 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5788 * If non-printable chars are present in the output. It returns the new offset <pos>
5789 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5790 * be at least 6 to support two "..." otherwise the result is undefined. The line
5791 * itself must have at least 7 chars allocated for the same reason.
5792 */
5793size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5794{
5795 size_t shift = 0;
5796 char *out = line;
5797 char *in = line;
5798 char *end = line + width;
5799
5800 if (pos >= width) {
5801 /* if we have to shift, we'll be out of context, so let's
5802 * try to put <pos> at the center of width.
5803 */
5804 shift = pos - width / 2;
5805 in += shift + 3;
5806 end = out + width - 3;
5807 out[0] = out[1] = out[2] = '.';
5808 out += 3;
5809 }
5810
5811 while (out < end && *in) {
5812 if (isspace((unsigned char)*in))
5813 *out++ = ' ';
5814 else if (isprint((unsigned char)*in))
5815 *out++ = *in;
5816 else
5817 *out++ = '?';
5818 in++;
5819 }
5820
5821 if (end < line + width) {
5822 out[0] = out[1] = out[2] = '.';
5823 out += 3;
5824 }
5825
5826 *out++ = 0;
5827 return pos - shift;
5828}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005829
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005830/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005831 * transitions between characters. <fp> is a 1024-entries array indexed as
5832 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005833 * 1..26=letter, 27=digit, 28=other/begin/end.
5834 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005835 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005836void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005837{
5838 const char *p;
5839 int from, to;
5840 int c;
5841
Willy Tarreauba2c4452021-03-12 09:01:52 +01005842 from = 28; // begin
5843 for (p = word; *p; p++) {
5844 c = tolower(*p);
5845 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005846 case 'a'...'z': to = c - 'a' + 1; break;
5847 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5848 case '0'...'9': to = 27; break;
5849 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005850 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005851 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005852 fp[32 * from + to]++;
5853 from = to;
5854 }
5855 to = 28; // end
5856 fp[32 * from + to]++;
5857}
5858
Erwan Le Goas9c766372022-09-14 17:40:24 +02005859/* This function hashes a word, scramble is the anonymizing key, returns
5860 * the hashed word when the key (scramble) != 0, else returns the word.
5861 * This function can be called NB_L_HASH_WORD times in a row, don't call
5862 * it if you called it more than NB_L_HASH_WORD.
5863 */
5864const char *hash_anon(uint32_t scramble, const char *string2hash, const char *prefix, const char *suffix)
5865{
5866 index_hash++;
Erwan Le Goasd2605cf2022-09-21 16:24:23 +02005867 if (index_hash == NB_L_HASH_WORD)
Erwan Le Goas9c766372022-09-14 17:40:24 +02005868 index_hash = 0;
5869
5870 /* don't hash empty strings */
5871 if (!string2hash[0] || (string2hash[0] == ' ' && string2hash[1] == 0))
5872 return string2hash;
5873
5874 if (scramble != 0) {
5875 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "%s%06x%s",
5876 prefix, HA_ANON(scramble, string2hash, strlen(string2hash)), suffix);
5877 return hash_word[index_hash];
5878 }
5879 else
5880 return string2hash;
5881}
5882
5883/* This function hashes or not an ip address ipstring, scramble is the anonymizing
5884 * key, returns the hashed ip with his port or ipstring when there is nothing to hash.
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005885 * Put hasport equal 0 to point out ipstring has no port, else put an other int.
5886 * Without port, return a simple hash or ipstring.
Erwan Le Goas9c766372022-09-14 17:40:24 +02005887 */
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005888const char *hash_ipanon(uint32_t scramble, char *ipstring, int hasport)
Erwan Le Goas9c766372022-09-14 17:40:24 +02005889{
5890 char *errmsg = NULL;
5891 struct sockaddr_storage *sa;
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005892 struct sockaddr_storage ss;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005893 char addr[46];
5894 int port;
5895
5896 index_hash++;
Erwan Le Goasd2605cf2022-09-21 16:24:23 +02005897 if (index_hash == NB_L_HASH_WORD) {
Erwan Le Goas9c766372022-09-14 17:40:24 +02005898 index_hash = 0;
5899 }
5900
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005901 if (scramble == 0) {
Erwan Le Goas9c766372022-09-14 17:40:24 +02005902 return ipstring;
5903 }
Christopher Faulet015bbc22022-09-29 11:53:07 +02005904 if (strcmp(ipstring, "localhost") == 0 ||
5905 strcmp(ipstring, "stdout") == 0 ||
5906 strcmp(ipstring, "stderr") == 0 ||
5907 strncmp(ipstring, "fd@", 3) == 0 ||
5908 strncmp(ipstring, "sockpair@", 9) == 0) {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005909 return ipstring;
5910 }
Erwan Le Goas9c766372022-09-14 17:40:24 +02005911 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005912 if (hasport == 0) {
5913 memset(&ss, 0, sizeof(ss));
5914 if (str2ip2(ipstring, &ss, 1) == NULL) {
5915 return HA_ANON_STR(scramble, ipstring);
5916 }
5917 sa = &ss;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005918 }
5919 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005920 sa = str2sa_range(ipstring, NULL, NULL, NULL, NULL, NULL, &errmsg, NULL, NULL,
Christopher Faulet7e50e4b2022-09-29 11:46:34 +02005921 PA_O_PORT_OK | PA_O_STREAM | PA_O_DGRAM | PA_O_XPRT | PA_O_CONNECT |
5922 PA_O_PORT_RANGE | PA_O_PORT_OFS | PA_O_RESOLVE);
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005923 if (sa == NULL) {
5924 return HA_ANON_STR(scramble, ipstring);
5925 }
5926 }
5927 addr_to_str(sa, addr, sizeof(addr));
5928 port = get_host_port(sa);
Erwan Le Goas9c766372022-09-14 17:40:24 +02005929
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005930 switch(sa->ss_family) {
5931 case AF_INET:
5932 if (strncmp(addr, "127", 3) == 0 || strncmp(addr, "255", 3) == 0 || strncmp(addr, "0", 1) == 0) {
5933 return ipstring;
5934 }
5935 else {
5936 if (port != 0) {
5937 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV4(%06x):%d", HA_ANON(scramble, addr, strlen(addr)), port);
5938 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005939 }
5940 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005941 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV4(%06x)", HA_ANON(scramble, addr, strlen(addr)));
5942 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005943 }
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005944 }
5945 break;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005946
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005947 case AF_INET6:
5948 if (strcmp(addr, "::1") == 0) {
5949 return ipstring;
5950 }
5951 else {
5952 if (port != 0) {
5953 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV6(%06x):%d", HA_ANON(scramble, addr, strlen(addr)), port);
5954 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005955 }
5956 else {
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005957 snprintf(hash_word[index_hash], sizeof(hash_word[index_hash]), "IPV6(%06x)", HA_ANON(scramble, addr, strlen(addr)));
5958 return hash_word[index_hash];
Erwan Le Goas9c766372022-09-14 17:40:24 +02005959 }
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005960 }
5961 break;
Erwan Le Goas9c766372022-09-14 17:40:24 +02005962
Erwan Le Goas5eef1582022-09-29 10:25:31 +02005963 case AF_UNIX:
5964 return HA_ANON_STR(scramble, ipstring);
5965 break;
5966
5967 default:
5968 return ipstring;
5969 break;
5970 };
Erwan Le Goas9c766372022-09-14 17:40:24 +02005971 }
5972 return ipstring;
5973}
5974
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005975/* Initialize array <fp> with the fingerprint of word <word> by counting the
5976 * transitions between characters. <fp> is a 1024-entries array indexed as
5977 * 32*from+to. Positions for 'from' and 'to' are:
5978 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5979 */
5980void make_word_fingerprint(uint8_t *fp, const char *word)
5981{
5982 memset(fp, 0, 1024);
5983 update_word_fingerprint(fp, word);
5984}
5985
Willy Tarreauba2c4452021-03-12 09:01:52 +01005986/* Return the distance between two word fingerprints created by function
5987 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005988 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005989 */
5990int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5991{
5992 int i, k, dist = 0;
5993
5994 for (i = 0; i < 1024; i++) {
5995 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005996 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005997 }
5998 return dist;
5999}
6000
William Lallemand3aeb3f92021-08-21 23:59:56 +02006001/*
6002 * This function compares the loaded openssl version with a string <version>
6003 * This function use the same return code as compare_current_version:
6004 *
6005 * -1 : the version in argument is older than the current openssl version
6006 * 0 : the version in argument is the same as the current openssl version
6007 * 1 : the version in argument is newer than the current openssl version
6008 *
6009 * Or some errors:
6010 * -2 : openssl is not available on this process
6011 * -3 : the version in argument is not parsable
6012 */
6013int openssl_compare_current_version(const char *version)
6014{
6015#ifdef USE_OPENSSL
6016 int numversion;
6017
6018 numversion = openssl_version_parser(version);
6019 if (numversion == 0)
6020 return -3;
6021
6022 if (numversion < OPENSSL_VERSION_NUMBER)
6023 return -1;
6024 else if (numversion > OPENSSL_VERSION_NUMBER)
6025 return 1;
6026 else
6027 return 0;
6028#else
6029 return -2;
6030#endif
6031}
6032
Remi Tricot-Le Bretonb01179a2021-10-11 15:34:12 +02006033/*
6034 * This function compares the loaded openssl name with a string <name>
6035 * This function returns 0 if the OpenSSL name starts like the passed parameter,
6036 * 1 otherwise.
6037 */
6038int openssl_compare_current_name(const char *name)
6039{
6040#ifdef USE_OPENSSL
6041 int name_len = 0;
6042 const char *openssl_version = OpenSSL_version(OPENSSL_VERSION);
6043
6044 if (name) {
6045 name_len = strlen(name);
6046 if (strlen(name) <= strlen(openssl_version))
6047 return strncmp(openssl_version, name, name_len);
6048 }
6049#endif
6050 return 1;
6051}
6052
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006053#if defined(RTLD_DEFAULT) || defined(RTLD_NEXT)
6054/* redefine dlopen() so that we can detect unexpected replacement of some
6055 * critical symbols, typically init/alloc/free functions coming from alternate
6056 * libraries. When called, a tainted flag is set (TAINTED_SHARED_LIBS).
6057 */
6058void *dlopen(const char *filename, int flags)
6059{
6060 static void *(*_dlopen)(const char *filename, int flags);
Willy Tarreau177aed52022-06-19 16:49:51 +02006061 struct {
6062 const char *name;
6063 void *curr, *next;
6064 } check_syms[] = {
6065 { .name = "malloc", },
6066 { .name = "free", },
6067 { .name = "SSL_library_init", },
6068 { .name = "X509_free", },
6069 /* insert only above, 0 must be the last one */
6070 { 0 },
6071 };
6072 const char *trace;
6073 void *addr;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006074 void *ret;
Willy Tarreau177aed52022-06-19 16:49:51 +02006075 int sym = 0;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006076
6077 if (!_dlopen) {
6078 _dlopen = get_sym_next_addr("dlopen");
6079 if (!_dlopen || _dlopen == dlopen) {
6080 _dlopen = NULL;
6081 return NULL;
6082 }
6083 }
6084
Willy Tarreau177aed52022-06-19 16:49:51 +02006085 /* save a few pointers to critical symbols. We keep a copy of both the
6086 * current and the next value, because we might already have replaced
6087 * some of them (e.g. malloc/free with DEBUG_MEM_STATS), and we're only
6088 * interested in verifying that a loaded library doesn't come with a
6089 * completely different definition that would be incompatible.
6090 */
6091 for (sym = 0; check_syms[sym].name; sym++) {
6092 check_syms[sym].curr = get_sym_curr_addr(check_syms[sym].name);
6093 check_syms[sym].next = get_sym_next_addr(check_syms[sym].name);
6094 }
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006095
6096 /* now open the requested lib */
6097 ret = _dlopen(filename, flags);
6098 if (!ret)
6099 return ret;
6100
6101 mark_tainted(TAINTED_SHARED_LIBS);
6102
Willy Tarreau177aed52022-06-19 16:49:51 +02006103 /* and check that critical symbols didn't change */
6104 for (sym = 0; check_syms[sym].name; sym++) {
6105 if (!check_syms[sym].curr && !check_syms[sym].next)
6106 continue;
6107
6108 addr = dlsym(ret, check_syms[sym].name);
6109 if (!addr || addr == check_syms[sym].curr || addr == check_syms[sym].next)
6110 continue;
6111
6112 /* OK it's clear that this symbol was redefined */
6113 mark_tainted(TAINTED_REDEFINITION);
6114
6115 trace = hlua_show_current_location("\n ");
6116 ha_warning("dlopen(): shared library '%s' brings a different definition of symbol '%s'. The process cannot be trusted anymore!%s%s\n",
6117 filename, check_syms[sym].name,
6118 trace ? " Suspected call location: \n " : "",
6119 trace ? trace : "");
6120 }
6121
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006122 return ret;
6123}
6124#endif
6125
Willy Tarreau06e69b52021-03-02 14:01:35 +01006126static int init_tools_per_thread()
6127{
6128 /* Let's make each thread start from a different position */
6129 statistical_prng_state += tid * MAX_THREADS;
6130 if (!statistical_prng_state)
6131 statistical_prng_state++;
6132 return 1;
6133}
6134REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02006135
Willy Tarreaubaaee002006-06-26 02:48:02 +02006136/*
6137 * Local variables:
6138 * c-indent-level: 8
6139 * c-basic-offset: 8
6140 * End:
6141 */