blob: 36db6a48a884d2ebb293bbdb189c3105bdd1a673 [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 Tarreau48fbcae2020-06-03 18:09:46 +020052
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020053#include <haproxy/api.h>
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +020054#include <haproxy/applet.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020055#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020056#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020057#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020058#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020059#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020060#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010061#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020062#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010063#include <haproxy/resolvers.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020064#include <haproxy/sc_strm.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010065#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020066#include <haproxy/ssl_sock.h>
William Lallemand3aeb3f92021-08-21 23:59:56 +020067#include <haproxy/ssl_utils.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020068#include <haproxy/stconn.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020069#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020070#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010071
Thierry Fournier93127942016-01-20 18:49:45 +010072/* This macro returns false if the test __x is false. Many
73 * of the following parsing function must be abort the processing
74 * if it returns 0, so this macro is useful for writing light code.
75 */
76#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
77
Willy Tarreau56adcf22012-12-23 18:00:29 +010078/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020079 * 2^64-1 = 18446744073709551615 or
80 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020081 *
82 * The HTML version needs room for adding the 25 characters
83 * '<span class="rls"></span>' around digits at positions 3N+1 in order
84 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020085 */
Christopher Faulet99bca652017-11-14 16:47:26 +010086THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
87THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020088
Willy Tarreau588297f2014-06-16 15:16:40 +020089/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
90 * to quote strings larger than a max configuration line.
91 */
Christopher Faulet99bca652017-11-14 16:47:26 +010092THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
93THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020094
Willy Tarreau06e69b52021-03-02 14:01:35 +010095/* thread-local PRNG state. It's modified to start from a different sequence
96 * on all threads upon startup. It must not be used or anything beyond getting
97 * statistical values as it's 100% predictable.
98 */
99THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
100
Willy Tarreau5b3cd952022-07-18 13:58:17 +0200101/* set to true if this is a static build */
102int build_is_static = 0;
103
Willy Tarreaubaaee002006-06-26 02:48:02 +0200104/*
William Lallemande7340ec2012-01-24 11:15:39 +0100105 * unsigned long long ASCII representation
106 *
107 * return the last char '\0' or NULL if no enough
108 * space in dst
109 */
110char *ulltoa(unsigned long long n, char *dst, size_t size)
111{
112 int i = 0;
113 char *res;
114
115 switch(n) {
116 case 1ULL ... 9ULL:
117 i = 0;
118 break;
119
120 case 10ULL ... 99ULL:
121 i = 1;
122 break;
123
124 case 100ULL ... 999ULL:
125 i = 2;
126 break;
127
128 case 1000ULL ... 9999ULL:
129 i = 3;
130 break;
131
132 case 10000ULL ... 99999ULL:
133 i = 4;
134 break;
135
136 case 100000ULL ... 999999ULL:
137 i = 5;
138 break;
139
140 case 1000000ULL ... 9999999ULL:
141 i = 6;
142 break;
143
144 case 10000000ULL ... 99999999ULL:
145 i = 7;
146 break;
147
148 case 100000000ULL ... 999999999ULL:
149 i = 8;
150 break;
151
152 case 1000000000ULL ... 9999999999ULL:
153 i = 9;
154 break;
155
156 case 10000000000ULL ... 99999999999ULL:
157 i = 10;
158 break;
159
160 case 100000000000ULL ... 999999999999ULL:
161 i = 11;
162 break;
163
164 case 1000000000000ULL ... 9999999999999ULL:
165 i = 12;
166 break;
167
168 case 10000000000000ULL ... 99999999999999ULL:
169 i = 13;
170 break;
171
172 case 100000000000000ULL ... 999999999999999ULL:
173 i = 14;
174 break;
175
176 case 1000000000000000ULL ... 9999999999999999ULL:
177 i = 15;
178 break;
179
180 case 10000000000000000ULL ... 99999999999999999ULL:
181 i = 16;
182 break;
183
184 case 100000000000000000ULL ... 999999999999999999ULL:
185 i = 17;
186 break;
187
188 case 1000000000000000000ULL ... 9999999999999999999ULL:
189 i = 18;
190 break;
191
192 case 10000000000000000000ULL ... ULLONG_MAX:
193 i = 19;
194 break;
195 }
196 if (i + 2 > size) // (i + 1) + '\0'
197 return NULL; // too long
198 res = dst + i + 1;
199 *res = '\0';
200 for (; i >= 0; i--) {
201 dst[i] = n % 10ULL + '0';
202 n /= 10ULL;
203 }
204 return res;
205}
206
207/*
208 * unsigned long ASCII representation
209 *
210 * return the last char '\0' or NULL if no enough
211 * space in dst
212 */
213char *ultoa_o(unsigned long n, char *dst, size_t size)
214{
215 int i = 0;
216 char *res;
217
218 switch (n) {
219 case 0U ... 9UL:
220 i = 0;
221 break;
222
223 case 10U ... 99UL:
224 i = 1;
225 break;
226
227 case 100U ... 999UL:
228 i = 2;
229 break;
230
231 case 1000U ... 9999UL:
232 i = 3;
233 break;
234
235 case 10000U ... 99999UL:
236 i = 4;
237 break;
238
239 case 100000U ... 999999UL:
240 i = 5;
241 break;
242
243 case 1000000U ... 9999999UL:
244 i = 6;
245 break;
246
247 case 10000000U ... 99999999UL:
248 i = 7;
249 break;
250
251 case 100000000U ... 999999999UL:
252 i = 8;
253 break;
254#if __WORDSIZE == 32
255
256 case 1000000000ULL ... ULONG_MAX:
257 i = 9;
258 break;
259
260#elif __WORDSIZE == 64
261
262 case 1000000000ULL ... 9999999999UL:
263 i = 9;
264 break;
265
266 case 10000000000ULL ... 99999999999UL:
267 i = 10;
268 break;
269
270 case 100000000000ULL ... 999999999999UL:
271 i = 11;
272 break;
273
274 case 1000000000000ULL ... 9999999999999UL:
275 i = 12;
276 break;
277
278 case 10000000000000ULL ... 99999999999999UL:
279 i = 13;
280 break;
281
282 case 100000000000000ULL ... 999999999999999UL:
283 i = 14;
284 break;
285
286 case 1000000000000000ULL ... 9999999999999999UL:
287 i = 15;
288 break;
289
290 case 10000000000000000ULL ... 99999999999999999UL:
291 i = 16;
292 break;
293
294 case 100000000000000000ULL ... 999999999999999999UL:
295 i = 17;
296 break;
297
298 case 1000000000000000000ULL ... 9999999999999999999UL:
299 i = 18;
300 break;
301
302 case 10000000000000000000ULL ... ULONG_MAX:
303 i = 19;
304 break;
305
306#endif
307 }
308 if (i + 2 > size) // (i + 1) + '\0'
309 return NULL; // too long
310 res = dst + i + 1;
311 *res = '\0';
312 for (; i >= 0; i--) {
313 dst[i] = n % 10U + '0';
314 n /= 10U;
315 }
316 return res;
317}
318
319/*
320 * signed long ASCII representation
321 *
322 * return the last char '\0' or NULL if no enough
323 * space in dst
324 */
325char *ltoa_o(long int n, char *dst, size_t size)
326{
327 char *pos = dst;
328
329 if (n < 0) {
330 if (size < 3)
331 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
332 *pos = '-';
333 pos++;
334 dst = ultoa_o(-n, pos, size - 1);
335 } else {
336 dst = ultoa_o(n, dst, size);
337 }
338 return dst;
339}
340
341/*
342 * signed long long ASCII representation
343 *
344 * return the last char '\0' or NULL if no enough
345 * space in dst
346 */
347char *lltoa(long long n, char *dst, size_t size)
348{
349 char *pos = dst;
350
351 if (n < 0) {
352 if (size < 3)
353 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
354 *pos = '-';
355 pos++;
356 dst = ulltoa(-n, pos, size - 1);
357 } else {
358 dst = ulltoa(n, dst, size);
359 }
360 return dst;
361}
362
363/*
364 * write a ascii representation of a unsigned into dst,
365 * return a pointer to the last character
366 * Pad the ascii representation with '0', using size.
367 */
368char *utoa_pad(unsigned int n, char *dst, size_t size)
369{
370 int i = 0;
371 char *ret;
372
373 switch(n) {
374 case 0U ... 9U:
375 i = 0;
376 break;
377
378 case 10U ... 99U:
379 i = 1;
380 break;
381
382 case 100U ... 999U:
383 i = 2;
384 break;
385
386 case 1000U ... 9999U:
387 i = 3;
388 break;
389
390 case 10000U ... 99999U:
391 i = 4;
392 break;
393
394 case 100000U ... 999999U:
395 i = 5;
396 break;
397
398 case 1000000U ... 9999999U:
399 i = 6;
400 break;
401
402 case 10000000U ... 99999999U:
403 i = 7;
404 break;
405
406 case 100000000U ... 999999999U:
407 i = 8;
408 break;
409
410 case 1000000000U ... 4294967295U:
411 i = 9;
412 break;
413 }
414 if (i + 2 > size) // (i + 1) + '\0'
415 return NULL; // too long
416 if (i < size)
417 i = size - 2; // padding - '\0'
418
419 ret = dst + i + 1;
420 *ret = '\0';
421 for (; i >= 0; i--) {
422 dst[i] = n % 10U + '0';
423 n /= 10U;
424 }
425 return ret;
426}
427
428/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200429 * copies at most <size-1> chars from <src> to <dst>. Last char is always
430 * set to 0, unless <size> is 0. The number of chars copied is returned
431 * (excluding the terminating zero).
432 * This code has been optimized for size and speed : on x86, it's 45 bytes
433 * long, uses only registers, and consumes only 4 cycles per char.
434 */
435int strlcpy2(char *dst, const char *src, int size)
436{
437 char *orig = dst;
438 if (size) {
439 while (--size && (*dst = *src)) {
440 src++; dst++;
441 }
442 *dst = 0;
443 }
444 return dst - orig;
445}
446
447/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200448 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200449 * the ascii representation for number 'n' in decimal.
450 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100451char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200452{
453 char *pos;
454
Willy Tarreau72d759c2007-10-25 12:14:10 +0200455 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200456 *pos-- = '\0';
457
458 do {
459 *pos-- = '0' + n % 10;
460 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200461 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200462 return pos + 1;
463}
464
Willy Tarreau91092e52007-10-25 16:58:42 +0200465/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200466 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200467 * the ascii representation for number 'n' in decimal.
468 */
469char *lltoa_r(long long int in, char *buffer, int size)
470{
471 char *pos;
472 int neg = 0;
473 unsigned long long int n;
474
475 pos = buffer + size - 1;
476 *pos-- = '\0';
477
478 if (in < 0) {
479 neg = 1;
480 n = -in;
481 }
482 else
483 n = in;
484
485 do {
486 *pos-- = '0' + n % 10;
487 n /= 10;
488 } while (n && pos >= buffer);
489 if (neg && pos > buffer)
490 *pos-- = '-';
491 return pos + 1;
492}
493
494/*
495 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200496 * the ascii representation for signed number 'n' in decimal.
497 */
498char *sltoa_r(long n, char *buffer, int size)
499{
500 char *pos;
501
502 if (n >= 0)
503 return ultoa_r(n, buffer, size);
504
505 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
506 *pos = '-';
507 return pos;
508}
509
510/*
511 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200512 * the ascii representation for number 'n' in decimal, formatted for
513 * HTML output with tags to create visual grouping by 3 digits. The
514 * output needs to support at least 171 characters.
515 */
516const char *ulltoh_r(unsigned long long n, char *buffer, int size)
517{
518 char *start;
519 int digit = 0;
520
521 start = buffer + size;
522 *--start = '\0';
523
524 do {
525 if (digit == 3 && start >= buffer + 7)
526 memcpy(start -= 7, "</span>", 7);
527
528 if (start >= buffer + 1) {
529 *--start = '0' + n % 10;
530 n /= 10;
531 }
532
533 if (digit == 3 && start >= buffer + 18)
534 memcpy(start -= 18, "<span class=\"rls\">", 18);
535
536 if (digit++ == 3)
537 digit = 1;
538 } while (n && start > buffer);
539 return start;
540}
541
542/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200543 * This function simply returns a locally allocated string containing the ascii
544 * representation for number 'n' in decimal, unless n is 0 in which case it
545 * returns the alternate string (or an empty string if the alternate string is
546 * NULL). It use is intended for limits reported in reports, where it's
547 * desirable not to display anything if there is no limit. Warning! it shares
548 * the same vector as ultoa_r().
549 */
550const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
551{
552 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
553}
554
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200555/* Trims the first "%f" float in a string to its minimum number of digits after
556 * the decimal point by trimming trailing zeroes, even dropping the decimal
557 * point if not needed. The string is in <buffer> of length <len>, and the
558 * number is expected to start at or after position <num_start> (the first
559 * point appearing there is considered). A NUL character is always placed at
560 * the end if some trimming occurs. The new buffer length is returned.
561 */
562size_t flt_trim(char *buffer, size_t num_start, size_t len)
563{
564 char *end = buffer + len;
565 char *p = buffer + num_start;
566 char *trim;
567
568 do {
569 if (p >= end)
570 return len;
571 trim = p++;
572 } while (*trim != '.');
573
574 /* For now <trim> is on the decimal point. Let's look for any other
575 * meaningful digit after it.
576 */
577 while (p < end) {
578 if (*p++ != '0')
579 trim = p;
580 }
581
582 if (trim < end)
583 *trim = 0;
584
585 return trim - buffer;
586}
587
Willy Tarreauae03d262021-05-08 07:35:00 +0200588/*
589 * This function simply returns a locally allocated string containing
590 * the ascii representation for number 'n' in decimal with useless trailing
591 * zeroes trimmed.
592 */
593char *ftoa_r(double n, char *buffer, int size)
594{
595 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
596 return buffer;
597}
598
Willy Tarreau588297f2014-06-16 15:16:40 +0200599/* returns a locally allocated string containing the quoted encoding of the
600 * input string. The output may be truncated to QSTR_SIZE chars, but it is
601 * guaranteed that the string will always be properly terminated. Quotes are
602 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
603 * always be at least 4 chars.
604 */
605const char *qstr(const char *str)
606{
607 char *ret = quoted_str[quoted_idx];
608 char *p, *end;
609
610 if (++quoted_idx >= NB_QSTR)
611 quoted_idx = 0;
612
613 p = ret;
614 end = ret + QSTR_SIZE;
615
616 *p++ = '"';
617
618 /* always keep 3 chars to support passing "" and the ending " */
619 while (*str && p < end - 3) {
620 if (*str == '"') {
621 *p++ = '"';
622 *p++ = '"';
623 }
624 else
625 *p++ = *str;
626 str++;
627 }
628 *p++ = '"';
629 return ret;
630}
631
Robert Tsai81ae1952007-12-05 10:47:29 +0100632/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200633 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
634 *
635 * It looks like this one would be a good candidate for inlining, but this is
636 * not interesting because it around 35 bytes long and often called multiple
637 * times within the same function.
638 */
639int ishex(char s)
640{
641 s -= '0';
642 if ((unsigned char)s <= 9)
643 return 1;
644 s -= 'A' - '0';
645 if ((unsigned char)s <= 5)
646 return 1;
647 s -= 'a' - 'A';
648 if ((unsigned char)s <= 5)
649 return 1;
650 return 0;
651}
652
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100653/* rounds <i> down to the closest value having max 2 digits */
654unsigned int round_2dig(unsigned int i)
655{
656 unsigned int mul = 1;
657
658 while (i >= 100) {
659 i /= 10;
660 mul *= 10;
661 }
662 return i * mul;
663}
664
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100665/*
666 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
667 * invalid character is found, a pointer to it is returned. If everything is
668 * fine, NULL is returned.
669 */
670const char *invalid_char(const char *name)
671{
672 if (!*name)
673 return name;
674
675 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100676 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100677 *name != '_' && *name != '-')
678 return name;
679 name++;
680 }
681 return NULL;
682}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200683
684/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200685 * Checks <name> for invalid characters. Valid chars are [_.-] and those
686 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200687 * If an invalid character is found, a pointer to it is returned.
688 * If everything is fine, NULL is returned.
689 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200690static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200691
692 if (!*name)
693 return name;
694
695 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100696 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200697 *name != '_' && *name != '-')
698 return name;
699
700 name++;
701 }
702
703 return NULL;
704}
705
706/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200707 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
708 * If an invalid character is found, a pointer to it is returned.
709 * If everything is fine, NULL is returned.
710 */
711const char *invalid_domainchar(const char *name) {
712 return __invalid_char(name, isalnum);
713}
714
715/*
716 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
717 * If an invalid character is found, a pointer to it is returned.
718 * If everything is fine, NULL is returned.
719 */
720const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200721 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200722}
723
724/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100726 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
727 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
728 * the function tries to guess the address family from the syntax. If the
729 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100730 * string is assumed to contain only an address, no port. The address can be a
731 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
732 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
733 * The return address will only have the address family and the address set,
734 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100735 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
736 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100737 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200738 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100739struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200740{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100741 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100742 /* max IPv6 length, including brackets and terminating NULL */
743 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100744 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100745
746 /* check IPv6 with square brackets */
747 if (str[0] == '[') {
748 size_t iplength = strlen(str);
749
750 if (iplength < 4) {
751 /* minimal size is 4 when using brackets "[::]" */
752 goto fail;
753 }
754 else if (iplength >= sizeof(tmpip)) {
755 /* IPv6 literal can not be larger than tmpip */
756 goto fail;
757 }
758 else {
759 if (str[iplength - 1] != ']') {
760 /* if address started with bracket, it should end with bracket */
761 goto fail;
762 }
763 else {
764 memcpy(tmpip, str + 1, iplength - 2);
765 tmpip[iplength - 2] = '\0';
766 str = tmpip;
767 }
768 }
769 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100770
Willy Tarreaufab5a432011-03-04 15:31:53 +0100771 /* Any IPv6 address */
772 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100773 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
774 sa->ss_family = AF_INET6;
775 else if (sa->ss_family != AF_INET6)
776 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100777 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100778 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100779 }
780
Willy Tarreau24709282013-03-10 21:32:12 +0100781 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100782 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100783 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
784 sa->ss_family = AF_INET;
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
789 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100790 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
791 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100792 sa->ss_family = AF_INET6;
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 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100798 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
799 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100800 sa->ss_family = AF_INET;
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
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100805 if (!resolve)
806 return NULL;
807
Emeric Brund30e9a12020-12-23 18:49:16 +0100808 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200809 return NULL;
810
David du Colombierd5f43282011-03-17 10:40:16 +0100811#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200812 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100813 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100814 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100815
816 memset(&result, 0, sizeof(result));
817 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100818 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100819 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200820 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100821 hints.ai_protocol = 0;
822
823 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100824 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
825 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100826 else if (sa->ss_family != result->ai_family) {
827 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100828 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100829 }
Willy Tarreau24709282013-03-10 21:32:12 +0100830
David du Colombierd5f43282011-03-17 10:40:16 +0100831 switch (result->ai_family) {
832 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100833 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100834 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100835 success = 1;
836 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100837 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100838 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100839 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100840 success = 1;
841 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100842 }
843 }
844
Sean Carey58ea0392013-02-15 23:39:18 +0100845 if (result)
846 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100847
848 if (success)
849 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100850 }
David du Colombierd5f43282011-03-17 10:40:16 +0100851#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200852 /* try to resolve an IPv4/IPv6 hostname */
853 he = gethostbyname(str);
854 if (he) {
855 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
856 sa->ss_family = he->h_addrtype;
857 else if (sa->ss_family != he->h_addrtype)
858 goto fail;
859
860 switch (sa->ss_family) {
861 case AF_INET:
862 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100863 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200864 return sa;
865 case AF_INET6:
866 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100867 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200868 return sa;
869 }
870 }
871
David du Colombierd5f43282011-03-17 10:40:16 +0100872 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100873 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100874 return NULL;
875}
876
877/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100878 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
879 * range or offset consisting in two integers that the caller will have to
880 * check to find the relevant input format. The following format are supported :
881 *
882 * String format | address | port | low | high
883 * addr | <addr> | 0 | 0 | 0
884 * addr: | <addr> | 0 | 0 | 0
885 * addr:port | <addr> | <port> | <port> | <port>
886 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
887 * addr:+port | <addr> | <port> | 0 | <port>
888 * addr:-port | <addr> |-<port> | <port> | 0
889 *
890 * The detection of a port range or increment by the caller is made by
891 * comparing <low> and <high>. If both are equal, then port 0 means no port
892 * was specified. The caller may pass NULL for <low> and <high> if it is not
893 * interested in retrieving port ranges.
894 *
895 * Note that <addr> above may also be :
896 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
897 * - "*" => family will be AF_INET and address will be INADDR_ANY
898 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
899 * - a host name => family and address will depend on host name resolving.
900 *
Willy Tarreau24709282013-03-10 21:32:12 +0100901 * A prefix may be passed in before the address above to force the family :
902 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
903 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
904 * - "unix@" => force address to be a path to a UNIX socket even if the
905 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200906 * - 'abns@' -> force address to belong to the abstract namespace (Linux
907 * only). These sockets are just like Unix sockets but without
908 * the need for an underlying file system. The address is a
909 * string. Technically it's like a Unix socket with a zero in
910 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100911 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100912 *
mildisff5d5102015-10-26 18:50:08 +0100913 * IPv6 addresses can be declared with or without square brackets. When using
914 * square brackets for IPv6 addresses, the port separator (colon) is optional.
915 * If not using square brackets, and in order to avoid any ambiguity with
916 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
917 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
918 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100919 *
920 * If <pfx> is non-null, it is used as a string prefix before any path-based
921 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100922 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200923 * if <fqdn> is non-null, it will be filled with :
924 * - a pointer to the FQDN of the server name to resolve if there's one, and
925 * that the caller will have to free(),
926 * - NULL if there was an explicit address that doesn't require resolution.
927 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200928 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
929 * still honored so it is possible for the caller to know whether a resolution
930 * failed by clearing this flag and checking if <fqdn> was filled, indicating
931 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200932 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100933 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200934 * the address when cast to sockaddr_in and the address family is
935 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200936 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200937 * The matching protocol will be set into <proto> if non-null.
938 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200939 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
940 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100941 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200942struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
943 struct protocol **proto, char **err,
944 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100945{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100946 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100947 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200948 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100949 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100950 char *port1, *port2;
951 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200952 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200953 int new_fd = -1;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200954 enum proto_type proto_type;
955 int ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100956
957 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200958 if (fqdn)
959 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200960
Willy Tarreaudad36a32013-03-11 01:20:04 +0100961 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100962 if (str2 == NULL) {
963 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100964 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100965 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200966
Willy Tarreau9f69f462015-09-08 16:01:25 +0200967 if (!*str2) {
968 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
969 goto out;
970 }
971
Willy Tarreau24709282013-03-10 21:32:12 +0100972 memset(&ss, 0, sizeof(ss));
973
Willy Tarreaue835bd82020-09-16 11:35:47 +0200974 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100975 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
Willy Tarreaue3b45182021-10-27 17:28:55 +0200976 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM))) {
977 proto_type = PROTO_TYPE_DGRAM;
978 ctrl_type = SOCK_DGRAM;
979 } else {
980 proto_type = PROTO_TYPE_STREAM;
981 ctrl_type = SOCK_STREAM;
982 }
Willy Tarreaue835bd82020-09-16 11:35:47 +0200983
984 if (strncmp(str2, "stream+", 7) == 0) {
985 str2 += 7;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200986 proto_type = PROTO_TYPE_STREAM;
987 ctrl_type = SOCK_STREAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200988 }
989 else if (strncmp(str2, "dgram+", 6) == 0) {
990 str2 += 6;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200991 proto_type = PROTO_TYPE_DGRAM;
992 ctrl_type = SOCK_DGRAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200993 }
994
Willy Tarreau24709282013-03-10 21:32:12 +0100995 if (strncmp(str2, "unix@", 5) == 0) {
996 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200997 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100998 ss.ss_family = AF_UNIX;
999 }
Emeric Brunce325c42021-04-02 17:05:09 +02001000 else if (strncmp(str2, "uxdg@", 5) == 0) {
1001 str2 += 5;
1002 abstract = 0;
1003 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001004 proto_type = PROTO_TYPE_DGRAM;
1005 ctrl_type = SOCK_DGRAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001006 }
1007 else if (strncmp(str2, "uxst@", 5) == 0) {
1008 str2 += 5;
1009 abstract = 0;
1010 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001011 proto_type = PROTO_TYPE_STREAM;
1012 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001013 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001014 else if (strncmp(str2, "abns@", 5) == 0) {
1015 str2 += 5;
1016 abstract = 1;
1017 ss.ss_family = AF_UNIX;
1018 }
Emeric Brunce325c42021-04-02 17:05:09 +02001019 else if (strncmp(str2, "ip@", 3) == 0) {
1020 str2 += 3;
1021 ss.ss_family = AF_UNSPEC;
1022 }
Willy Tarreau24709282013-03-10 21:32:12 +01001023 else if (strncmp(str2, "ipv4@", 5) == 0) {
1024 str2 += 5;
1025 ss.ss_family = AF_INET;
1026 }
1027 else if (strncmp(str2, "ipv6@", 5) == 0) {
1028 str2 += 5;
1029 ss.ss_family = AF_INET6;
1030 }
Emeric Brunce325c42021-04-02 17:05:09 +02001031 else if (strncmp(str2, "tcp4@", 5) == 0) {
1032 str2 += 5;
1033 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001034 proto_type = PROTO_TYPE_STREAM;
1035 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001036 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001037 else if (strncmp(str2, "udp4@", 5) == 0) {
1038 str2 += 5;
1039 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001040 proto_type = PROTO_TYPE_DGRAM;
1041 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001042 }
Emeric Brunce325c42021-04-02 17:05:09 +02001043 else if (strncmp(str2, "tcp6@", 5) == 0) {
1044 str2 += 5;
1045 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001046 proto_type = PROTO_TYPE_STREAM;
1047 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001048 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001049 else if (strncmp(str2, "udp6@", 5) == 0) {
1050 str2 += 5;
1051 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001052 proto_type = PROTO_TYPE_DGRAM;
1053 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001054 }
Emeric Brunce325c42021-04-02 17:05:09 +02001055 else if (strncmp(str2, "tcp@", 4) == 0) {
1056 str2 += 4;
1057 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001058 proto_type = PROTO_TYPE_STREAM;
1059 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001060 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001061 else if (strncmp(str2, "udp@", 4) == 0) {
1062 str2 += 4;
1063 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001064 proto_type = PROTO_TYPE_DGRAM;
1065 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001066 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001067 else if (strncmp(str2, "quic4@", 6) == 0) {
1068 str2 += 6;
1069 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001070 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001071 ctrl_type = SOCK_STREAM;
1072 }
1073 else if (strncmp(str2, "quic6@", 6) == 0) {
1074 str2 += 6;
1075 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001076 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001077 ctrl_type = SOCK_STREAM;
1078 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001079 else if (strncmp(str2, "fd@", 3) == 0) {
1080 str2 += 3;
1081 ss.ss_family = AF_CUST_EXISTING_FD;
1082 }
1083 else if (strncmp(str2, "sockpair@", 9) == 0) {
1084 str2 += 9;
1085 ss.ss_family = AF_CUST_SOCKPAIR;
1086 }
Willy Tarreau24709282013-03-10 21:32:12 +01001087 else if (*str2 == '/') {
1088 ss.ss_family = AF_UNIX;
1089 }
1090 else
1091 ss.ss_family = AF_UNSPEC;
1092
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001093 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001094 struct sockaddr_storage ss2;
1095 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001096 char *endptr;
1097
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001098 new_fd = strtol(str2, &endptr, 10);
1099 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001100 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1101 goto out;
1102 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001103
Willy Tarreaua215be22020-09-16 10:14:16 +02001104 /* just verify that it's a socket */
1105 addr_len = sizeof(ss2);
1106 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1107 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1108 goto out;
1109 }
1110
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001111 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1112 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001113 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001114 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001115 char *endptr;
1116
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001117 new_fd = strtol(str2, &endptr, 10);
1118 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001119 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001120 goto out;
1121 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001122
Willy Tarreau6edc7222020-09-15 17:41:56 +02001123 if (opts & PA_O_SOCKET_FD) {
1124 socklen_t addr_len;
1125 int type;
1126
1127 addr_len = sizeof(ss);
1128 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1129 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1130 goto out;
1131 }
1132
1133 addr_len = sizeof(type);
1134 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue3b45182021-10-27 17:28:55 +02001135 (type == SOCK_STREAM) != (proto_type == PROTO_TYPE_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001136 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1137 goto out;
1138 }
1139
1140 porta = portl = porth = get_host_port(&ss);
1141 } else if (opts & PA_O_RAW_FD) {
1142 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1143 ((struct sockaddr_in *)&ss)->sin_port = 0;
1144 } else {
1145 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1146 goto out;
1147 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001148 }
1149 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001150 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001151 int prefix_path_len;
1152 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001153 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001154
1155 /* complete unix socket path name during startup or soft-restart is
1156 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1157 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001158 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001159 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001160 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001161
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001162 adr_len = strlen(str2);
1163 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001164 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1165 goto out;
1166 }
1167
Willy Tarreauccfccef2014-05-10 01:49:15 +02001168 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001169 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001170 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001171 memcpy(un->sun_path, pfx, prefix_path_len);
1172 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001173 }
Willy Tarreau24709282013-03-10 21:32:12 +01001174 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001175 char *end = str2 + strlen(str2);
1176 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001177
mildisff5d5102015-10-26 18:50:08 +01001178 /* search for : or ] whatever comes first */
1179 for (chr = end-1; chr > str2; chr--) {
1180 if (*chr == ']' || *chr == ':')
1181 break;
1182 }
1183
1184 if (*chr == ':') {
1185 /* Found a colon before a closing-bracket, must be a port separator.
1186 * This guarantee backward compatibility.
1187 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001188 if (!(opts & PA_O_PORT_OK)) {
1189 memprintf(err, "port specification not permitted here in '%s'", str);
1190 goto out;
1191 }
mildisff5d5102015-10-26 18:50:08 +01001192 *chr++ = '\0';
1193 port1 = chr;
1194 }
1195 else {
1196 /* Either no colon and no closing-bracket
1197 * or directly ending with a closing-bracket.
1198 * However, no port.
1199 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001200 if (opts & PA_O_PORT_MAND) {
1201 memprintf(err, "missing port specification in '%s'", str);
1202 goto out;
1203 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001204 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001205 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001206
Willy Tarreau90807112020-02-25 08:16:33 +01001207 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001208 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001209 if (port2) {
1210 if (!(opts & PA_O_PORT_RANGE)) {
1211 memprintf(err, "port range not permitted here in '%s'", str);
1212 goto out;
1213 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001214 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001215 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001216 else
1217 port2 = port1;
1218 portl = atoi(port1);
1219 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001220
1221 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1222 memprintf(err, "invalid port '%s'", port1);
1223 goto out;
1224 }
1225
1226 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1227 memprintf(err, "invalid port '%s'", port2);
1228 goto out;
1229 }
1230
1231 if (portl > porth) {
1232 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1233 goto out;
1234 }
1235
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001236 porta = portl;
1237 }
1238 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001239 if (!(opts & PA_O_PORT_OFS)) {
1240 memprintf(err, "port offset not permitted here in '%s'", str);
1241 goto out;
1242 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001243 portl = atoi(port1 + 1);
1244 porta = -portl;
1245 }
1246 else if (*port1 == '+') { /* positive 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 porth = atoi(port1 + 1);
1252 porta = porth;
1253 }
1254 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001255 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001256 goto out;
1257 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001258 else if (opts & PA_O_PORT_MAND) {
1259 memprintf(err, "missing port specification in '%s'", str);
1260 goto out;
1261 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001262
1263 /* first try to parse the IP without resolving. If it fails, it
1264 * tells us we need to keep a copy of the FQDN to resolve later
1265 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001266 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001267 */
1268 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001269 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1270 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001271 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1272 goto out;
1273 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001274
Willy Tarreauceccdd72016-11-02 22:27:10 +01001275 if (fqdn) {
1276 if (str2 != back)
1277 memmove(back, str2, strlen(str2) + 1);
1278 *fqdn = back;
1279 back = NULL;
1280 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001281 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001282 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001283 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001284
Willy Tarreaue835bd82020-09-16 11:35:47 +02001285 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001286 memprintf(err, "stream-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001287 goto out;
1288 }
1289 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001290 memprintf(err, "dgram-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001291 goto out;
1292 }
1293
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001294 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001295 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001296 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1297 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001298 * in which case the address is not known yet (this is only
1299 * for servers actually).
1300 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001301 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreaue3b45182021-10-27 17:28:55 +02001302 proto_type,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001303 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001304
Emeric Brun26754902021-04-07 14:26:44 +02001305 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001306 memprintf(err, "unsupported %s protocol for %s family %d address '%s'%s",
Willy Tarreau2b049b82022-05-20 17:28:30 +02001307 (ctrl_type == SOCK_DGRAM) ? "datagram" : "stream",
1308 (proto_type == PROTO_TYPE_DGRAM) ? "datagram" : "stream",
1309 ss.ss_family,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001310 str,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001311#ifndef USE_QUIC
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001312 (ctrl_type == SOCK_STREAM && proto_type == PROTO_TYPE_DGRAM)
1313 ? "; QUIC is not compiled in if this is what you were looking for."
1314 : ""
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001315#else
1316 ""
1317#endif
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001318 );
Willy Tarreau5fc93282020-09-16 18:25:03 +02001319 goto out;
1320 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001321
1322 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1323 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1324 goto out;
1325 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001326 }
1327
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001328 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001329 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001330 if (port)
1331 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001332 if (low)
1333 *low = portl;
1334 if (high)
1335 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001336 if (fd)
1337 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001338 if (proto)
1339 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001340 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001341 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001342}
1343
Thayne McCombs92149f92020-11-20 01:28:26 -07001344/* converts <addr> and <port> into a string representation of the address and port. This is sort
1345 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1346 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1347 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1348 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1349 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1350 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1351 *
1352 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1353 */
1354char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1355{
1356 char buffer[INET6_ADDRSTRLEN];
1357 char *out = NULL;
1358 const void *ptr;
1359 const char *path;
1360
1361 switch (addr->ss_family) {
1362 case AF_INET:
1363 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1364 break;
1365 case AF_INET6:
1366 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1367 break;
1368 case AF_UNIX:
1369 path = ((struct sockaddr_un *)addr)->sun_path;
1370 if (path[0] == '\0') {
1371 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1372 return memprintf(&out, "abns@%.*s", max_length, path+1);
1373 } else {
1374 return strdup(path);
1375 }
1376 case AF_CUST_SOCKPAIR:
1377 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1378 default:
1379 return NULL;
1380 }
Tim Duesterhus22535a52022-05-23 09:30:49 +02001381 if (inet_ntop(addr->ss_family, ptr, buffer, sizeof(buffer)) == NULL) {
1382 BUG_ON(errno == ENOSPC);
1383 return NULL;
1384 }
Thayne McCombs92149f92020-11-20 01:28:26 -07001385 if (map_ports)
1386 return memprintf(&out, "%s:%+d", buffer, port);
1387 else
1388 return memprintf(&out, "%s:%d", buffer, port);
1389}
1390
1391
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001392/* converts <str> to a struct in_addr containing a network mask. It can be
1393 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001394 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001395 */
1396int str2mask(const char *str, struct in_addr *mask)
1397{
1398 if (strchr(str, '.') != NULL) { /* dotted notation */
1399 if (!inet_pton(AF_INET, str, mask))
1400 return 0;
1401 }
1402 else { /* mask length */
1403 char *err;
1404 unsigned long len = strtol(str, &err, 10);
1405
1406 if (!*str || (err && *err) || (unsigned)len > 32)
1407 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001408
1409 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001410 }
1411 return 1;
1412}
1413
Tim Duesterhus47185172018-01-25 16:24:49 +01001414/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001415 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001416 * if the conversion succeeds otherwise zero.
1417 */
1418int str2mask6(const char *str, struct in6_addr *mask)
1419{
1420 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1421 if (!inet_pton(AF_INET6, str, mask))
1422 return 0;
1423 }
1424 else { /* mask length */
1425 char *err;
1426 unsigned long len = strtol(str, &err, 10);
1427
1428 if (!*str || (err && *err) || (unsigned)len > 128)
1429 return 0;
1430
1431 len2mask6(len, mask);
1432 }
1433 return 1;
1434}
1435
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001436/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1437 * succeeds otherwise zero.
1438 */
1439int cidr2dotted(int cidr, struct in_addr *mask) {
1440
1441 if (cidr < 0 || cidr > 32)
1442 return 0;
1443
1444 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1445 return 1;
1446}
1447
Thierry Fournier70473a52016-02-17 17:12:14 +01001448/* Convert mask from bit length form to in_addr form.
1449 * This function never fails.
1450 */
1451void len2mask4(int len, struct in_addr *addr)
1452{
1453 if (len >= 32) {
1454 addr->s_addr = 0xffffffff;
1455 return;
1456 }
1457 if (len <= 0) {
1458 addr->s_addr = 0x00000000;
1459 return;
1460 }
1461 addr->s_addr = 0xffffffff << (32 - len);
1462 addr->s_addr = htonl(addr->s_addr);
1463}
1464
1465/* Convert mask from bit length form to in6_addr form.
1466 * This function never fails.
1467 */
1468void len2mask6(int len, struct in6_addr *addr)
1469{
1470 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1471 len -= 32;
1472 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1473 len -= 32;
1474 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1475 len -= 32;
1476 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1477}
1478
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001479/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001480 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001481 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001482 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001483 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1484 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001485int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001486{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001487 __label__ out_free, out_err;
1488 char *c, *s;
1489 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001490
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001491 s = strdup(str);
1492 if (!s)
1493 return 0;
1494
Willy Tarreaubaaee002006-06-26 02:48:02 +02001495 memset(mask, 0, sizeof(*mask));
1496 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001497
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001498 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001499 *c++ = '\0';
1500 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001501 if (!str2mask(c, mask))
1502 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001503 }
1504 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001505 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001506 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001507 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001508 struct hostent *he;
1509
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001510 if (!resolve)
1511 goto out_err;
1512
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001513 if ((he = gethostbyname(s)) == NULL) {
1514 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001515 }
1516 else
1517 *addr = *(struct in_addr *) *(he->h_addr_list);
1518 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001519
1520 ret_val = 1;
1521 out_free:
1522 free(s);
1523 return ret_val;
1524 out_err:
1525 ret_val = 0;
1526 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001527}
1528
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001529
1530/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001531 * converts <str> to two struct in6_addr* which must be pre-allocated.
1532 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001533 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001534 * Returns 1 if OK, 0 if error.
1535 */
1536int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1537{
1538 char *c, *s;
1539 int ret_val = 0;
1540 char *err;
1541 unsigned long len = 128;
1542
1543 s = strdup(str);
1544 if (!s)
1545 return 0;
1546
1547 memset(mask, 0, sizeof(*mask));
1548 memset(addr, 0, sizeof(*addr));
1549
1550 if ((c = strrchr(s, '/')) != NULL) {
1551 *c++ = '\0'; /* c points to the mask */
1552 if (!*c)
1553 goto out_free;
1554
1555 len = strtoul(c, &err, 10);
1556 if ((err && *err) || (unsigned)len > 128)
1557 goto out_free;
1558 }
1559 *mask = len; /* OK we have a valid mask in <len> */
1560
1561 if (!inet_pton(AF_INET6, s, addr))
1562 goto out_free;
1563
1564 ret_val = 1;
1565 out_free:
1566 free(s);
1567 return ret_val;
1568}
1569
1570
1571/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001572 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1573 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1574 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001575 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001576int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001577{
1578 int saw_digit, octets, ch;
1579 u_char tmp[4], *tp;
1580 const char *cp = addr;
1581
1582 saw_digit = 0;
1583 octets = 0;
1584 *(tp = tmp) = 0;
1585
1586 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001587 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001588 if (digit > 9 && ch != '.')
1589 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001590 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001591 if (digit <= 9) {
1592 u_int new = *tp * 10 + digit;
1593 if (new > 255)
1594 return 0;
1595 *tp = new;
1596 if (!saw_digit) {
1597 if (++octets > 4)
1598 return 0;
1599 saw_digit = 1;
1600 }
1601 } else if (ch == '.' && saw_digit) {
1602 if (octets == 4)
1603 return 0;
1604 *++tp = 0;
1605 saw_digit = 0;
1606 } else
1607 return 0;
1608 }
1609
1610 if (octets < 4)
1611 return 0;
1612
1613 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001614 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001615}
1616
1617/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001618 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001619 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001620 * the hostname. Actually only http and https are supported. <out> can be NULL.
1621 * This function returns the consumed length. It is useful if you parse complete
1622 * url like http://host:port/path, because the consumed length corresponds to
1623 * the first character of the path. If the conversion fails, it returns -1.
1624 *
1625 * This function tries to resolve the DNS name if haproxy is in starting mode.
1626 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001627 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001628int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001629{
1630 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001631 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001632 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001633 unsigned long long int http_code = 0;
1634 int default_port;
1635 struct hostent *he;
1636 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001637
1638 /* Firstly, try to find :// pattern */
1639 while (curr < url+ulen && url_code != 0x3a2f2f) {
1640 url_code = ((url_code & 0xffff) << 8);
1641 url_code += (unsigned char)*curr++;
1642 }
1643
1644 /* Secondly, if :// pattern is found, verify parsed stuff
1645 * before pattern is matching our http pattern.
1646 * If so parse ip address and port in uri.
1647 *
1648 * WARNING: Current code doesn't support dynamic async dns resolver.
1649 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001650 if (url_code != 0x3a2f2f)
1651 return -1;
1652
1653 /* Copy scheme, and utrn to lower case. */
1654 while (cp < curr - 3)
1655 http_code = (http_code << 8) + *cp++;
1656 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001657
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001658 /* HTTP or HTTPS url matching */
1659 if (http_code == 0x2020202068747470ULL) {
1660 default_port = 80;
1661 if (out)
1662 out->scheme = SCH_HTTP;
1663 }
1664 else if (http_code == 0x2020206874747073ULL) {
1665 default_port = 443;
1666 if (out)
1667 out->scheme = SCH_HTTPS;
1668 }
1669 else
1670 return -1;
1671
1672 /* If the next char is '[', the host address is IPv6. */
1673 if (*curr == '[') {
1674 curr++;
1675
1676 /* Check trash size */
1677 if (trash.size < ulen)
1678 return -1;
1679
1680 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001681 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001682 for (end = curr;
1683 end < url + ulen && *end != ']';
1684 end++, p++)
1685 *p = *end;
1686 if (*end != ']')
1687 return -1;
1688 *p = '\0';
1689
1690 /* Update out. */
1691 if (out) {
1692 out->host = curr;
1693 out->host_len = end - curr;
1694 }
1695
1696 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001697 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001698 return -1;
1699 end++;
1700
1701 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001702 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001703 end++;
1704 default_port = read_uint(&end, url + ulen);
1705 }
1706 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1707 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1708 return end - url;
1709 }
1710 else {
William Lallemand8a913742022-02-18 16:13:12 +01001711 /* we need to copy the string into the trash because url2ipv4
1712 * needs a \0 at the end of the string */
1713 if (trash.size < ulen)
1714 return -1;
1715
1716 memcpy(trash.area, curr, ulen - (curr - url));
1717 trash.area[ulen - (curr - url)] = '\0';
1718
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001719 /* We are looking for IP address. If you want to parse and
1720 * resolve hostname found in url, you can use str2sa_range(), but
1721 * be warned this can slow down global daemon performances
1722 * while handling lagging dns responses.
1723 */
William Lallemand8a913742022-02-18 16:13:12 +01001724 ret = url2ipv4(trash.area, &((struct sockaddr_in *)addr)->sin_addr);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001725 if (ret) {
1726 /* Update out. */
1727 if (out) {
1728 out->host = curr;
1729 out->host_len = ret;
1730 }
1731
William Lallemandb938b772022-03-24 21:59:03 +01001732 curr += ret;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001733
1734 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001735 if (curr < url + ulen && *curr == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001736 curr++;
1737 default_port = read_uint(&curr, url + ulen);
1738 }
1739 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1740
1741 /* Set family. */
1742 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1743 return curr - url;
1744 }
1745 else if (global.mode & MODE_STARTING) {
1746 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1747 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001748 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001749
1750 /* look for : or / or end */
1751 for (end = curr;
1752 end < url + ulen && *end != '/' && *end != ':';
1753 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001754 memcpy(trash.area, curr, end - curr);
1755 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001756
1757 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001758 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001759 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001760 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001761
1762 /* Update out. */
1763 if (out) {
1764 out->host = curr;
1765 out->host_len = end - curr;
1766 }
1767
1768 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001769 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001770 end++;
1771 default_port = read_uint(&end, url + ulen);
1772 }
1773
1774 /* Copy IP address, set port and family. */
1775 switch (he->h_addrtype) {
1776 case AF_INET:
1777 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1778 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1779 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1780 return end - url;
1781
1782 case AF_INET6:
1783 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1784 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1785 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1786 return end - url;
1787 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001788 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001789 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001790 return -1;
1791}
1792
Willy Tarreau631f01c2011-09-05 00:36:48 +02001793/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1794 * address family is returned so that it's easy for the caller to adapt to the
1795 * output format. Zero is returned if the address family is not supported. -1
1796 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1797 * supported.
1798 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001799int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001800{
1801
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001802 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001803
1804 if (size < 5)
1805 return 0;
1806 *str = '\0';
1807
1808 switch (addr->ss_family) {
1809 case AF_INET:
1810 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1811 break;
1812 case AF_INET6:
1813 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1814 break;
1815 case AF_UNIX:
1816 memcpy(str, "unix", 5);
1817 return addr->ss_family;
1818 default:
1819 return 0;
1820 }
1821
1822 if (inet_ntop(addr->ss_family, ptr, str, size))
1823 return addr->ss_family;
1824
1825 /* failed */
1826 return -1;
1827}
1828
Simon Horman75ab8bd2014-06-16 09:39:41 +09001829/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1830 * address family is returned so that it's easy for the caller to adapt to the
1831 * output format. Zero is returned if the address family is not supported. -1
1832 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1833 * supported.
1834 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001835int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001836{
1837
1838 uint16_t port;
1839
1840
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001841 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001842 return 0;
1843 *str = '\0';
1844
1845 switch (addr->ss_family) {
1846 case AF_INET:
1847 port = ((struct sockaddr_in *)addr)->sin_port;
1848 break;
1849 case AF_INET6:
1850 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1851 break;
1852 case AF_UNIX:
1853 memcpy(str, "unix", 5);
1854 return addr->ss_family;
1855 default:
1856 return 0;
1857 }
1858
1859 snprintf(str, size, "%u", ntohs(port));
1860 return addr->ss_family;
1861}
1862
Willy Tarreau16e01562016-08-09 16:46:18 +02001863/* check if the given address is local to the system or not. It will return
1864 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1865 * it is. We don't want to iterate over all interfaces for this (and it is not
1866 * portable). So instead we try to bind in UDP to this address on a free non
1867 * privileged port and to connect to the same address, port 0 (connect doesn't
1868 * care). If it succeeds, we own the address. Note that non-inet addresses are
1869 * considered local since they're most likely AF_UNIX.
1870 */
1871int addr_is_local(const struct netns_entry *ns,
1872 const struct sockaddr_storage *orig)
1873{
1874 struct sockaddr_storage addr;
1875 int result;
1876 int fd;
1877
1878 if (!is_inet_addr(orig))
1879 return 1;
1880
1881 memcpy(&addr, orig, sizeof(addr));
1882 set_host_port(&addr, 0);
1883
1884 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1885 if (fd < 0)
1886 return -1;
1887
1888 result = -1;
1889 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1890 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1891 result = 0; // fail, non-local address
1892 else
1893 result = 1; // success, local address
1894 }
1895 else {
1896 if (errno == EADDRNOTAVAIL)
1897 result = 0; // definitely not local :-)
1898 }
1899 close(fd);
1900
1901 return result;
1902}
1903
Willy Tarreaubaaee002006-06-26 02:48:02 +02001904/* will try to encode the string <string> replacing all characters tagged in
1905 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1906 * prefixed by <escape>, and will store the result between <start> (included)
1907 * and <stop> (excluded), and will always terminate the string with a '\0'
1908 * before <stop>. The position of the '\0' is returned if the conversion
1909 * completes. If bytes are missing between <start> and <stop>, then the
1910 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1911 * cannot even be stored so we return <start> without writing the 0.
1912 * The input string must also be zero-terminated.
1913 */
1914const char hextab[16] = "0123456789ABCDEF";
1915char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001916 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001917 const char *string)
1918{
1919 if (start < stop) {
1920 stop--; /* reserve one byte for the final '\0' */
1921 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001922 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001923 *start++ = *string;
1924 else {
1925 if (start + 3 >= stop)
1926 break;
1927 *start++ = escape;
1928 *start++ = hextab[(*string >> 4) & 15];
1929 *start++ = hextab[*string & 15];
1930 }
1931 string++;
1932 }
1933 *start = '\0';
1934 }
1935 return start;
1936}
1937
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001938/*
1939 * Same behavior as encode_string() above, except that it encodes chunk
1940 * <chunk> instead of a string.
1941 */
1942char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001943 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001944 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001945{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001946 char *str = chunk->area;
1947 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001948
1949 if (start < stop) {
1950 stop--; /* reserve one byte for the final '\0' */
1951 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001952 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001953 *start++ = *str;
1954 else {
1955 if (start + 3 >= stop)
1956 break;
1957 *start++ = escape;
1958 *start++ = hextab[(*str >> 4) & 15];
1959 *start++ = hextab[*str & 15];
1960 }
1961 str++;
1962 }
1963 *start = '\0';
1964 }
1965 return start;
1966}
1967
Dragan Dosen0edd1092016-02-12 13:23:02 +01001968/*
1969 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001970 * character. The input <string> must be zero-terminated. The result will
1971 * be stored between <start> (included) and <stop> (excluded). This
1972 * function will always try to terminate the resulting string with a '\0'
1973 * before <stop>, and will return its position if the conversion
1974 * completes.
1975 */
1976char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001977 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001978 const char *string)
1979{
1980 if (start < stop) {
1981 stop--; /* reserve one byte for the final '\0' */
1982 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001983 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001984 *start++ = *string;
1985 else {
1986 if (start + 2 >= stop)
1987 break;
1988 *start++ = escape;
1989 *start++ = *string;
1990 }
1991 string++;
1992 }
1993 *start = '\0';
1994 }
1995 return start;
1996}
1997
1998/*
1999 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01002000 * character. <chunk> contains the input to be escaped. The result will be
2001 * stored between <start> (included) and <stop> (excluded). The function
2002 * will always try to terminate the resulting string with a '\0' before
2003 * <stop>, and will return its position if the conversion completes.
2004 */
2005char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02002006 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02002007 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01002008{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002009 char *str = chunk->area;
2010 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01002011
2012 if (start < stop) {
2013 stop--; /* reserve one byte for the final '\0' */
2014 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02002015 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01002016 *start++ = *str;
2017 else {
2018 if (start + 2 >= stop)
2019 break;
2020 *start++ = escape;
2021 *start++ = *str;
2022 }
2023 str++;
2024 }
2025 *start = '\0';
2026 }
2027 return start;
2028}
2029
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002030/* Check a string for using it in a CSV output format. If the string contains
2031 * one of the following four char <">, <,>, CR or LF, the string is
2032 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2033 * <str> is the input string to be escaped. The function assumes that
2034 * the input string is null-terminated.
2035 *
2036 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002037 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002038 * format.
2039 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002040 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002041 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002042 * If <quote> is 1, the converter puts the quotes only if any reserved character
2043 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002044 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002045 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002046 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002047 * The function returns the converted string on its output. If an error
2048 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002049 * for using the function directly as printf() argument.
2050 *
2051 * If the output buffer is too short to contain the input string, the result
2052 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002053 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002054 * This function appends the encoding to the existing output chunk, and it
2055 * guarantees that it starts immediately at the first available character of
2056 * the chunk. Please use csv_enc() instead if you want to replace the output
2057 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002058 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002059const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002060{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002061 char *end = output->area + output->size;
2062 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002063 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002064
Willy Tarreaub631c292016-01-08 10:04:08 +01002065 if (quote == 1) {
2066 /* automatic quoting: first verify if we'll have to quote the string */
2067 if (!strpbrk(str, "\n\r,\""))
2068 quote = 0;
2069 }
2070
2071 if (quote)
2072 *ptr++ = '"';
2073
Willy Tarreau898529b2016-01-06 18:07:04 +01002074 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2075 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002076 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002077 ptr++;
2078 if (ptr >= end - 2) {
2079 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002080 break;
2081 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002082 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002083 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002084 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002085 str++;
2086 }
2087
Willy Tarreaub631c292016-01-08 10:04:08 +01002088 if (quote)
2089 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002090
Willy Tarreau898529b2016-01-06 18:07:04 +01002091 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002092 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002093 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002094}
2095
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002096/* Decode an URL-encoded string in-place. The resulting string might
2097 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002098 * aborted, the string is truncated before the issue and a negative value is
2099 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002100 * If the 'in_form' argument is non-nul the string is assumed to be part of
2101 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2102 * turned to a space. If it's zero, this will only be done after a question
2103 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002104 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002105int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002106{
2107 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002108 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002109
2110 in = string;
2111 out = string;
2112 while (*in) {
2113 switch (*in) {
2114 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002115 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002116 break;
2117 case '%' :
2118 if (!ishex(in[1]) || !ishex(in[2]))
2119 goto end;
2120 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2121 in += 2;
2122 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002123 case '?':
2124 in_form = 1;
2125 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002126 default:
2127 *out++ = *in;
2128 break;
2129 }
2130 in++;
2131 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002132 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002133 end:
2134 *out = 0;
2135 return ret;
2136}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002137
Willy Tarreau6911fa42007-03-04 18:06:08 +01002138unsigned int str2ui(const char *s)
2139{
2140 return __str2ui(s);
2141}
2142
2143unsigned int str2uic(const char *s)
2144{
2145 return __str2uic(s);
2146}
2147
2148unsigned int strl2ui(const char *s, int len)
2149{
2150 return __strl2ui(s, len);
2151}
2152
2153unsigned int strl2uic(const char *s, int len)
2154{
2155 return __strl2uic(s, len);
2156}
2157
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002158unsigned int read_uint(const char **s, const char *end)
2159{
2160 return __read_uint(s, end);
2161}
2162
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002163/* This function reads an unsigned integer from the string pointed to by <s> and
2164 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2165 * function automatically stops at <end>. If the number overflows, the 2^64-1
2166 * value is returned.
2167 */
2168unsigned long long int read_uint64(const char **s, const char *end)
2169{
2170 const char *ptr = *s;
2171 unsigned long long int i = 0, tmp;
2172 unsigned int j;
2173
2174 while (ptr < end) {
2175
2176 /* read next char */
2177 j = *ptr - '0';
2178 if (j > 9)
2179 goto read_uint64_end;
2180
2181 /* add char to the number and check overflow. */
2182 tmp = i * 10;
2183 if (tmp / 10 != i) {
2184 i = ULLONG_MAX;
2185 goto read_uint64_eat;
2186 }
2187 if (ULLONG_MAX - tmp < j) {
2188 i = ULLONG_MAX;
2189 goto read_uint64_eat;
2190 }
2191 i = tmp + j;
2192 ptr++;
2193 }
2194read_uint64_eat:
2195 /* eat each numeric char */
2196 while (ptr < end) {
2197 if ((unsigned int)(*ptr - '0') > 9)
2198 break;
2199 ptr++;
2200 }
2201read_uint64_end:
2202 *s = ptr;
2203 return i;
2204}
2205
2206/* This function reads an integer from the string pointed to by <s> and returns
2207 * it. The <s> pointer is adjusted to point to the first unread char. The function
2208 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2209 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2210 * returned.
2211 */
2212long long int read_int64(const char **s, const char *end)
2213{
2214 unsigned long long int i = 0;
2215 int neg = 0;
2216
2217 /* Look for minus char. */
2218 if (**s == '-') {
2219 neg = 1;
2220 (*s)++;
2221 }
2222 else if (**s == '+')
2223 (*s)++;
2224
2225 /* convert as positive number. */
2226 i = read_uint64(s, end);
2227
2228 if (neg) {
2229 if (i > 0x8000000000000000ULL)
2230 return LLONG_MIN;
2231 return -i;
2232 }
2233 if (i > 0x7fffffffffffffffULL)
2234 return LLONG_MAX;
2235 return i;
2236}
2237
Willy Tarreau6911fa42007-03-04 18:06:08 +01002238/* This one is 7 times faster than strtol() on athlon with checks.
2239 * It returns the value of the number composed of all valid digits read,
2240 * and can process negative numbers too.
2241 */
2242int strl2ic(const char *s, int len)
2243{
2244 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002245 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002246
2247 if (len > 0) {
2248 if (*s != '-') {
2249 /* positive number */
2250 while (len-- > 0) {
2251 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002252 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002253 if (j > 9)
2254 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002255 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002256 }
2257 } else {
2258 /* negative number */
2259 s++;
2260 while (--len > 0) {
2261 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002262 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002263 if (j > 9)
2264 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002265 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002266 }
2267 }
2268 }
2269 return i;
2270}
2271
2272
2273/* This function reads exactly <len> chars from <s> and converts them to a
2274 * signed integer which it stores into <ret>. It accurately detects any error
2275 * (truncated string, invalid chars, overflows). It is meant to be used in
2276 * applications designed for hostile environments. It returns zero when the
2277 * number has successfully been converted, non-zero otherwise. When an error
2278 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2279 * faster than strtol().
2280 */
2281int strl2irc(const char *s, int len, int *ret)
2282{
2283 int i = 0;
2284 int j;
2285
2286 if (!len)
2287 return 1;
2288
2289 if (*s != '-') {
2290 /* positive number */
2291 while (len-- > 0) {
2292 j = (*s++) - '0';
2293 if (j > 9) return 1; /* invalid char */
2294 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2295 i = i * 10;
2296 if (i + j < i) return 1; /* check for addition overflow */
2297 i = i + j;
2298 }
2299 } else {
2300 /* negative number */
2301 s++;
2302 while (--len > 0) {
2303 j = (*s++) - '0';
2304 if (j > 9) return 1; /* invalid char */
2305 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2306 i = i * 10;
2307 if (i - j > i) return 1; /* check for subtract overflow */
2308 i = i - j;
2309 }
2310 }
2311 *ret = i;
2312 return 0;
2313}
2314
2315
2316/* This function reads exactly <len> chars from <s> and converts them to a
2317 * signed integer which it stores into <ret>. It accurately detects any error
2318 * (truncated string, invalid chars, overflows). It is meant to be used in
2319 * applications designed for hostile environments. It returns zero when the
2320 * number has successfully been converted, non-zero otherwise. When an error
2321 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002322 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002323 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002324
2325int strl2llrc(const char *s, int len, long long *ret)
2326{
2327 long long i = 0;
2328 int j;
2329
2330 if (!len)
2331 return 1;
2332
2333 if (*s != '-') {
2334 /* positive number */
2335 while (len-- > 0) {
2336 j = (*s++) - '0';
2337 if (j > 9) return 1; /* invalid char */
2338 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2339 i = i * 10LL;
2340 if (i + j < i) return 1; /* check for addition overflow */
2341 i = i + j;
2342 }
2343 } else {
2344 /* negative number */
2345 s++;
2346 while (--len > 0) {
2347 j = (*s++) - '0';
2348 if (j > 9) return 1; /* invalid char */
2349 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2350 i = i * 10LL;
2351 if (i - j > i) return 1; /* check for subtract overflow */
2352 i = i - j;
2353 }
2354 }
2355 *ret = i;
2356 return 0;
2357}
2358
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002359/* This function is used with pat_parse_dotted_ver(). It converts a string
2360 * composed by two number separated by a dot. Each part must contain in 16 bits
2361 * because internally they will be represented as a 32-bit quantity stored in
2362 * a 64-bit integer. It returns zero when the number has successfully been
2363 * converted, non-zero otherwise. When an error is returned, the <ret> value
2364 * is left untouched.
2365 *
2366 * "1.3" -> 0x0000000000010003
2367 * "65535.65535" -> 0x00000000ffffffff
2368 */
2369int strl2llrc_dotted(const char *text, int len, long long *ret)
2370{
2371 const char *end = &text[len];
2372 const char *p;
2373 long long major, minor;
2374
2375 /* Look for dot. */
2376 for (p = text; p < end; p++)
2377 if (*p == '.')
2378 break;
2379
2380 /* Convert major. */
2381 if (strl2llrc(text, p - text, &major) != 0)
2382 return 1;
2383
2384 /* Check major. */
2385 if (major >= 65536)
2386 return 1;
2387
2388 /* Convert minor. */
2389 minor = 0;
2390 if (p < end)
2391 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2392 return 1;
2393
2394 /* Check minor. */
2395 if (minor >= 65536)
2396 return 1;
2397
2398 /* Compose value. */
2399 *ret = (major << 16) | (minor & 0xffff);
2400 return 0;
2401}
2402
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002403/* This function parses a time value optionally followed by a unit suffix among
2404 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2405 * expected by the caller. The computation does its best to avoid overflows.
2406 * The value is returned in <ret> if everything is fine, and a NULL is returned
2407 * by the function. In case of error, a pointer to the error is returned and
2408 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002409 * Values resulting in values larger than or equal to 2^31 after conversion are
2410 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2411 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002412 */
2413const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2414{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002415 unsigned long long imult, idiv;
2416 unsigned long long omult, odiv;
2417 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002418 const char *str = text;
2419
2420 if (!isdigit((unsigned char)*text))
2421 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002422
2423 omult = odiv = 1;
2424
2425 switch (unit_flags & TIME_UNIT_MASK) {
2426 case TIME_UNIT_US: omult = 1000000; break;
2427 case TIME_UNIT_MS: omult = 1000; break;
2428 case TIME_UNIT_S: break;
2429 case TIME_UNIT_MIN: odiv = 60; break;
2430 case TIME_UNIT_HOUR: odiv = 3600; break;
2431 case TIME_UNIT_DAY: odiv = 86400; break;
2432 default: break;
2433 }
2434
2435 value = 0;
2436
2437 while (1) {
2438 unsigned int j;
2439
2440 j = *text - '0';
2441 if (j > 9)
2442 break;
2443 text++;
2444 value *= 10;
2445 value += j;
2446 }
2447
2448 imult = idiv = 1;
2449 switch (*text) {
2450 case '\0': /* no unit = default unit */
2451 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002452 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002453 case 's': /* second = unscaled unit */
2454 break;
2455 case 'u': /* microsecond : "us" */
2456 if (text[1] == 's') {
2457 idiv = 1000000;
2458 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002459 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002460 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002461 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002462 case 'm': /* millisecond : "ms" or minute: "m" */
2463 if (text[1] == 's') {
2464 idiv = 1000;
2465 text++;
2466 } else
2467 imult = 60;
2468 break;
2469 case 'h': /* hour : "h" */
2470 imult = 3600;
2471 break;
2472 case 'd': /* day : "d" */
2473 imult = 86400;
2474 break;
2475 default:
2476 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002477 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002478 if (*(++text) != '\0') {
2479 ha_warning("unexpected character '%c' after the timer value '%s', only "
2480 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2481 " This will be reported as an error in next versions.\n", *text, str);
2482 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002483
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002484 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002485 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2486 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2487 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2488 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2489
Willy Tarreau9faebe32019-06-07 19:00:37 +02002490 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2491 if (result >= 0x80000000)
2492 return PARSE_TIME_OVER;
2493 if (!result && value)
2494 return PARSE_TIME_UNDER;
2495 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002496 return NULL;
2497}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002498
Emeric Brun39132b22010-01-04 14:57:24 +01002499/* this function converts the string starting at <text> to an unsigned int
2500 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002501 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002502 */
2503const char *parse_size_err(const char *text, unsigned *ret) {
2504 unsigned value = 0;
2505
Christopher Faulet82635a02020-12-11 09:30:45 +01002506 if (!isdigit((unsigned char)*text))
2507 return text;
2508
Emeric Brun39132b22010-01-04 14:57:24 +01002509 while (1) {
2510 unsigned int j;
2511
2512 j = *text - '0';
2513 if (j > 9)
2514 break;
2515 if (value > ~0U / 10)
2516 return text;
2517 value *= 10;
2518 if (value > (value + j))
2519 return text;
2520 value += j;
2521 text++;
2522 }
2523
2524 switch (*text) {
2525 case '\0':
2526 break;
2527 case 'K':
2528 case 'k':
2529 if (value > ~0U >> 10)
2530 return text;
2531 value = value << 10;
2532 break;
2533 case 'M':
2534 case 'm':
2535 if (value > ~0U >> 20)
2536 return text;
2537 value = value << 20;
2538 break;
2539 case 'G':
2540 case 'g':
2541 if (value > ~0U >> 30)
2542 return text;
2543 value = value << 30;
2544 break;
2545 default:
2546 return text;
2547 }
2548
Godbach58048a22015-01-28 17:36:16 +08002549 if (*text != '\0' && *++text != '\0')
2550 return text;
2551
Emeric Brun39132b22010-01-04 14:57:24 +01002552 *ret = value;
2553 return NULL;
2554}
2555
Willy Tarreau126d4062013-12-03 17:50:47 +01002556/*
2557 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002558 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002559 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002560 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002561 */
2562int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2563{
2564 int len;
2565 const char *p = source;
2566 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002567 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002568
2569 len = strlen(source);
2570 if (len % 2) {
2571 memprintf(err, "an even number of hex digit is expected");
2572 return 0;
2573 }
2574
2575 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002576
Willy Tarreau126d4062013-12-03 17:50:47 +01002577 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002578 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002579 if (!*binstr) {
2580 memprintf(err, "out of memory while loading string pattern");
2581 return 0;
2582 }
2583 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002584 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002585 else {
2586 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002587 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002588 len, *binstrlen);
2589 return 0;
2590 }
2591 alloc = 0;
2592 }
2593 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002594
2595 i = j = 0;
2596 while (j < len) {
2597 if (!ishex(p[i++]))
2598 goto bad_input;
2599 if (!ishex(p[i++]))
2600 goto bad_input;
2601 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2602 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002603 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002604
2605bad_input:
2606 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002607 if (alloc)
2608 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002609 return 0;
2610}
2611
Willy Tarreau946ba592009-05-10 15:41:18 +02002612/* copies at most <n> characters from <src> and always terminates with '\0' */
2613char *my_strndup(const char *src, int n)
2614{
2615 int len = 0;
2616 char *ret;
2617
2618 while (len < n && src[len])
2619 len++;
2620
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002621 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002622 if (!ret)
2623 return ret;
2624 memcpy(ret, src, len);
2625 ret[len] = '\0';
2626 return ret;
2627}
2628
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002629/*
2630 * search needle in haystack
2631 * returns the pointer if found, returns NULL otherwise
2632 */
2633const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2634{
2635 const void *c = NULL;
2636 unsigned char f;
2637
2638 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2639 return NULL;
2640
2641 f = *(char *)needle;
2642 c = haystack;
2643 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2644 if ((haystacklen - (c - haystack)) < needlelen)
2645 return NULL;
2646
2647 if (memcmp(c, needle, needlelen) == 0)
2648 return c;
2649 ++c;
2650 }
2651 return NULL;
2652}
2653
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002654/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002655size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2656{
2657 size_t ret = 0;
2658
2659 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2660 str++;
2661 ret++;
2662 }
2663 return ret;
2664}
2665
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002666/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002667size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2668{
2669 size_t ret = 0;
2670
2671 while (ret < len) {
2672 if(memchr(reject, *((int *)str), rejectlen))
2673 return ret;
2674 str++;
2675 ret++;
2676 }
2677 return ret;
2678}
2679
Willy Tarreau482b00d2009-10-04 22:48:42 +02002680/* This function returns the first unused key greater than or equal to <key> in
2681 * ID tree <root>. Zero is returned if no place is found.
2682 */
2683unsigned int get_next_id(struct eb_root *root, unsigned int key)
2684{
2685 struct eb32_node *used;
2686
2687 do {
2688 used = eb32_lookup_ge(root, key);
2689 if (!used || used->key > key)
2690 return key; /* key is available */
2691 key++;
2692 } while (key);
2693 return key;
2694}
2695
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002696/* dump the full tree to <file> in DOT format for debugging purposes. Will
2697 * optionally highlight node <subj> if found, depending on operation <op> :
2698 * 0 : nothing
2699 * >0 : insertion, node/leaf are surrounded in red
2700 * <0 : removal, node/leaf are dashed with no background
2701 * Will optionally add "desc" as a label on the graph if set and non-null.
2702 */
2703void 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 +01002704{
2705 struct eb32sc_node *node;
2706 unsigned long scope = -1;
2707
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002708 fprintf(file, "digraph ebtree {\n");
2709
2710 if (desc && *desc) {
2711 fprintf(file,
2712 " fontname=\"fixed\";\n"
2713 " fontsize=8;\n"
2714 " label=\"%s\";\n", desc);
2715 }
2716
Willy Tarreaued3cda02017-11-15 15:04:05 +01002717 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002718 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2719 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002720 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2721 );
2722
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002723 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002724 (long)eb_root_to_node(root),
2725 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002726 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2727
2728 node = eb32sc_first(root, scope);
2729 while (node) {
2730 if (node->node.node_p) {
2731 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002732 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2733 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2734 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002735
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002736 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002737 (long)node,
2738 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002739 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002740
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002741 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002742 (long)node,
2743 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002744 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2745
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002746 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002747 (long)node,
2748 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002749 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2750 }
2751
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002752 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2753 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2754 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002755
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002756 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002757 (long)node,
2758 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002759 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002760 node = eb32sc_next(node, scope);
2761 }
2762 fprintf(file, "}\n");
2763}
2764
Willy Tarreau348238b2010-01-18 15:05:57 +01002765/* This function compares a sample word possibly followed by blanks to another
2766 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2767 * otherwise zero. This intends to be used when checking HTTP headers for some
2768 * values. Note that it validates a word followed only by blanks but does not
2769 * validate a word followed by blanks then other chars.
2770 */
2771int word_match(const char *sample, int slen, const char *word, int wlen)
2772{
2773 if (slen < wlen)
2774 return 0;
2775
2776 while (wlen) {
2777 char c = *sample ^ *word;
2778 if (c && c != ('A' ^ 'a'))
2779 return 0;
2780 sample++;
2781 word++;
2782 slen--;
2783 wlen--;
2784 }
2785
2786 while (slen) {
2787 if (*sample != ' ' && *sample != '\t')
2788 return 0;
2789 sample++;
2790 slen--;
2791 }
2792 return 1;
2793}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002794
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002795/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2796 * is particularly fast because it avoids expensive operations such as
2797 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002798 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002799 */
2800unsigned int inetaddr_host(const char *text)
2801{
2802 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2803 register unsigned int dig100, dig10, dig1;
2804 int s;
2805 const char *p, *d;
2806
2807 dig1 = dig10 = dig100 = ascii_zero;
2808 s = 24;
2809
2810 p = text;
2811 while (1) {
2812 if (((unsigned)(*p - '0')) <= 9) {
2813 p++;
2814 continue;
2815 }
2816
2817 /* here, we have a complete byte between <text> and <p> (exclusive) */
2818 if (p == text)
2819 goto end;
2820
2821 d = p - 1;
2822 dig1 |= (unsigned int)(*d << s);
2823 if (d == text)
2824 goto end;
2825
2826 d--;
2827 dig10 |= (unsigned int)(*d << s);
2828 if (d == text)
2829 goto end;
2830
2831 d--;
2832 dig100 |= (unsigned int)(*d << s);
2833 end:
2834 if (!s || *p != '.')
2835 break;
2836
2837 s -= 8;
2838 text = ++p;
2839 }
2840
2841 dig100 -= ascii_zero;
2842 dig10 -= ascii_zero;
2843 dig1 -= ascii_zero;
2844 return ((dig100 * 10) + dig10) * 10 + dig1;
2845}
2846
2847/*
2848 * Idem except the first unparsed character has to be passed in <stop>.
2849 */
2850unsigned int inetaddr_host_lim(const char *text, const char *stop)
2851{
2852 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2853 register unsigned int dig100, dig10, dig1;
2854 int s;
2855 const char *p, *d;
2856
2857 dig1 = dig10 = dig100 = ascii_zero;
2858 s = 24;
2859
2860 p = text;
2861 while (1) {
2862 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2863 p++;
2864 continue;
2865 }
2866
2867 /* here, we have a complete byte between <text> and <p> (exclusive) */
2868 if (p == text)
2869 goto end;
2870
2871 d = p - 1;
2872 dig1 |= (unsigned int)(*d << s);
2873 if (d == text)
2874 goto end;
2875
2876 d--;
2877 dig10 |= (unsigned int)(*d << s);
2878 if (d == text)
2879 goto end;
2880
2881 d--;
2882 dig100 |= (unsigned int)(*d << s);
2883 end:
2884 if (!s || p == stop || *p != '.')
2885 break;
2886
2887 s -= 8;
2888 text = ++p;
2889 }
2890
2891 dig100 -= ascii_zero;
2892 dig10 -= ascii_zero;
2893 dig1 -= ascii_zero;
2894 return ((dig100 * 10) + dig10) * 10 + dig1;
2895}
2896
2897/*
2898 * Idem except the pointer to first unparsed byte is returned into <ret> which
2899 * must not be NULL.
2900 */
Willy Tarreau74172752010-10-15 23:21:42 +02002901unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002902{
2903 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2904 register unsigned int dig100, dig10, dig1;
2905 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002906 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002907
2908 dig1 = dig10 = dig100 = ascii_zero;
2909 s = 24;
2910
2911 p = text;
2912 while (1) {
2913 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2914 p++;
2915 continue;
2916 }
2917
2918 /* here, we have a complete byte between <text> and <p> (exclusive) */
2919 if (p == text)
2920 goto end;
2921
2922 d = p - 1;
2923 dig1 |= (unsigned int)(*d << s);
2924 if (d == text)
2925 goto end;
2926
2927 d--;
2928 dig10 |= (unsigned int)(*d << s);
2929 if (d == text)
2930 goto end;
2931
2932 d--;
2933 dig100 |= (unsigned int)(*d << s);
2934 end:
2935 if (!s || p == stop || *p != '.')
2936 break;
2937
2938 s -= 8;
2939 text = ++p;
2940 }
2941
2942 *ret = p;
2943 dig100 -= ascii_zero;
2944 dig10 -= ascii_zero;
2945 dig1 -= ascii_zero;
2946 return ((dig100 * 10) + dig10) * 10 + dig1;
2947}
2948
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002949/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2950 * or the number of chars read in case of success. Maybe this could be replaced
2951 * by one of the functions above. Also, apparently this function does not support
2952 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002953 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002954 */
2955int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2956{
2957 const char *addr;
2958 int saw_digit, octets, ch;
2959 u_char tmp[4], *tp;
2960 const char *cp = buf;
2961
2962 saw_digit = 0;
2963 octets = 0;
2964 *(tp = tmp) = 0;
2965
2966 for (addr = buf; addr - buf < len; addr++) {
2967 unsigned char digit = (ch = *addr) - '0';
2968
2969 if (digit > 9 && ch != '.')
2970 break;
2971
2972 if (digit <= 9) {
2973 u_int new = *tp * 10 + digit;
2974
2975 if (new > 255)
2976 return 0;
2977
2978 *tp = new;
2979
2980 if (!saw_digit) {
2981 if (++octets > 4)
2982 return 0;
2983 saw_digit = 1;
2984 }
2985 } else if (ch == '.' && saw_digit) {
2986 if (octets == 4)
2987 return 0;
2988
2989 *++tp = 0;
2990 saw_digit = 0;
2991 } else
2992 return 0;
2993 }
2994
2995 if (octets < 4)
2996 return 0;
2997
2998 memcpy(&dst->s_addr, tmp, 4);
2999 return addr - cp;
3000}
3001
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003002/* This function converts the string in <buf> of the len <len> to
3003 * struct in6_addr <dst> which must be allocated by the caller.
3004 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01003005 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003006 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003007int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
3008{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003009 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01003010 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003011
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003012 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003013 return 0;
3014
3015 memcpy(null_term_ip6, buf, len);
3016 null_term_ip6[len] = '\0';
3017
Willy Tarreau075415a2013-12-12 11:29:39 +01003018 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003019 return 0;
3020
Willy Tarreau075415a2013-12-12 11:29:39 +01003021 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003022 return 1;
3023}
3024
Willy Tarreauacf95772010-06-14 19:09:21 +02003025/* To be used to quote config arg positions. Returns the short string at <ptr>
3026 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
3027 * if ptr is NULL or empty. The string is locally allocated.
3028 */
3029const char *quote_arg(const char *ptr)
3030{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003031 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003032 int i;
3033
3034 if (!ptr || !*ptr)
3035 return "end of line";
3036 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003037 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003038 val[i] = *ptr++;
3039 val[i++] = '\'';
3040 val[i] = '\0';
3041 return val;
3042}
3043
Willy Tarreau5b180202010-07-18 10:40:48 +02003044/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3045int get_std_op(const char *str)
3046{
3047 int ret = -1;
3048
3049 if (*str == 'e' && str[1] == 'q')
3050 ret = STD_OP_EQ;
3051 else if (*str == 'n' && str[1] == 'e')
3052 ret = STD_OP_NE;
3053 else if (*str == 'l') {
3054 if (str[1] == 'e') ret = STD_OP_LE;
3055 else if (str[1] == 't') ret = STD_OP_LT;
3056 }
3057 else if (*str == 'g') {
3058 if (str[1] == 'e') ret = STD_OP_GE;
3059 else if (str[1] == 't') ret = STD_OP_GT;
3060 }
3061
3062 if (ret == -1 || str[2] != '\0')
3063 return -1;
3064 return ret;
3065}
3066
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003067/* hash a 32-bit integer to another 32-bit integer */
3068unsigned int full_hash(unsigned int a)
3069{
3070 return __full_hash(a);
3071}
3072
Willy Tarreauf3241112019-02-26 09:56:22 +01003073/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3074 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3075 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3076 * a popcount variant and is described here :
3077 * https://graphics.stanford.edu/~seander/bithacks.html
3078 */
3079unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3080{
3081 unsigned long a, b, c, d;
3082 unsigned int s;
3083 unsigned int t;
3084
3085 a = m - ((m >> 1) & ~0UL/3);
3086 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3087 c = (b + (b >> 4)) & ~0UL/0x11;
3088 d = (c + (c >> 8)) & ~0UL/0x101;
3089
3090 r++; // make r be 1..64
3091
3092 t = 0;
3093 s = LONGBITS;
3094 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003095 unsigned long d2 = (d >> 16) >> 16;
3096 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003097 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3098 }
3099
3100 t = (d >> (s - 16)) & 0xff;
3101 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3102 t = (c >> (s - 8)) & 0xf;
3103 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3104 t = (b >> (s - 4)) & 0x7;
3105 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3106 t = (a >> (s - 2)) & 0x3;
3107 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3108 t = (m >> (s - 1)) & 0x1;
3109 s -= ((t - r) & 256) >> 8;
3110
3111 return s - 1;
3112}
3113
3114/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3115 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3116 * using mask_prep_rank_map() below.
3117 */
3118unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3119 unsigned long a, unsigned long b,
3120 unsigned long c, unsigned long d)
3121{
3122 unsigned int s;
3123 unsigned int t;
3124
3125 r++; // make r be 1..64
3126
3127 t = 0;
3128 s = LONGBITS;
3129 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003130 unsigned long d2 = (d >> 16) >> 16;
3131 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003132 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3133 }
3134
3135 t = (d >> (s - 16)) & 0xff;
3136 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3137 t = (c >> (s - 8)) & 0xf;
3138 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3139 t = (b >> (s - 4)) & 0x7;
3140 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3141 t = (a >> (s - 2)) & 0x3;
3142 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3143 t = (m >> (s - 1)) & 0x1;
3144 s -= ((t - r) & 256) >> 8;
3145
3146 return s - 1;
3147}
3148
3149/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3150 * above.
3151 */
3152void mask_prep_rank_map(unsigned long m,
3153 unsigned long *a, unsigned long *b,
3154 unsigned long *c, unsigned long *d)
3155{
3156 *a = m - ((m >> 1) & ~0UL/3);
3157 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3158 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3159 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3160}
3161
Willy Tarreauc7a8a3c2022-06-21 20:19:54 +02003162/* Returns the position of one bit set in <v>, starting at position <bit>, and
3163 * searching in other halves if not found. This is intended to be used to
3164 * report the position of one bit set among several based on a counter or a
3165 * random generator while preserving a relatively good distribution so that
3166 * values made of holes in the middle do not see one of the bits around the
3167 * hole being returned much more often than the other one. It can be seen as a
3168 * disturbed ffsl() where the initial search starts at bit <bit>. The look up
3169 * is performed in O(logN) time for N bit words, yielding a bit among 64 in
3170 * about 16 cycles. Its usage differs from the rank find function in that the
3171 * bit passed doesn't need to be limited to the value's popcount, making the
3172 * function easier to use for random picking, and twice as fast. Passing value
3173 * 0 for <v> makes no sense and -1 is returned in this case.
3174 */
3175int one_among_mask(unsigned long v, int bit)
3176{
3177 /* note, these masks may be produced by ~0UL/((1UL<<scale)+1) but
3178 * that's more expensive.
3179 */
3180 static const unsigned long halves[] = {
3181 (unsigned long)0x5555555555555555ULL,
3182 (unsigned long)0x3333333333333333ULL,
3183 (unsigned long)0x0F0F0F0F0F0F0F0FULL,
3184 (unsigned long)0x00FF00FF00FF00FFULL,
3185 (unsigned long)0x0000FFFF0000FFFFULL,
3186 (unsigned long)0x00000000FFFFFFFFULL
3187 };
3188 unsigned long halfword = ~0UL;
3189 int scope = 0;
3190 int mirror;
3191 int scale;
3192
3193 if (!v)
3194 return -1;
3195
3196 /* we check if the exact bit is set or if it's present in a mirror
3197 * position based on the current scale we're checking, in which case
3198 * it's returned with its current (or mirrored) value. Otherwise we'll
3199 * make sure there's at least one bit in the half we're in, and will
3200 * scale down to a smaller scope and try again, until we find the
3201 * closest bit.
3202 */
3203 for (scale = (sizeof(long) > 4) ? 5 : 4; scale >= 0; scale--) {
3204 halfword >>= (1UL << scale);
3205 scope |= (1UL << scale);
3206 mirror = bit ^ (1UL << scale);
3207 if (v & ((1UL << bit) | (1UL << mirror)))
3208 return (v & (1UL << bit)) ? bit : mirror;
3209
3210 if (!((v >> (bit & scope)) & halves[scale] & halfword))
3211 bit = mirror;
3212 }
3213 return bit;
3214}
3215
David du Colombier4f92d322011-03-24 11:09:31 +01003216/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003217 * otherwise zero. Note that <addr> may not necessarily be aligned
3218 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003219 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003220int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003221{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003222 struct in_addr addr_copy;
3223
3224 memcpy(&addr_copy, addr, sizeof(addr_copy));
3225 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003226}
3227
3228/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003229 * otherwise zero. Note that <addr> may not necessarily be aligned
3230 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003231 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003232int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003233{
3234 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003235 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003236
Willy Tarreaueec1d382016-07-13 11:59:39 +02003237 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003238 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003239 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003240 (((int *)net)[i] & ((int *)mask)[i]))
3241 return 0;
3242 return 1;
3243}
3244
3245/* RFC 4291 prefix */
3246const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3247 0x00, 0x00, 0x00, 0x00,
3248 0x00, 0x00, 0xFF, 0xFF };
3249
Joseph Herlant32b83272018-11-15 11:58:28 -08003250/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003251 * Input and output may overlap.
3252 */
David du Colombier4f92d322011-03-24 11:09:31 +01003253void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3254{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003255 struct in_addr tmp_addr;
3256
3257 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003258 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003259 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003260}
3261
Joseph Herlant32b83272018-11-15 11:58:28 -08003262/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003263 * Return true if conversion is possible and false otherwise.
3264 */
3265int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3266{
3267 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3268 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3269 sizeof(struct in_addr));
3270 return 1;
3271 }
3272
3273 return 0;
3274}
3275
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003276/* compare two struct sockaddr_storage and return:
3277 * 0 (true) if the addr is the same in both
3278 * 1 (false) if the addr is not the same in both
3279 * -1 (unable) if one of the addr is not AF_INET*
3280 */
3281int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3282{
3283 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3284 return -1;
3285
3286 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3287 return -1;
3288
3289 if (ss1->ss_family != ss2->ss_family)
3290 return 1;
3291
3292 switch (ss1->ss_family) {
3293 case AF_INET:
3294 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3295 &((struct sockaddr_in *)ss2)->sin_addr,
3296 sizeof(struct in_addr)) != 0;
3297 case AF_INET6:
3298 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3299 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3300 sizeof(struct in6_addr)) != 0;
3301 }
3302
3303 return 1;
3304}
3305
Christopher Faulet9553de72021-02-26 09:12:50 +01003306/* compare a struct sockaddr_storage to a struct net_addr and return :
3307 * 0 (true) if <addr> is matching <net>
3308 * 1 (false) if <addr> is not matching <net>
3309 * -1 (unable) if <addr> or <net> is not AF_INET*
3310 */
3311int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3312{
3313 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3314 return -1;
3315
3316 if ((net->family != AF_INET) && (net->family != AF_INET6))
3317 return -1;
3318
3319 if (addr->ss_family != net->family)
3320 return 1;
3321
3322 if (addr->ss_family == AF_INET &&
3323 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3324 return 0;
3325 else {
3326 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3327 const struct in6_addr *nip6 = &net->addr.v6.ip;
3328 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3329
3330 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3331 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3332 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3333 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3334 return 0;
3335 }
3336
3337 return 1;
3338}
3339
Baptiste Assmann08396c82016-01-31 00:27:17 +01003340/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003341 * The caller must allocate and clear <dest> before calling.
3342 * The source must be in either AF_INET or AF_INET6 family, or the destination
3343 * address will be undefined. If the destination address used to hold a port,
3344 * it is preserved, so that this function can be used to switch to another
3345 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003346 */
3347struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3348{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003349 int prev_port;
3350
3351 prev_port = get_net_port(dest);
3352 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003353 dest->ss_family = source->ss_family;
3354
3355 /* copy new addr and apply it */
3356 switch (source->ss_family) {
3357 case AF_INET:
3358 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003359 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003360 break;
3361 case AF_INET6:
3362 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 +01003363 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003364 break;
3365 }
3366
3367 return dest;
3368}
3369
William Lallemand421f5b52012-02-06 18:15:57 +01003370char *human_time(int t, short hz_div) {
3371 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3372 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003373 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003374 int cnt=2; // print two numbers
3375
3376 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003377 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003378 return rv;
3379 }
3380
3381 if (unlikely(hz_div > 1))
3382 t /= hz_div;
3383
3384 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003385 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003386 cnt--;
3387 }
3388
3389 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003390 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003391 cnt--;
3392 }
3393
3394 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003395 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003396 cnt--;
3397 }
3398
3399 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003400 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003401
3402 return rv;
3403}
3404
3405const char *monthname[12] = {
3406 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3407 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3408};
3409
3410/* date2str_log: write a date in the format :
3411 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3412 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3413 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3414 *
3415 * without using sprintf. return a pointer to the last char written (\0) or
3416 * NULL if there isn't enough space.
3417 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003418char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003419{
3420
3421 if (size < 25) /* the size is fixed: 24 chars + \0 */
3422 return NULL;
3423
3424 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003425 if (!dst)
3426 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003427 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003428
William Lallemand421f5b52012-02-06 18:15:57 +01003429 memcpy(dst, monthname[tm->tm_mon], 3); // month
3430 dst += 3;
3431 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003432
William Lallemand421f5b52012-02-06 18:15:57 +01003433 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003434 if (!dst)
3435 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003436 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003437
William Lallemand421f5b52012-02-06 18:15:57 +01003438 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003439 if (!dst)
3440 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003441 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003442
William Lallemand421f5b52012-02-06 18:15:57 +01003443 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003444 if (!dst)
3445 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003446 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003447
William Lallemand421f5b52012-02-06 18:15:57 +01003448 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003449 if (!dst)
3450 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003451 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003452
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003453 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003454 if (!dst)
3455 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003456 *dst = '\0';
3457
3458 return dst;
3459}
3460
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003461/* Base year used to compute leap years */
3462#define TM_YEAR_BASE 1900
3463
3464/* Return the difference in seconds between two times (leap seconds are ignored).
3465 * Retrieved from glibc 2.18 source code.
3466 */
3467static int my_tm_diff(const struct tm *a, const struct tm *b)
3468{
3469 /* Compute intervening leap days correctly even if year is negative.
3470 * Take care to avoid int overflow in leap day calculations,
3471 * but it's OK to assume that A and B are close to each other.
3472 */
3473 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3474 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3475 int a100 = a4 / 25 - (a4 % 25 < 0);
3476 int b100 = b4 / 25 - (b4 % 25 < 0);
3477 int a400 = a100 >> 2;
3478 int b400 = b100 >> 2;
3479 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3480 int years = a->tm_year - b->tm_year;
3481 int days = (365 * years + intervening_leap_days
3482 + (a->tm_yday - b->tm_yday));
3483 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3484 + (a->tm_min - b->tm_min))
3485 + (a->tm_sec - b->tm_sec));
3486}
3487
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003488/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003489 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003490 * The string returned has the same format as returned by strftime(... "%z", tm).
3491 * Offsets are kept in an internal cache for better performances.
3492 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003493const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003494{
3495 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003496 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003497
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003498 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003499 struct tm tm_gmt;
3500 int diff;
3501 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003502
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003503 /* Pretend DST not active if its status is unknown */
3504 if (isdst < 0)
3505 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003506
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003507 /* Fetch the offset and initialize it if needed */
3508 gmt_offset = gmt_offsets[isdst & 0x01];
3509 if (unlikely(!*gmt_offset)) {
3510 get_gmtime(t, &tm_gmt);
3511 diff = my_tm_diff(tm, &tm_gmt);
3512 if (diff < 0) {
3513 diff = -diff;
3514 *gmt_offset = '-';
3515 } else {
3516 *gmt_offset = '+';
3517 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003518 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003519 diff /= 60; /* Convert to minutes */
3520 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3521 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003522
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003523 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003524}
3525
William Lallemand421f5b52012-02-06 18:15:57 +01003526/* gmt2str_log: write a date in the format :
3527 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3528 * return a pointer to the last char written (\0) or
3529 * NULL if there isn't enough space.
3530 */
3531char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3532{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003533 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003534 return NULL;
3535
3536 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003537 if (!dst)
3538 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003539 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003540
William Lallemand421f5b52012-02-06 18:15:57 +01003541 memcpy(dst, monthname[tm->tm_mon], 3); // month
3542 dst += 3;
3543 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003544
William Lallemand421f5b52012-02-06 18:15:57 +01003545 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003546 if (!dst)
3547 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003548 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003549
William Lallemand421f5b52012-02-06 18:15:57 +01003550 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003551 if (!dst)
3552 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003553 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003554
William Lallemand421f5b52012-02-06 18:15:57 +01003555 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003556 if (!dst)
3557 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003558 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003559
William Lallemand421f5b52012-02-06 18:15:57 +01003560 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003561 if (!dst)
3562 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003563 *dst++ = ' ';
3564 *dst++ = '+';
3565 *dst++ = '0';
3566 *dst++ = '0';
3567 *dst++ = '0';
3568 *dst++ = '0';
3569 *dst = '\0';
3570
3571 return dst;
3572}
3573
Yuxans Yao4e25b012012-10-19 10:36:09 +08003574/* localdate2str_log: write a date in the format :
3575 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003576 * Both t and tm must represent the same time.
3577 * return a pointer to the last char written (\0) or
3578 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003579 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003580char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003581{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003582 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003583 if (size < 27) /* the size is fixed: 26 chars + \0 */
3584 return NULL;
3585
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003586 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003587
Yuxans Yao4e25b012012-10-19 10:36:09 +08003588 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003589 if (!dst)
3590 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003591 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003592
Yuxans Yao4e25b012012-10-19 10:36:09 +08003593 memcpy(dst, monthname[tm->tm_mon], 3); // month
3594 dst += 3;
3595 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003596
Yuxans Yao4e25b012012-10-19 10:36:09 +08003597 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003598 if (!dst)
3599 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003600 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003601
Yuxans Yao4e25b012012-10-19 10:36:09 +08003602 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003603 if (!dst)
3604 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003605 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003606
Yuxans Yao4e25b012012-10-19 10:36:09 +08003607 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003608 if (!dst)
3609 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003610 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003611
Yuxans Yao4e25b012012-10-19 10:36:09 +08003612 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003613 if (!dst)
3614 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003615 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003616
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003617 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003618 dst += 5;
3619 *dst = '\0';
3620
3621 return dst;
3622}
3623
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003624/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3625 * It is meant as a portable replacement for timegm() for use with valid inputs.
3626 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3627 */
3628time_t my_timegm(const struct tm *tm)
3629{
3630 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3631 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3632 * sum of the extra N days for elapsed months. The sum of all these N
3633 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3634 * in a 5-bit word. This means that with 60 bits we can represent a
3635 * matrix of all these values at once, which is fast and efficient to
3636 * access. The extra February day for leap years is not counted here.
3637 *
3638 * Jan : none = 0 (0)
3639 * Feb : Jan = 3 (3)
3640 * Mar : Jan..Feb = 3 (3 + 0)
3641 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3642 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3643 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3644 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3645 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3646 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3647 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3648 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3649 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3650 */
3651 uint64_t extra =
3652 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3653 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3654 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3655 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3656
3657 unsigned int y = tm->tm_year + 1900;
3658 unsigned int m = tm->tm_mon;
3659 unsigned long days = 0;
3660
3661 /* days since 1/1/1970 for full years */
3662 days += days_since_zero(y) - days_since_zero(1970);
3663
3664 /* days for full months in the current year */
3665 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3666
3667 /* count + 1 after March for leap years. A leap year is a year multiple
3668 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3669 * is leap, 1900 isn't, 1904 is.
3670 */
3671 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3672 days++;
3673
3674 days += tm->tm_mday - 1;
3675 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3676}
3677
Thierry Fournier93127942016-01-20 18:49:45 +01003678/* This function check a char. It returns true and updates
3679 * <date> and <len> pointer to the new position if the
3680 * character is found.
3681 */
3682static inline int parse_expect_char(const char **date, int *len, char c)
3683{
3684 if (*len < 1 || **date != c)
3685 return 0;
3686 (*len)--;
3687 (*date)++;
3688 return 1;
3689}
3690
3691/* This function expects a string <str> of len <l>. It return true and updates.
3692 * <date> and <len> if the string matches, otherwise, it returns false.
3693 */
3694static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3695{
3696 if (*len < l || strncmp(*date, str, l) != 0)
3697 return 0;
3698 (*len) -= l;
3699 (*date) += l;
3700 return 1;
3701}
3702
3703/* This macro converts 3 chars name in integer. */
3704#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3705
3706/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3707 * / %x54.75.65 ; "Tue", case-sensitive
3708 * / %x57.65.64 ; "Wed", case-sensitive
3709 * / %x54.68.75 ; "Thu", case-sensitive
3710 * / %x46.72.69 ; "Fri", case-sensitive
3711 * / %x53.61.74 ; "Sat", case-sensitive
3712 * / %x53.75.6E ; "Sun", case-sensitive
3713 *
3714 * This array must be alphabetically sorted
3715 */
3716static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3717{
3718 if (*len < 3)
3719 return 0;
3720 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3721 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3722 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3723 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3724 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3725 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3726 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3727 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3728 default: return 0;
3729 }
3730 *len -= 3;
3731 *date += 3;
3732 return 1;
3733}
3734
3735/* month = %x4A.61.6E ; "Jan", case-sensitive
3736 * / %x46.65.62 ; "Feb", case-sensitive
3737 * / %x4D.61.72 ; "Mar", case-sensitive
3738 * / %x41.70.72 ; "Apr", case-sensitive
3739 * / %x4D.61.79 ; "May", case-sensitive
3740 * / %x4A.75.6E ; "Jun", case-sensitive
3741 * / %x4A.75.6C ; "Jul", case-sensitive
3742 * / %x41.75.67 ; "Aug", case-sensitive
3743 * / %x53.65.70 ; "Sep", case-sensitive
3744 * / %x4F.63.74 ; "Oct", case-sensitive
3745 * / %x4E.6F.76 ; "Nov", case-sensitive
3746 * / %x44.65.63 ; "Dec", case-sensitive
3747 *
3748 * This array must be alphabetically sorted
3749 */
3750static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3751{
3752 if (*len < 3)
3753 return 0;
3754 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3755 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3756 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3757 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3758 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3759 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3760 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3761 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3762 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3763 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3764 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3765 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3766 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3767 default: return 0;
3768 }
3769 *len -= 3;
3770 *date += 3;
3771 return 1;
3772}
3773
3774/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3775 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3776 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3777 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3778 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3779 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3780 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3781 *
3782 * This array must be alphabetically sorted
3783 */
3784static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3785{
3786 if (*len < 6) /* Minimum length. */
3787 return 0;
3788 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3789 case STR2I3('M','o','n'):
3790 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3791 tm->tm_wday = 1;
3792 return 1;
3793 case STR2I3('T','u','e'):
3794 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3795 tm->tm_wday = 2;
3796 return 1;
3797 case STR2I3('W','e','d'):
3798 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3799 tm->tm_wday = 3;
3800 return 1;
3801 case STR2I3('T','h','u'):
3802 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3803 tm->tm_wday = 4;
3804 return 1;
3805 case STR2I3('F','r','i'):
3806 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3807 tm->tm_wday = 5;
3808 return 1;
3809 case STR2I3('S','a','t'):
3810 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3811 tm->tm_wday = 6;
3812 return 1;
3813 case STR2I3('S','u','n'):
3814 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3815 tm->tm_wday = 7;
3816 return 1;
3817 }
3818 return 0;
3819}
3820
3821/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3822static inline int parse_digit(const char **date, int *len, int *digit)
3823{
3824 if (*len < 1 || **date < '0' || **date > '9')
3825 return 0;
3826 *digit = (**date - '0');
3827 (*date)++;
3828 (*len)--;
3829 return 1;
3830}
3831
3832/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3833static inline int parse_2digit(const char **date, int *len, int *digit)
3834{
3835 int value;
3836
3837 RET0_UNLESS(parse_digit(date, len, &value));
3838 (*digit) = value * 10;
3839 RET0_UNLESS(parse_digit(date, len, &value));
3840 (*digit) += value;
3841
3842 return 1;
3843}
3844
3845/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3846static inline int parse_4digit(const char **date, int *len, int *digit)
3847{
3848 int value;
3849
3850 RET0_UNLESS(parse_digit(date, len, &value));
3851 (*digit) = value * 1000;
3852
3853 RET0_UNLESS(parse_digit(date, len, &value));
3854 (*digit) += value * 100;
3855
3856 RET0_UNLESS(parse_digit(date, len, &value));
3857 (*digit) += value * 10;
3858
3859 RET0_UNLESS(parse_digit(date, len, &value));
3860 (*digit) += value;
3861
3862 return 1;
3863}
3864
3865/* time-of-day = hour ":" minute ":" second
3866 * ; 00:00:00 - 23:59:60 (leap second)
3867 *
3868 * hour = 2DIGIT
3869 * minute = 2DIGIT
3870 * second = 2DIGIT
3871 */
3872static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3873{
3874 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3875 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3876 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3877 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3878 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3879 return 1;
3880}
3881
3882/* From RFC7231
3883 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3884 *
3885 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3886 * ; fixed length/zone/capitalization subset of the format
3887 * ; see Section 3.3 of [RFC5322]
3888 *
3889 *
3890 * date1 = day SP month SP year
3891 * ; e.g., 02 Jun 1982
3892 *
3893 * day = 2DIGIT
3894 * year = 4DIGIT
3895 *
3896 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3897 *
3898 * time-of-day = hour ":" minute ":" second
3899 * ; 00:00:00 - 23:59:60 (leap second)
3900 *
3901 * hour = 2DIGIT
3902 * minute = 2DIGIT
3903 * second = 2DIGIT
3904 *
3905 * DIGIT = decimal 0-9
3906 */
3907int parse_imf_date(const char *date, int len, struct tm *tm)
3908{
David Carlier327298c2016-11-20 10:42:38 +00003909 /* tm_gmtoff, if present, ought to be zero'ed */
3910 memset(tm, 0, sizeof(*tm));
3911
Thierry Fournier93127942016-01-20 18:49:45 +01003912 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3913 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3914 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3915 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3916 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3917 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3918 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3919 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3920 tm->tm_year -= 1900;
3921 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3922 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3923 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3924 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3925 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003926 return 1;
3927}
3928
3929/* From RFC7231
3930 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3931 *
3932 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3933 * date2 = day "-" month "-" 2DIGIT
3934 * ; e.g., 02-Jun-82
3935 *
3936 * day = 2DIGIT
3937 */
3938int parse_rfc850_date(const char *date, int len, struct tm *tm)
3939{
3940 int year;
3941
David Carlier327298c2016-11-20 10:42:38 +00003942 /* tm_gmtoff, if present, ought to be zero'ed */
3943 memset(tm, 0, sizeof(*tm));
3944
Thierry Fournier93127942016-01-20 18:49:45 +01003945 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3946 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3947 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3948 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3949 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3950 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3951 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3952
3953 /* year = 2DIGIT
3954 *
3955 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3956 * two-digit year, MUST interpret a timestamp that appears to be more
3957 * than 50 years in the future as representing the most recent year in
3958 * the past that had the same last two digits.
3959 */
3960 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3961
3962 /* expect SP */
3963 if (!parse_expect_char(&date, &len, ' ')) {
3964 /* Maybe we have the date with 4 digits. */
3965 RET0_UNLESS(parse_2digit(&date, &len, &year));
3966 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3967 /* expect SP */
3968 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3969 } else {
3970 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3971 * tm_year is the number of year since 1900, so for +1900, we
3972 * do nothing, and for +2000, we add 100.
3973 */
3974 if (tm->tm_year <= 60)
3975 tm->tm_year += 100;
3976 }
3977
3978 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3979 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3980 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3981 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003982
3983 return 1;
3984}
3985
3986/* From RFC7231
3987 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3988 *
3989 * asctime-date = day-name SP date3 SP time-of-day SP year
3990 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3991 * ; e.g., Jun 2
3992 *
3993 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3994 * whitespace in an HTTP-date beyond that specifically included as SP in
3995 * the grammar.
3996 */
3997int parse_asctime_date(const char *date, int len, struct tm *tm)
3998{
David Carlier327298c2016-11-20 10:42:38 +00003999 /* tm_gmtoff, if present, ought to be zero'ed */
4000 memset(tm, 0, sizeof(*tm));
4001
Thierry Fournier93127942016-01-20 18:49:45 +01004002 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
4003 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4004 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
4005 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4006
4007 /* expect SP and 1DIGIT or 2DIGIT */
4008 if (parse_expect_char(&date, &len, ' '))
4009 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
4010 else
4011 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
4012
4013 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4014 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4015 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4016 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
4017 tm->tm_year -= 1900;
4018 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004019 return 1;
4020}
4021
4022/* From RFC7231
4023 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4024 *
4025 * HTTP-date = IMF-fixdate / obs-date
4026 * obs-date = rfc850-date / asctime-date
4027 *
4028 * parses an HTTP date in the RFC format and is accepted
4029 * alternatives. <date> is the strinf containing the date,
4030 * len is the len of the string. <tm> is filled with the
4031 * parsed time. We must considers this time as GMT.
4032 */
4033int parse_http_date(const char *date, int len, struct tm *tm)
4034{
4035 if (parse_imf_date(date, len, tm))
4036 return 1;
4037
4038 if (parse_rfc850_date(date, len, tm))
4039 return 1;
4040
4041 if (parse_asctime_date(date, len, tm))
4042 return 1;
4043
4044 return 0;
4045}
4046
Willy Tarreau4deeb102021-01-29 10:47:52 +01004047/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
4048 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
4049 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
4050 * surrounded by <pfx> and <sfx> respectively if not NULL.
4051 */
4052int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
4053{
4054 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
4055 const char *unit;
4056
4057 if (!pfx)
4058 pfx = "";
4059 if (!sfx)
4060 sfx = "";
4061
4062 do {
4063 unit = " - "; if (val <= 0.0) break;
4064 unit = "ns"; if (val < 1000.0) break;
4065 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
4066 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
4067 unit = "s "; val /= 1000.0; if (val < 60.0) break;
4068 unit = "m "; val /= 60.0; if (val < 60.0) break;
4069 unit = "h "; val /= 60.0; if (val < 24.0) break;
4070 unit = "d "; val /= 24.0; if (val < 365.0) break;
4071 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
4072 unit = " inf "; val = 0.0; break;
4073 } while (0);
4074
4075 if (val <= 0.0)
4076 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
4077 else if (val < 10.0)
4078 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
4079 else if (val < 100.0)
4080 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
4081 else
4082 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4083}
4084
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004085/* Dynamically allocates a string of the proper length to hold the formatted
4086 * output. NULL is returned on error. The caller is responsible for freeing the
4087 * memory area using free(). The resulting string is returned in <out> if the
4088 * pointer is not NULL. A previous version of <out> might be used to build the
4089 * new string, and it will be freed before returning if it is not NULL, which
4090 * makes it possible to build complex strings from iterative calls without
4091 * having to care about freeing intermediate values, as in the example below :
4092 *
4093 * memprintf(&err, "invalid argument: '%s'", arg);
4094 * ...
4095 * memprintf(&err, "parser said : <%s>\n", *err);
4096 * ...
4097 * free(*err);
4098 *
4099 * This means that <err> must be initialized to NULL before first invocation.
4100 * The return value also holds the allocated string, which eases error checking
4101 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004102 * passed instead and it will be ignored. The returned message will then also
4103 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004104 *
4105 * It is also convenient to use it without any free except the last one :
4106 * err = NULL;
4107 * if (!fct1(err)) report(*err);
4108 * if (!fct2(err)) report(*err);
4109 * if (!fct3(err)) report(*err);
4110 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004111 *
4112 * memprintf relies on memvprintf. This last version can be called from any
4113 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004114 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004115char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004116{
4117 va_list args;
4118 char *ret = NULL;
4119 int allocated = 0;
4120 int needed = 0;
4121
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004122 if (!out)
4123 return NULL;
4124
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004125 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004126 char buf1;
4127
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004128 /* vsnprintf() will return the required length even when the
4129 * target buffer is NULL. We do this in a loop just in case
4130 * intermediate evaluations get wrong.
4131 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004132 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004133 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004134 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004135 if (needed < allocated) {
4136 /* Note: on Solaris 8, the first iteration always
4137 * returns -1 if allocated is zero, so we force a
4138 * retry.
4139 */
4140 if (!allocated)
4141 needed = 0;
4142 else
4143 break;
4144 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004145
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004146 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004147 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004148 } while (ret);
4149
4150 if (needed < 0) {
4151 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004152 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004153 }
4154
4155 if (out) {
4156 free(*out);
4157 *out = ret;
4158 }
4159
4160 return ret;
4161}
William Lallemand421f5b52012-02-06 18:15:57 +01004162
Christopher Faulet93a518f2017-10-24 11:25:33 +02004163char *memprintf(char **out, const char *format, ...)
4164{
4165 va_list args;
4166 char *ret = NULL;
4167
4168 va_start(args, format);
4169 ret = memvprintf(out, format, args);
4170 va_end(args);
4171
4172 return ret;
4173}
4174
Willy Tarreau21c705b2012-09-14 11:40:36 +02004175/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4176 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004177 * freed by the caller. It also supports being passed a NULL which results in the same
4178 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004179 * Example of use :
4180 * parse(cmd, &err); (callee: memprintf(&err, ...))
4181 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4182 * free(err);
4183 */
4184char *indent_msg(char **out, int level)
4185{
4186 char *ret, *in, *p;
4187 int needed = 0;
4188 int lf = 0;
4189 int lastlf = 0;
4190 int len;
4191
Willy Tarreau70eec382012-10-10 08:56:47 +02004192 if (!out || !*out)
4193 return NULL;
4194
Willy Tarreau21c705b2012-09-14 11:40:36 +02004195 in = *out - 1;
4196 while ((in = strchr(in + 1, '\n')) != NULL) {
4197 lastlf = in - *out;
4198 lf++;
4199 }
4200
4201 if (!lf) /* single line, no LF, return it as-is */
4202 return *out;
4203
4204 len = strlen(*out);
4205
4206 if (lf == 1 && lastlf == len - 1) {
4207 /* single line, LF at end, strip it and return as-is */
4208 (*out)[lastlf] = 0;
4209 return *out;
4210 }
4211
4212 /* OK now we have at least one LF, we need to process the whole string
4213 * as a multi-line string. What we'll do :
4214 * - prefix with an LF if there is none
4215 * - add <level> spaces before each line
4216 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4217 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4218 */
4219
4220 needed = 1 + level * (lf + 1) + len + 1;
4221 p = ret = malloc(needed);
4222 in = *out;
4223
4224 /* skip initial LFs */
4225 while (*in == '\n')
4226 in++;
4227
4228 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4229 while (*in) {
4230 *p++ = '\n';
4231 memset(p, ' ', level);
4232 p += level;
4233 do {
4234 *p++ = *in++;
4235 } while (*in && *in != '\n');
4236 if (*in)
4237 in++;
4238 }
4239 *p = 0;
4240
4241 free(*out);
4242 *out = ret;
4243
4244 return ret;
4245}
4246
Willy Tarreaua2c99112019-08-21 13:17:37 +02004247/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4248 * and end of lines replaced with <eol> if not 0. The first line to indent has
4249 * to be indicated in <first> (starts at zero), so that it is possible to skip
4250 * indenting the first line if it has to be appended after an existing message.
4251 * Empty strings are never indented, and NULL strings are considered empty both
4252 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4253 * character, non-zero otherwise.
4254 */
4255int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4256{
4257 int bol, lf;
4258 int pfxlen = pfx ? strlen(pfx) : 0;
4259
4260 if (!in)
4261 return 0;
4262
4263 bol = 1;
4264 lf = 0;
4265 while (*in) {
4266 if (bol && pfxlen) {
4267 if (first > 0)
4268 first--;
4269 else
4270 b_putblk(out, pfx, pfxlen);
4271 bol = 0;
4272 }
4273
4274 lf = (*in == '\n');
4275 bol |= lf;
4276 b_putchr(out, (lf && eol) ? eol : *in);
4277 in++;
4278 }
4279 return lf;
4280}
4281
Willy Tarreau9d22e562019-03-29 18:49:09 +01004282/* removes environment variable <name> from the environment as found in
4283 * environ. This is only provided as an alternative for systems without
4284 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004285 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004286 * <name> and to replace the matching pointers with the last pointer of
4287 * the array (since variables are not ordered).
4288 * It always returns 0 (success).
4289 */
4290int my_unsetenv(const char *name)
4291{
4292 extern char **environ;
4293 char **p = environ;
4294 int vars;
4295 int next;
4296 int len;
4297
4298 len = strlen(name);
4299 for (vars = 0; p[vars]; vars++)
4300 ;
4301 next = 0;
4302 while (next < vars) {
4303 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4304 next++;
4305 continue;
4306 }
4307 if (next < vars - 1)
4308 p[next] = p[vars - 1];
4309 p[--vars] = NULL;
4310 }
4311 return 0;
4312}
4313
Willy Tarreaudad36a32013-03-11 01:20:04 +01004314/* Convert occurrences of environment variables in the input string to their
4315 * corresponding value. A variable is identified as a series of alphanumeric
4316 * characters or underscores following a '$' sign. The <in> string must be
4317 * free()able. NULL returns NULL. The resulting string might be reallocated if
4318 * some expansion is made. Variable names may also be enclosed into braces if
4319 * needed (eg: to concatenate alphanum characters).
4320 */
4321char *env_expand(char *in)
4322{
4323 char *txt_beg;
4324 char *out;
4325 char *txt_end;
4326 char *var_beg;
4327 char *var_end;
4328 char *value;
4329 char *next;
4330 int out_len;
4331 int val_len;
4332
4333 if (!in)
4334 return in;
4335
4336 value = out = NULL;
4337 out_len = 0;
4338
4339 txt_beg = in;
4340 do {
4341 /* look for next '$' sign in <in> */
4342 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4343
4344 if (!*txt_end && !out) /* end and no expansion performed */
4345 return in;
4346
4347 val_len = 0;
4348 next = txt_end;
4349 if (*txt_end == '$') {
4350 char save;
4351
4352 var_beg = txt_end + 1;
4353 if (*var_beg == '{')
4354 var_beg++;
4355
4356 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004357 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004358 var_end++;
4359 }
4360
4361 next = var_end;
4362 if (*var_end == '}' && (var_beg > txt_end + 1))
4363 next++;
4364
4365 /* get value of the variable name at this location */
4366 save = *var_end;
4367 *var_end = '\0';
4368 value = getenv(var_beg);
4369 *var_end = save;
4370 val_len = value ? strlen(value) : 0;
4371 }
4372
Hubert Verstraete831962e2016-06-28 22:44:26 +02004373 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004374 if (txt_end > txt_beg) {
4375 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4376 out_len += txt_end - txt_beg;
4377 }
4378 if (val_len) {
4379 memcpy(out + out_len, value, val_len);
4380 out_len += val_len;
4381 }
4382 out[out_len] = 0;
4383 txt_beg = next;
4384 } while (*txt_beg);
4385
4386 /* here we know that <out> was allocated and that we don't need <in> anymore */
4387 free(in);
4388 return out;
4389}
4390
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004391
4392/* same as strstr() but case-insensitive and with limit length */
4393const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4394{
4395 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004396 unsigned int slen, plen;
4397 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004398
4399 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4400 return NULL;
4401
4402 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4403 return str1;
4404
4405 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4406 return NULL;
4407
4408 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 +02004409 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004410 start++;
4411 slen--;
4412 tmp1++;
4413
4414 if (tmp1 >= len_str1)
4415 return NULL;
4416
4417 /* if pattern longer than string */
4418 if (slen < plen)
4419 return NULL;
4420 }
4421
4422 sptr = start;
4423 pptr = (char *)str2;
4424
4425 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004426 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004427 sptr++;
4428 pptr++;
4429 tmp2++;
4430
4431 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4432 return start;
4433 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4434 return NULL;
4435 }
4436 }
4437 return NULL;
4438}
4439
Willy Tarreau3ff476e2022-03-30 10:02:56 +02004440/* Returns true if s1 < s2 < s3 otherwise zero. Both s1 and s3 may be NULL and
4441 * in this case only non-null strings are compared. This allows to pass initial
4442 * values in iterators and in sort functions.
4443 */
4444int strordered(const char *s1, const char *s2, const char *s3)
4445{
4446 return (!s1 || strcmp(s1, s2) < 0) && (!s3 || strcmp(s2, s3) < 0);
4447}
4448
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004449/* This function read the next valid utf8 char.
4450 * <s> is the byte srray to be decode, <len> is its length.
4451 * The function returns decoded char encoded like this:
4452 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4453 * are the length read. The decoded character is stored in <c>.
4454 */
4455unsigned char utf8_next(const char *s, int len, unsigned int *c)
4456{
4457 const unsigned char *p = (unsigned char *)s;
4458 int dec;
4459 unsigned char code = UTF8_CODE_OK;
4460
4461 if (len < 1)
4462 return UTF8_CODE_OK;
4463
4464 /* Check the type of UTF8 sequence
4465 *
4466 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4467 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4468 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4469 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4470 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4471 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4472 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4473 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4474 */
4475 switch (*p) {
4476 case 0x00 ... 0x7f:
4477 *c = *p;
4478 return UTF8_CODE_OK | 1;
4479
4480 case 0x80 ... 0xbf:
4481 *c = *p;
4482 return UTF8_CODE_BADSEQ | 1;
4483
4484 case 0xc0 ... 0xdf:
4485 if (len < 2) {
4486 *c = *p;
4487 return UTF8_CODE_BADSEQ | 1;
4488 }
4489 *c = *p & 0x1f;
4490 dec = 1;
4491 break;
4492
4493 case 0xe0 ... 0xef:
4494 if (len < 3) {
4495 *c = *p;
4496 return UTF8_CODE_BADSEQ | 1;
4497 }
4498 *c = *p & 0x0f;
4499 dec = 2;
4500 break;
4501
4502 case 0xf0 ... 0xf7:
4503 if (len < 4) {
4504 *c = *p;
4505 return UTF8_CODE_BADSEQ | 1;
4506 }
4507 *c = *p & 0x07;
4508 dec = 3;
4509 break;
4510
4511 case 0xf8 ... 0xfb:
4512 if (len < 5) {
4513 *c = *p;
4514 return UTF8_CODE_BADSEQ | 1;
4515 }
4516 *c = *p & 0x03;
4517 dec = 4;
4518 break;
4519
4520 case 0xfc ... 0xfd:
4521 if (len < 6) {
4522 *c = *p;
4523 return UTF8_CODE_BADSEQ | 1;
4524 }
4525 *c = *p & 0x01;
4526 dec = 5;
4527 break;
4528
4529 case 0xfe ... 0xff:
4530 default:
4531 *c = *p;
4532 return UTF8_CODE_BADSEQ | 1;
4533 }
4534
4535 p++;
4536
4537 while (dec > 0) {
4538
4539 /* need 0x10 for the 2 first bits */
4540 if ( ( *p & 0xc0 ) != 0x80 )
4541 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4542
4543 /* add data at char */
4544 *c = ( *c << 6 ) | ( *p & 0x3f );
4545
4546 dec--;
4547 p++;
4548 }
4549
4550 /* Check ovelong encoding.
4551 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4552 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4553 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4554 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004555 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004556 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4557 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4558 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4559 code |= UTF8_CODE_OVERLONG;
4560
4561 /* Check invalid UTF8 range. */
4562 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4563 (*c >= 0xfffe && *c <= 0xffff))
4564 code |= UTF8_CODE_INVRANGE;
4565
4566 return code | ((p-(unsigned char *)s)&0x0f);
4567}
4568
Maxime de Roucydc887852016-05-13 23:52:54 +02004569/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4570 * On failure : return 0 and <err> filled with an error message.
4571 * The caller is responsible for freeing the <err> and <str> copy
4572 * memory area using free()
4573 */
4574int list_append_word(struct list *li, const char *str, char **err)
4575{
4576 struct wordlist *wl;
4577
4578 wl = calloc(1, sizeof(*wl));
4579 if (!wl) {
4580 memprintf(err, "out of memory");
4581 goto fail_wl;
4582 }
4583
4584 wl->s = strdup(str);
4585 if (!wl->s) {
4586 memprintf(err, "out of memory");
4587 goto fail_wl_s;
4588 }
4589
Willy Tarreau2b718102021-04-21 07:32:39 +02004590 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004591
4592 return 1;
4593
4594fail_wl_s:
4595 free(wl->s);
4596fail_wl:
4597 free(wl);
4598 return 0;
4599}
4600
Willy Tarreau37101052019-05-20 16:48:20 +02004601/* indicates if a memory location may safely be read or not. The trick consists
4602 * in performing a harmless syscall using this location as an input and letting
4603 * the operating system report whether it's OK or not. For this we have the
4604 * stat() syscall, which will return EFAULT when the memory location supposed
4605 * to contain the file name is not readable. If it is readable it will then
4606 * either return 0 if the area contains an existing file name, or -1 with
4607 * another code. This must not be abused, and some audit systems might detect
4608 * this as abnormal activity. It's used only for unsafe dumps.
4609 */
4610int may_access(const void *ptr)
4611{
4612 struct stat buf;
4613
4614 if (stat(ptr, &buf) == 0)
4615 return 1;
4616 if (errno == EFAULT)
4617 return 0;
4618 return 1;
4619}
4620
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004621/* print a string of text buffer to <out>. The format is :
4622 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4623 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4624 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4625 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004626int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004627{
4628 unsigned char c;
Tim Duesterhus18795d42021-08-29 00:58:22 +02004629 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004630
Tim Duesterhus18795d42021-08-29 00:58:22 +02004631 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004632 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004633 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004634 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004635 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004636 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004637 }
4638 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004639 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004640 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004641 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004642 switch (c) {
4643 case ' ': c = ' '; break;
4644 case '\t': c = 't'; break;
4645 case '\n': c = 'n'; break;
4646 case '\r': c = 'r'; break;
4647 case '\e': c = 'e'; break;
4648 case '\\': c = '\\'; break;
4649 case '=': c = '='; break;
4650 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004651 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004652 }
4653 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004654 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004655 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004656 out->area[out->data++] = '\\';
4657 out->area[out->data++] = 'x';
4658 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4659 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004660 }
4661 ptr++;
4662 }
4663
4664 return ptr;
4665}
4666
4667/* print a buffer in hexa.
4668 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4669 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004670int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004671{
4672 unsigned char c;
4673 int ptr = 0;
4674
4675 while (ptr < bsize) {
4676 c = buf[ptr];
4677
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004678 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004679 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004680 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4681 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004682
4683 ptr++;
4684 }
4685 return ptr;
4686}
4687
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004688/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4689 * prepending each line with prefix <pfx>. The output is *not* initialized.
4690 * The output will not wrap pas the buffer's end so it is more optimal if the
4691 * caller makes sure the buffer is aligned first. A trailing zero will always
4692 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004693 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4694 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004695 */
Willy Tarreau37101052019-05-20 16:48:20 +02004696void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004697{
4698 const unsigned char *d = buf;
4699 int i, j, start;
4700
4701 d = (const unsigned char *)(((unsigned long)buf) & -16);
4702 start = ((unsigned long)buf) & 15;
4703
4704 for (i = 0; i < start + len; i += 16) {
4705 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4706
Willy Tarreau37101052019-05-20 16:48:20 +02004707 // 0: unchecked, 1: checked safe, 2: danger
4708 unsafe = !!unsafe;
4709 if (unsafe && !may_access(d + i))
4710 unsafe = 2;
4711
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004712 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004713 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004714 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004715 else if (unsafe > 1)
4716 chunk_strcat(out, "** ");
4717 else
4718 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004719
4720 if (j == 7)
4721 chunk_strcat(out, "- ");
4722 }
4723 chunk_strcat(out, " ");
4724 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004725 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004726 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004727 else if (unsafe > 1)
4728 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004729 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004730 chunk_appendf(out, "%c", d[i + j]);
4731 else
4732 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004733 }
4734 chunk_strcat(out, "\n");
4735 }
4736}
4737
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004738/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4739 * enclosed in brackets after the address itself, formatted on 14 chars
4740 * including the "0x" prefix. This is meant to be used as a prefix for code
4741 * areas. For example:
4742 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4743 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4744 * is emitted. A NULL <pfx> will be considered empty.
4745 */
4746void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4747{
4748 int ok = 0;
4749 int i;
4750
4751 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4752
4753 for (i = 0; i < n; i++) {
4754 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4755 ok = may_access(addr + i);
4756 if (ok)
4757 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4758 else
4759 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4760 }
4761}
4762
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004763/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4764 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4765 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4766 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4767 * lines are respected within the limit of 70 output chars. Lines that are
4768 * continuation of a previous truncated line begin with "+" instead of " "
4769 * after the offset. The new pointer is returned.
4770 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004771int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004772 int *line, int ptr)
4773{
4774 int end;
4775 unsigned char c;
4776
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004777 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004778 if (end > out->size)
4779 return ptr;
4780
4781 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4782
4783 while (ptr < len && ptr < bsize) {
4784 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004785 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004786 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004787 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004788 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004789 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004790 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004791 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004792 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004793 switch (c) {
4794 case '\t': c = 't'; break;
4795 case '\n': c = 'n'; break;
4796 case '\r': c = 'r'; break;
4797 case '\e': c = 'e'; break;
4798 case '\\': c = '\\'; break;
4799 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004800 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004801 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004802 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004803 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004804 out->area[out->data++] = '\\';
4805 out->area[out->data++] = 'x';
4806 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4807 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004808 }
4809 if (buf[ptr++] == '\n') {
4810 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004811 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004812 *line = ptr;
4813 return ptr;
4814 }
4815 }
4816 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004817 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004818 return ptr;
4819}
4820
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004821/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004822 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4823 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004824 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004825void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4826 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004827{
Willy Tarreau73459792017-04-11 07:58:08 +02004828 unsigned int i;
4829 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004830
4831 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4832 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004833 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004834 for (j = 0; j < 8; j++) {
4835 if (b + j >= 0 && b + j < len)
4836 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4837 else
4838 fprintf(out, " ");
4839 }
4840
4841 if (b + j >= 0 && b + j < len)
4842 fputc('-', out);
4843 else
4844 fputc(' ', out);
4845
4846 for (j = 8; j < 16; j++) {
4847 if (b + j >= 0 && b + j < len)
4848 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4849 else
4850 fprintf(out, " ");
4851 }
4852
4853 fprintf(out, " ");
4854 for (j = 0; j < 16; j++) {
4855 if (b + j >= 0 && b + j < len) {
4856 if (isprint((unsigned char)buf[b + j]))
4857 fputc((unsigned char)buf[b + j], out);
4858 else
4859 fputc('.', out);
4860 }
4861 else
4862 fputc(' ', out);
4863 }
4864 fputc('\n', out);
4865 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004866}
4867
Willy Tarreaubb869862020-04-16 10:52:41 +02004868/* Tries to report the executable path name on platforms supporting this. If
4869 * not found or not possible, returns NULL.
4870 */
4871const char *get_exec_path()
4872{
4873 const char *ret = NULL;
4874
David Carlier43a56852022-03-04 15:50:48 +00004875#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004876 long execfn = getauxval(AT_EXECFN);
4877
4878 if (execfn && execfn != ENOENT)
4879 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004880#elif defined(__FreeBSD__)
4881 Elf_Auxinfo *auxv;
4882 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4883 if (auxv->a_type == AT_EXECPATH) {
4884 ret = (const char *)auxv->a_un.a_ptr;
4885 break;
4886 }
4887 }
David Carlierbd2cced2021-08-17 08:44:25 +01004888#elif defined(__NetBSD__)
4889 AuxInfo *auxv;
4890 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4891 if (auxv->a_type == AT_SUN_EXECNAME) {
4892 ret = (const char *)auxv->a_v;
4893 break;
4894 }
4895 }
David Carlier7198c702022-05-14 17:15:49 +01004896#elif defined(__sun)
4897 ret = getexecname();
Willy Tarreaubb869862020-04-16 10:52:41 +02004898#endif
4899 return ret;
4900}
4901
Baruch Siache1651b22020-07-24 07:52:20 +03004902#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004903/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4904 * also returns the symbol size in <size>, otherwise returns 0 there.
4905 */
4906static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4907{
4908 int ret;
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004909#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreauf3d5c4b2022-01-28 09:42:29 +01004910 const ElfW(Sym) *sym __attribute__((may_alias));
Willy Tarreau9133e482020-03-04 10:19:36 +01004911
4912 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4913 if (ret)
4914 *size = sym ? sym->st_size : 0;
4915#else
David Carlierae5c42f2021-12-31 08:15:29 +00004916#if defined(__sun)
4917 ret = dladdr((void *)addr, dli);
4918#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004919 ret = dladdr(addr, dli);
David Carlierae5c42f2021-12-31 08:15:29 +00004920#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004921 *size = 0;
4922#endif
4923 return ret;
4924}
Willy Tarreau64192392021-05-05 09:06:21 +02004925
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004926/* Sets build_is_static to true if we detect a static build. Some older glibcs
4927 * tend to crash inside dlsym() in static builds, but tests show that at least
4928 * dladdr() still works (and will fail to resolve anything of course). Thus we
4929 * try to determine if we're on a static build to avoid calling dlsym() in this
4930 * case.
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004931 */
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004932void check_if_static_build()
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004933{
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004934 Dl_info dli = { };
4935 size_t size = 0;
4936
4937 /* Now let's try to be smarter */
4938 if (!dladdr_and_size(&main, &dli, &size))
4939 build_is_static = 1;
4940 else
4941 build_is_static = 0;
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004942}
4943
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004944INITCALL0(STG_PREPARE, check_if_static_build);
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004945
Willy Tarreau64192392021-05-05 09:06:21 +02004946/* Tries to retrieve the address of the first occurrence symbol <name>.
4947 * Note that NULL in return is not always an error as a symbol may have that
4948 * address in special situations.
4949 */
4950void *get_sym_curr_addr(const char *name)
4951{
4952 void *ptr = NULL;
4953
4954#ifdef RTLD_DEFAULT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004955 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004956 ptr = dlsym(RTLD_DEFAULT, name);
Willy Tarreau64192392021-05-05 09:06:21 +02004957#endif
4958 return ptr;
4959}
4960
4961
4962/* Tries to retrieve the address of the next occurrence of symbol <name>
4963 * Note that NULL in return is not always an error as a symbol may have that
4964 * address in special situations.
4965 */
4966void *get_sym_next_addr(const char *name)
4967{
4968 void *ptr = NULL;
4969
4970#ifdef RTLD_NEXT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004971 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02004972 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004973#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004974 return ptr;
4975}
4976
4977#else /* elf & linux & dl */
4978
4979/* no possible resolving on other platforms at the moment */
4980void *get_sym_curr_addr(const char *name)
4981{
4982 return NULL;
4983}
4984
4985void *get_sym_next_addr(const char *name)
4986{
4987 return NULL;
4988}
4989
4990#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004991
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004992/* Tries to append to buffer <buf> some indications about the symbol at address
4993 * <addr> using the following form:
4994 * lib:+0xoffset (unresolvable address from lib's base)
4995 * main+0xoffset (unresolvable address from main (+/-))
4996 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4997 * name (resolved exact exec address)
4998 * lib:name (resolved exact lib address)
4999 * name+0xoffset/0xsize (resolved address within exec symbol)
5000 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
5001 *
5002 * The file name (lib or executable) is limited to what lies between the last
5003 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
5004 * 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 +03005005 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005006 *
5007 * The symbol's base address is returned, or NULL when unresolved, in order to
5008 * allow the caller to match it against known ones.
5009 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01005010const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005011{
5012 const struct {
5013 const void *func;
5014 const char *name;
5015 } fcts[] = {
5016 { .func = process_stream, .name = "process_stream" },
5017 { .func = task_run_applet, .name = "task_run_applet" },
Willy Tarreau462b9892022-05-18 18:06:53 +02005018 { .func = sc_conn_io_cb, .name = "sc_conn_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01005019 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005020 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
5021 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01005022 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005023 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
5024 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01005025 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01005026#ifdef USE_THREAD
5027 { .func = accept_queue_process, .name = "accept_queue_process" },
5028#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005029#ifdef USE_LUA
5030 { .func = hlua_process_task, .name = "hlua_process_task" },
5031#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005032#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005033 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
5034 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
5035#endif
5036 };
5037
Baruch Siache1651b22020-07-24 07:52:20 +03005038#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005039 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01005040 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005041 const char *fname, *p;
5042#endif
5043 int i;
5044
5045 if (pfx)
5046 chunk_appendf(buf, "%s", pfx);
5047
5048 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
5049 if (addr == fcts[i].func) {
5050 chunk_appendf(buf, "%s", fcts[i].name);
5051 return addr;
5052 }
5053 }
5054
Baruch Siache1651b22020-07-24 07:52:20 +03005055#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005056 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01005057 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005058 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005059
5060 /* 1. prefix the library name if it's not the same object as the one
5061 * that contains the main function. The name is picked between last '/'
5062 * and first following '.'.
5063 */
5064 if (!dladdr(main, &dli_main))
5065 dli_main.dli_fbase = NULL;
5066
5067 if (dli_main.dli_fbase != dli.dli_fbase) {
5068 fname = dli.dli_fname;
5069 p = strrchr(fname, '/');
5070 if (p++)
5071 fname = p;
5072 p = strchr(fname, '.');
5073 if (!p)
5074 p = fname + strlen(fname);
5075
5076 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
5077 }
5078
5079 /* 2. symbol name */
5080 if (dli.dli_sname) {
5081 /* known, dump it and return symbol's address (exact or relative) */
5082 chunk_appendf(buf, "%s", dli.dli_sname);
5083 if (addr != dli.dli_saddr) {
5084 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01005085 if (size)
5086 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005087 }
5088 return dli.dli_saddr;
5089 }
5090 else if (dli_main.dli_fbase != dli.dli_fbase) {
5091 /* unresolved symbol from a known library, report relative offset */
5092 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
5093 return NULL;
5094 }
Baruch Siache1651b22020-07-24 07:52:20 +03005095#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005096 unknown:
5097 /* unresolved symbol from the main file, report relative offset to main */
5098 if ((void*)addr < (void*)main)
5099 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
5100 else
5101 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
5102 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01005103}
5104
Willy Tarreau6ab7b212021-12-28 09:57:10 +01005105/* On systems where this is supported, let's provide a possibility to enumerate
5106 * the list of object files. The output is appended to a buffer initialized by
5107 * the caller, with one name per line. A trailing zero is always emitted if data
5108 * are written. Only real objects are dumped (executable and .so libs). The
5109 * function returns non-zero if it dumps anything. These functions do not make
5110 * use of the trash so that it is possible for the caller to call them with the
5111 * trash on input. The output format may be platform-specific but at least one
5112 * version must emit raw object file names when argument is zero.
5113 */
5114#if defined(HA_HAVE_DUMP_LIBS)
5115# if defined(HA_HAVE_DL_ITERATE_PHDR)
5116/* the private <data> we pass below is a dump context initialized like this */
5117struct dl_dump_ctx {
5118 struct buffer *buf;
5119 int with_addr;
5120};
5121
5122static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5123{
5124 struct dl_dump_ctx *ctx = data;
5125 const char *fname;
5126 size_t p1, p2, beg, end;
5127 int idx;
5128
5129 if (!info || !info->dlpi_name)
5130 goto leave;
5131
5132 if (!*info->dlpi_name)
5133 fname = get_exec_path();
5134 else if (strchr(info->dlpi_name, '/'))
5135 fname = info->dlpi_name;
5136 else
5137 /* else it's a VDSO or similar and we're not interested */
5138 goto leave;
5139
5140 if (!ctx->with_addr)
5141 goto dump_name;
5142
5143 /* virtual addresses are relative to the load address and are per
5144 * pseudo-header, so we have to scan them all to find the furthest
5145 * one from the beginning. In this case we only dump entries if
5146 * they have at least one section.
5147 */
5148 beg = ~0; end = 0;
5149 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5150 if (!info->dlpi_phdr[idx].p_memsz)
5151 continue;
5152 p1 = info->dlpi_phdr[idx].p_vaddr;
5153 if (p1 < beg)
5154 beg = p1;
5155 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5156 if (p2 > end)
5157 end = p2;
5158 }
5159
5160 if (!idx)
5161 goto leave;
5162
5163 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5164 (ullong)info->dlpi_addr + beg,
5165 (ullong)info->dlpi_addr + end,
5166 (ullong)(end - beg + 1));
5167 dump_name:
5168 chunk_appendf(ctx->buf, "%s\n", fname);
5169 leave:
5170 return 0;
5171}
5172
5173/* dumps lib names and optionally address ranges */
5174int dump_libs(struct buffer *output, int with_addr)
5175{
5176 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5177 size_t old_data = output->data;
5178
5179 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5180 return output->data != old_data;
5181}
5182# else // no DL_ITERATE_PHDR
5183# error "No dump_libs() function for this platform"
5184# endif
5185#else // no HA_HAVE_DUMP_LIBS
5186
5187/* unsupported platform: do not dump anything */
5188int dump_libs(struct buffer *output, int with_addr)
5189{
5190 return 0;
5191}
5192
5193#endif // HA_HAVE_DUMP_LIBS
5194
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005195/*
5196 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005197 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005198 *
5199 * First, initializes the value with <sz> as address to 0 and initializes the
5200 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5201 * address updating <sz> pointed value to the size of this array.
5202 *
5203 * Returns 1 if succeeded, 0 if not.
5204 */
5205int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5206{
5207 unsigned int *n;
5208 const char *s, *end;
5209
5210 s = str;
5211 *sz = 0;
5212 end = str + strlen(str);
5213 *nums = n = NULL;
5214
5215 while (1) {
5216 unsigned int r;
5217
5218 if (s >= end)
5219 break;
5220
5221 r = read_uint(&s, end);
5222 /* Expected characters after having read an uint: '\0' or '.',
5223 * if '.', must not be terminal.
5224 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005225 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5226 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005227 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005228 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005229
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005230 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005231 if (!n)
5232 return 0;
5233
5234 n[(*sz)++] = r;
5235 }
5236 *nums = n;
5237
5238 return 1;
5239}
5240
Willy Tarreau4d589e72019-08-23 19:02:26 +02005241
5242/* returns the number of bytes needed to encode <v> as a varint. An inline
5243 * version exists for use with constants (__varint_bytes()).
5244 */
5245int varint_bytes(uint64_t v)
5246{
5247 int len = 1;
5248
5249 if (v >= 240) {
5250 v = (v - 240) >> 4;
5251 while (1) {
5252 len++;
5253 if (v < 128)
5254 break;
5255 v = (v - 128) >> 7;
5256 }
5257 }
5258 return len;
5259}
5260
Willy Tarreau52bf8392020-03-08 00:42:37 +01005261
5262/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005263static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005264
5265/* This is a thread-safe implementation of xoroshiro128** described below:
5266 * http://prng.di.unimi.it/
5267 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5268 * supports fast jumps and passes all common quality tests. It is thread-safe,
5269 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5270 * local lock on other ones.
5271 */
5272uint64_t ha_random64()
5273{
Willy Tarreau1544c142020-03-12 00:31:18 +01005274 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5275 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005276
5277#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5278 static HA_SPINLOCK_T rand_lock;
5279
5280 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5281#endif
5282
5283 old[0] = ha_random_state[0];
5284 old[1] = ha_random_state[1];
5285
5286#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5287 do {
5288#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005289 new[1] = old[0] ^ old[1];
5290 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5291 new[1] = rotl64(new[1], 37); // c
5292
5293#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5294 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5295#else
5296 ha_random_state[0] = new[0];
5297 ha_random_state[1] = new[1];
5298#if defined(USE_THREAD)
5299 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5300#endif
5301#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005302 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005303}
5304
5305/* seeds the random state using up to <len> bytes from <seed>, starting with
5306 * the first non-zero byte.
5307 */
5308void ha_random_seed(const unsigned char *seed, size_t len)
5309{
5310 size_t pos;
5311
5312 /* the seed must not be all zeroes, so we pre-fill it with alternating
5313 * bits and overwrite part of them with the block starting at the first
5314 * non-zero byte from the seed.
5315 */
5316 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5317
5318 for (pos = 0; pos < len; pos++)
5319 if (seed[pos] != 0)
5320 break;
5321
5322 if (pos == len)
5323 return;
5324
5325 seed += pos;
5326 len -= pos;
5327
5328 if (len > sizeof(ha_random_state))
5329 len = sizeof(ha_random_state);
5330
5331 memcpy(ha_random_state, seed, len);
5332}
5333
5334/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5335 * and is equivalent to calling ha_random64() as many times. It is used to
5336 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5337 * different generators (i.e. different processes after a fork). The <dist>
5338 * argument is the distance to jump to and is used in a loop so it rather not
5339 * be too large if the processing time is a concern.
5340 *
5341 * BEWARE: this function is NOT thread-safe and must not be called during
5342 * concurrent accesses to ha_random64().
5343 */
5344void ha_random_jump96(uint32_t dist)
5345{
5346 while (dist--) {
5347 uint64_t s0 = 0;
5348 uint64_t s1 = 0;
5349 int b;
5350
5351 for (b = 0; b < 64; b++) {
5352 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5353 s0 ^= ha_random_state[0];
5354 s1 ^= ha_random_state[1];
5355 }
5356 ha_random64();
5357 }
5358
5359 for (b = 0; b < 64; b++) {
5360 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5361 s0 ^= ha_random_state[0];
5362 s1 ^= ha_random_state[1];
5363 }
5364 ha_random64();
5365 }
5366 ha_random_state[0] = s0;
5367 ha_random_state[1] = s1;
5368 }
5369}
5370
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005371/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5372 * bytes large.
5373 */
5374void ha_generate_uuid(struct buffer *output)
5375{
5376 uint32_t rnd[4];
5377 uint64_t last;
5378
5379 last = ha_random64();
5380 rnd[0] = last;
5381 rnd[1] = last >> 32;
5382
5383 last = ha_random64();
5384 rnd[2] = last;
5385 rnd[3] = last >> 32;
5386
5387 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5388 rnd[0],
5389 rnd[1] & 0xFFFF,
5390 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5391 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5392 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5393}
5394
5395
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005396/* only used by parse_line() below. It supports writing in place provided that
5397 * <in> is updated to the next location before calling it. In that case, the
5398 * char at <in> may be overwritten.
5399 */
5400#define EMIT_CHAR(x) \
5401 do { \
5402 char __c = (char)(x); \
5403 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5404 err |= PARSE_ERR_OVERLAP; \
5405 if (outpos >= outmax) \
5406 err |= PARSE_ERR_TOOLARGE; \
5407 if (!err) \
5408 out[outpos] = __c; \
5409 outpos++; \
5410 } while (0)
5411
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005412/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005413 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5414 * extraneous ones are not emitted but <outlen> is updated so that the caller
5415 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5416 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005417 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5418 * it is guaranteed that at least one arg will point to the zero. It is safe
5419 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005420 *
5421 * <out> may overlap with <in> provided that it never goes further, in which
5422 * case the parser will accept to perform in-place parsing and unquoting/
5423 * unescaping but only if environment variables do not lead to expansion that
5424 * causes overlapping, otherwise the input string being destroyed, the error
5425 * will not be recoverable. Note that even during out-of-place <in> will
5426 * experience temporary modifications in-place for variable resolution and must
5427 * be writable, and will also receive zeroes to delimit words when using
5428 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5429 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5430 * starting point of the first invalid character sequence or unmatched
5431 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5432 * error reporting might be difficult since zeroes will have been inserted into
5433 * the string. One solution for the caller may consist in replacing all args
5434 * delimiters with spaces in this case.
5435 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005436uint32_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 +02005437{
5438 char *quote = NULL;
5439 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005440 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005441 unsigned char hex1, hex2;
5442 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005443 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005444 size_t outpos = 0;
5445 int squote = 0;
5446 int dquote = 0;
5447 int arg = 0;
5448 uint32_t err = 0;
5449
5450 *nbargs = 0;
5451 *outlen = 0;
5452
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005453 /* argsmax may be -1 here, protecting args[] from any write */
5454 if (arg < argsmax)
5455 args[arg] = out;
5456
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005457 while (1) {
5458 if (*in >= '-' && *in != '\\') {
5459 /* speedup: directly send all regular chars starting
5460 * with '-', '.', '/', alnum etc...
5461 */
5462 EMIT_CHAR(*in++);
5463 continue;
5464 }
5465 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5466 /* end of line */
5467 break;
5468 }
5469 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5470 /* comment */
5471 break;
5472 }
5473 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5474 if (dquote) {
5475 dquote = 0;
5476 quote = NULL;
5477 }
5478 else {
5479 dquote = 1;
5480 quote = in;
5481 }
5482 in++;
5483 continue;
5484 }
5485 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5486 if (squote) {
5487 squote = 0;
5488 quote = NULL;
5489 }
5490 else {
5491 squote = 1;
5492 quote = in;
5493 }
5494 in++;
5495 continue;
5496 }
5497 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5498 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5499 * C equivalent value but only when they have a special meaning and within
5500 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5501 */
5502 char tosend = *in;
5503
5504 switch (in[1]) {
5505 case ' ':
5506 case '\\':
5507 tosend = in[1];
5508 in++;
5509 break;
5510
5511 case 't':
5512 tosend = '\t';
5513 in++;
5514 break;
5515
5516 case 'n':
5517 tosend = '\n';
5518 in++;
5519 break;
5520
5521 case 'r':
5522 tosend = '\r';
5523 in++;
5524 break;
5525
5526 case '#':
5527 /* escaping of "#" only if comments are supported */
5528 if (opts & PARSE_OPT_SHARP)
5529 in++;
5530 tosend = *in;
5531 break;
5532
5533 case '\'':
5534 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5535 if (opts & PARSE_OPT_SQUOTE && !squote)
5536 in++;
5537 tosend = *in;
5538 break;
5539
5540 case '"':
5541 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5542 if (opts & PARSE_OPT_DQUOTE && !squote)
5543 in++;
5544 tosend = *in;
5545 break;
5546
5547 case '$':
5548 /* escaping of '$' only inside double quotes and only if env supported */
5549 if (opts & PARSE_OPT_ENV && dquote)
5550 in++;
5551 tosend = *in;
5552 break;
5553
5554 case 'x':
5555 if (!ishex(in[2]) || !ishex(in[3])) {
5556 /* invalid or incomplete hex sequence */
5557 err |= PARSE_ERR_HEX;
5558 if (errptr)
5559 *errptr = in;
5560 goto leave;
5561 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005562 hex1 = toupper((unsigned char)in[2]) - '0';
5563 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005564 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5565 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5566 tosend = (hex1 << 4) + hex2;
5567 in += 3;
5568 break;
5569
5570 default:
5571 /* other combinations are not escape sequences */
5572 break;
5573 }
5574
5575 in++;
5576 EMIT_CHAR(tosend);
5577 }
5578 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5579 /* a non-escaped space is an argument separator */
5580 while (isspace((unsigned char)*in))
5581 in++;
5582 EMIT_CHAR(0);
5583 arg++;
5584 if (arg < argsmax)
5585 args[arg] = out + outpos;
5586 else
5587 err |= PARSE_ERR_TOOMANY;
5588 }
5589 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5590 /* environment variables are evaluated anywhere, or only
5591 * inside double quotes if they are supported.
5592 */
5593 char *var_name;
5594 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005595 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005596
5597 in++;
5598
5599 if (*in == '{')
5600 brace = in++;
5601
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005602 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005603 /* unacceptable character in variable name */
5604 err |= PARSE_ERR_VARNAME;
5605 if (errptr)
5606 *errptr = in;
5607 goto leave;
5608 }
5609
5610 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005611 if (*in == '.')
5612 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005613 while (isalnum((unsigned char)*in) || *in == '_')
5614 in++;
5615
5616 save_char = *in;
5617 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005618 if (unlikely(*var_name == '.')) {
5619 /* internal pseudo-variables */
5620 if (strcmp(var_name, ".LINE") == 0)
5621 value = ultoa(global.cfg_curr_line);
5622 else if (strcmp(var_name, ".FILE") == 0)
5623 value = global.cfg_curr_file;
5624 else if (strcmp(var_name, ".SECTION") == 0)
5625 value = global.cfg_curr_section;
5626 else {
5627 /* unsupported internal variable name */
5628 err |= PARSE_ERR_VARNAME;
5629 if (errptr)
5630 *errptr = var_name;
5631 goto leave;
5632 }
5633 } else {
5634 value = getenv(var_name);
5635 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005636 *in = save_char;
5637
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005638 /* support for '[*]' sequence to force word expansion,
5639 * only available inside braces */
5640 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5641 word_expand = in++;
5642
5643 if (*in++ != '*' || *in++ != ']') {
5644 err |= PARSE_ERR_WRONG_EXPAND;
5645 if (errptr)
5646 *errptr = word_expand;
5647 goto leave;
5648 }
5649 }
5650
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005651 if (brace) {
Willy Tarreauec347b12021-11-18 17:42:50 +01005652 if (*in == '-') {
5653 /* default value starts just after the '-' */
5654 if (!value)
5655 value = in + 1;
5656
5657 while (*in && *in != '}')
5658 in++;
5659 if (!*in)
5660 goto no_brace;
5661 *in = 0; // terminate the default value
5662 }
5663 else if (*in != '}') {
5664 no_brace:
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005665 /* unmatched brace */
5666 err |= PARSE_ERR_BRACE;
5667 if (errptr)
5668 *errptr = brace;
5669 goto leave;
5670 }
Willy Tarreauec347b12021-11-18 17:42:50 +01005671
5672 /* brace found, skip it */
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005673 in++;
5674 brace = NULL;
5675 }
5676
5677 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005678 while (*value) {
5679 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005680 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005681 EMIT_CHAR(0);
5682 ++arg;
5683 if (arg < argsmax)
5684 args[arg] = out + outpos;
5685 else
5686 err |= PARSE_ERR_TOOMANY;
5687
5688 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005689 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005690 ;
5691 } else {
5692 EMIT_CHAR(*value++);
5693 }
5694 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005695 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005696 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005697 }
5698 else {
5699 /* any other regular char */
5700 EMIT_CHAR(*in++);
5701 }
5702 }
5703
5704 /* end of output string */
5705 EMIT_CHAR(0);
5706 arg++;
5707
5708 if (quote) {
5709 /* unmatched quote */
5710 err |= PARSE_ERR_QUOTE;
5711 if (errptr)
5712 *errptr = quote;
5713 goto leave;
5714 }
5715 leave:
5716 *nbargs = arg;
5717 *outlen = outpos;
5718
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005719 /* empty all trailing args by making them point to the trailing zero,
5720 * at least the last one in any case.
5721 */
5722 if (arg > argsmax)
5723 arg = argsmax;
5724
5725 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005726 args[arg++] = out + outpos - 1;
5727
5728 return err;
5729}
5730#undef EMIT_CHAR
5731
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005732/* This is used to sanitize an input line that's about to be used for error reporting.
5733 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5734 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5735 * If non-printable chars are present in the output. It returns the new offset <pos>
5736 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5737 * be at least 6 to support two "..." otherwise the result is undefined. The line
5738 * itself must have at least 7 chars allocated for the same reason.
5739 */
5740size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5741{
5742 size_t shift = 0;
5743 char *out = line;
5744 char *in = line;
5745 char *end = line + width;
5746
5747 if (pos >= width) {
5748 /* if we have to shift, we'll be out of context, so let's
5749 * try to put <pos> at the center of width.
5750 */
5751 shift = pos - width / 2;
5752 in += shift + 3;
5753 end = out + width - 3;
5754 out[0] = out[1] = out[2] = '.';
5755 out += 3;
5756 }
5757
5758 while (out < end && *in) {
5759 if (isspace((unsigned char)*in))
5760 *out++ = ' ';
5761 else if (isprint((unsigned char)*in))
5762 *out++ = *in;
5763 else
5764 *out++ = '?';
5765 in++;
5766 }
5767
5768 if (end < line + width) {
5769 out[0] = out[1] = out[2] = '.';
5770 out += 3;
5771 }
5772
5773 *out++ = 0;
5774 return pos - shift;
5775}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005776
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005777/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005778 * transitions between characters. <fp> is a 1024-entries array indexed as
5779 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005780 * 1..26=letter, 27=digit, 28=other/begin/end.
5781 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005782 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005783void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005784{
5785 const char *p;
5786 int from, to;
5787 int c;
5788
Willy Tarreauba2c4452021-03-12 09:01:52 +01005789 from = 28; // begin
5790 for (p = word; *p; p++) {
5791 c = tolower(*p);
5792 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005793 case 'a'...'z': to = c - 'a' + 1; break;
5794 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5795 case '0'...'9': to = 27; break;
5796 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005797 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005798 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005799 fp[32 * from + to]++;
5800 from = to;
5801 }
5802 to = 28; // end
5803 fp[32 * from + to]++;
5804}
5805
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005806/* Initialize array <fp> with the fingerprint of word <word> by counting the
5807 * transitions between characters. <fp> is a 1024-entries array indexed as
5808 * 32*from+to. Positions for 'from' and 'to' are:
5809 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5810 */
5811void make_word_fingerprint(uint8_t *fp, const char *word)
5812{
5813 memset(fp, 0, 1024);
5814 update_word_fingerprint(fp, word);
5815}
5816
Willy Tarreauba2c4452021-03-12 09:01:52 +01005817/* Return the distance between two word fingerprints created by function
5818 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005819 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005820 */
5821int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5822{
5823 int i, k, dist = 0;
5824
5825 for (i = 0; i < 1024; i++) {
5826 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005827 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005828 }
5829 return dist;
5830}
5831
William Lallemand3aeb3f92021-08-21 23:59:56 +02005832/*
5833 * This function compares the loaded openssl version with a string <version>
5834 * This function use the same return code as compare_current_version:
5835 *
5836 * -1 : the version in argument is older than the current openssl version
5837 * 0 : the version in argument is the same as the current openssl version
5838 * 1 : the version in argument is newer than the current openssl version
5839 *
5840 * Or some errors:
5841 * -2 : openssl is not available on this process
5842 * -3 : the version in argument is not parsable
5843 */
5844int openssl_compare_current_version(const char *version)
5845{
5846#ifdef USE_OPENSSL
5847 int numversion;
5848
5849 numversion = openssl_version_parser(version);
5850 if (numversion == 0)
5851 return -3;
5852
5853 if (numversion < OPENSSL_VERSION_NUMBER)
5854 return -1;
5855 else if (numversion > OPENSSL_VERSION_NUMBER)
5856 return 1;
5857 else
5858 return 0;
5859#else
5860 return -2;
5861#endif
5862}
5863
Remi Tricot-Le Bretonb01179a2021-10-11 15:34:12 +02005864/*
5865 * This function compares the loaded openssl name with a string <name>
5866 * This function returns 0 if the OpenSSL name starts like the passed parameter,
5867 * 1 otherwise.
5868 */
5869int openssl_compare_current_name(const char *name)
5870{
5871#ifdef USE_OPENSSL
5872 int name_len = 0;
5873 const char *openssl_version = OpenSSL_version(OPENSSL_VERSION);
5874
5875 if (name) {
5876 name_len = strlen(name);
5877 if (strlen(name) <= strlen(openssl_version))
5878 return strncmp(openssl_version, name, name_len);
5879 }
5880#endif
5881 return 1;
5882}
5883
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005884#if defined(RTLD_DEFAULT) || defined(RTLD_NEXT)
5885/* redefine dlopen() so that we can detect unexpected replacement of some
5886 * critical symbols, typically init/alloc/free functions coming from alternate
5887 * libraries. When called, a tainted flag is set (TAINTED_SHARED_LIBS).
5888 */
5889void *dlopen(const char *filename, int flags)
5890{
5891 static void *(*_dlopen)(const char *filename, int flags);
Willy Tarreau177aed52022-06-19 16:49:51 +02005892 struct {
5893 const char *name;
5894 void *curr, *next;
5895 } check_syms[] = {
5896 { .name = "malloc", },
5897 { .name = "free", },
5898 { .name = "SSL_library_init", },
5899 { .name = "X509_free", },
5900 /* insert only above, 0 must be the last one */
5901 { 0 },
5902 };
5903 const char *trace;
5904 void *addr;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005905 void *ret;
Willy Tarreau177aed52022-06-19 16:49:51 +02005906 int sym = 0;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005907
5908 if (!_dlopen) {
5909 _dlopen = get_sym_next_addr("dlopen");
5910 if (!_dlopen || _dlopen == dlopen) {
5911 _dlopen = NULL;
5912 return NULL;
5913 }
5914 }
5915
Willy Tarreau177aed52022-06-19 16:49:51 +02005916 /* save a few pointers to critical symbols. We keep a copy of both the
5917 * current and the next value, because we might already have replaced
5918 * some of them (e.g. malloc/free with DEBUG_MEM_STATS), and we're only
5919 * interested in verifying that a loaded library doesn't come with a
5920 * completely different definition that would be incompatible.
5921 */
5922 for (sym = 0; check_syms[sym].name; sym++) {
5923 check_syms[sym].curr = get_sym_curr_addr(check_syms[sym].name);
5924 check_syms[sym].next = get_sym_next_addr(check_syms[sym].name);
5925 }
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005926
5927 /* now open the requested lib */
5928 ret = _dlopen(filename, flags);
5929 if (!ret)
5930 return ret;
5931
5932 mark_tainted(TAINTED_SHARED_LIBS);
5933
Willy Tarreau177aed52022-06-19 16:49:51 +02005934 /* and check that critical symbols didn't change */
5935 for (sym = 0; check_syms[sym].name; sym++) {
5936 if (!check_syms[sym].curr && !check_syms[sym].next)
5937 continue;
5938
5939 addr = dlsym(ret, check_syms[sym].name);
5940 if (!addr || addr == check_syms[sym].curr || addr == check_syms[sym].next)
5941 continue;
5942
5943 /* OK it's clear that this symbol was redefined */
5944 mark_tainted(TAINTED_REDEFINITION);
5945
5946 trace = hlua_show_current_location("\n ");
5947 ha_warning("dlopen(): shared library '%s' brings a different definition of symbol '%s'. The process cannot be trusted anymore!%s%s\n",
5948 filename, check_syms[sym].name,
5949 trace ? " Suspected call location: \n " : "",
5950 trace ? trace : "");
5951 }
5952
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005953 return ret;
5954}
5955#endif
5956
Willy Tarreau06e69b52021-03-02 14:01:35 +01005957static int init_tools_per_thread()
5958{
5959 /* Let's make each thread start from a different position */
5960 statistical_prng_state += tid * MAX_THREADS;
5961 if (!statistical_prng_state)
5962 statistical_prng_state++;
5963 return 1;
5964}
5965REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005966
Willy Tarreaubaaee002006-06-26 02:48:02 +02005967/*
5968 * Local variables:
5969 * c-indent-level: 8
5970 * c-basic-offset: 8
5971 * End:
5972 */