blob: 1bbdef13e6d7779861a49e7b358cdef5527e66d8 [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.com49a32282021-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 Carlier1b9d57d2021-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
Willy Tarreau1ee71dd2021-08-30 10:15:35 +020046#if 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>
Willy Tarreauc13ed532020-06-02 10:22:45 +020054#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020055#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020056#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020057#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020058#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020059#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010060#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020061#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010062#include <haproxy/resolvers.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010063#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020064#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020065#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020066#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020067#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010068
Thierry Fournier93127942016-01-20 18:49:45 +010069/* This macro returns false if the test __x is false. Many
70 * of the following parsing function must be abort the processing
71 * if it returns 0, so this macro is useful for writing light code.
72 */
73#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
74
Willy Tarreau56adcf22012-12-23 18:00:29 +010075/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020076 * 2^64-1 = 18446744073709551615 or
77 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020078 *
79 * The HTML version needs room for adding the 25 characters
80 * '<span class="rls"></span>' around digits at positions 3N+1 in order
81 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020082 */
Christopher Faulet99bca652017-11-14 16:47:26 +010083THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
84THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020085
Willy Tarreau588297f2014-06-16 15:16:40 +020086/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
87 * to quote strings larger than a max configuration line.
88 */
Christopher Faulet99bca652017-11-14 16:47:26 +010089THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
90THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020091
Willy Tarreau06e69b52021-03-02 14:01:35 +010092/* thread-local PRNG state. It's modified to start from a different sequence
93 * on all threads upon startup. It must not be used or anything beyond getting
94 * statistical values as it's 100% predictable.
95 */
96THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
97
Willy Tarreau263aacd2022-07-18 13:58:17 +020098/* set to true if this is a static build */
99int build_is_static = 0;
100
Willy Tarreaubaaee002006-06-26 02:48:02 +0200101/*
William Lallemande7340ec2012-01-24 11:15:39 +0100102 * unsigned long long ASCII representation
103 *
104 * return the last char '\0' or NULL if no enough
105 * space in dst
106 */
107char *ulltoa(unsigned long long n, char *dst, size_t size)
108{
109 int i = 0;
110 char *res;
111
112 switch(n) {
113 case 1ULL ... 9ULL:
114 i = 0;
115 break;
116
117 case 10ULL ... 99ULL:
118 i = 1;
119 break;
120
121 case 100ULL ... 999ULL:
122 i = 2;
123 break;
124
125 case 1000ULL ... 9999ULL:
126 i = 3;
127 break;
128
129 case 10000ULL ... 99999ULL:
130 i = 4;
131 break;
132
133 case 100000ULL ... 999999ULL:
134 i = 5;
135 break;
136
137 case 1000000ULL ... 9999999ULL:
138 i = 6;
139 break;
140
141 case 10000000ULL ... 99999999ULL:
142 i = 7;
143 break;
144
145 case 100000000ULL ... 999999999ULL:
146 i = 8;
147 break;
148
149 case 1000000000ULL ... 9999999999ULL:
150 i = 9;
151 break;
152
153 case 10000000000ULL ... 99999999999ULL:
154 i = 10;
155 break;
156
157 case 100000000000ULL ... 999999999999ULL:
158 i = 11;
159 break;
160
161 case 1000000000000ULL ... 9999999999999ULL:
162 i = 12;
163 break;
164
165 case 10000000000000ULL ... 99999999999999ULL:
166 i = 13;
167 break;
168
169 case 100000000000000ULL ... 999999999999999ULL:
170 i = 14;
171 break;
172
173 case 1000000000000000ULL ... 9999999999999999ULL:
174 i = 15;
175 break;
176
177 case 10000000000000000ULL ... 99999999999999999ULL:
178 i = 16;
179 break;
180
181 case 100000000000000000ULL ... 999999999999999999ULL:
182 i = 17;
183 break;
184
185 case 1000000000000000000ULL ... 9999999999999999999ULL:
186 i = 18;
187 break;
188
189 case 10000000000000000000ULL ... ULLONG_MAX:
190 i = 19;
191 break;
192 }
193 if (i + 2 > size) // (i + 1) + '\0'
194 return NULL; // too long
195 res = dst + i + 1;
196 *res = '\0';
197 for (; i >= 0; i--) {
198 dst[i] = n % 10ULL + '0';
199 n /= 10ULL;
200 }
201 return res;
202}
203
204/*
205 * unsigned long ASCII representation
206 *
207 * return the last char '\0' or NULL if no enough
208 * space in dst
209 */
210char *ultoa_o(unsigned long n, char *dst, size_t size)
211{
212 int i = 0;
213 char *res;
214
215 switch (n) {
216 case 0U ... 9UL:
217 i = 0;
218 break;
219
220 case 10U ... 99UL:
221 i = 1;
222 break;
223
224 case 100U ... 999UL:
225 i = 2;
226 break;
227
228 case 1000U ... 9999UL:
229 i = 3;
230 break;
231
232 case 10000U ... 99999UL:
233 i = 4;
234 break;
235
236 case 100000U ... 999999UL:
237 i = 5;
238 break;
239
240 case 1000000U ... 9999999UL:
241 i = 6;
242 break;
243
244 case 10000000U ... 99999999UL:
245 i = 7;
246 break;
247
248 case 100000000U ... 999999999UL:
249 i = 8;
250 break;
251#if __WORDSIZE == 32
252
253 case 1000000000ULL ... ULONG_MAX:
254 i = 9;
255 break;
256
257#elif __WORDSIZE == 64
258
259 case 1000000000ULL ... 9999999999UL:
260 i = 9;
261 break;
262
263 case 10000000000ULL ... 99999999999UL:
264 i = 10;
265 break;
266
267 case 100000000000ULL ... 999999999999UL:
268 i = 11;
269 break;
270
271 case 1000000000000ULL ... 9999999999999UL:
272 i = 12;
273 break;
274
275 case 10000000000000ULL ... 99999999999999UL:
276 i = 13;
277 break;
278
279 case 100000000000000ULL ... 999999999999999UL:
280 i = 14;
281 break;
282
283 case 1000000000000000ULL ... 9999999999999999UL:
284 i = 15;
285 break;
286
287 case 10000000000000000ULL ... 99999999999999999UL:
288 i = 16;
289 break;
290
291 case 100000000000000000ULL ... 999999999999999999UL:
292 i = 17;
293 break;
294
295 case 1000000000000000000ULL ... 9999999999999999999UL:
296 i = 18;
297 break;
298
299 case 10000000000000000000ULL ... ULONG_MAX:
300 i = 19;
301 break;
302
303#endif
304 }
305 if (i + 2 > size) // (i + 1) + '\0'
306 return NULL; // too long
307 res = dst + i + 1;
308 *res = '\0';
309 for (; i >= 0; i--) {
310 dst[i] = n % 10U + '0';
311 n /= 10U;
312 }
313 return res;
314}
315
316/*
317 * signed long ASCII representation
318 *
319 * return the last char '\0' or NULL if no enough
320 * space in dst
321 */
322char *ltoa_o(long int n, char *dst, size_t size)
323{
324 char *pos = dst;
325
326 if (n < 0) {
327 if (size < 3)
328 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
329 *pos = '-';
330 pos++;
331 dst = ultoa_o(-n, pos, size - 1);
332 } else {
333 dst = ultoa_o(n, dst, size);
334 }
335 return dst;
336}
337
338/*
339 * signed long long ASCII representation
340 *
341 * return the last char '\0' or NULL if no enough
342 * space in dst
343 */
344char *lltoa(long long n, char *dst, size_t size)
345{
346 char *pos = dst;
347
348 if (n < 0) {
349 if (size < 3)
350 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
351 *pos = '-';
352 pos++;
353 dst = ulltoa(-n, pos, size - 1);
354 } else {
355 dst = ulltoa(n, dst, size);
356 }
357 return dst;
358}
359
360/*
361 * write a ascii representation of a unsigned into dst,
362 * return a pointer to the last character
363 * Pad the ascii representation with '0', using size.
364 */
365char *utoa_pad(unsigned int n, char *dst, size_t size)
366{
367 int i = 0;
368 char *ret;
369
370 switch(n) {
371 case 0U ... 9U:
372 i = 0;
373 break;
374
375 case 10U ... 99U:
376 i = 1;
377 break;
378
379 case 100U ... 999U:
380 i = 2;
381 break;
382
383 case 1000U ... 9999U:
384 i = 3;
385 break;
386
387 case 10000U ... 99999U:
388 i = 4;
389 break;
390
391 case 100000U ... 999999U:
392 i = 5;
393 break;
394
395 case 1000000U ... 9999999U:
396 i = 6;
397 break;
398
399 case 10000000U ... 99999999U:
400 i = 7;
401 break;
402
403 case 100000000U ... 999999999U:
404 i = 8;
405 break;
406
407 case 1000000000U ... 4294967295U:
408 i = 9;
409 break;
410 }
411 if (i + 2 > size) // (i + 1) + '\0'
412 return NULL; // too long
413 if (i < size)
414 i = size - 2; // padding - '\0'
415
416 ret = dst + i + 1;
417 *ret = '\0';
418 for (; i >= 0; i--) {
419 dst[i] = n % 10U + '0';
420 n /= 10U;
421 }
422 return ret;
423}
424
425/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200426 * copies at most <size-1> chars from <src> to <dst>. Last char is always
427 * set to 0, unless <size> is 0. The number of chars copied is returned
428 * (excluding the terminating zero).
429 * This code has been optimized for size and speed : on x86, it's 45 bytes
430 * long, uses only registers, and consumes only 4 cycles per char.
431 */
432int strlcpy2(char *dst, const char *src, int size)
433{
434 char *orig = dst;
435 if (size) {
436 while (--size && (*dst = *src)) {
437 src++; dst++;
438 }
439 *dst = 0;
440 }
441 return dst - orig;
442}
443
444/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200445 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200446 * the ascii representation for number 'n' in decimal.
447 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100448char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200449{
450 char *pos;
451
Willy Tarreau72d759c2007-10-25 12:14:10 +0200452 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200453 *pos-- = '\0';
454
455 do {
456 *pos-- = '0' + n % 10;
457 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200458 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200459 return pos + 1;
460}
461
Willy Tarreau91092e52007-10-25 16:58:42 +0200462/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200463 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200464 * the ascii representation for number 'n' in decimal.
465 */
466char *lltoa_r(long long int in, char *buffer, int size)
467{
468 char *pos;
469 int neg = 0;
470 unsigned long long int n;
471
472 pos = buffer + size - 1;
473 *pos-- = '\0';
474
475 if (in < 0) {
476 neg = 1;
477 n = -in;
478 }
479 else
480 n = in;
481
482 do {
483 *pos-- = '0' + n % 10;
484 n /= 10;
485 } while (n && pos >= buffer);
486 if (neg && pos > buffer)
487 *pos-- = '-';
488 return pos + 1;
489}
490
491/*
492 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200493 * the ascii representation for signed number 'n' in decimal.
494 */
495char *sltoa_r(long n, char *buffer, int size)
496{
497 char *pos;
498
499 if (n >= 0)
500 return ultoa_r(n, buffer, size);
501
502 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
503 *pos = '-';
504 return pos;
505}
506
507/*
508 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200509 * the ascii representation for number 'n' in decimal, formatted for
510 * HTML output with tags to create visual grouping by 3 digits. The
511 * output needs to support at least 171 characters.
512 */
513const char *ulltoh_r(unsigned long long n, char *buffer, int size)
514{
515 char *start;
516 int digit = 0;
517
518 start = buffer + size;
519 *--start = '\0';
520
521 do {
522 if (digit == 3 && start >= buffer + 7)
523 memcpy(start -= 7, "</span>", 7);
524
525 if (start >= buffer + 1) {
526 *--start = '0' + n % 10;
527 n /= 10;
528 }
529
530 if (digit == 3 && start >= buffer + 18)
531 memcpy(start -= 18, "<span class=\"rls\">", 18);
532
533 if (digit++ == 3)
534 digit = 1;
535 } while (n && start > buffer);
536 return start;
537}
538
539/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200540 * This function simply returns a locally allocated string containing the ascii
541 * representation for number 'n' in decimal, unless n is 0 in which case it
542 * returns the alternate string (or an empty string if the alternate string is
543 * NULL). It use is intended for limits reported in reports, where it's
544 * desirable not to display anything if there is no limit. Warning! it shares
545 * the same vector as ultoa_r().
546 */
547const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
548{
549 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
550}
551
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200552/* Trims the first "%f" float in a string to its minimum number of digits after
553 * the decimal point by trimming trailing zeroes, even dropping the decimal
554 * point if not needed. The string is in <buffer> of length <len>, and the
555 * number is expected to start at or after position <num_start> (the first
556 * point appearing there is considered). A NUL character is always placed at
557 * the end if some trimming occurs. The new buffer length is returned.
558 */
559size_t flt_trim(char *buffer, size_t num_start, size_t len)
560{
561 char *end = buffer + len;
562 char *p = buffer + num_start;
563 char *trim;
564
565 do {
566 if (p >= end)
567 return len;
568 trim = p++;
569 } while (*trim != '.');
570
571 /* For now <trim> is on the decimal point. Let's look for any other
572 * meaningful digit after it.
573 */
574 while (p < end) {
575 if (*p++ != '0')
576 trim = p;
577 }
578
579 if (trim < end)
580 *trim = 0;
581
582 return trim - buffer;
583}
584
Willy Tarreauae03d262021-05-08 07:35:00 +0200585/*
586 * This function simply returns a locally allocated string containing
587 * the ascii representation for number 'n' in decimal with useless trailing
588 * zeroes trimmed.
589 */
590char *ftoa_r(double n, char *buffer, int size)
591{
592 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
593 return buffer;
594}
595
Willy Tarreau588297f2014-06-16 15:16:40 +0200596/* returns a locally allocated string containing the quoted encoding of the
597 * input string. The output may be truncated to QSTR_SIZE chars, but it is
598 * guaranteed that the string will always be properly terminated. Quotes are
599 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
600 * always be at least 4 chars.
601 */
602const char *qstr(const char *str)
603{
604 char *ret = quoted_str[quoted_idx];
605 char *p, *end;
606
607 if (++quoted_idx >= NB_QSTR)
608 quoted_idx = 0;
609
610 p = ret;
611 end = ret + QSTR_SIZE;
612
613 *p++ = '"';
614
615 /* always keep 3 chars to support passing "" and the ending " */
616 while (*str && p < end - 3) {
617 if (*str == '"') {
618 *p++ = '"';
619 *p++ = '"';
620 }
621 else
622 *p++ = *str;
623 str++;
624 }
625 *p++ = '"';
626 return ret;
627}
628
Robert Tsai81ae1952007-12-05 10:47:29 +0100629/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200630 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
631 *
632 * It looks like this one would be a good candidate for inlining, but this is
633 * not interesting because it around 35 bytes long and often called multiple
634 * times within the same function.
635 */
636int ishex(char s)
637{
638 s -= '0';
639 if ((unsigned char)s <= 9)
640 return 1;
641 s -= 'A' - '0';
642 if ((unsigned char)s <= 5)
643 return 1;
644 s -= 'a' - 'A';
645 if ((unsigned char)s <= 5)
646 return 1;
647 return 0;
648}
649
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100650/* rounds <i> down to the closest value having max 2 digits */
651unsigned int round_2dig(unsigned int i)
652{
653 unsigned int mul = 1;
654
655 while (i >= 100) {
656 i /= 10;
657 mul *= 10;
658 }
659 return i * mul;
660}
661
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100662/*
663 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
664 * invalid character is found, a pointer to it is returned. If everything is
665 * fine, NULL is returned.
666 */
667const char *invalid_char(const char *name)
668{
669 if (!*name)
670 return name;
671
672 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100673 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100674 *name != '_' && *name != '-')
675 return name;
676 name++;
677 }
678 return NULL;
679}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200680
681/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200682 * Checks <name> for invalid characters. Valid chars are [_.-] and those
683 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200684 * If an invalid character is found, a pointer to it is returned.
685 * If everything is fine, NULL is returned.
686 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200687static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200688
689 if (!*name)
690 return name;
691
692 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100693 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200694 *name != '_' && *name != '-')
695 return name;
696
697 name++;
698 }
699
700 return NULL;
701}
702
703/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200704 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
705 * If an invalid character is found, a pointer to it is returned.
706 * If everything is fine, NULL is returned.
707 */
708const char *invalid_domainchar(const char *name) {
709 return __invalid_char(name, isalnum);
710}
711
712/*
713 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
714 * If an invalid character is found, a pointer to it is returned.
715 * If everything is fine, NULL is returned.
716 */
717const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200718 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200719}
720
721/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100722 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100723 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
724 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
725 * the function tries to guess the address family from the syntax. If the
726 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100727 * string is assumed to contain only an address, no port. The address can be a
728 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
729 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
730 * The return address will only have the address family and the address set,
731 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100732 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
733 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100734 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200735 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100736struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200737{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100738 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100739 /* max IPv6 length, including brackets and terminating NULL */
740 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100741 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100742
743 /* check IPv6 with square brackets */
744 if (str[0] == '[') {
745 size_t iplength = strlen(str);
746
747 if (iplength < 4) {
748 /* minimal size is 4 when using brackets "[::]" */
749 goto fail;
750 }
751 else if (iplength >= sizeof(tmpip)) {
752 /* IPv6 literal can not be larger than tmpip */
753 goto fail;
754 }
755 else {
756 if (str[iplength - 1] != ']') {
757 /* if address started with bracket, it should end with bracket */
758 goto fail;
759 }
760 else {
761 memcpy(tmpip, str + 1, iplength - 2);
762 tmpip[iplength - 2] = '\0';
763 str = tmpip;
764 }
765 }
766 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100767
Willy Tarreaufab5a432011-03-04 15:31:53 +0100768 /* Any IPv6 address */
769 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100770 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
771 sa->ss_family = AF_INET6;
772 else if (sa->ss_family != AF_INET6)
773 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100774 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100775 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100776 }
777
Willy Tarreau24709282013-03-10 21:32:12 +0100778 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100779 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100780 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
781 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100782 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100783 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100784 }
785
786 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100787 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
788 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100789 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100790 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100791 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100792 }
793
794 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100795 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
796 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100797 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100798 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100799 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100800 }
801
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100802 if (!resolve)
803 return NULL;
804
Emeric Brund30e9a12020-12-23 18:49:16 +0100805 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200806 return NULL;
807
David du Colombierd5f43282011-03-17 10:40:16 +0100808#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200809 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100810 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100811 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100812
813 memset(&result, 0, sizeof(result));
814 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100815 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100816 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200817 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100818 hints.ai_protocol = 0;
819
820 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100821 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
822 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100823 else if (sa->ss_family != result->ai_family) {
824 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100825 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100826 }
Willy Tarreau24709282013-03-10 21:32:12 +0100827
David du Colombierd5f43282011-03-17 10:40:16 +0100828 switch (result->ai_family) {
829 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100830 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100831 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100832 success = 1;
833 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100834 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100835 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100836 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100837 success = 1;
838 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100839 }
840 }
841
Sean Carey58ea0392013-02-15 23:39:18 +0100842 if (result)
843 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100844
845 if (success)
846 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100847 }
David du Colombierd5f43282011-03-17 10:40:16 +0100848#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200849 /* try to resolve an IPv4/IPv6 hostname */
850 he = gethostbyname(str);
851 if (he) {
852 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
853 sa->ss_family = he->h_addrtype;
854 else if (sa->ss_family != he->h_addrtype)
855 goto fail;
856
857 switch (sa->ss_family) {
858 case AF_INET:
859 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100860 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200861 return sa;
862 case AF_INET6:
863 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100864 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200865 return sa;
866 }
867 }
868
David du Colombierd5f43282011-03-17 10:40:16 +0100869 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100870 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100871 return NULL;
872}
873
874/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100875 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
876 * range or offset consisting in two integers that the caller will have to
877 * check to find the relevant input format. The following format are supported :
878 *
879 * String format | address | port | low | high
880 * addr | <addr> | 0 | 0 | 0
881 * addr: | <addr> | 0 | 0 | 0
882 * addr:port | <addr> | <port> | <port> | <port>
883 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
884 * addr:+port | <addr> | <port> | 0 | <port>
885 * addr:-port | <addr> |-<port> | <port> | 0
886 *
887 * The detection of a port range or increment by the caller is made by
888 * comparing <low> and <high>. If both are equal, then port 0 means no port
889 * was specified. The caller may pass NULL for <low> and <high> if it is not
890 * interested in retrieving port ranges.
891 *
892 * Note that <addr> above may also be :
893 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
894 * - "*" => family will be AF_INET and address will be INADDR_ANY
895 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
896 * - a host name => family and address will depend on host name resolving.
897 *
Willy Tarreau24709282013-03-10 21:32:12 +0100898 * A prefix may be passed in before the address above to force the family :
899 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
900 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
901 * - "unix@" => force address to be a path to a UNIX socket even if the
902 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200903 * - 'abns@' -> force address to belong to the abstract namespace (Linux
904 * only). These sockets are just like Unix sockets but without
905 * the need for an underlying file system. The address is a
906 * string. Technically it's like a Unix socket with a zero in
907 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100908 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100909 *
mildisff5d5102015-10-26 18:50:08 +0100910 * IPv6 addresses can be declared with or without square brackets. When using
911 * square brackets for IPv6 addresses, the port separator (colon) is optional.
912 * If not using square brackets, and in order to avoid any ambiguity with
913 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
914 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
915 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100916 *
917 * If <pfx> is non-null, it is used as a string prefix before any path-based
918 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100919 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200920 * if <fqdn> is non-null, it will be filled with :
921 * - a pointer to the FQDN of the server name to resolve if there's one, and
922 * that the caller will have to free(),
923 * - NULL if there was an explicit address that doesn't require resolution.
924 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200925 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
926 * still honored so it is possible for the caller to know whether a resolution
927 * failed by clearing this flag and checking if <fqdn> was filled, indicating
928 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200929 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100930 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200931 * the address when cast to sockaddr_in and the address family is
932 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200933 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200934 * The matching protocol will be set into <proto> if non-null.
935 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200936 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
937 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100938 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200939struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
940 struct protocol **proto, char **err,
941 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100942{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100943 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100944 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200945 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100946 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100947 char *port1, *port2;
948 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200949 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200950 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200951 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100952
953 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200954 if (fqdn)
955 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200956
Willy Tarreaudad36a32013-03-11 01:20:04 +0100957 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100958 if (str2 == NULL) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +0200959 memprintf(err, "out of memory in '%s'", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100960 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100961 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200962
Willy Tarreau9f69f462015-09-08 16:01:25 +0200963 if (!*str2) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +0200964 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)", str);
Willy Tarreau9f69f462015-09-08 16:01:25 +0200965 goto out;
966 }
967
Willy Tarreau24709282013-03-10 21:32:12 +0100968 memset(&ss, 0, sizeof(ss));
969
Willy Tarreaue835bd82020-09-16 11:35:47 +0200970 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100971 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
972 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM)))
Willy Tarreaue835bd82020-09-16 11:35:47 +0200973 sock_type = ctrl_type = SOCK_DGRAM;
974 else
975 sock_type = ctrl_type = SOCK_STREAM;
976
977 if (strncmp(str2, "stream+", 7) == 0) {
978 str2 += 7;
979 sock_type = ctrl_type = SOCK_STREAM;
980 }
981 else if (strncmp(str2, "dgram+", 6) == 0) {
982 str2 += 6;
983 sock_type = ctrl_type = SOCK_DGRAM;
984 }
985
Willy Tarreau24709282013-03-10 21:32:12 +0100986 if (strncmp(str2, "unix@", 5) == 0) {
987 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200988 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100989 ss.ss_family = AF_UNIX;
990 }
Emeric Brunce325c42021-04-02 17:05:09 +0200991 else if (strncmp(str2, "uxdg@", 5) == 0) {
992 str2 += 5;
993 abstract = 0;
994 ss.ss_family = AF_UNIX;
995 sock_type = ctrl_type = SOCK_DGRAM;
996 }
997 else if (strncmp(str2, "uxst@", 5) == 0) {
998 str2 += 5;
999 abstract = 0;
1000 ss.ss_family = AF_UNIX;
1001 sock_type = ctrl_type = SOCK_STREAM;
1002 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001003 else if (strncmp(str2, "abns@", 5) == 0) {
1004 str2 += 5;
1005 abstract = 1;
1006 ss.ss_family = AF_UNIX;
1007 }
Emeric Brunce325c42021-04-02 17:05:09 +02001008 else if (strncmp(str2, "ip@", 3) == 0) {
1009 str2 += 3;
1010 ss.ss_family = AF_UNSPEC;
1011 }
Willy Tarreau24709282013-03-10 21:32:12 +01001012 else if (strncmp(str2, "ipv4@", 5) == 0) {
1013 str2 += 5;
1014 ss.ss_family = AF_INET;
1015 }
1016 else if (strncmp(str2, "ipv6@", 5) == 0) {
1017 str2 += 5;
1018 ss.ss_family = AF_INET6;
1019 }
Emeric Brunce325c42021-04-02 17:05:09 +02001020 else if (strncmp(str2, "tcp4@", 5) == 0) {
1021 str2 += 5;
1022 ss.ss_family = AF_INET;
1023 sock_type = ctrl_type = SOCK_STREAM;
1024 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001025 else if (strncmp(str2, "udp4@", 5) == 0) {
1026 str2 += 5;
1027 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001028 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001029 }
Emeric Brunce325c42021-04-02 17:05:09 +02001030 else if (strncmp(str2, "tcp6@", 5) == 0) {
1031 str2 += 5;
1032 ss.ss_family = AF_INET6;
1033 sock_type = ctrl_type = SOCK_STREAM;
1034 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001035 else if (strncmp(str2, "udp6@", 5) == 0) {
1036 str2 += 5;
1037 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001038 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001039 }
Emeric Brunce325c42021-04-02 17:05:09 +02001040 else if (strncmp(str2, "tcp@", 4) == 0) {
1041 str2 += 4;
1042 ss.ss_family = AF_UNSPEC;
1043 sock_type = ctrl_type = SOCK_STREAM;
1044 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001045 else if (strncmp(str2, "udp@", 4) == 0) {
1046 str2 += 4;
1047 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001048 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001049 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001050 else if (strncmp(str2, "quic4@", 6) == 0) {
1051 str2 += 6;
1052 ss.ss_family = AF_INET;
1053 sock_type = SOCK_DGRAM;
1054 ctrl_type = SOCK_STREAM;
1055 }
1056 else if (strncmp(str2, "quic6@", 6) == 0) {
1057 str2 += 6;
1058 ss.ss_family = AF_INET6;
1059 sock_type = SOCK_DGRAM;
1060 ctrl_type = SOCK_STREAM;
1061 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001062 else if (strncmp(str2, "fd@", 3) == 0) {
1063 str2 += 3;
1064 ss.ss_family = AF_CUST_EXISTING_FD;
1065 }
1066 else if (strncmp(str2, "sockpair@", 9) == 0) {
1067 str2 += 9;
1068 ss.ss_family = AF_CUST_SOCKPAIR;
1069 }
Willy Tarreau24709282013-03-10 21:32:12 +01001070 else if (*str2 == '/') {
1071 ss.ss_family = AF_UNIX;
1072 }
1073 else
1074 ss.ss_family = AF_UNSPEC;
1075
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001076 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001077 struct sockaddr_storage ss2;
1078 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001079 char *endptr;
1080
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001081 new_fd = strtol(str2, &endptr, 10);
1082 if (!*str2 || new_fd < 0 || *endptr) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001083 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'", str2, str);
William Lallemand2fe7dd02018-09-11 16:51:29 +02001084 goto out;
1085 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001086
Willy Tarreaua215be22020-09-16 10:14:16 +02001087 /* just verify that it's a socket */
1088 addr_len = sizeof(ss2);
1089 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001090 memprintf(err, "cannot use file descriptor '%d' : %s.", new_fd, strerror(errno));
Willy Tarreaua215be22020-09-16 10:14:16 +02001091 goto out;
1092 }
1093
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001094 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1095 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001096 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001097 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001098 char *endptr;
1099
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001100 new_fd = strtol(str2, &endptr, 10);
1101 if (!*str2 || new_fd < 0 || *endptr) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001102 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001103 goto out;
1104 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001105
Willy Tarreau6edc7222020-09-15 17:41:56 +02001106 if (opts & PA_O_SOCKET_FD) {
1107 socklen_t addr_len;
1108 int type;
1109
1110 addr_len = sizeof(ss);
1111 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001112 memprintf(err, "cannot use file descriptor '%d' : %s.", new_fd, strerror(errno));
Willy Tarreau6edc7222020-09-15 17:41:56 +02001113 goto out;
1114 }
1115
1116 addr_len = sizeof(type);
1117 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001118 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001119 memprintf(err, "socket on file descriptor '%d' is of the wrong type.", new_fd);
Willy Tarreau6edc7222020-09-15 17:41:56 +02001120 goto out;
1121 }
1122
1123 porta = portl = porth = get_host_port(&ss);
1124 } else if (opts & PA_O_RAW_FD) {
1125 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1126 ((struct sockaddr_in *)&ss)->sin_port = 0;
1127 } else {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001128 memprintf(err, "a file descriptor is not acceptable here in '%s'", str);
Willy Tarreau6edc7222020-09-15 17:41:56 +02001129 goto out;
1130 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001131 }
1132 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001133 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001134 int prefix_path_len;
1135 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001136 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001137
1138 /* complete unix socket path name during startup or soft-restart is
1139 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1140 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001141 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001142 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001143 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001144
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001145 adr_len = strlen(str2);
1146 if (adr_len > max_path_len) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001147 memprintf(err, "socket path '%s' too long (max %d)", str, max_path_len);
Willy Tarreau15586382013-03-04 19:48:14 +01001148 goto out;
1149 }
1150
Willy Tarreauccfccef2014-05-10 01:49:15 +02001151 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001152 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001153 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001154 memcpy(un->sun_path, pfx, prefix_path_len);
1155 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001156 }
Willy Tarreau24709282013-03-10 21:32:12 +01001157 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001158 char *end = str2 + strlen(str2);
1159 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001160
mildisff5d5102015-10-26 18:50:08 +01001161 /* search for : or ] whatever comes first */
1162 for (chr = end-1; chr > str2; chr--) {
1163 if (*chr == ']' || *chr == ':')
1164 break;
1165 }
1166
1167 if (*chr == ':') {
1168 /* Found a colon before a closing-bracket, must be a port separator.
1169 * This guarantee backward compatibility.
1170 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001171 if (!(opts & PA_O_PORT_OK)) {
1172 memprintf(err, "port specification not permitted here in '%s'", str);
1173 goto out;
1174 }
mildisff5d5102015-10-26 18:50:08 +01001175 *chr++ = '\0';
1176 port1 = chr;
1177 }
1178 else {
1179 /* Either no colon and no closing-bracket
1180 * or directly ending with a closing-bracket.
1181 * However, no port.
1182 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001183 if (opts & PA_O_PORT_MAND) {
1184 memprintf(err, "missing port specification in '%s'", str);
1185 goto out;
1186 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001187 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001188 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001189
Willy Tarreau90807112020-02-25 08:16:33 +01001190 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001191 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001192 if (port2) {
1193 if (!(opts & PA_O_PORT_RANGE)) {
1194 memprintf(err, "port range not permitted here in '%s'", str);
1195 goto out;
1196 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001197 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001198 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001199 else
1200 port2 = port1;
1201 portl = atoi(port1);
1202 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001203
1204 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1205 memprintf(err, "invalid port '%s'", port1);
1206 goto out;
1207 }
1208
1209 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1210 memprintf(err, "invalid port '%s'", port2);
1211 goto out;
1212 }
1213
1214 if (portl > porth) {
1215 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1216 goto out;
1217 }
1218
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001219 porta = portl;
1220 }
1221 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001222 if (!(opts & PA_O_PORT_OFS)) {
1223 memprintf(err, "port offset not permitted here in '%s'", str);
1224 goto out;
1225 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001226 portl = atoi(port1 + 1);
1227 porta = -portl;
1228 }
1229 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001230 if (!(opts & PA_O_PORT_OFS)) {
1231 memprintf(err, "port offset not permitted here in '%s'", str);
1232 goto out;
1233 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001234 porth = atoi(port1 + 1);
1235 porta = porth;
1236 }
1237 else if (*port1) { /* other any unexpected char */
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001238 memprintf(err, "invalid character '%c' in port number '%s' in '%s'", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001239 goto out;
1240 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001241 else if (opts & PA_O_PORT_MAND) {
1242 memprintf(err, "missing port specification in '%s'", str);
1243 goto out;
1244 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001245
1246 /* first try to parse the IP without resolving. If it fails, it
1247 * tells us we need to keep a copy of the FQDN to resolve later
1248 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001249 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001250 */
1251 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001252 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1253 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001254 memprintf(err, "invalid address: '%s' in '%s'", str2, str);
Willy Tarreauceccdd72016-11-02 22:27:10 +01001255 goto out;
1256 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001257
Willy Tarreauceccdd72016-11-02 22:27:10 +01001258 if (fqdn) {
1259 if (str2 != back)
1260 memmove(back, str2, strlen(str2) + 1);
1261 *fqdn = back;
1262 back = NULL;
1263 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001264 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001265 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001266 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001267
Willy Tarreaue835bd82020-09-16 11:35:47 +02001268 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001269 memprintf(err, "stream-type socket not acceptable in '%s'", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001270 goto out;
1271 }
1272 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
Thierry Fournier6ba28a82023-05-23 17:58:03 +02001273 memprintf(err, "dgram-type socket not acceptable in '%s'", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001274 goto out;
1275 }
1276
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001277 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001278 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001279 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1280 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001281 * in which case the address is not known yet (this is only
1282 * for servers actually).
1283 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001284 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001285 sock_type == SOCK_DGRAM,
1286 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001287
Emeric Brun26754902021-04-07 14:26:44 +02001288 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001289 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1290 goto out;
1291 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001292
1293 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1294 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1295 goto out;
1296 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001297 }
1298
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001299 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001300 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001301 if (port)
1302 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001303 if (low)
1304 *low = portl;
1305 if (high)
1306 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001307 if (fd)
1308 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001309 if (proto)
1310 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001311 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001312 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001313}
1314
Thayne McCombs92149f92020-11-20 01:28:26 -07001315/* converts <addr> and <port> into a string representation of the address and port. This is sort
1316 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1317 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1318 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1319 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1320 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1321 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1322 *
1323 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1324 */
1325char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1326{
1327 char buffer[INET6_ADDRSTRLEN];
1328 char *out = NULL;
1329 const void *ptr;
1330 const char *path;
1331
1332 switch (addr->ss_family) {
1333 case AF_INET:
1334 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1335 break;
1336 case AF_INET6:
1337 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1338 break;
1339 case AF_UNIX:
1340 path = ((struct sockaddr_un *)addr)->sun_path;
1341 if (path[0] == '\0') {
1342 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1343 return memprintf(&out, "abns@%.*s", max_length, path+1);
1344 } else {
1345 return strdup(path);
1346 }
1347 case AF_CUST_SOCKPAIR:
1348 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1349 default:
1350 return NULL;
1351 }
Tim Duesterhus189c0082022-05-22 13:06:27 +02001352 inet_ntop(addr->ss_family, ptr, buffer, sizeof(buffer));
Thayne McCombs92149f92020-11-20 01:28:26 -07001353 if (map_ports)
1354 return memprintf(&out, "%s:%+d", buffer, port);
1355 else
1356 return memprintf(&out, "%s:%d", buffer, port);
1357}
1358
1359
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001360/* converts <str> to a struct in_addr containing a network mask. It can be
1361 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001362 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001363 */
1364int str2mask(const char *str, struct in_addr *mask)
1365{
1366 if (strchr(str, '.') != NULL) { /* dotted notation */
1367 if (!inet_pton(AF_INET, str, mask))
1368 return 0;
1369 }
1370 else { /* mask length */
1371 char *err;
1372 unsigned long len = strtol(str, &err, 10);
1373
1374 if (!*str || (err && *err) || (unsigned)len > 32)
1375 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001376
1377 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001378 }
1379 return 1;
1380}
1381
Tim Duesterhus47185172018-01-25 16:24:49 +01001382/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001383 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001384 * if the conversion succeeds otherwise zero.
1385 */
1386int str2mask6(const char *str, struct in6_addr *mask)
1387{
1388 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1389 if (!inet_pton(AF_INET6, str, mask))
1390 return 0;
1391 }
1392 else { /* mask length */
1393 char *err;
1394 unsigned long len = strtol(str, &err, 10);
1395
1396 if (!*str || (err && *err) || (unsigned)len > 128)
1397 return 0;
1398
1399 len2mask6(len, mask);
1400 }
1401 return 1;
1402}
1403
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001404/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1405 * succeeds otherwise zero.
1406 */
1407int cidr2dotted(int cidr, struct in_addr *mask) {
1408
1409 if (cidr < 0 || cidr > 32)
1410 return 0;
1411
1412 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1413 return 1;
1414}
1415
Thierry Fournier70473a52016-02-17 17:12:14 +01001416/* Convert mask from bit length form to in_addr form.
1417 * This function never fails.
1418 */
1419void len2mask4(int len, struct in_addr *addr)
1420{
1421 if (len >= 32) {
1422 addr->s_addr = 0xffffffff;
1423 return;
1424 }
1425 if (len <= 0) {
1426 addr->s_addr = 0x00000000;
1427 return;
1428 }
1429 addr->s_addr = 0xffffffff << (32 - len);
1430 addr->s_addr = htonl(addr->s_addr);
1431}
1432
1433/* Convert mask from bit length form to in6_addr form.
1434 * This function never fails.
1435 */
1436void len2mask6(int len, struct in6_addr *addr)
1437{
1438 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1439 len -= 32;
1440 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1441 len -= 32;
1442 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1443 len -= 32;
1444 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1445}
1446
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001447/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001448 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001449 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001450 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001451 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1452 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001453int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001454{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001455 __label__ out_free, out_err;
1456 char *c, *s;
1457 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001458
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001459 s = strdup(str);
1460 if (!s)
1461 return 0;
1462
Willy Tarreaubaaee002006-06-26 02:48:02 +02001463 memset(mask, 0, sizeof(*mask));
1464 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001465
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001466 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001467 *c++ = '\0';
1468 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001469 if (!str2mask(c, mask))
1470 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001471 }
1472 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001473 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001474 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001475 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001476 struct hostent *he;
1477
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001478 if (!resolve)
1479 goto out_err;
1480
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001481 if ((he = gethostbyname(s)) == NULL) {
1482 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001483 }
1484 else
1485 *addr = *(struct in_addr *) *(he->h_addr_list);
1486 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001487
1488 ret_val = 1;
1489 out_free:
1490 free(s);
1491 return ret_val;
1492 out_err:
1493 ret_val = 0;
1494 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001495}
1496
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001497
1498/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001499 * converts <str> to two struct in6_addr* which must be pre-allocated.
1500 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001501 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001502 * Returns 1 if OK, 0 if error.
1503 */
1504int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1505{
1506 char *c, *s;
1507 int ret_val = 0;
1508 char *err;
1509 unsigned long len = 128;
1510
1511 s = strdup(str);
1512 if (!s)
1513 return 0;
1514
1515 memset(mask, 0, sizeof(*mask));
1516 memset(addr, 0, sizeof(*addr));
1517
1518 if ((c = strrchr(s, '/')) != NULL) {
1519 *c++ = '\0'; /* c points to the mask */
1520 if (!*c)
1521 goto out_free;
1522
1523 len = strtoul(c, &err, 10);
1524 if ((err && *err) || (unsigned)len > 128)
1525 goto out_free;
1526 }
1527 *mask = len; /* OK we have a valid mask in <len> */
1528
1529 if (!inet_pton(AF_INET6, s, addr))
1530 goto out_free;
1531
1532 ret_val = 1;
1533 out_free:
1534 free(s);
1535 return ret_val;
1536}
1537
1538
1539/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001540 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1541 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1542 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001543 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001544int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001545{
1546 int saw_digit, octets, ch;
1547 u_char tmp[4], *tp;
1548 const char *cp = addr;
1549
1550 saw_digit = 0;
1551 octets = 0;
1552 *(tp = tmp) = 0;
1553
1554 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001555 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001556 if (digit > 9 && ch != '.')
1557 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001558 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001559 if (digit <= 9) {
1560 u_int new = *tp * 10 + digit;
1561 if (new > 255)
1562 return 0;
1563 *tp = new;
1564 if (!saw_digit) {
1565 if (++octets > 4)
1566 return 0;
1567 saw_digit = 1;
1568 }
1569 } else if (ch == '.' && saw_digit) {
1570 if (octets == 4)
1571 return 0;
1572 *++tp = 0;
1573 saw_digit = 0;
1574 } else
1575 return 0;
1576 }
1577
1578 if (octets < 4)
1579 return 0;
1580
1581 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001582 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001583}
1584
1585/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001586 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001587 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001588 * the hostname. Actually only http and https are supported. <out> can be NULL.
1589 * This function returns the consumed length. It is useful if you parse complete
1590 * url like http://host:port/path, because the consumed length corresponds to
1591 * the first character of the path. If the conversion fails, it returns -1.
1592 *
1593 * This function tries to resolve the DNS name if haproxy is in starting mode.
1594 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001595 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001596int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001597{
1598 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001599 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001600 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001601 unsigned long long int http_code = 0;
1602 int default_port;
1603 struct hostent *he;
1604 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001605
1606 /* Firstly, try to find :// pattern */
1607 while (curr < url+ulen && url_code != 0x3a2f2f) {
1608 url_code = ((url_code & 0xffff) << 8);
1609 url_code += (unsigned char)*curr++;
1610 }
1611
1612 /* Secondly, if :// pattern is found, verify parsed stuff
1613 * before pattern is matching our http pattern.
1614 * If so parse ip address and port in uri.
1615 *
1616 * WARNING: Current code doesn't support dynamic async dns resolver.
1617 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001618 if (url_code != 0x3a2f2f)
1619 return -1;
1620
1621 /* Copy scheme, and utrn to lower case. */
1622 while (cp < curr - 3)
1623 http_code = (http_code << 8) + *cp++;
1624 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001625
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001626 /* HTTP or HTTPS url matching */
1627 if (http_code == 0x2020202068747470ULL) {
1628 default_port = 80;
1629 if (out)
1630 out->scheme = SCH_HTTP;
1631 }
1632 else if (http_code == 0x2020206874747073ULL) {
1633 default_port = 443;
1634 if (out)
1635 out->scheme = SCH_HTTPS;
1636 }
1637 else
1638 return -1;
1639
1640 /* If the next char is '[', the host address is IPv6. */
1641 if (*curr == '[') {
1642 curr++;
1643
1644 /* Check trash size */
1645 if (trash.size < ulen)
1646 return -1;
1647
1648 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001649 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001650 for (end = curr;
1651 end < url + ulen && *end != ']';
1652 end++, p++)
1653 *p = *end;
1654 if (*end != ']')
1655 return -1;
1656 *p = '\0';
1657
1658 /* Update out. */
1659 if (out) {
1660 out->host = curr;
1661 out->host_len = end - curr;
1662 }
1663
1664 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001665 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001666 return -1;
1667 end++;
1668
1669 /* Decode port. */
William Lallemande2e6cd92022-03-25 17:37:51 +01001670 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001671 end++;
1672 default_port = read_uint(&end, url + ulen);
1673 }
1674 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1675 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1676 return end - url;
1677 }
1678 else {
William Lallemand12e3b252022-02-18 16:13:12 +01001679 /* we need to copy the string into the trash because url2ipv4
1680 * needs a \0 at the end of the string */
1681 if (trash.size < ulen)
1682 return -1;
1683
1684 memcpy(trash.area, curr, ulen - (curr - url));
1685 trash.area[ulen - (curr - url)] = '\0';
1686
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001687 /* We are looking for IP address. If you want to parse and
1688 * resolve hostname found in url, you can use str2sa_range(), but
1689 * be warned this can slow down global daemon performances
1690 * while handling lagging dns responses.
1691 */
William Lallemand12e3b252022-02-18 16:13:12 +01001692 ret = url2ipv4(trash.area, &((struct sockaddr_in *)addr)->sin_addr);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001693 if (ret) {
1694 /* Update out. */
1695 if (out) {
1696 out->host = curr;
1697 out->host_len = ret;
1698 }
1699
William Lallemand086323a2022-03-24 21:59:03 +01001700 curr += ret;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001701
1702 /* Decode port. */
William Lallemande2e6cd92022-03-25 17:37:51 +01001703 if (curr < url + ulen && *curr == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001704 curr++;
1705 default_port = read_uint(&curr, url + ulen);
1706 }
1707 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1708
1709 /* Set family. */
1710 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1711 return curr - url;
1712 }
1713 else if (global.mode & MODE_STARTING) {
1714 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1715 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001716 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001717
1718 /* look for : or / or end */
1719 for (end = curr;
1720 end < url + ulen && *end != '/' && *end != ':';
1721 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001722 memcpy(trash.area, curr, end - curr);
1723 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001724
1725 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001726 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001727 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001728 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001729
1730 /* Update out. */
1731 if (out) {
1732 out->host = curr;
1733 out->host_len = end - curr;
1734 }
1735
1736 /* Decode port. */
William Lallemande2e6cd92022-03-25 17:37:51 +01001737 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001738 end++;
1739 default_port = read_uint(&end, url + ulen);
1740 }
1741
1742 /* Copy IP address, set port and family. */
1743 switch (he->h_addrtype) {
1744 case AF_INET:
1745 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1746 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1747 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1748 return end - url;
1749
1750 case AF_INET6:
1751 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1752 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1753 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1754 return end - url;
1755 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001756 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001757 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001758 return -1;
1759}
1760
Willy Tarreau631f01c2011-09-05 00:36:48 +02001761/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1762 * address family is returned so that it's easy for the caller to adapt to the
1763 * output format. Zero is returned if the address family is not supported. -1
1764 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1765 * supported.
1766 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001767int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001768{
1769
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001770 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001771
1772 if (size < 5)
1773 return 0;
1774 *str = '\0';
1775
1776 switch (addr->ss_family) {
1777 case AF_INET:
1778 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1779 break;
1780 case AF_INET6:
1781 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1782 break;
1783 case AF_UNIX:
1784 memcpy(str, "unix", 5);
1785 return addr->ss_family;
1786 default:
1787 return 0;
1788 }
1789
1790 if (inet_ntop(addr->ss_family, ptr, str, size))
1791 return addr->ss_family;
1792
1793 /* failed */
1794 return -1;
1795}
1796
Simon Horman75ab8bd2014-06-16 09:39:41 +09001797/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1798 * address family is returned so that it's easy for the caller to adapt to the
1799 * output format. Zero is returned if the address family is not supported. -1
1800 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1801 * supported.
1802 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001803int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001804{
1805
1806 uint16_t port;
1807
1808
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001809 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001810 return 0;
1811 *str = '\0';
1812
1813 switch (addr->ss_family) {
1814 case AF_INET:
1815 port = ((struct sockaddr_in *)addr)->sin_port;
1816 break;
1817 case AF_INET6:
1818 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1819 break;
1820 case AF_UNIX:
1821 memcpy(str, "unix", 5);
1822 return addr->ss_family;
1823 default:
1824 return 0;
1825 }
1826
1827 snprintf(str, size, "%u", ntohs(port));
1828 return addr->ss_family;
1829}
1830
Willy Tarreau16e01562016-08-09 16:46:18 +02001831/* check if the given address is local to the system or not. It will return
1832 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1833 * it is. We don't want to iterate over all interfaces for this (and it is not
1834 * portable). So instead we try to bind in UDP to this address on a free non
1835 * privileged port and to connect to the same address, port 0 (connect doesn't
1836 * care). If it succeeds, we own the address. Note that non-inet addresses are
1837 * considered local since they're most likely AF_UNIX.
1838 */
1839int addr_is_local(const struct netns_entry *ns,
1840 const struct sockaddr_storage *orig)
1841{
1842 struct sockaddr_storage addr;
1843 int result;
1844 int fd;
1845
1846 if (!is_inet_addr(orig))
1847 return 1;
1848
1849 memcpy(&addr, orig, sizeof(addr));
1850 set_host_port(&addr, 0);
1851
1852 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1853 if (fd < 0)
1854 return -1;
1855
1856 result = -1;
1857 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1858 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1859 result = 0; // fail, non-local address
1860 else
1861 result = 1; // success, local address
1862 }
1863 else {
1864 if (errno == EADDRNOTAVAIL)
1865 result = 0; // definitely not local :-)
1866 }
1867 close(fd);
1868
1869 return result;
1870}
1871
Willy Tarreaubaaee002006-06-26 02:48:02 +02001872/* will try to encode the string <string> replacing all characters tagged in
1873 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1874 * prefixed by <escape>, and will store the result between <start> (included)
1875 * and <stop> (excluded), and will always terminate the string with a '\0'
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001876 * before <stop>. If bytes are missing between <start> and <stop>, then the
1877 * conversion will be incomplete and truncated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001878 * The input string must also be zero-terminated.
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001879 *
1880 * Return the address of the \0 character, or NULL on error
Willy Tarreaubaaee002006-06-26 02:48:02 +02001881 */
1882const char hextab[16] = "0123456789ABCDEF";
1883char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001884 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001885 const char *string)
1886{
1887 if (start < stop) {
1888 stop--; /* reserve one byte for the final '\0' */
1889 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001890 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001891 *start++ = *string;
1892 else {
1893 if (start + 3 >= stop)
1894 break;
1895 *start++ = escape;
1896 *start++ = hextab[(*string >> 4) & 15];
1897 *start++ = hextab[*string & 15];
1898 }
1899 string++;
1900 }
1901 *start = '\0';
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001902 return start;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001903 }
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001904 return NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001905}
1906
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001907/*
1908 * Same behavior as encode_string() above, except that it encodes chunk
1909 * <chunk> instead of a string.
1910 */
1911char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001912 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001913 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001914{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001915 char *str = chunk->area;
1916 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001917
1918 if (start < stop) {
1919 stop--; /* reserve one byte for the final '\0' */
1920 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001921 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001922 *start++ = *str;
1923 else {
1924 if (start + 3 >= stop)
1925 break;
1926 *start++ = escape;
1927 *start++ = hextab[(*str >> 4) & 15];
1928 *start++ = hextab[*str & 15];
1929 }
1930 str++;
1931 }
1932 *start = '\0';
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001933 return start;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001934 }
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001935 return NULL;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001936}
1937
Dragan Dosen0edd1092016-02-12 13:23:02 +01001938/*
1939 * Tries to prefix characters tagged in the <map> with the <escape>
Aurelien DARRAGONa5c621a2022-09-20 14:33:18 +02001940 * character. The input <string> is processed until string_stop
1941 * is reached or NULL-byte is encountered. The result will
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001942 * be stored between <start> (included) and <stop> (excluded). This
1943 * function will always try to terminate the resulting string with a '\0'
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001944 * before <stop>.
1945 *
1946 * Return the address of the \0 character, or NULL on error
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001947 */
1948char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001949 const char escape, const long *map,
Aurelien DARRAGONa5c621a2022-09-20 14:33:18 +02001950 const char *string, const char *string_stop)
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001951{
1952 if (start < stop) {
1953 stop--; /* reserve one byte for the final '\0' */
Aurelien DARRAGONa5c621a2022-09-20 14:33:18 +02001954 while (start < stop && string < string_stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001955 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001956 *start++ = *string;
1957 else {
1958 if (start + 2 >= stop)
1959 break;
1960 *start++ = escape;
1961 *start++ = *string;
1962 }
1963 string++;
1964 }
1965 *start = '\0';
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001966 return start;
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001967 }
Aurelien DARRAGONd946cdf2024-04-09 11:44:54 +02001968 return NULL;
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001969}
1970
1971/*
1972 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001973 * character. <chunk> contains the input to be escaped. The result will be
1974 * stored between <start> (included) and <stop> (excluded). The function
1975 * will always try to terminate the resulting string with a '\0' before
1976 * <stop>, and will return its position if the conversion completes.
1977 */
1978char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001979 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001980 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001981{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001982 char *str = chunk->area;
1983 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001984
1985 if (start < stop) {
1986 stop--; /* reserve one byte for the final '\0' */
1987 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001988 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001989 *start++ = *str;
1990 else {
1991 if (start + 2 >= stop)
1992 break;
1993 *start++ = escape;
1994 *start++ = *str;
1995 }
1996 str++;
1997 }
1998 *start = '\0';
1999 }
2000 return start;
2001}
2002
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002003/* Check a string for using it in a CSV output format. If the string contains
2004 * one of the following four char <">, <,>, CR or LF, the string is
2005 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2006 * <str> is the input string to be escaped. The function assumes that
2007 * the input string is null-terminated.
2008 *
2009 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002010 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002011 * format.
2012 *
Emeric Brun7366c842024-01-23 15:44:32 +01002013 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002014 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002015 * If <quote> is 1, the converter puts the quotes only if any reserved character
2016 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002017 *
Emeric Brun7366c842024-01-23 15:44:32 +01002018 * If <oneline> is not 0, CRs are skipped and LFs are replaced by spaces.
2019 * This re-format multi-lines strings to only one line. The purpose is to
2020 * allow a line by line parsing but also to keep the output compliant with
2021 * the CLI witch uses LF to defines the end of the response.
2022 *
2023 * If <oneline> is 2, In addition to previous action, the trailing spaces are
2024 * removed.
2025 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002026 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002027 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002028 * The function returns the converted string on its output. If an error
2029 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002030 * for using the function directly as printf() argument.
2031 *
2032 * If the output buffer is too short to contain the input string, the result
2033 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002034 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002035 * This function appends the encoding to the existing output chunk, and it
2036 * guarantees that it starts immediately at the first available character of
2037 * the chunk. Please use csv_enc() instead if you want to replace the output
2038 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002039 */
Emeric Brun7366c842024-01-23 15:44:32 +01002040const char *csv_enc_append(const char *str, int quote, int oneline, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002041{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002042 char *end = output->area + output->size;
2043 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002044 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002045
Willy Tarreaub631c292016-01-08 10:04:08 +01002046 if (quote == 1) {
2047 /* automatic quoting: first verify if we'll have to quote the string */
2048 if (!strpbrk(str, "\n\r,\""))
2049 quote = 0;
2050 }
2051
2052 if (quote)
2053 *ptr++ = '"';
2054
Willy Tarreau898529b2016-01-06 18:07:04 +01002055 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
Emeric Brun7366c842024-01-23 15:44:32 +01002056 if (oneline) {
2057 if (*str == '\n' ) {
2058 /* replace LF by a space */
2059 *ptr++ = ' ';
2060 str++;
2061 continue;
2062 }
2063 else if (*str == '\r' ) {
2064 /* skip CR */
2065 str++;
2066 continue;
2067 }
2068 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002069 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002070 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002071 ptr++;
2072 if (ptr >= end - 2) {
2073 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002074 break;
2075 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002076 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002077 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002078 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002079 str++;
2080 }
2081
Emeric Brun7366c842024-01-23 15:44:32 +01002082 if (oneline == 2) {
2083 /* remove trailing spaces */
2084 while (ptr > out && *(ptr - 1) == ' ')
2085 ptr--;
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;
2477 break;
2478 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002479 if (*(++text) != '\0') {
2480 ha_warning("unexpected character '%c' after the timer value '%s', only "
2481 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2482 " This will be reported as an error in next versions.\n", *text, str);
2483 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002484
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002485 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002486 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2487 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2488 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2489 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2490
Willy Tarreau9faebe32019-06-07 19:00:37 +02002491 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2492 if (result >= 0x80000000)
2493 return PARSE_TIME_OVER;
2494 if (!result && value)
2495 return PARSE_TIME_UNDER;
2496 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002497 return NULL;
2498}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002499
Emeric Brun39132b22010-01-04 14:57:24 +01002500/* this function converts the string starting at <text> to an unsigned int
2501 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002502 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002503 */
2504const char *parse_size_err(const char *text, unsigned *ret) {
2505 unsigned value = 0;
2506
Christopher Faulet82635a02020-12-11 09:30:45 +01002507 if (!isdigit((unsigned char)*text))
2508 return text;
2509
Emeric Brun39132b22010-01-04 14:57:24 +01002510 while (1) {
2511 unsigned int j;
2512
2513 j = *text - '0';
2514 if (j > 9)
2515 break;
2516 if (value > ~0U / 10)
2517 return text;
2518 value *= 10;
2519 if (value > (value + j))
2520 return text;
2521 value += j;
2522 text++;
2523 }
2524
2525 switch (*text) {
2526 case '\0':
2527 break;
2528 case 'K':
2529 case 'k':
2530 if (value > ~0U >> 10)
2531 return text;
2532 value = value << 10;
2533 break;
2534 case 'M':
2535 case 'm':
2536 if (value > ~0U >> 20)
2537 return text;
2538 value = value << 20;
2539 break;
2540 case 'G':
2541 case 'g':
2542 if (value > ~0U >> 30)
2543 return text;
2544 value = value << 30;
2545 break;
2546 default:
2547 return text;
2548 }
2549
Godbach58048a22015-01-28 17:36:16 +08002550 if (*text != '\0' && *++text != '\0')
2551 return text;
2552
Emeric Brun39132b22010-01-04 14:57:24 +01002553 *ret = value;
2554 return NULL;
2555}
2556
Willy Tarreau126d4062013-12-03 17:50:47 +01002557/*
2558 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002559 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002560 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002561 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002562 */
2563int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2564{
2565 int len;
2566 const char *p = source;
2567 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002568 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002569
2570 len = strlen(source);
2571 if (len % 2) {
2572 memprintf(err, "an even number of hex digit is expected");
2573 return 0;
2574 }
2575
2576 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002577
Willy Tarreau126d4062013-12-03 17:50:47 +01002578 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002579 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002580 if (!*binstr) {
2581 memprintf(err, "out of memory while loading string pattern");
2582 return 0;
2583 }
2584 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002585 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002586 else {
2587 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002588 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002589 len, *binstrlen);
2590 return 0;
2591 }
2592 alloc = 0;
2593 }
2594 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002595
2596 i = j = 0;
2597 while (j < len) {
2598 if (!ishex(p[i++]))
2599 goto bad_input;
2600 if (!ishex(p[i++]))
2601 goto bad_input;
2602 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2603 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002604 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002605
2606bad_input:
2607 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002608 if (alloc)
2609 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002610 return 0;
2611}
2612
Willy Tarreau946ba592009-05-10 15:41:18 +02002613/* copies at most <n> characters from <src> and always terminates with '\0' */
2614char *my_strndup(const char *src, int n)
2615{
2616 int len = 0;
2617 char *ret;
2618
2619 while (len < n && src[len])
2620 len++;
2621
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002622 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002623 if (!ret)
2624 return ret;
2625 memcpy(ret, src, len);
2626 ret[len] = '\0';
2627 return ret;
2628}
2629
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002630/*
2631 * search needle in haystack
2632 * returns the pointer if found, returns NULL otherwise
2633 */
2634const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2635{
2636 const void *c = NULL;
2637 unsigned char f;
2638
2639 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2640 return NULL;
2641
2642 f = *(char *)needle;
2643 c = haystack;
2644 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2645 if ((haystacklen - (c - haystack)) < needlelen)
2646 return NULL;
2647
2648 if (memcmp(c, needle, needlelen) == 0)
2649 return c;
2650 ++c;
2651 }
2652 return NULL;
2653}
2654
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002655/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002656size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2657{
2658 size_t ret = 0;
2659
2660 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2661 str++;
2662 ret++;
2663 }
2664 return ret;
2665}
2666
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002667/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002668size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2669{
2670 size_t ret = 0;
2671
2672 while (ret < len) {
2673 if(memchr(reject, *((int *)str), rejectlen))
2674 return ret;
2675 str++;
2676 ret++;
2677 }
2678 return ret;
2679}
2680
Willy Tarreau482b00d2009-10-04 22:48:42 +02002681/* This function returns the first unused key greater than or equal to <key> in
2682 * ID tree <root>. Zero is returned if no place is found.
2683 */
2684unsigned int get_next_id(struct eb_root *root, unsigned int key)
2685{
2686 struct eb32_node *used;
2687
2688 do {
2689 used = eb32_lookup_ge(root, key);
2690 if (!used || used->key > key)
2691 return key; /* key is available */
2692 key++;
2693 } while (key);
2694 return key;
2695}
2696
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002697/* dump the full tree to <file> in DOT format for debugging purposes. Will
2698 * optionally highlight node <subj> if found, depending on operation <op> :
2699 * 0 : nothing
2700 * >0 : insertion, node/leaf are surrounded in red
2701 * <0 : removal, node/leaf are dashed with no background
2702 * Will optionally add "desc" as a label on the graph if set and non-null.
2703 */
2704void 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 +01002705{
2706 struct eb32sc_node *node;
2707 unsigned long scope = -1;
2708
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002709 fprintf(file, "digraph ebtree {\n");
2710
2711 if (desc && *desc) {
2712 fprintf(file,
2713 " fontname=\"fixed\";\n"
2714 " fontsize=8;\n"
2715 " label=\"%s\";\n", desc);
2716 }
2717
Willy Tarreaued3cda02017-11-15 15:04:05 +01002718 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002719 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2720 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002721 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2722 );
2723
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002724 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002725 (long)eb_root_to_node(root),
2726 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002727 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2728
2729 node = eb32sc_first(root, scope);
2730 while (node) {
2731 if (node->node.node_p) {
2732 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002733 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2734 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2735 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002736
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002737 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002738 (long)node,
2739 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002740 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002741
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002742 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002743 (long)node,
2744 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002745 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2746
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002747 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002748 (long)node,
2749 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002750 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2751 }
2752
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002753 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2754 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2755 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002756
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002757 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002758 (long)node,
2759 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002760 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002761 node = eb32sc_next(node, scope);
2762 }
2763 fprintf(file, "}\n");
2764}
2765
Willy Tarreau348238b2010-01-18 15:05:57 +01002766/* This function compares a sample word possibly followed by blanks to another
2767 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2768 * otherwise zero. This intends to be used when checking HTTP headers for some
2769 * values. Note that it validates a word followed only by blanks but does not
2770 * validate a word followed by blanks then other chars.
2771 */
2772int word_match(const char *sample, int slen, const char *word, int wlen)
2773{
2774 if (slen < wlen)
2775 return 0;
2776
2777 while (wlen) {
2778 char c = *sample ^ *word;
2779 if (c && c != ('A' ^ 'a'))
2780 return 0;
2781 sample++;
2782 word++;
2783 slen--;
2784 wlen--;
2785 }
2786
2787 while (slen) {
2788 if (*sample != ' ' && *sample != '\t')
2789 return 0;
2790 sample++;
2791 slen--;
2792 }
2793 return 1;
2794}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002795
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002796/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2797 * is particularly fast because it avoids expensive operations such as
2798 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002799 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002800 */
2801unsigned int inetaddr_host(const char *text)
2802{
2803 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2804 register unsigned int dig100, dig10, dig1;
2805 int s;
2806 const char *p, *d;
2807
2808 dig1 = dig10 = dig100 = ascii_zero;
2809 s = 24;
2810
2811 p = text;
2812 while (1) {
2813 if (((unsigned)(*p - '0')) <= 9) {
2814 p++;
2815 continue;
2816 }
2817
2818 /* here, we have a complete byte between <text> and <p> (exclusive) */
2819 if (p == text)
2820 goto end;
2821
2822 d = p - 1;
2823 dig1 |= (unsigned int)(*d << s);
2824 if (d == text)
2825 goto end;
2826
2827 d--;
2828 dig10 |= (unsigned int)(*d << s);
2829 if (d == text)
2830 goto end;
2831
2832 d--;
2833 dig100 |= (unsigned int)(*d << s);
2834 end:
2835 if (!s || *p != '.')
2836 break;
2837
2838 s -= 8;
2839 text = ++p;
2840 }
2841
2842 dig100 -= ascii_zero;
2843 dig10 -= ascii_zero;
2844 dig1 -= ascii_zero;
2845 return ((dig100 * 10) + dig10) * 10 + dig1;
2846}
2847
2848/*
2849 * Idem except the first unparsed character has to be passed in <stop>.
2850 */
2851unsigned int inetaddr_host_lim(const char *text, const char *stop)
2852{
2853 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2854 register unsigned int dig100, dig10, dig1;
2855 int s;
2856 const char *p, *d;
2857
2858 dig1 = dig10 = dig100 = ascii_zero;
2859 s = 24;
2860
2861 p = text;
2862 while (1) {
2863 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2864 p++;
2865 continue;
2866 }
2867
2868 /* here, we have a complete byte between <text> and <p> (exclusive) */
2869 if (p == text)
2870 goto end;
2871
2872 d = p - 1;
2873 dig1 |= (unsigned int)(*d << s);
2874 if (d == text)
2875 goto end;
2876
2877 d--;
2878 dig10 |= (unsigned int)(*d << s);
2879 if (d == text)
2880 goto end;
2881
2882 d--;
2883 dig100 |= (unsigned int)(*d << s);
2884 end:
2885 if (!s || p == stop || *p != '.')
2886 break;
2887
2888 s -= 8;
2889 text = ++p;
2890 }
2891
2892 dig100 -= ascii_zero;
2893 dig10 -= ascii_zero;
2894 dig1 -= ascii_zero;
2895 return ((dig100 * 10) + dig10) * 10 + dig1;
2896}
2897
2898/*
2899 * Idem except the pointer to first unparsed byte is returned into <ret> which
2900 * must not be NULL.
2901 */
Willy Tarreau74172752010-10-15 23:21:42 +02002902unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002903{
2904 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2905 register unsigned int dig100, dig10, dig1;
2906 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002907 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002908
2909 dig1 = dig10 = dig100 = ascii_zero;
2910 s = 24;
2911
2912 p = text;
2913 while (1) {
2914 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2915 p++;
2916 continue;
2917 }
2918
2919 /* here, we have a complete byte between <text> and <p> (exclusive) */
2920 if (p == text)
2921 goto end;
2922
2923 d = p - 1;
2924 dig1 |= (unsigned int)(*d << s);
2925 if (d == text)
2926 goto end;
2927
2928 d--;
2929 dig10 |= (unsigned int)(*d << s);
2930 if (d == text)
2931 goto end;
2932
2933 d--;
2934 dig100 |= (unsigned int)(*d << s);
2935 end:
2936 if (!s || p == stop || *p != '.')
2937 break;
2938
2939 s -= 8;
2940 text = ++p;
2941 }
2942
2943 *ret = p;
2944 dig100 -= ascii_zero;
2945 dig10 -= ascii_zero;
2946 dig1 -= ascii_zero;
2947 return ((dig100 * 10) + dig10) * 10 + dig1;
2948}
2949
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002950/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2951 * or the number of chars read in case of success. Maybe this could be replaced
2952 * by one of the functions above. Also, apparently this function does not support
2953 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002954 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002955 */
2956int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2957{
2958 const char *addr;
2959 int saw_digit, octets, ch;
2960 u_char tmp[4], *tp;
2961 const char *cp = buf;
2962
2963 saw_digit = 0;
2964 octets = 0;
2965 *(tp = tmp) = 0;
2966
2967 for (addr = buf; addr - buf < len; addr++) {
2968 unsigned char digit = (ch = *addr) - '0';
2969
2970 if (digit > 9 && ch != '.')
2971 break;
2972
2973 if (digit <= 9) {
2974 u_int new = *tp * 10 + digit;
2975
2976 if (new > 255)
2977 return 0;
2978
2979 *tp = new;
2980
2981 if (!saw_digit) {
2982 if (++octets > 4)
2983 return 0;
2984 saw_digit = 1;
2985 }
2986 } else if (ch == '.' && saw_digit) {
2987 if (octets == 4)
2988 return 0;
2989
2990 *++tp = 0;
2991 saw_digit = 0;
2992 } else
2993 return 0;
2994 }
2995
2996 if (octets < 4)
2997 return 0;
2998
2999 memcpy(&dst->s_addr, tmp, 4);
3000 return addr - cp;
3001}
3002
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003003/* This function converts the string in <buf> of the len <len> to
3004 * struct in6_addr <dst> which must be allocated by the caller.
3005 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01003006 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003007 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003008int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
3009{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003010 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01003011 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003012
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003013 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003014 return 0;
3015
3016 memcpy(null_term_ip6, buf, len);
3017 null_term_ip6[len] = '\0';
3018
Willy Tarreau075415a2013-12-12 11:29:39 +01003019 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003020 return 0;
3021
Willy Tarreau075415a2013-12-12 11:29:39 +01003022 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003023 return 1;
3024}
3025
Willy Tarreauacf95772010-06-14 19:09:21 +02003026/* To be used to quote config arg positions. Returns the short string at <ptr>
3027 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
3028 * if ptr is NULL or empty. The string is locally allocated.
3029 */
3030const char *quote_arg(const char *ptr)
3031{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003032 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003033 int i;
3034
3035 if (!ptr || !*ptr)
3036 return "end of line";
3037 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003038 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003039 val[i] = *ptr++;
3040 val[i++] = '\'';
3041 val[i] = '\0';
3042 return val;
3043}
3044
Willy Tarreau5b180202010-07-18 10:40:48 +02003045/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3046int get_std_op(const char *str)
3047{
3048 int ret = -1;
3049
3050 if (*str == 'e' && str[1] == 'q')
3051 ret = STD_OP_EQ;
3052 else if (*str == 'n' && str[1] == 'e')
3053 ret = STD_OP_NE;
3054 else if (*str == 'l') {
3055 if (str[1] == 'e') ret = STD_OP_LE;
3056 else if (str[1] == 't') ret = STD_OP_LT;
3057 }
3058 else if (*str == 'g') {
3059 if (str[1] == 'e') ret = STD_OP_GE;
3060 else if (str[1] == 't') ret = STD_OP_GT;
3061 }
3062
3063 if (ret == -1 || str[2] != '\0')
3064 return -1;
3065 return ret;
3066}
3067
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003068/* hash a 32-bit integer to another 32-bit integer */
3069unsigned int full_hash(unsigned int a)
3070{
3071 return __full_hash(a);
3072}
3073
Willy Tarreauf3241112019-02-26 09:56:22 +01003074/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3075 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3076 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3077 * a popcount variant and is described here :
3078 * https://graphics.stanford.edu/~seander/bithacks.html
3079 */
3080unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3081{
3082 unsigned long a, b, c, d;
3083 unsigned int s;
3084 unsigned int t;
3085
3086 a = m - ((m >> 1) & ~0UL/3);
3087 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3088 c = (b + (b >> 4)) & ~0UL/0x11;
3089 d = (c + (c >> 8)) & ~0UL/0x101;
3090
3091 r++; // make r be 1..64
3092
3093 t = 0;
3094 s = LONGBITS;
3095 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003096 unsigned long d2 = (d >> 16) >> 16;
3097 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003098 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3099 }
3100
3101 t = (d >> (s - 16)) & 0xff;
3102 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3103 t = (c >> (s - 8)) & 0xf;
3104 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3105 t = (b >> (s - 4)) & 0x7;
3106 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3107 t = (a >> (s - 2)) & 0x3;
3108 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3109 t = (m >> (s - 1)) & 0x1;
3110 s -= ((t - r) & 256) >> 8;
3111
3112 return s - 1;
3113}
3114
3115/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3116 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3117 * using mask_prep_rank_map() below.
3118 */
3119unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3120 unsigned long a, unsigned long b,
3121 unsigned long c, unsigned long d)
3122{
3123 unsigned int s;
3124 unsigned int t;
3125
3126 r++; // make r be 1..64
3127
3128 t = 0;
3129 s = LONGBITS;
3130 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003131 unsigned long d2 = (d >> 16) >> 16;
3132 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003133 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3134 }
3135
3136 t = (d >> (s - 16)) & 0xff;
3137 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3138 t = (c >> (s - 8)) & 0xf;
3139 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3140 t = (b >> (s - 4)) & 0x7;
3141 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3142 t = (a >> (s - 2)) & 0x3;
3143 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3144 t = (m >> (s - 1)) & 0x1;
3145 s -= ((t - r) & 256) >> 8;
3146
3147 return s - 1;
3148}
3149
3150/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3151 * above.
3152 */
3153void mask_prep_rank_map(unsigned long m,
3154 unsigned long *a, unsigned long *b,
3155 unsigned long *c, unsigned long *d)
3156{
3157 *a = m - ((m >> 1) & ~0UL/3);
3158 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3159 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3160 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3161}
3162
David du Colombier4f92d322011-03-24 11:09:31 +01003163/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003164 * otherwise zero. Note that <addr> may not necessarily be aligned
3165 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003166 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003167int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003168{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003169 struct in_addr addr_copy;
3170
3171 memcpy(&addr_copy, addr, sizeof(addr_copy));
3172 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003173}
3174
3175/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003176 * otherwise zero. Note that <addr> may not necessarily be aligned
3177 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003178 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003179int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003180{
3181 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003182 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003183
Willy Tarreaueec1d382016-07-13 11:59:39 +02003184 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003185 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003186 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003187 (((int *)net)[i] & ((int *)mask)[i]))
3188 return 0;
3189 return 1;
3190}
3191
3192/* RFC 4291 prefix */
3193const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3194 0x00, 0x00, 0x00, 0x00,
3195 0x00, 0x00, 0xFF, 0xFF };
3196
Joseph Herlant32b83272018-11-15 11:58:28 -08003197/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003198 * Input and output may overlap.
3199 */
David du Colombier4f92d322011-03-24 11:09:31 +01003200void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3201{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003202 struct in_addr tmp_addr;
3203
3204 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003205 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003206 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003207}
3208
Joseph Herlant32b83272018-11-15 11:58:28 -08003209/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003210 * Return true if conversion is possible and false otherwise.
3211 */
3212int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3213{
3214 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3215 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3216 sizeof(struct in_addr));
3217 return 1;
3218 }
3219
3220 return 0;
3221}
3222
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003223/* compare two struct sockaddr_storage and return:
3224 * 0 (true) if the addr is the same in both
3225 * 1 (false) if the addr is not the same in both
3226 * -1 (unable) if one of the addr is not AF_INET*
3227 */
3228int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3229{
3230 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3231 return -1;
3232
3233 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3234 return -1;
3235
3236 if (ss1->ss_family != ss2->ss_family)
3237 return 1;
3238
3239 switch (ss1->ss_family) {
3240 case AF_INET:
3241 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3242 &((struct sockaddr_in *)ss2)->sin_addr,
3243 sizeof(struct in_addr)) != 0;
3244 case AF_INET6:
3245 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3246 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3247 sizeof(struct in6_addr)) != 0;
3248 }
3249
3250 return 1;
3251}
3252
Christopher Faulet9553de72021-02-26 09:12:50 +01003253/* compare a struct sockaddr_storage to a struct net_addr and return :
3254 * 0 (true) if <addr> is matching <net>
3255 * 1 (false) if <addr> is not matching <net>
3256 * -1 (unable) if <addr> or <net> is not AF_INET*
3257 */
3258int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3259{
3260 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3261 return -1;
3262
3263 if ((net->family != AF_INET) && (net->family != AF_INET6))
3264 return -1;
3265
3266 if (addr->ss_family != net->family)
3267 return 1;
3268
3269 if (addr->ss_family == AF_INET &&
3270 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3271 return 0;
3272 else {
3273 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3274 const struct in6_addr *nip6 = &net->addr.v6.ip;
3275 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3276
3277 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3278 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3279 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3280 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3281 return 0;
3282 }
3283
3284 return 1;
3285}
3286
Baptiste Assmann08396c82016-01-31 00:27:17 +01003287/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003288 * The caller must allocate and clear <dest> before calling.
3289 * The source must be in either AF_INET or AF_INET6 family, or the destination
3290 * address will be undefined. If the destination address used to hold a port,
3291 * it is preserved, so that this function can be used to switch to another
3292 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003293 */
3294struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3295{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003296 int prev_port;
3297
3298 prev_port = get_net_port(dest);
3299 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003300 dest->ss_family = source->ss_family;
3301
3302 /* copy new addr and apply it */
3303 switch (source->ss_family) {
3304 case AF_INET:
3305 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003306 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003307 break;
3308 case AF_INET6:
3309 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 +01003310 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003311 break;
3312 }
3313
3314 return dest;
3315}
3316
William Lallemand421f5b52012-02-06 18:15:57 +01003317char *human_time(int t, short hz_div) {
3318 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3319 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003320 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003321 int cnt=2; // print two numbers
3322
3323 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003324 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003325 return rv;
3326 }
3327
3328 if (unlikely(hz_div > 1))
3329 t /= hz_div;
3330
3331 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003332 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003333 cnt--;
3334 }
3335
3336 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003337 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003338 cnt--;
3339 }
3340
3341 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003342 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003343 cnt--;
3344 }
3345
3346 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003347 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003348
3349 return rv;
3350}
3351
3352const char *monthname[12] = {
3353 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3354 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3355};
3356
3357/* date2str_log: write a date in the format :
3358 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3359 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3360 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3361 *
3362 * without using sprintf. return a pointer to the last char written (\0) or
3363 * NULL if there isn't enough space.
3364 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003365char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003366{
3367
3368 if (size < 25) /* the size is fixed: 24 chars + \0 */
3369 return NULL;
3370
3371 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003372 if (!dst)
3373 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003374 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003375
William Lallemand421f5b52012-02-06 18:15:57 +01003376 memcpy(dst, monthname[tm->tm_mon], 3); // month
3377 dst += 3;
3378 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003379
William Lallemand421f5b52012-02-06 18:15:57 +01003380 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003381 if (!dst)
3382 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003383 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003384
William Lallemand421f5b52012-02-06 18:15:57 +01003385 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003386 if (!dst)
3387 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003388 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003389
William Lallemand421f5b52012-02-06 18:15:57 +01003390 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003391 if (!dst)
3392 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003393 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003394
William Lallemand421f5b52012-02-06 18:15:57 +01003395 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003396 if (!dst)
3397 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003398 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003399
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003400 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003401 if (!dst)
3402 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003403 *dst = '\0';
3404
3405 return dst;
3406}
3407
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003408/* Base year used to compute leap years */
3409#define TM_YEAR_BASE 1900
3410
3411/* Return the difference in seconds between two times (leap seconds are ignored).
3412 * Retrieved from glibc 2.18 source code.
3413 */
3414static int my_tm_diff(const struct tm *a, const struct tm *b)
3415{
3416 /* Compute intervening leap days correctly even if year is negative.
3417 * Take care to avoid int overflow in leap day calculations,
3418 * but it's OK to assume that A and B are close to each other.
3419 */
3420 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3421 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3422 int a100 = a4 / 25 - (a4 % 25 < 0);
3423 int b100 = b4 / 25 - (b4 % 25 < 0);
3424 int a400 = a100 >> 2;
3425 int b400 = b100 >> 2;
3426 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3427 int years = a->tm_year - b->tm_year;
3428 int days = (365 * years + intervening_leap_days
3429 + (a->tm_yday - b->tm_yday));
3430 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3431 + (a->tm_min - b->tm_min))
3432 + (a->tm_sec - b->tm_sec));
3433}
3434
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003435/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003436 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003437 * The string returned has the same format as returned by strftime(... "%z", tm).
3438 * Offsets are kept in an internal cache for better performances.
3439 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003440const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003441{
3442 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003443 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003444
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003445 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003446 struct tm tm_gmt;
3447 int diff;
3448 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003449
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003450 /* Pretend DST not active if its status is unknown */
3451 if (isdst < 0)
3452 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003453
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003454 /* Fetch the offset and initialize it if needed */
3455 gmt_offset = gmt_offsets[isdst & 0x01];
3456 if (unlikely(!*gmt_offset)) {
3457 get_gmtime(t, &tm_gmt);
3458 diff = my_tm_diff(tm, &tm_gmt);
3459 if (diff < 0) {
3460 diff = -diff;
3461 *gmt_offset = '-';
3462 } else {
3463 *gmt_offset = '+';
3464 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003465 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003466 diff /= 60; /* Convert to minutes */
3467 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3468 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003469
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003470 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003471}
3472
William Lallemand421f5b52012-02-06 18:15:57 +01003473/* gmt2str_log: write a date in the format :
3474 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3475 * return a pointer to the last char written (\0) or
3476 * NULL if there isn't enough space.
3477 */
3478char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3479{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003480 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003481 return NULL;
3482
3483 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003484 if (!dst)
3485 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003486 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003487
William Lallemand421f5b52012-02-06 18:15:57 +01003488 memcpy(dst, monthname[tm->tm_mon], 3); // month
3489 dst += 3;
3490 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003491
William Lallemand421f5b52012-02-06 18:15:57 +01003492 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003493 if (!dst)
3494 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003495 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003496
William Lallemand421f5b52012-02-06 18:15:57 +01003497 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003498 if (!dst)
3499 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003500 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003501
William Lallemand421f5b52012-02-06 18:15:57 +01003502 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003503 if (!dst)
3504 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003505 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003506
William Lallemand421f5b52012-02-06 18:15:57 +01003507 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003508 if (!dst)
3509 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003510 *dst++ = ' ';
3511 *dst++ = '+';
3512 *dst++ = '0';
3513 *dst++ = '0';
3514 *dst++ = '0';
3515 *dst++ = '0';
3516 *dst = '\0';
3517
3518 return dst;
3519}
3520
Yuxans Yao4e25b012012-10-19 10:36:09 +08003521/* localdate2str_log: write a date in the format :
3522 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003523 * Both t and tm must represent the same time.
3524 * return a pointer to the last char written (\0) or
3525 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003526 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003527char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003528{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003529 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003530 if (size < 27) /* the size is fixed: 26 chars + \0 */
3531 return NULL;
3532
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003533 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003534
Yuxans Yao4e25b012012-10-19 10:36:09 +08003535 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003536 if (!dst)
3537 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003538 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003539
Yuxans Yao4e25b012012-10-19 10:36:09 +08003540 memcpy(dst, monthname[tm->tm_mon], 3); // month
3541 dst += 3;
3542 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003543
Yuxans Yao4e25b012012-10-19 10:36:09 +08003544 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003545 if (!dst)
3546 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003547 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003548
Yuxans Yao4e25b012012-10-19 10:36:09 +08003549 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003550 if (!dst)
3551 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003552 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003553
Yuxans Yao4e25b012012-10-19 10:36:09 +08003554 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003555 if (!dst)
3556 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003557 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003558
Yuxans Yao4e25b012012-10-19 10:36:09 +08003559 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003560 if (!dst)
3561 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003562 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003563
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003564 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003565 dst += 5;
3566 *dst = '\0';
3567
3568 return dst;
3569}
3570
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003571/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3572 * It is meant as a portable replacement for timegm() for use with valid inputs.
3573 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3574 */
3575time_t my_timegm(const struct tm *tm)
3576{
3577 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3578 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3579 * sum of the extra N days for elapsed months. The sum of all these N
3580 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3581 * in a 5-bit word. This means that with 60 bits we can represent a
3582 * matrix of all these values at once, which is fast and efficient to
3583 * access. The extra February day for leap years is not counted here.
3584 *
3585 * Jan : none = 0 (0)
3586 * Feb : Jan = 3 (3)
3587 * Mar : Jan..Feb = 3 (3 + 0)
3588 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3589 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3590 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3591 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3592 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3593 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3594 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3595 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3596 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3597 */
3598 uint64_t extra =
3599 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3600 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3601 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3602 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3603
3604 unsigned int y = tm->tm_year + 1900;
3605 unsigned int m = tm->tm_mon;
3606 unsigned long days = 0;
3607
3608 /* days since 1/1/1970 for full years */
3609 days += days_since_zero(y) - days_since_zero(1970);
3610
3611 /* days for full months in the current year */
3612 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3613
3614 /* count + 1 after March for leap years. A leap year is a year multiple
3615 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3616 * is leap, 1900 isn't, 1904 is.
3617 */
3618 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3619 days++;
3620
3621 days += tm->tm_mday - 1;
3622 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3623}
3624
Thierry Fournier93127942016-01-20 18:49:45 +01003625/* This function check a char. It returns true and updates
3626 * <date> and <len> pointer to the new position if the
3627 * character is found.
3628 */
3629static inline int parse_expect_char(const char **date, int *len, char c)
3630{
3631 if (*len < 1 || **date != c)
3632 return 0;
3633 (*len)--;
3634 (*date)++;
3635 return 1;
3636}
3637
3638/* This function expects a string <str> of len <l>. It return true and updates.
3639 * <date> and <len> if the string matches, otherwise, it returns false.
3640 */
3641static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3642{
3643 if (*len < l || strncmp(*date, str, l) != 0)
3644 return 0;
3645 (*len) -= l;
3646 (*date) += l;
3647 return 1;
3648}
3649
3650/* This macro converts 3 chars name in integer. */
3651#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3652
3653/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3654 * / %x54.75.65 ; "Tue", case-sensitive
3655 * / %x57.65.64 ; "Wed", case-sensitive
3656 * / %x54.68.75 ; "Thu", case-sensitive
3657 * / %x46.72.69 ; "Fri", case-sensitive
3658 * / %x53.61.74 ; "Sat", case-sensitive
3659 * / %x53.75.6E ; "Sun", case-sensitive
3660 *
3661 * This array must be alphabetically sorted
3662 */
3663static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3664{
3665 if (*len < 3)
3666 return 0;
3667 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3668 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3669 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3670 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3671 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3672 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3673 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3674 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3675 default: return 0;
3676 }
3677 *len -= 3;
3678 *date += 3;
3679 return 1;
3680}
3681
3682/* month = %x4A.61.6E ; "Jan", case-sensitive
3683 * / %x46.65.62 ; "Feb", case-sensitive
3684 * / %x4D.61.72 ; "Mar", case-sensitive
3685 * / %x41.70.72 ; "Apr", case-sensitive
3686 * / %x4D.61.79 ; "May", case-sensitive
3687 * / %x4A.75.6E ; "Jun", case-sensitive
3688 * / %x4A.75.6C ; "Jul", case-sensitive
3689 * / %x41.75.67 ; "Aug", case-sensitive
3690 * / %x53.65.70 ; "Sep", case-sensitive
3691 * / %x4F.63.74 ; "Oct", case-sensitive
3692 * / %x4E.6F.76 ; "Nov", case-sensitive
3693 * / %x44.65.63 ; "Dec", case-sensitive
3694 *
3695 * This array must be alphabetically sorted
3696 */
3697static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3698{
3699 if (*len < 3)
3700 return 0;
3701 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3702 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3703 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3704 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3705 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3706 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3707 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3708 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3709 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3710 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3711 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3712 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3713 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3714 default: return 0;
3715 }
3716 *len -= 3;
3717 *date += 3;
3718 return 1;
3719}
3720
3721/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3722 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3723 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3724 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3725 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3726 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3727 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3728 *
3729 * This array must be alphabetically sorted
3730 */
3731static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3732{
3733 if (*len < 6) /* Minimum length. */
3734 return 0;
3735 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3736 case STR2I3('M','o','n'):
3737 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3738 tm->tm_wday = 1;
3739 return 1;
3740 case STR2I3('T','u','e'):
3741 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3742 tm->tm_wday = 2;
3743 return 1;
3744 case STR2I3('W','e','d'):
3745 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3746 tm->tm_wday = 3;
3747 return 1;
3748 case STR2I3('T','h','u'):
3749 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3750 tm->tm_wday = 4;
3751 return 1;
3752 case STR2I3('F','r','i'):
3753 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3754 tm->tm_wday = 5;
3755 return 1;
3756 case STR2I3('S','a','t'):
3757 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3758 tm->tm_wday = 6;
3759 return 1;
3760 case STR2I3('S','u','n'):
3761 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3762 tm->tm_wday = 7;
3763 return 1;
3764 }
3765 return 0;
3766}
3767
3768/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3769static inline int parse_digit(const char **date, int *len, int *digit)
3770{
3771 if (*len < 1 || **date < '0' || **date > '9')
3772 return 0;
3773 *digit = (**date - '0');
3774 (*date)++;
3775 (*len)--;
3776 return 1;
3777}
3778
3779/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3780static inline int parse_2digit(const char **date, int *len, int *digit)
3781{
3782 int value;
3783
3784 RET0_UNLESS(parse_digit(date, len, &value));
3785 (*digit) = value * 10;
3786 RET0_UNLESS(parse_digit(date, len, &value));
3787 (*digit) += value;
3788
3789 return 1;
3790}
3791
3792/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3793static inline int parse_4digit(const char **date, int *len, int *digit)
3794{
3795 int value;
3796
3797 RET0_UNLESS(parse_digit(date, len, &value));
3798 (*digit) = value * 1000;
3799
3800 RET0_UNLESS(parse_digit(date, len, &value));
3801 (*digit) += value * 100;
3802
3803 RET0_UNLESS(parse_digit(date, len, &value));
3804 (*digit) += value * 10;
3805
3806 RET0_UNLESS(parse_digit(date, len, &value));
3807 (*digit) += value;
3808
3809 return 1;
3810}
3811
3812/* time-of-day = hour ":" minute ":" second
3813 * ; 00:00:00 - 23:59:60 (leap second)
3814 *
3815 * hour = 2DIGIT
3816 * minute = 2DIGIT
3817 * second = 2DIGIT
3818 */
3819static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3820{
3821 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3822 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3823 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3824 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3825 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3826 return 1;
3827}
3828
3829/* From RFC7231
3830 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3831 *
3832 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3833 * ; fixed length/zone/capitalization subset of the format
3834 * ; see Section 3.3 of [RFC5322]
3835 *
3836 *
3837 * date1 = day SP month SP year
3838 * ; e.g., 02 Jun 1982
3839 *
3840 * day = 2DIGIT
3841 * year = 4DIGIT
3842 *
3843 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3844 *
3845 * time-of-day = hour ":" minute ":" second
3846 * ; 00:00:00 - 23:59:60 (leap second)
3847 *
3848 * hour = 2DIGIT
3849 * minute = 2DIGIT
3850 * second = 2DIGIT
3851 *
3852 * DIGIT = decimal 0-9
3853 */
3854int parse_imf_date(const char *date, int len, struct tm *tm)
3855{
David Carlier327298c2016-11-20 10:42:38 +00003856 /* tm_gmtoff, if present, ought to be zero'ed */
3857 memset(tm, 0, sizeof(*tm));
3858
Thierry Fournier93127942016-01-20 18:49:45 +01003859 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3860 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3861 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3862 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3863 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3864 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3865 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3866 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3867 tm->tm_year -= 1900;
3868 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3869 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3870 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3871 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3872 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003873 return 1;
3874}
3875
3876/* From RFC7231
3877 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3878 *
3879 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3880 * date2 = day "-" month "-" 2DIGIT
3881 * ; e.g., 02-Jun-82
3882 *
3883 * day = 2DIGIT
3884 */
3885int parse_rfc850_date(const char *date, int len, struct tm *tm)
3886{
3887 int year;
3888
David Carlier327298c2016-11-20 10:42:38 +00003889 /* tm_gmtoff, if present, ought to be zero'ed */
3890 memset(tm, 0, sizeof(*tm));
3891
Thierry Fournier93127942016-01-20 18:49:45 +01003892 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3893 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3894 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3895 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3896 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3897 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3898 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3899
3900 /* year = 2DIGIT
3901 *
3902 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3903 * two-digit year, MUST interpret a timestamp that appears to be more
3904 * than 50 years in the future as representing the most recent year in
3905 * the past that had the same last two digits.
3906 */
3907 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3908
3909 /* expect SP */
3910 if (!parse_expect_char(&date, &len, ' ')) {
3911 /* Maybe we have the date with 4 digits. */
3912 RET0_UNLESS(parse_2digit(&date, &len, &year));
3913 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3914 /* expect SP */
3915 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3916 } else {
3917 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3918 * tm_year is the number of year since 1900, so for +1900, we
3919 * do nothing, and for +2000, we add 100.
3920 */
3921 if (tm->tm_year <= 60)
3922 tm->tm_year += 100;
3923 }
3924
3925 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3926 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3927 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3928 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003929
3930 return 1;
3931}
3932
3933/* From RFC7231
3934 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3935 *
3936 * asctime-date = day-name SP date3 SP time-of-day SP year
3937 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3938 * ; e.g., Jun 2
3939 *
3940 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3941 * whitespace in an HTTP-date beyond that specifically included as SP in
3942 * the grammar.
3943 */
3944int parse_asctime_date(const char *date, int len, struct tm *tm)
3945{
David Carlier327298c2016-11-20 10:42:38 +00003946 /* tm_gmtoff, if present, ought to be zero'ed */
3947 memset(tm, 0, sizeof(*tm));
3948
Thierry Fournier93127942016-01-20 18:49:45 +01003949 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3950 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3951 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3952 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3953
3954 /* expect SP and 1DIGIT or 2DIGIT */
3955 if (parse_expect_char(&date, &len, ' '))
3956 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3957 else
3958 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3959
3960 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3961 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3962 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3963 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3964 tm->tm_year -= 1900;
3965 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003966 return 1;
3967}
3968
3969/* From RFC7231
3970 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3971 *
3972 * HTTP-date = IMF-fixdate / obs-date
3973 * obs-date = rfc850-date / asctime-date
3974 *
3975 * parses an HTTP date in the RFC format and is accepted
3976 * alternatives. <date> is the strinf containing the date,
3977 * len is the len of the string. <tm> is filled with the
3978 * parsed time. We must considers this time as GMT.
3979 */
3980int parse_http_date(const char *date, int len, struct tm *tm)
3981{
3982 if (parse_imf_date(date, len, tm))
3983 return 1;
3984
3985 if (parse_rfc850_date(date, len, tm))
3986 return 1;
3987
3988 if (parse_asctime_date(date, len, tm))
3989 return 1;
3990
3991 return 0;
3992}
3993
Willy Tarreau4deeb102021-01-29 10:47:52 +01003994/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3995 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3996 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3997 * surrounded by <pfx> and <sfx> respectively if not NULL.
3998 */
3999int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
4000{
4001 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
4002 const char *unit;
4003
4004 if (!pfx)
4005 pfx = "";
4006 if (!sfx)
4007 sfx = "";
4008
4009 do {
4010 unit = " - "; if (val <= 0.0) break;
4011 unit = "ns"; if (val < 1000.0) break;
4012 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
4013 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
4014 unit = "s "; val /= 1000.0; if (val < 60.0) break;
4015 unit = "m "; val /= 60.0; if (val < 60.0) break;
4016 unit = "h "; val /= 60.0; if (val < 24.0) break;
4017 unit = "d "; val /= 24.0; if (val < 365.0) break;
4018 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
4019 unit = " inf "; val = 0.0; break;
4020 } while (0);
4021
4022 if (val <= 0.0)
4023 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
4024 else if (val < 10.0)
4025 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
4026 else if (val < 100.0)
4027 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
4028 else
4029 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4030}
4031
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004032/* Dynamically allocates a string of the proper length to hold the formatted
4033 * output. NULL is returned on error. The caller is responsible for freeing the
4034 * memory area using free(). The resulting string is returned in <out> if the
4035 * pointer is not NULL. A previous version of <out> might be used to build the
4036 * new string, and it will be freed before returning if it is not NULL, which
4037 * makes it possible to build complex strings from iterative calls without
4038 * having to care about freeing intermediate values, as in the example below :
4039 *
4040 * memprintf(&err, "invalid argument: '%s'", arg);
4041 * ...
4042 * memprintf(&err, "parser said : <%s>\n", *err);
4043 * ...
4044 * free(*err);
4045 *
4046 * This means that <err> must be initialized to NULL before first invocation.
4047 * The return value also holds the allocated string, which eases error checking
4048 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004049 * passed instead and it will be ignored. The returned message will then also
4050 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004051 *
4052 * It is also convenient to use it without any free except the last one :
4053 * err = NULL;
4054 * if (!fct1(err)) report(*err);
4055 * if (!fct2(err)) report(*err);
4056 * if (!fct3(err)) report(*err);
4057 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004058 *
4059 * memprintf relies on memvprintf. This last version can be called from any
4060 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004061 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004062char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004063{
4064 va_list args;
4065 char *ret = NULL;
4066 int allocated = 0;
4067 int needed = 0;
4068
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004069 if (!out)
4070 return NULL;
4071
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004072 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004073 char buf1;
4074
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004075 /* vsnprintf() will return the required length even when the
4076 * target buffer is NULL. We do this in a loop just in case
4077 * intermediate evaluations get wrong.
4078 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004079 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004080 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004081 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004082 if (needed < allocated) {
4083 /* Note: on Solaris 8, the first iteration always
4084 * returns -1 if allocated is zero, so we force a
4085 * retry.
4086 */
4087 if (!allocated)
4088 needed = 0;
4089 else
4090 break;
4091 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004092
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004093 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004094 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004095 } while (ret);
4096
4097 if (needed < 0) {
4098 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004099 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004100 }
4101
4102 if (out) {
4103 free(*out);
4104 *out = ret;
4105 }
4106
4107 return ret;
4108}
William Lallemand421f5b52012-02-06 18:15:57 +01004109
Christopher Faulet93a518f2017-10-24 11:25:33 +02004110char *memprintf(char **out, const char *format, ...)
4111{
4112 va_list args;
4113 char *ret = NULL;
4114
4115 va_start(args, format);
4116 ret = memvprintf(out, format, args);
4117 va_end(args);
4118
4119 return ret;
4120}
4121
Willy Tarreau21c705b2012-09-14 11:40:36 +02004122/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4123 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004124 * freed by the caller. It also supports being passed a NULL which results in the same
4125 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004126 * Example of use :
4127 * parse(cmd, &err); (callee: memprintf(&err, ...))
4128 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4129 * free(err);
4130 */
4131char *indent_msg(char **out, int level)
4132{
4133 char *ret, *in, *p;
4134 int needed = 0;
4135 int lf = 0;
4136 int lastlf = 0;
4137 int len;
4138
Willy Tarreau70eec382012-10-10 08:56:47 +02004139 if (!out || !*out)
4140 return NULL;
4141
Willy Tarreau21c705b2012-09-14 11:40:36 +02004142 in = *out - 1;
4143 while ((in = strchr(in + 1, '\n')) != NULL) {
4144 lastlf = in - *out;
4145 lf++;
4146 }
4147
4148 if (!lf) /* single line, no LF, return it as-is */
4149 return *out;
4150
4151 len = strlen(*out);
4152
4153 if (lf == 1 && lastlf == len - 1) {
4154 /* single line, LF at end, strip it and return as-is */
4155 (*out)[lastlf] = 0;
4156 return *out;
4157 }
4158
4159 /* OK now we have at least one LF, we need to process the whole string
4160 * as a multi-line string. What we'll do :
4161 * - prefix with an LF if there is none
4162 * - add <level> spaces before each line
4163 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4164 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4165 */
4166
4167 needed = 1 + level * (lf + 1) + len + 1;
4168 p = ret = malloc(needed);
4169 in = *out;
4170
4171 /* skip initial LFs */
4172 while (*in == '\n')
4173 in++;
4174
4175 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4176 while (*in) {
4177 *p++ = '\n';
4178 memset(p, ' ', level);
4179 p += level;
4180 do {
4181 *p++ = *in++;
4182 } while (*in && *in != '\n');
4183 if (*in)
4184 in++;
4185 }
4186 *p = 0;
4187
4188 free(*out);
4189 *out = ret;
4190
4191 return ret;
4192}
4193
Willy Tarreaua2c99112019-08-21 13:17:37 +02004194/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4195 * and end of lines replaced with <eol> if not 0. The first line to indent has
4196 * to be indicated in <first> (starts at zero), so that it is possible to skip
4197 * indenting the first line if it has to be appended after an existing message.
4198 * Empty strings are never indented, and NULL strings are considered empty both
4199 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4200 * character, non-zero otherwise.
4201 */
4202int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4203{
4204 int bol, lf;
4205 int pfxlen = pfx ? strlen(pfx) : 0;
4206
4207 if (!in)
4208 return 0;
4209
4210 bol = 1;
4211 lf = 0;
4212 while (*in) {
4213 if (bol && pfxlen) {
4214 if (first > 0)
4215 first--;
4216 else
4217 b_putblk(out, pfx, pfxlen);
4218 bol = 0;
4219 }
4220
4221 lf = (*in == '\n');
4222 bol |= lf;
4223 b_putchr(out, (lf && eol) ? eol : *in);
4224 in++;
4225 }
4226 return lf;
4227}
4228
Willy Tarreau9d22e562019-03-29 18:49:09 +01004229/* removes environment variable <name> from the environment as found in
4230 * environ. This is only provided as an alternative for systems without
4231 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004232 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004233 * <name> and to replace the matching pointers with the last pointer of
4234 * the array (since variables are not ordered).
4235 * It always returns 0 (success).
4236 */
4237int my_unsetenv(const char *name)
4238{
4239 extern char **environ;
4240 char **p = environ;
4241 int vars;
4242 int next;
4243 int len;
4244
4245 len = strlen(name);
4246 for (vars = 0; p[vars]; vars++)
4247 ;
4248 next = 0;
4249 while (next < vars) {
4250 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4251 next++;
4252 continue;
4253 }
4254 if (next < vars - 1)
4255 p[next] = p[vars - 1];
4256 p[--vars] = NULL;
4257 }
4258 return 0;
4259}
4260
Willy Tarreaudad36a32013-03-11 01:20:04 +01004261/* Convert occurrences of environment variables in the input string to their
4262 * corresponding value. A variable is identified as a series of alphanumeric
4263 * characters or underscores following a '$' sign. The <in> string must be
4264 * free()able. NULL returns NULL. The resulting string might be reallocated if
4265 * some expansion is made. Variable names may also be enclosed into braces if
4266 * needed (eg: to concatenate alphanum characters).
4267 */
4268char *env_expand(char *in)
4269{
4270 char *txt_beg;
4271 char *out;
4272 char *txt_end;
4273 char *var_beg;
4274 char *var_end;
4275 char *value;
4276 char *next;
4277 int out_len;
4278 int val_len;
4279
4280 if (!in)
4281 return in;
4282
4283 value = out = NULL;
4284 out_len = 0;
4285
4286 txt_beg = in;
4287 do {
4288 /* look for next '$' sign in <in> */
4289 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4290
4291 if (!*txt_end && !out) /* end and no expansion performed */
4292 return in;
4293
4294 val_len = 0;
4295 next = txt_end;
4296 if (*txt_end == '$') {
4297 char save;
4298
4299 var_beg = txt_end + 1;
4300 if (*var_beg == '{')
4301 var_beg++;
4302
4303 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004304 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004305 var_end++;
4306 }
4307
4308 next = var_end;
4309 if (*var_end == '}' && (var_beg > txt_end + 1))
4310 next++;
4311
4312 /* get value of the variable name at this location */
4313 save = *var_end;
4314 *var_end = '\0';
4315 value = getenv(var_beg);
4316 *var_end = save;
4317 val_len = value ? strlen(value) : 0;
4318 }
4319
Hubert Verstraete831962e2016-06-28 22:44:26 +02004320 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004321 if (txt_end > txt_beg) {
4322 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4323 out_len += txt_end - txt_beg;
4324 }
4325 if (val_len) {
4326 memcpy(out + out_len, value, val_len);
4327 out_len += val_len;
4328 }
4329 out[out_len] = 0;
4330 txt_beg = next;
4331 } while (*txt_beg);
4332
4333 /* here we know that <out> was allocated and that we don't need <in> anymore */
4334 free(in);
4335 return out;
4336}
4337
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004338
4339/* same as strstr() but case-insensitive and with limit length */
4340const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4341{
4342 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004343 unsigned int slen, plen;
4344 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004345
4346 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4347 return NULL;
4348
4349 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4350 return str1;
4351
4352 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4353 return NULL;
4354
4355 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 +02004356 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004357 start++;
4358 slen--;
4359 tmp1++;
4360
4361 if (tmp1 >= len_str1)
4362 return NULL;
4363
4364 /* if pattern longer than string */
4365 if (slen < plen)
4366 return NULL;
4367 }
4368
4369 sptr = start;
4370 pptr = (char *)str2;
4371
4372 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004373 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004374 sptr++;
4375 pptr++;
4376 tmp2++;
4377
4378 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4379 return start;
4380 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4381 return NULL;
4382 }
4383 }
4384 return NULL;
4385}
4386
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004387/* This function read the next valid utf8 char.
4388 * <s> is the byte srray to be decode, <len> is its length.
4389 * The function returns decoded char encoded like this:
4390 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4391 * are the length read. The decoded character is stored in <c>.
4392 */
4393unsigned char utf8_next(const char *s, int len, unsigned int *c)
4394{
4395 const unsigned char *p = (unsigned char *)s;
4396 int dec;
4397 unsigned char code = UTF8_CODE_OK;
4398
4399 if (len < 1)
4400 return UTF8_CODE_OK;
4401
4402 /* Check the type of UTF8 sequence
4403 *
4404 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4405 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4406 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4407 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4408 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4409 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4410 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4411 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4412 */
4413 switch (*p) {
4414 case 0x00 ... 0x7f:
4415 *c = *p;
4416 return UTF8_CODE_OK | 1;
4417
4418 case 0x80 ... 0xbf:
4419 *c = *p;
4420 return UTF8_CODE_BADSEQ | 1;
4421
4422 case 0xc0 ... 0xdf:
4423 if (len < 2) {
4424 *c = *p;
4425 return UTF8_CODE_BADSEQ | 1;
4426 }
4427 *c = *p & 0x1f;
4428 dec = 1;
4429 break;
4430
4431 case 0xe0 ... 0xef:
4432 if (len < 3) {
4433 *c = *p;
4434 return UTF8_CODE_BADSEQ | 1;
4435 }
4436 *c = *p & 0x0f;
4437 dec = 2;
4438 break;
4439
4440 case 0xf0 ... 0xf7:
4441 if (len < 4) {
4442 *c = *p;
4443 return UTF8_CODE_BADSEQ | 1;
4444 }
4445 *c = *p & 0x07;
4446 dec = 3;
4447 break;
4448
4449 case 0xf8 ... 0xfb:
4450 if (len < 5) {
4451 *c = *p;
4452 return UTF8_CODE_BADSEQ | 1;
4453 }
4454 *c = *p & 0x03;
4455 dec = 4;
4456 break;
4457
4458 case 0xfc ... 0xfd:
4459 if (len < 6) {
4460 *c = *p;
4461 return UTF8_CODE_BADSEQ | 1;
4462 }
4463 *c = *p & 0x01;
4464 dec = 5;
4465 break;
4466
4467 case 0xfe ... 0xff:
4468 default:
4469 *c = *p;
4470 return UTF8_CODE_BADSEQ | 1;
4471 }
4472
4473 p++;
4474
4475 while (dec > 0) {
4476
4477 /* need 0x10 for the 2 first bits */
4478 if ( ( *p & 0xc0 ) != 0x80 )
4479 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4480
4481 /* add data at char */
4482 *c = ( *c << 6 ) | ( *p & 0x3f );
4483
4484 dec--;
4485 p++;
4486 }
4487
4488 /* Check ovelong encoding.
4489 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4490 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4491 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4492 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004493 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004494 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4495 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4496 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4497 code |= UTF8_CODE_OVERLONG;
4498
4499 /* Check invalid UTF8 range. */
4500 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4501 (*c >= 0xfffe && *c <= 0xffff))
4502 code |= UTF8_CODE_INVRANGE;
4503
4504 return code | ((p-(unsigned char *)s)&0x0f);
4505}
4506
Maxime de Roucydc887852016-05-13 23:52:54 +02004507/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4508 * On failure : return 0 and <err> filled with an error message.
4509 * The caller is responsible for freeing the <err> and <str> copy
4510 * memory area using free()
4511 */
4512int list_append_word(struct list *li, const char *str, char **err)
4513{
4514 struct wordlist *wl;
4515
4516 wl = calloc(1, sizeof(*wl));
4517 if (!wl) {
4518 memprintf(err, "out of memory");
4519 goto fail_wl;
4520 }
4521
4522 wl->s = strdup(str);
4523 if (!wl->s) {
4524 memprintf(err, "out of memory");
4525 goto fail_wl_s;
4526 }
4527
Willy Tarreau2b718102021-04-21 07:32:39 +02004528 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004529
4530 return 1;
4531
4532fail_wl_s:
4533 free(wl->s);
4534fail_wl:
4535 free(wl);
4536 return 0;
4537}
4538
Willy Tarreau37101052019-05-20 16:48:20 +02004539/* indicates if a memory location may safely be read or not. The trick consists
4540 * in performing a harmless syscall using this location as an input and letting
4541 * the operating system report whether it's OK or not. For this we have the
4542 * stat() syscall, which will return EFAULT when the memory location supposed
4543 * to contain the file name is not readable. If it is readable it will then
4544 * either return 0 if the area contains an existing file name, or -1 with
4545 * another code. This must not be abused, and some audit systems might detect
4546 * this as abnormal activity. It's used only for unsafe dumps.
4547 */
4548int may_access(const void *ptr)
4549{
4550 struct stat buf;
4551
4552 if (stat(ptr, &buf) == 0)
4553 return 1;
4554 if (errno == EFAULT)
4555 return 0;
4556 return 1;
4557}
4558
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004559/* print a string of text buffer to <out>. The format is :
4560 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4561 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4562 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4563 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004564int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004565{
4566 unsigned char c;
Tim Duesterhuscd5521e2021-08-29 00:58:22 +02004567 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004568
Tim Duesterhuscd5521e2021-08-29 00:58:22 +02004569 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004570 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004571 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004572 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004573 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004574 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004575 }
4576 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004577 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004578 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004579 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004580 switch (c) {
4581 case ' ': c = ' '; break;
4582 case '\t': c = 't'; break;
4583 case '\n': c = 'n'; break;
4584 case '\r': c = 'r'; break;
4585 case '\e': c = 'e'; break;
4586 case '\\': c = '\\'; break;
4587 case '=': c = '='; break;
4588 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004589 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004590 }
4591 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004592 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004593 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004594 out->area[out->data++] = '\\';
4595 out->area[out->data++] = 'x';
4596 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4597 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004598 }
4599 ptr++;
4600 }
4601
4602 return ptr;
4603}
4604
4605/* print a buffer in hexa.
4606 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4607 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004608int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004609{
4610 unsigned char c;
4611 int ptr = 0;
4612
4613 while (ptr < bsize) {
4614 c = buf[ptr];
4615
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004616 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004617 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004618 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4619 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004620
4621 ptr++;
4622 }
4623 return ptr;
4624}
4625
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004626/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4627 * prepending each line with prefix <pfx>. The output is *not* initialized.
4628 * The output will not wrap pas the buffer's end so it is more optimal if the
4629 * caller makes sure the buffer is aligned first. A trailing zero will always
4630 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004631 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4632 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004633 */
Willy Tarreau37101052019-05-20 16:48:20 +02004634void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004635{
4636 const unsigned char *d = buf;
4637 int i, j, start;
4638
4639 d = (const unsigned char *)(((unsigned long)buf) & -16);
4640 start = ((unsigned long)buf) & 15;
4641
4642 for (i = 0; i < start + len; i += 16) {
4643 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4644
Willy Tarreau37101052019-05-20 16:48:20 +02004645 // 0: unchecked, 1: checked safe, 2: danger
4646 unsafe = !!unsafe;
4647 if (unsafe && !may_access(d + i))
4648 unsafe = 2;
4649
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004650 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004651 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004652 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004653 else if (unsafe > 1)
4654 chunk_strcat(out, "** ");
4655 else
4656 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004657
4658 if (j == 7)
4659 chunk_strcat(out, "- ");
4660 }
4661 chunk_strcat(out, " ");
4662 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004663 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004664 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004665 else if (unsafe > 1)
4666 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004667 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004668 chunk_appendf(out, "%c", d[i + j]);
4669 else
4670 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004671 }
4672 chunk_strcat(out, "\n");
4673 }
4674}
4675
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004676/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4677 * enclosed in brackets after the address itself, formatted on 14 chars
4678 * including the "0x" prefix. This is meant to be used as a prefix for code
4679 * areas. For example:
4680 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4681 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4682 * is emitted. A NULL <pfx> will be considered empty.
4683 */
4684void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4685{
4686 int ok = 0;
4687 int i;
4688
4689 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4690
4691 for (i = 0; i < n; i++) {
4692 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4693 ok = may_access(addr + i);
4694 if (ok)
4695 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4696 else
4697 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4698 }
4699}
4700
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004701/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4702 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4703 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4704 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4705 * lines are respected within the limit of 70 output chars. Lines that are
4706 * continuation of a previous truncated line begin with "+" instead of " "
4707 * after the offset. The new pointer is returned.
4708 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004709int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004710 int *line, int ptr)
4711{
4712 int end;
4713 unsigned char c;
4714
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004715 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004716 if (end > out->size)
4717 return ptr;
4718
4719 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4720
4721 while (ptr < len && ptr < bsize) {
4722 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004723 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004724 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004725 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004726 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004727 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004728 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004729 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004730 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004731 switch (c) {
4732 case '\t': c = 't'; break;
4733 case '\n': c = 'n'; break;
4734 case '\r': c = 'r'; break;
4735 case '\e': c = 'e'; break;
4736 case '\\': c = '\\'; break;
4737 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004738 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004739 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004740 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004741 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004742 out->area[out->data++] = '\\';
4743 out->area[out->data++] = 'x';
4744 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4745 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004746 }
4747 if (buf[ptr++] == '\n') {
4748 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004749 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004750 *line = ptr;
4751 return ptr;
4752 }
4753 }
4754 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004755 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004756 return ptr;
4757}
4758
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004759/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004760 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4761 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004762 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004763void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4764 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004765{
Willy Tarreau73459792017-04-11 07:58:08 +02004766 unsigned int i;
4767 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004768
4769 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4770 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004771 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004772 for (j = 0; j < 8; j++) {
4773 if (b + j >= 0 && b + j < len)
4774 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4775 else
4776 fprintf(out, " ");
4777 }
4778
4779 if (b + j >= 0 && b + j < len)
4780 fputc('-', out);
4781 else
4782 fputc(' ', out);
4783
4784 for (j = 8; j < 16; j++) {
4785 if (b + j >= 0 && b + j < len)
4786 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4787 else
4788 fprintf(out, " ");
4789 }
4790
4791 fprintf(out, " ");
4792 for (j = 0; j < 16; j++) {
4793 if (b + j >= 0 && b + j < len) {
4794 if (isprint((unsigned char)buf[b + j]))
4795 fputc((unsigned char)buf[b + j], out);
4796 else
4797 fputc('.', out);
4798 }
4799 else
4800 fputc(' ', out);
4801 }
4802 fputc('\n', out);
4803 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004804}
4805
Willy Tarreaubb869862020-04-16 10:52:41 +02004806/* Tries to report the executable path name on platforms supporting this. If
4807 * not found or not possible, returns NULL.
4808 */
4809const char *get_exec_path()
4810{
4811 const char *ret = NULL;
4812
Willy Tarreau1ee71dd2021-08-30 10:15:35 +02004813#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004814 long execfn = getauxval(AT_EXECFN);
4815
4816 if (execfn && execfn != ENOENT)
4817 ret = (const char *)execfn;
devnexen@gmail.com49a32282021-08-17 12:55:49 +01004818#elif defined(__FreeBSD__)
4819 Elf_Auxinfo *auxv;
4820 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4821 if (auxv->a_type == AT_EXECPATH) {
4822 ret = (const char *)auxv->a_un.a_ptr;
4823 break;
4824 }
4825 }
David Carlier1b9d57d2021-08-17 08:44:25 +01004826#elif defined(__NetBSD__)
4827 AuxInfo *auxv;
4828 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4829 if (auxv->a_type == AT_SUN_EXECNAME) {
4830 ret = (const char *)auxv->a_v;
4831 break;
4832 }
4833 }
David Carlier451b06f2022-05-14 17:15:49 +01004834#elif defined(__sun)
4835 ret = getexecname();
Willy Tarreaubb869862020-04-16 10:52:41 +02004836#endif
4837 return ret;
4838}
4839
Baruch Siache1651b22020-07-24 07:52:20 +03004840#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004841/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4842 * also returns the symbol size in <size>, otherwise returns 0 there.
4843 */
4844static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4845{
4846 int ret;
Willy Tarreau1ee71dd2021-08-30 10:15:35 +02004847#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004848 const ElfW(Sym) *sym;
4849
4850 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4851 if (ret)
4852 *size = sym ? sym->st_size : 0;
4853#else
David Carlier7b6de262021-12-31 08:15:29 +00004854#if defined(__sun)
4855 ret = dladdr((void *)addr, dli);
4856#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004857 ret = dladdr(addr, dli);
David Carlier7b6de262021-12-31 08:15:29 +00004858#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004859 *size = 0;
4860#endif
4861 return ret;
4862}
Willy Tarreau64192392021-05-05 09:06:21 +02004863
Willy Tarreau263aacd2022-07-18 13:58:17 +02004864/* Sets build_is_static to true if we detect a static build. Some older glibcs
4865 * tend to crash inside dlsym() in static builds, but tests show that at least
4866 * dladdr() still works (and will fail to resolve anything of course). Thus we
4867 * try to determine if we're on a static build to avoid calling dlsym() in this
4868 * case.
Willy Tarreauf72f24e2022-07-16 13:49:34 +02004869 */
Willy Tarreau263aacd2022-07-18 13:58:17 +02004870void check_if_static_build()
Willy Tarreauf72f24e2022-07-16 13:49:34 +02004871{
Willy Tarreau263aacd2022-07-18 13:58:17 +02004872 Dl_info dli = { };
4873 size_t size = 0;
4874
4875 /* Now let's try to be smarter */
4876 if (!dladdr_and_size(&main, &dli, &size))
4877 build_is_static = 1;
4878 else
4879 build_is_static = 0;
Willy Tarreauf72f24e2022-07-16 13:49:34 +02004880}
4881
Willy Tarreau263aacd2022-07-18 13:58:17 +02004882INITCALL0(STG_PREPARE, check_if_static_build);
Willy Tarreauf72f24e2022-07-16 13:49:34 +02004883
Willy Tarreau64192392021-05-05 09:06:21 +02004884/* Tries to retrieve the address of the first occurrence symbol <name>.
4885 * Note that NULL in return is not always an error as a symbol may have that
4886 * address in special situations.
4887 */
4888void *get_sym_curr_addr(const char *name)
4889{
4890 void *ptr = NULL;
4891
4892#ifdef RTLD_DEFAULT
Willy Tarreau263aacd2022-07-18 13:58:17 +02004893 if (!build_is_static)
Willy Tarreauf72f24e2022-07-16 13:49:34 +02004894 ptr = dlsym(RTLD_DEFAULT, name);
Willy Tarreau64192392021-05-05 09:06:21 +02004895#endif
4896 return ptr;
4897}
4898
4899
4900/* Tries to retrieve the address of the next occurrence of symbol <name>
4901 * Note that NULL in return is not always an error as a symbol may have that
4902 * address in special situations.
4903 */
4904void *get_sym_next_addr(const char *name)
4905{
4906 void *ptr = NULL;
4907
4908#ifdef RTLD_NEXT
Willy Tarreau263aacd2022-07-18 13:58:17 +02004909 if (!build_is_static)
Willy Tarreauf72f24e2022-07-16 13:49:34 +02004910 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004911#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004912 return ptr;
4913}
4914
4915#else /* elf & linux & dl */
4916
4917/* no possible resolving on other platforms at the moment */
4918void *get_sym_curr_addr(const char *name)
4919{
4920 return NULL;
4921}
4922
4923void *get_sym_next_addr(const char *name)
4924{
4925 return NULL;
4926}
4927
4928#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004929
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004930/* Tries to append to buffer <buf> some indications about the symbol at address
4931 * <addr> using the following form:
4932 * lib:+0xoffset (unresolvable address from lib's base)
4933 * main+0xoffset (unresolvable address from main (+/-))
4934 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4935 * name (resolved exact exec address)
4936 * lib:name (resolved exact lib address)
4937 * name+0xoffset/0xsize (resolved address within exec symbol)
4938 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4939 *
4940 * The file name (lib or executable) is limited to what lies between the last
4941 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4942 * 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 +03004943 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004944 *
4945 * The symbol's base address is returned, or NULL when unresolved, in order to
4946 * allow the caller to match it against known ones.
4947 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004948const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004949{
4950 const struct {
4951 const void *func;
4952 const char *name;
4953 } fcts[] = {
4954 { .func = process_stream, .name = "process_stream" },
4955 { .func = task_run_applet, .name = "task_run_applet" },
4956 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004957 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004958 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4959 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004960 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004961 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4962 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004963 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004964#ifdef USE_THREAD
4965 { .func = accept_queue_process, .name = "accept_queue_process" },
4966#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004967#ifdef USE_LUA
4968 { .func = hlua_process_task, .name = "hlua_process_task" },
4969#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004970#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004971 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4972 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4973#endif
4974 };
4975
Baruch Siache1651b22020-07-24 07:52:20 +03004976#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004977 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004978 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004979 const char *fname, *p;
4980#endif
4981 int i;
4982
4983 if (pfx)
4984 chunk_appendf(buf, "%s", pfx);
4985
4986 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4987 if (addr == fcts[i].func) {
4988 chunk_appendf(buf, "%s", fcts[i].name);
4989 return addr;
4990 }
4991 }
4992
Baruch Siache1651b22020-07-24 07:52:20 +03004993#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004994 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004995 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004996 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004997
4998 /* 1. prefix the library name if it's not the same object as the one
4999 * that contains the main function. The name is picked between last '/'
5000 * and first following '.'.
5001 */
5002 if (!dladdr(main, &dli_main))
5003 dli_main.dli_fbase = NULL;
5004
5005 if (dli_main.dli_fbase != dli.dli_fbase) {
5006 fname = dli.dli_fname;
5007 p = strrchr(fname, '/');
5008 if (p++)
5009 fname = p;
5010 p = strchr(fname, '.');
5011 if (!p)
5012 p = fname + strlen(fname);
5013
5014 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
5015 }
5016
5017 /* 2. symbol name */
5018 if (dli.dli_sname) {
5019 /* known, dump it and return symbol's address (exact or relative) */
5020 chunk_appendf(buf, "%s", dli.dli_sname);
5021 if (addr != dli.dli_saddr) {
5022 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01005023 if (size)
5024 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005025 }
5026 return dli.dli_saddr;
5027 }
5028 else if (dli_main.dli_fbase != dli.dli_fbase) {
5029 /* unresolved symbol from a known library, report relative offset */
5030 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
5031 return NULL;
5032 }
Baruch Siache1651b22020-07-24 07:52:20 +03005033#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005034 unknown:
5035 /* unresolved symbol from the main file, report relative offset to main */
5036 if ((void*)addr < (void*)main)
5037 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
5038 else
5039 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
5040 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01005041}
5042
Willy Tarreau37857332021-12-28 09:57:10 +01005043/* On systems where this is supported, let's provide a possibility to enumerate
5044 * the list of object files. The output is appended to a buffer initialized by
5045 * the caller, with one name per line. A trailing zero is always emitted if data
5046 * are written. Only real objects are dumped (executable and .so libs). The
5047 * function returns non-zero if it dumps anything. These functions do not make
5048 * use of the trash so that it is possible for the caller to call them with the
5049 * trash on input. The output format may be platform-specific but at least one
5050 * version must emit raw object file names when argument is zero.
5051 */
5052#if defined(HA_HAVE_DUMP_LIBS)
5053# if defined(HA_HAVE_DL_ITERATE_PHDR)
5054/* the private <data> we pass below is a dump context initialized like this */
5055struct dl_dump_ctx {
5056 struct buffer *buf;
5057 int with_addr;
5058};
5059
5060static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5061{
5062 struct dl_dump_ctx *ctx = data;
5063 const char *fname;
5064 size_t p1, p2, beg, end;
5065 int idx;
5066
5067 if (!info || !info->dlpi_name)
5068 goto leave;
5069
5070 if (!*info->dlpi_name)
5071 fname = get_exec_path();
5072 else if (strchr(info->dlpi_name, '/'))
5073 fname = info->dlpi_name;
5074 else
5075 /* else it's a VDSO or similar and we're not interested */
5076 goto leave;
5077
5078 if (!ctx->with_addr)
5079 goto dump_name;
5080
5081 /* virtual addresses are relative to the load address and are per
5082 * pseudo-header, so we have to scan them all to find the furthest
5083 * one from the beginning. In this case we only dump entries if
5084 * they have at least one section.
5085 */
5086 beg = ~0; end = 0;
5087 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5088 if (!info->dlpi_phdr[idx].p_memsz)
5089 continue;
5090 p1 = info->dlpi_phdr[idx].p_vaddr;
5091 if (p1 < beg)
5092 beg = p1;
5093 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5094 if (p2 > end)
5095 end = p2;
5096 }
5097
5098 if (!idx)
5099 goto leave;
5100
5101 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5102 (ullong)info->dlpi_addr + beg,
5103 (ullong)info->dlpi_addr + end,
5104 (ullong)(end - beg + 1));
5105 dump_name:
5106 chunk_appendf(ctx->buf, "%s\n", fname);
5107 leave:
5108 return 0;
5109}
5110
5111/* dumps lib names and optionally address ranges */
5112int dump_libs(struct buffer *output, int with_addr)
5113{
5114 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5115 size_t old_data = output->data;
5116
5117 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5118 return output->data != old_data;
5119}
5120# else // no DL_ITERATE_PHDR
5121# error "No dump_libs() function for this platform"
5122# endif
5123#else // no HA_HAVE_DUMP_LIBS
5124
5125/* unsupported platform: do not dump anything */
5126int dump_libs(struct buffer *output, int with_addr)
5127{
5128 return 0;
5129}
5130
5131#endif // HA_HAVE_DUMP_LIBS
5132
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005133/*
5134 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005135 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005136 *
5137 * First, initializes the value with <sz> as address to 0 and initializes the
5138 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5139 * address updating <sz> pointed value to the size of this array.
5140 *
5141 * Returns 1 if succeeded, 0 if not.
5142 */
5143int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5144{
5145 unsigned int *n;
5146 const char *s, *end;
5147
5148 s = str;
5149 *sz = 0;
5150 end = str + strlen(str);
5151 *nums = n = NULL;
5152
5153 while (1) {
5154 unsigned int r;
5155
5156 if (s >= end)
5157 break;
5158
5159 r = read_uint(&s, end);
5160 /* Expected characters after having read an uint: '\0' or '.',
5161 * if '.', must not be terminal.
5162 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005163 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5164 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005165 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005166 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005167
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005168 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005169 if (!n)
5170 return 0;
5171
5172 n[(*sz)++] = r;
5173 }
5174 *nums = n;
5175
5176 return 1;
5177}
5178
Willy Tarreau4d589e72019-08-23 19:02:26 +02005179
5180/* returns the number of bytes needed to encode <v> as a varint. An inline
5181 * version exists for use with constants (__varint_bytes()).
5182 */
5183int varint_bytes(uint64_t v)
5184{
5185 int len = 1;
5186
5187 if (v >= 240) {
5188 v = (v - 240) >> 4;
5189 while (1) {
5190 len++;
5191 if (v < 128)
5192 break;
5193 v = (v - 128) >> 7;
5194 }
5195 }
5196 return len;
5197}
5198
Willy Tarreau52bf8392020-03-08 00:42:37 +01005199
5200/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005201static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005202
5203/* This is a thread-safe implementation of xoroshiro128** described below:
5204 * http://prng.di.unimi.it/
5205 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5206 * supports fast jumps and passes all common quality tests. It is thread-safe,
5207 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5208 * local lock on other ones.
5209 */
5210uint64_t ha_random64()
5211{
Willy Tarreau1544c142020-03-12 00:31:18 +01005212 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5213 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005214
5215#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5216 static HA_SPINLOCK_T rand_lock;
5217
5218 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5219#endif
5220
5221 old[0] = ha_random_state[0];
5222 old[1] = ha_random_state[1];
5223
5224#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5225 do {
5226#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005227 new[1] = old[0] ^ old[1];
5228 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5229 new[1] = rotl64(new[1], 37); // c
5230
5231#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5232 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5233#else
5234 ha_random_state[0] = new[0];
5235 ha_random_state[1] = new[1];
5236#if defined(USE_THREAD)
5237 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5238#endif
5239#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005240 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005241}
5242
5243/* seeds the random state using up to <len> bytes from <seed>, starting with
5244 * the first non-zero byte.
5245 */
5246void ha_random_seed(const unsigned char *seed, size_t len)
5247{
5248 size_t pos;
5249
5250 /* the seed must not be all zeroes, so we pre-fill it with alternating
5251 * bits and overwrite part of them with the block starting at the first
5252 * non-zero byte from the seed.
5253 */
5254 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5255
5256 for (pos = 0; pos < len; pos++)
5257 if (seed[pos] != 0)
5258 break;
5259
5260 if (pos == len)
5261 return;
5262
5263 seed += pos;
5264 len -= pos;
5265
5266 if (len > sizeof(ha_random_state))
5267 len = sizeof(ha_random_state);
5268
5269 memcpy(ha_random_state, seed, len);
5270}
5271
5272/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5273 * and is equivalent to calling ha_random64() as many times. It is used to
5274 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5275 * different generators (i.e. different processes after a fork). The <dist>
5276 * argument is the distance to jump to and is used in a loop so it rather not
5277 * be too large if the processing time is a concern.
5278 *
5279 * BEWARE: this function is NOT thread-safe and must not be called during
5280 * concurrent accesses to ha_random64().
5281 */
5282void ha_random_jump96(uint32_t dist)
5283{
5284 while (dist--) {
5285 uint64_t s0 = 0;
5286 uint64_t s1 = 0;
5287 int b;
5288
5289 for (b = 0; b < 64; b++) {
5290 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5291 s0 ^= ha_random_state[0];
5292 s1 ^= ha_random_state[1];
5293 }
5294 ha_random64();
5295 }
5296
5297 for (b = 0; b < 64; b++) {
5298 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5299 s0 ^= ha_random_state[0];
5300 s1 ^= ha_random_state[1];
5301 }
5302 ha_random64();
5303 }
5304 ha_random_state[0] = s0;
5305 ha_random_state[1] = s1;
5306 }
5307}
5308
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005309/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5310 * bytes large.
5311 */
5312void ha_generate_uuid(struct buffer *output)
5313{
5314 uint32_t rnd[4];
5315 uint64_t last;
5316
5317 last = ha_random64();
5318 rnd[0] = last;
5319 rnd[1] = last >> 32;
5320
5321 last = ha_random64();
5322 rnd[2] = last;
5323 rnd[3] = last >> 32;
5324
5325 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5326 rnd[0],
5327 rnd[1] & 0xFFFF,
5328 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5329 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5330 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5331}
5332
5333
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005334/* only used by parse_line() below. It supports writing in place provided that
5335 * <in> is updated to the next location before calling it. In that case, the
5336 * char at <in> may be overwritten.
5337 */
5338#define EMIT_CHAR(x) \
5339 do { \
5340 char __c = (char)(x); \
5341 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5342 err |= PARSE_ERR_OVERLAP; \
5343 if (outpos >= outmax) \
5344 err |= PARSE_ERR_TOOLARGE; \
5345 if (!err) \
5346 out[outpos] = __c; \
5347 outpos++; \
5348 } while (0)
5349
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005350/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005351 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5352 * extraneous ones are not emitted but <outlen> is updated so that the caller
5353 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5354 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005355 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5356 * it is guaranteed that at least one arg will point to the zero. It is safe
5357 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005358 *
5359 * <out> may overlap with <in> provided that it never goes further, in which
5360 * case the parser will accept to perform in-place parsing and unquoting/
5361 * unescaping but only if environment variables do not lead to expansion that
5362 * causes overlapping, otherwise the input string being destroyed, the error
5363 * will not be recoverable. Note that even during out-of-place <in> will
5364 * experience temporary modifications in-place for variable resolution and must
5365 * be writable, and will also receive zeroes to delimit words when using
5366 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5367 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5368 * starting point of the first invalid character sequence or unmatched
5369 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5370 * error reporting might be difficult since zeroes will have been inserted into
5371 * the string. One solution for the caller may consist in replacing all args
5372 * delimiters with spaces in this case.
5373 */
5374uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
5375{
5376 char *quote = NULL;
5377 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005378 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005379 unsigned char hex1, hex2;
5380 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005381 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005382 size_t outpos = 0;
5383 int squote = 0;
5384 int dquote = 0;
5385 int arg = 0;
5386 uint32_t err = 0;
5387
5388 *nbargs = 0;
5389 *outlen = 0;
5390
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005391 /* argsmax may be -1 here, protecting args[] from any write */
5392 if (arg < argsmax)
5393 args[arg] = out;
5394
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005395 while (1) {
5396 if (*in >= '-' && *in != '\\') {
5397 /* speedup: directly send all regular chars starting
5398 * with '-', '.', '/', alnum etc...
5399 */
5400 EMIT_CHAR(*in++);
5401 continue;
5402 }
5403 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5404 /* end of line */
5405 break;
5406 }
5407 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5408 /* comment */
5409 break;
5410 }
5411 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5412 if (dquote) {
5413 dquote = 0;
5414 quote = NULL;
5415 }
5416 else {
5417 dquote = 1;
5418 quote = in;
5419 }
5420 in++;
5421 continue;
5422 }
5423 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5424 if (squote) {
5425 squote = 0;
5426 quote = NULL;
5427 }
5428 else {
5429 squote = 1;
5430 quote = in;
5431 }
5432 in++;
5433 continue;
5434 }
5435 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5436 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5437 * C equivalent value but only when they have a special meaning and within
5438 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5439 */
5440 char tosend = *in;
5441
5442 switch (in[1]) {
5443 case ' ':
5444 case '\\':
5445 tosend = in[1];
5446 in++;
5447 break;
5448
5449 case 't':
5450 tosend = '\t';
5451 in++;
5452 break;
5453
5454 case 'n':
5455 tosend = '\n';
5456 in++;
5457 break;
5458
5459 case 'r':
5460 tosend = '\r';
5461 in++;
5462 break;
5463
5464 case '#':
5465 /* escaping of "#" only if comments are supported */
5466 if (opts & PARSE_OPT_SHARP)
5467 in++;
5468 tosend = *in;
5469 break;
5470
5471 case '\'':
5472 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5473 if (opts & PARSE_OPT_SQUOTE && !squote)
5474 in++;
5475 tosend = *in;
5476 break;
5477
5478 case '"':
5479 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5480 if (opts & PARSE_OPT_DQUOTE && !squote)
5481 in++;
5482 tosend = *in;
5483 break;
5484
5485 case '$':
5486 /* escaping of '$' only inside double quotes and only if env supported */
5487 if (opts & PARSE_OPT_ENV && dquote)
5488 in++;
5489 tosend = *in;
5490 break;
5491
5492 case 'x':
5493 if (!ishex(in[2]) || !ishex(in[3])) {
5494 /* invalid or incomplete hex sequence */
5495 err |= PARSE_ERR_HEX;
5496 if (errptr)
5497 *errptr = in;
5498 goto leave;
5499 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005500 hex1 = toupper((unsigned char)in[2]) - '0';
5501 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005502 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5503 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5504 tosend = (hex1 << 4) + hex2;
5505 in += 3;
5506 break;
5507
5508 default:
5509 /* other combinations are not escape sequences */
5510 break;
5511 }
5512
5513 in++;
5514 EMIT_CHAR(tosend);
5515 }
5516 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5517 /* a non-escaped space is an argument separator */
5518 while (isspace((unsigned char)*in))
5519 in++;
5520 EMIT_CHAR(0);
5521 arg++;
5522 if (arg < argsmax)
5523 args[arg] = out + outpos;
5524 else
5525 err |= PARSE_ERR_TOOMANY;
5526 }
5527 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5528 /* environment variables are evaluated anywhere, or only
5529 * inside double quotes if they are supported.
5530 */
5531 char *var_name;
5532 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005533 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005534
5535 in++;
5536
5537 if (*in == '{')
5538 brace = in++;
5539
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005540 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005541 /* unacceptable character in variable name */
5542 err |= PARSE_ERR_VARNAME;
5543 if (errptr)
5544 *errptr = in;
5545 goto leave;
5546 }
5547
5548 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005549 if (*in == '.')
5550 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005551 while (isalnum((unsigned char)*in) || *in == '_')
5552 in++;
5553
5554 save_char = *in;
5555 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005556 if (unlikely(*var_name == '.')) {
5557 /* internal pseudo-variables */
5558 if (strcmp(var_name, ".LINE") == 0)
5559 value = ultoa(global.cfg_curr_line);
5560 else if (strcmp(var_name, ".FILE") == 0)
5561 value = global.cfg_curr_file;
5562 else if (strcmp(var_name, ".SECTION") == 0)
5563 value = global.cfg_curr_section;
5564 else {
5565 /* unsupported internal variable name */
5566 err |= PARSE_ERR_VARNAME;
5567 if (errptr)
5568 *errptr = var_name;
5569 goto leave;
5570 }
5571 } else {
5572 value = getenv(var_name);
5573 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005574 *in = save_char;
5575
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005576 /* support for '[*]' sequence to force word expansion,
5577 * only available inside braces */
5578 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5579 word_expand = in++;
5580
5581 if (*in++ != '*' || *in++ != ']') {
5582 err |= PARSE_ERR_WRONG_EXPAND;
5583 if (errptr)
5584 *errptr = word_expand;
5585 goto leave;
5586 }
5587 }
5588
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005589 if (brace) {
5590 if (*in != '}') {
5591 /* unmatched brace */
5592 err |= PARSE_ERR_BRACE;
5593 if (errptr)
5594 *errptr = brace;
5595 goto leave;
5596 }
5597 in++;
5598 brace = NULL;
5599 }
5600
5601 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005602 while (*value) {
5603 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005604 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005605 EMIT_CHAR(0);
5606 ++arg;
5607 if (arg < argsmax)
5608 args[arg] = out + outpos;
5609 else
5610 err |= PARSE_ERR_TOOMANY;
5611
5612 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005613 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005614 ;
5615 } else {
5616 EMIT_CHAR(*value++);
5617 }
5618 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005619 }
Frédéric Lécaille1893b3f2023-11-30 09:26:05 +01005620 else {
5621 /* An unmatched environment variable was parsed.
5622 * Let's skip the trailing double-quote character
5623 * and spaces.
5624 */
5625 if (likely(*var_name != '.') && *in == '"') {
5626 in++;
5627 while (isspace((unsigned char)*in))
5628 in++;
5629 if (dquote) {
5630 dquote = 0;
5631 quote = NULL;
5632 }
5633 }
5634 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005635 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005636 }
5637 else {
5638 /* any other regular char */
5639 EMIT_CHAR(*in++);
5640 }
5641 }
5642
5643 /* end of output string */
5644 EMIT_CHAR(0);
5645 arg++;
5646
5647 if (quote) {
5648 /* unmatched quote */
5649 err |= PARSE_ERR_QUOTE;
5650 if (errptr)
5651 *errptr = quote;
5652 goto leave;
5653 }
5654 leave:
5655 *nbargs = arg;
5656 *outlen = outpos;
5657
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005658 /* empty all trailing args by making them point to the trailing zero,
5659 * at least the last one in any case.
5660 */
5661 if (arg > argsmax)
5662 arg = argsmax;
5663
5664 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005665 args[arg++] = out + outpos - 1;
5666
5667 return err;
5668}
5669#undef EMIT_CHAR
5670
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005671/* This is used to sanitize an input line that's about to be used for error reporting.
5672 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5673 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5674 * If non-printable chars are present in the output. It returns the new offset <pos>
5675 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5676 * be at least 6 to support two "..." otherwise the result is undefined. The line
5677 * itself must have at least 7 chars allocated for the same reason.
5678 */
5679size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5680{
5681 size_t shift = 0;
5682 char *out = line;
5683 char *in = line;
5684 char *end = line + width;
5685
5686 if (pos >= width) {
5687 /* if we have to shift, we'll be out of context, so let's
5688 * try to put <pos> at the center of width.
5689 */
5690 shift = pos - width / 2;
5691 in += shift + 3;
5692 end = out + width - 3;
5693 out[0] = out[1] = out[2] = '.';
5694 out += 3;
5695 }
5696
5697 while (out < end && *in) {
5698 if (isspace((unsigned char)*in))
5699 *out++ = ' ';
5700 else if (isprint((unsigned char)*in))
5701 *out++ = *in;
5702 else
5703 *out++ = '?';
5704 in++;
5705 }
5706
5707 if (end < line + width) {
5708 out[0] = out[1] = out[2] = '.';
5709 out += 3;
5710 }
5711
5712 *out++ = 0;
5713 return pos - shift;
5714}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005715
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005716/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005717 * transitions between characters. <fp> is a 1024-entries array indexed as
5718 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005719 * 1..26=letter, 27=digit, 28=other/begin/end.
5720 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005721 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005722void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005723{
5724 const char *p;
5725 int from, to;
5726 int c;
5727
Willy Tarreauba2c4452021-03-12 09:01:52 +01005728 from = 28; // begin
5729 for (p = word; *p; p++) {
5730 c = tolower(*p);
5731 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005732 case 'a'...'z': to = c - 'a' + 1; break;
5733 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5734 case '0'...'9': to = 27; break;
5735 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005736 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005737 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005738 fp[32 * from + to]++;
5739 from = to;
5740 }
5741 to = 28; // end
5742 fp[32 * from + to]++;
5743}
5744
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005745/* Initialize array <fp> with the fingerprint of word <word> by counting the
5746 * transitions between characters. <fp> is a 1024-entries array indexed as
5747 * 32*from+to. Positions for 'from' and 'to' are:
5748 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5749 */
5750void make_word_fingerprint(uint8_t *fp, const char *word)
5751{
5752 memset(fp, 0, 1024);
5753 update_word_fingerprint(fp, word);
5754}
5755
Willy Tarreauba2c4452021-03-12 09:01:52 +01005756/* Return the distance between two word fingerprints created by function
5757 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005758 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005759 */
5760int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5761{
5762 int i, k, dist = 0;
5763
5764 for (i = 0; i < 1024; i++) {
5765 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005766 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005767 }
5768 return dist;
5769}
5770
Willy Tarreau06e69b52021-03-02 14:01:35 +01005771static int init_tools_per_thread()
5772{
5773 /* Let's make each thread start from a different position */
Willy Tarreau090a1462024-03-01 16:17:47 +01005774 statistical_prng_state += ha_random32();
Willy Tarreau06e69b52021-03-02 14:01:35 +01005775 if (!statistical_prng_state)
5776 statistical_prng_state++;
5777 return 1;
5778}
5779REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005780
Willy Tarreaubaaee002006-06-26 02:48:02 +02005781/*
5782 * Local variables:
5783 * c-indent-level: 8
5784 * c-basic-offset: 8
5785 * End:
5786 */