blob: 2311f725a65acb55665e4d92f235733b39614470 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
devnexen@gmail.comc4e52322021-08-17 12:55:49 +010019#if defined(__FreeBSD__)
20#include <elf.h>
21#include <dlfcn.h>
22extern void *__elf_aux_vector;
23#endif
24
David Carlierbd2cced2021-08-17 08:44:25 +010025#if defined(__NetBSD__)
26#include <sys/exec_elf.h>
27#include <dlfcn.h>
28#endif
29
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010030#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020033#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020034#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035#include <stdlib.h>
36#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010037#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020038#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010039#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020040#include <sys/stat.h>
41#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010042#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020043#include <netinet/in.h>
44#include <arpa/inet.h>
45
David Carlier43a56852022-03-04 15:50:48 +000046#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreau30053062020-08-20 16:39:14 +020047#include <sys/auxv.h>
48#endif
49
Willy Tarreau48fbcae2020-06-03 18:09:46 +020050#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <import/eb32tree.h>
Willy Tarreau0dc9e6d2022-08-01 11:55:57 +020052#include <import/ebmbtree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020053
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020054#include <haproxy/api.h>
Christopher Faulet6b0a0fb2022-04-04 11:29:28 +020055#include <haproxy/applet.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020056#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020057#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020058#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020059#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020060#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020061#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010062#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020063#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010064#include <haproxy/resolvers.h>
Willy Tarreau5edca2f2022-05-27 09:25:10 +020065#include <haproxy/sc_strm.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010066#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020067#include <haproxy/ssl_sock.h>
William Lallemand3aeb3f92021-08-21 23:59:56 +020068#include <haproxy/ssl_utils.h>
Willy Tarreaucb086c62022-05-27 09:47:12 +020069#include <haproxy/stconn.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020070#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020071#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010072
Thierry Fournier93127942016-01-20 18:49:45 +010073/* This macro returns false if the test __x is false. Many
74 * of the following parsing function must be abort the processing
75 * if it returns 0, so this macro is useful for writing light code.
76 */
77#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
78
Willy Tarreau56adcf22012-12-23 18:00:29 +010079/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020080 * 2^64-1 = 18446744073709551615 or
81 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020082 *
83 * The HTML version needs room for adding the 25 characters
84 * '<span class="rls"></span>' around digits at positions 3N+1 in order
85 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020086 */
Christopher Faulet99bca652017-11-14 16:47:26 +010087THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
88THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020089
Willy Tarreau588297f2014-06-16 15:16:40 +020090/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
91 * to quote strings larger than a max configuration line.
92 */
Christopher Faulet99bca652017-11-14 16:47:26 +010093THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
94THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020095
Willy Tarreau06e69b52021-03-02 14:01:35 +010096/* thread-local PRNG state. It's modified to start from a different sequence
97 * on all threads upon startup. It must not be used or anything beyond getting
98 * statistical values as it's 100% predictable.
99 */
100THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
101
Willy Tarreau5b3cd952022-07-18 13:58:17 +0200102/* set to true if this is a static build */
103int build_is_static = 0;
104
Willy Tarreaubaaee002006-06-26 02:48:02 +0200105/*
William Lallemande7340ec2012-01-24 11:15:39 +0100106 * unsigned long long ASCII representation
107 *
108 * return the last char '\0' or NULL if no enough
109 * space in dst
110 */
111char *ulltoa(unsigned long long n, char *dst, size_t size)
112{
113 int i = 0;
114 char *res;
115
116 switch(n) {
117 case 1ULL ... 9ULL:
118 i = 0;
119 break;
120
121 case 10ULL ... 99ULL:
122 i = 1;
123 break;
124
125 case 100ULL ... 999ULL:
126 i = 2;
127 break;
128
129 case 1000ULL ... 9999ULL:
130 i = 3;
131 break;
132
133 case 10000ULL ... 99999ULL:
134 i = 4;
135 break;
136
137 case 100000ULL ... 999999ULL:
138 i = 5;
139 break;
140
141 case 1000000ULL ... 9999999ULL:
142 i = 6;
143 break;
144
145 case 10000000ULL ... 99999999ULL:
146 i = 7;
147 break;
148
149 case 100000000ULL ... 999999999ULL:
150 i = 8;
151 break;
152
153 case 1000000000ULL ... 9999999999ULL:
154 i = 9;
155 break;
156
157 case 10000000000ULL ... 99999999999ULL:
158 i = 10;
159 break;
160
161 case 100000000000ULL ... 999999999999ULL:
162 i = 11;
163 break;
164
165 case 1000000000000ULL ... 9999999999999ULL:
166 i = 12;
167 break;
168
169 case 10000000000000ULL ... 99999999999999ULL:
170 i = 13;
171 break;
172
173 case 100000000000000ULL ... 999999999999999ULL:
174 i = 14;
175 break;
176
177 case 1000000000000000ULL ... 9999999999999999ULL:
178 i = 15;
179 break;
180
181 case 10000000000000000ULL ... 99999999999999999ULL:
182 i = 16;
183 break;
184
185 case 100000000000000000ULL ... 999999999999999999ULL:
186 i = 17;
187 break;
188
189 case 1000000000000000000ULL ... 9999999999999999999ULL:
190 i = 18;
191 break;
192
193 case 10000000000000000000ULL ... ULLONG_MAX:
194 i = 19;
195 break;
196 }
197 if (i + 2 > size) // (i + 1) + '\0'
198 return NULL; // too long
199 res = dst + i + 1;
200 *res = '\0';
201 for (; i >= 0; i--) {
202 dst[i] = n % 10ULL + '0';
203 n /= 10ULL;
204 }
205 return res;
206}
207
208/*
209 * unsigned long ASCII representation
210 *
211 * return the last char '\0' or NULL if no enough
212 * space in dst
213 */
214char *ultoa_o(unsigned long n, char *dst, size_t size)
215{
216 int i = 0;
217 char *res;
218
219 switch (n) {
220 case 0U ... 9UL:
221 i = 0;
222 break;
223
224 case 10U ... 99UL:
225 i = 1;
226 break;
227
228 case 100U ... 999UL:
229 i = 2;
230 break;
231
232 case 1000U ... 9999UL:
233 i = 3;
234 break;
235
236 case 10000U ... 99999UL:
237 i = 4;
238 break;
239
240 case 100000U ... 999999UL:
241 i = 5;
242 break;
243
244 case 1000000U ... 9999999UL:
245 i = 6;
246 break;
247
248 case 10000000U ... 99999999UL:
249 i = 7;
250 break;
251
252 case 100000000U ... 999999999UL:
253 i = 8;
254 break;
255#if __WORDSIZE == 32
256
257 case 1000000000ULL ... ULONG_MAX:
258 i = 9;
259 break;
260
261#elif __WORDSIZE == 64
262
263 case 1000000000ULL ... 9999999999UL:
264 i = 9;
265 break;
266
267 case 10000000000ULL ... 99999999999UL:
268 i = 10;
269 break;
270
271 case 100000000000ULL ... 999999999999UL:
272 i = 11;
273 break;
274
275 case 1000000000000ULL ... 9999999999999UL:
276 i = 12;
277 break;
278
279 case 10000000000000ULL ... 99999999999999UL:
280 i = 13;
281 break;
282
283 case 100000000000000ULL ... 999999999999999UL:
284 i = 14;
285 break;
286
287 case 1000000000000000ULL ... 9999999999999999UL:
288 i = 15;
289 break;
290
291 case 10000000000000000ULL ... 99999999999999999UL:
292 i = 16;
293 break;
294
295 case 100000000000000000ULL ... 999999999999999999UL:
296 i = 17;
297 break;
298
299 case 1000000000000000000ULL ... 9999999999999999999UL:
300 i = 18;
301 break;
302
303 case 10000000000000000000ULL ... ULONG_MAX:
304 i = 19;
305 break;
306
307#endif
308 }
309 if (i + 2 > size) // (i + 1) + '\0'
310 return NULL; // too long
311 res = dst + i + 1;
312 *res = '\0';
313 for (; i >= 0; i--) {
314 dst[i] = n % 10U + '0';
315 n /= 10U;
316 }
317 return res;
318}
319
320/*
321 * signed long ASCII representation
322 *
323 * return the last char '\0' or NULL if no enough
324 * space in dst
325 */
326char *ltoa_o(long int n, char *dst, size_t size)
327{
328 char *pos = dst;
329
330 if (n < 0) {
331 if (size < 3)
332 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
333 *pos = '-';
334 pos++;
335 dst = ultoa_o(-n, pos, size - 1);
336 } else {
337 dst = ultoa_o(n, dst, size);
338 }
339 return dst;
340}
341
342/*
343 * signed long long ASCII representation
344 *
345 * return the last char '\0' or NULL if no enough
346 * space in dst
347 */
348char *lltoa(long long n, char *dst, size_t size)
349{
350 char *pos = dst;
351
352 if (n < 0) {
353 if (size < 3)
354 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
355 *pos = '-';
356 pos++;
357 dst = ulltoa(-n, pos, size - 1);
358 } else {
359 dst = ulltoa(n, dst, size);
360 }
361 return dst;
362}
363
364/*
365 * write a ascii representation of a unsigned into dst,
366 * return a pointer to the last character
367 * Pad the ascii representation with '0', using size.
368 */
369char *utoa_pad(unsigned int n, char *dst, size_t size)
370{
371 int i = 0;
372 char *ret;
373
374 switch(n) {
375 case 0U ... 9U:
376 i = 0;
377 break;
378
379 case 10U ... 99U:
380 i = 1;
381 break;
382
383 case 100U ... 999U:
384 i = 2;
385 break;
386
387 case 1000U ... 9999U:
388 i = 3;
389 break;
390
391 case 10000U ... 99999U:
392 i = 4;
393 break;
394
395 case 100000U ... 999999U:
396 i = 5;
397 break;
398
399 case 1000000U ... 9999999U:
400 i = 6;
401 break;
402
403 case 10000000U ... 99999999U:
404 i = 7;
405 break;
406
407 case 100000000U ... 999999999U:
408 i = 8;
409 break;
410
411 case 1000000000U ... 4294967295U:
412 i = 9;
413 break;
414 }
415 if (i + 2 > size) // (i + 1) + '\0'
416 return NULL; // too long
417 if (i < size)
418 i = size - 2; // padding - '\0'
419
420 ret = dst + i + 1;
421 *ret = '\0';
422 for (; i >= 0; i--) {
423 dst[i] = n % 10U + '0';
424 n /= 10U;
425 }
426 return ret;
427}
428
429/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200430 * copies at most <size-1> chars from <src> to <dst>. Last char is always
431 * set to 0, unless <size> is 0. The number of chars copied is returned
432 * (excluding the terminating zero).
433 * This code has been optimized for size and speed : on x86, it's 45 bytes
434 * long, uses only registers, and consumes only 4 cycles per char.
435 */
436int strlcpy2(char *dst, const char *src, int size)
437{
438 char *orig = dst;
439 if (size) {
440 while (--size && (*dst = *src)) {
441 src++; dst++;
442 }
443 *dst = 0;
444 }
445 return dst - orig;
446}
447
448/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200449 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200450 * the ascii representation for number 'n' in decimal.
451 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100452char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200453{
454 char *pos;
455
Willy Tarreau72d759c2007-10-25 12:14:10 +0200456 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200457 *pos-- = '\0';
458
459 do {
460 *pos-- = '0' + n % 10;
461 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200462 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200463 return pos + 1;
464}
465
Willy Tarreau91092e52007-10-25 16:58:42 +0200466/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200467 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200468 * the ascii representation for number 'n' in decimal.
469 */
470char *lltoa_r(long long int in, char *buffer, int size)
471{
472 char *pos;
473 int neg = 0;
474 unsigned long long int n;
475
476 pos = buffer + size - 1;
477 *pos-- = '\0';
478
479 if (in < 0) {
480 neg = 1;
481 n = -in;
482 }
483 else
484 n = in;
485
486 do {
487 *pos-- = '0' + n % 10;
488 n /= 10;
489 } while (n && pos >= buffer);
490 if (neg && pos > buffer)
491 *pos-- = '-';
492 return pos + 1;
493}
494
495/*
496 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200497 * the ascii representation for signed number 'n' in decimal.
498 */
499char *sltoa_r(long n, char *buffer, int size)
500{
501 char *pos;
502
503 if (n >= 0)
504 return ultoa_r(n, buffer, size);
505
506 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
507 *pos = '-';
508 return pos;
509}
510
511/*
512 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200513 * the ascii representation for number 'n' in decimal, formatted for
514 * HTML output with tags to create visual grouping by 3 digits. The
515 * output needs to support at least 171 characters.
516 */
517const char *ulltoh_r(unsigned long long n, char *buffer, int size)
518{
519 char *start;
520 int digit = 0;
521
522 start = buffer + size;
523 *--start = '\0';
524
525 do {
526 if (digit == 3 && start >= buffer + 7)
527 memcpy(start -= 7, "</span>", 7);
528
529 if (start >= buffer + 1) {
530 *--start = '0' + n % 10;
531 n /= 10;
532 }
533
534 if (digit == 3 && start >= buffer + 18)
535 memcpy(start -= 18, "<span class=\"rls\">", 18);
536
537 if (digit++ == 3)
538 digit = 1;
539 } while (n && start > buffer);
540 return start;
541}
542
543/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200544 * This function simply returns a locally allocated string containing the ascii
545 * representation for number 'n' in decimal, unless n is 0 in which case it
546 * returns the alternate string (or an empty string if the alternate string is
547 * NULL). It use is intended for limits reported in reports, where it's
548 * desirable not to display anything if there is no limit. Warning! it shares
549 * the same vector as ultoa_r().
550 */
551const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
552{
553 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
554}
555
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200556/* Trims the first "%f" float in a string to its minimum number of digits after
557 * the decimal point by trimming trailing zeroes, even dropping the decimal
558 * point if not needed. The string is in <buffer> of length <len>, and the
559 * number is expected to start at or after position <num_start> (the first
560 * point appearing there is considered). A NUL character is always placed at
561 * the end if some trimming occurs. The new buffer length is returned.
562 */
563size_t flt_trim(char *buffer, size_t num_start, size_t len)
564{
565 char *end = buffer + len;
566 char *p = buffer + num_start;
567 char *trim;
568
569 do {
570 if (p >= end)
571 return len;
572 trim = p++;
573 } while (*trim != '.');
574
575 /* For now <trim> is on the decimal point. Let's look for any other
576 * meaningful digit after it.
577 */
578 while (p < end) {
579 if (*p++ != '0')
580 trim = p;
581 }
582
583 if (trim < end)
584 *trim = 0;
585
586 return trim - buffer;
587}
588
Willy Tarreauae03d262021-05-08 07:35:00 +0200589/*
590 * This function simply returns a locally allocated string containing
591 * the ascii representation for number 'n' in decimal with useless trailing
592 * zeroes trimmed.
593 */
594char *ftoa_r(double n, char *buffer, int size)
595{
596 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
597 return buffer;
598}
599
Willy Tarreau588297f2014-06-16 15:16:40 +0200600/* returns a locally allocated string containing the quoted encoding of the
601 * input string. The output may be truncated to QSTR_SIZE chars, but it is
602 * guaranteed that the string will always be properly terminated. Quotes are
603 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
604 * always be at least 4 chars.
605 */
606const char *qstr(const char *str)
607{
608 char *ret = quoted_str[quoted_idx];
609 char *p, *end;
610
611 if (++quoted_idx >= NB_QSTR)
612 quoted_idx = 0;
613
614 p = ret;
615 end = ret + QSTR_SIZE;
616
617 *p++ = '"';
618
619 /* always keep 3 chars to support passing "" and the ending " */
620 while (*str && p < end - 3) {
621 if (*str == '"') {
622 *p++ = '"';
623 *p++ = '"';
624 }
625 else
626 *p++ = *str;
627 str++;
628 }
629 *p++ = '"';
630 return ret;
631}
632
Robert Tsai81ae1952007-12-05 10:47:29 +0100633/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200634 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
635 *
636 * It looks like this one would be a good candidate for inlining, but this is
637 * not interesting because it around 35 bytes long and often called multiple
638 * times within the same function.
639 */
640int ishex(char s)
641{
642 s -= '0';
643 if ((unsigned char)s <= 9)
644 return 1;
645 s -= 'A' - '0';
646 if ((unsigned char)s <= 5)
647 return 1;
648 s -= 'a' - 'A';
649 if ((unsigned char)s <= 5)
650 return 1;
651 return 0;
652}
653
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100654/* rounds <i> down to the closest value having max 2 digits */
655unsigned int round_2dig(unsigned int i)
656{
657 unsigned int mul = 1;
658
659 while (i >= 100) {
660 i /= 10;
661 mul *= 10;
662 }
663 return i * mul;
664}
665
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100666/*
667 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
668 * invalid character is found, a pointer to it is returned. If everything is
669 * fine, NULL is returned.
670 */
671const char *invalid_char(const char *name)
672{
673 if (!*name)
674 return name;
675
676 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100677 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100678 *name != '_' && *name != '-')
679 return name;
680 name++;
681 }
682 return NULL;
683}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200684
685/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200686 * Checks <name> for invalid characters. Valid chars are [_.-] and those
687 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200688 * If an invalid character is found, a pointer to it is returned.
689 * If everything is fine, NULL is returned.
690 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200691static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200692
693 if (!*name)
694 return name;
695
696 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100697 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200698 *name != '_' && *name != '-')
699 return name;
700
701 name++;
702 }
703
704 return NULL;
705}
706
707/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200708 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
709 * If an invalid character is found, a pointer to it is returned.
710 * If everything is fine, NULL is returned.
711 */
712const char *invalid_domainchar(const char *name) {
713 return __invalid_char(name, isalnum);
714}
715
716/*
717 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
718 * If an invalid character is found, a pointer to it is returned.
719 * If everything is fine, NULL is returned.
720 */
721const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200722 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200723}
724
725/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100726 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100727 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
728 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
729 * the function tries to guess the address family from the syntax. If the
730 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100731 * string is assumed to contain only an address, no port. The address can be a
732 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
733 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
734 * The return address will only have the address family and the address set,
735 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100736 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
737 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100738 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200739 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100740struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200741{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100742 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100743 /* max IPv6 length, including brackets and terminating NULL */
744 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100745 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100746
747 /* check IPv6 with square brackets */
748 if (str[0] == '[') {
749 size_t iplength = strlen(str);
750
751 if (iplength < 4) {
752 /* minimal size is 4 when using brackets "[::]" */
753 goto fail;
754 }
755 else if (iplength >= sizeof(tmpip)) {
756 /* IPv6 literal can not be larger than tmpip */
757 goto fail;
758 }
759 else {
760 if (str[iplength - 1] != ']') {
761 /* if address started with bracket, it should end with bracket */
762 goto fail;
763 }
764 else {
765 memcpy(tmpip, str + 1, iplength - 2);
766 tmpip[iplength - 2] = '\0';
767 str = tmpip;
768 }
769 }
770 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100771
Willy Tarreaufab5a432011-03-04 15:31:53 +0100772 /* Any IPv6 address */
773 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100774 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
775 sa->ss_family = AF_INET6;
776 else if (sa->ss_family != AF_INET6)
777 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100778 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100779 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100780 }
781
Willy Tarreau24709282013-03-10 21:32:12 +0100782 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100783 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100784 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
785 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100786 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100787 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100788 }
789
790 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100791 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
792 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100793 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100794 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100795 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100796 }
797
798 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100799 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
800 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100801 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100802 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100803 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100804 }
805
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100806 if (!resolve)
807 return NULL;
808
Emeric Brund30e9a12020-12-23 18:49:16 +0100809 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200810 return NULL;
811
David du Colombierd5f43282011-03-17 10:40:16 +0100812#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200813 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100814 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100815 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100816
817 memset(&result, 0, sizeof(result));
818 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100819 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100820 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200821 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100822 hints.ai_protocol = 0;
823
824 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100825 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
826 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100827 else if (sa->ss_family != result->ai_family) {
828 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100829 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100830 }
Willy Tarreau24709282013-03-10 21:32:12 +0100831
David du Colombierd5f43282011-03-17 10:40:16 +0100832 switch (result->ai_family) {
833 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100834 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100835 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100836 success = 1;
837 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100838 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100839 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100840 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100841 success = 1;
842 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100843 }
844 }
845
Sean Carey58ea0392013-02-15 23:39:18 +0100846 if (result)
847 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100848
849 if (success)
850 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100851 }
David du Colombierd5f43282011-03-17 10:40:16 +0100852#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200853 /* try to resolve an IPv4/IPv6 hostname */
854 he = gethostbyname(str);
855 if (he) {
856 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
857 sa->ss_family = he->h_addrtype;
858 else if (sa->ss_family != he->h_addrtype)
859 goto fail;
860
861 switch (sa->ss_family) {
862 case AF_INET:
863 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_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 case AF_INET6:
867 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100868 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200869 return sa;
870 }
871 }
872
David du Colombierd5f43282011-03-17 10:40:16 +0100873 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100874 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100875 return NULL;
876}
877
878/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100879 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
880 * range or offset consisting in two integers that the caller will have to
881 * check to find the relevant input format. The following format are supported :
882 *
883 * String format | address | port | low | high
884 * addr | <addr> | 0 | 0 | 0
885 * addr: | <addr> | 0 | 0 | 0
886 * addr:port | <addr> | <port> | <port> | <port>
887 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
888 * addr:+port | <addr> | <port> | 0 | <port>
889 * addr:-port | <addr> |-<port> | <port> | 0
890 *
891 * The detection of a port range or increment by the caller is made by
892 * comparing <low> and <high>. If both are equal, then port 0 means no port
893 * was specified. The caller may pass NULL for <low> and <high> if it is not
894 * interested in retrieving port ranges.
895 *
896 * Note that <addr> above may also be :
897 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
898 * - "*" => family will be AF_INET and address will be INADDR_ANY
899 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
900 * - a host name => family and address will depend on host name resolving.
901 *
Willy Tarreau24709282013-03-10 21:32:12 +0100902 * A prefix may be passed in before the address above to force the family :
903 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
904 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
905 * - "unix@" => force address to be a path to a UNIX socket even if the
906 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200907 * - 'abns@' -> force address to belong to the abstract namespace (Linux
908 * only). These sockets are just like Unix sockets but without
909 * the need for an underlying file system. The address is a
910 * string. Technically it's like a Unix socket with a zero in
911 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100912 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100913 *
mildisff5d5102015-10-26 18:50:08 +0100914 * IPv6 addresses can be declared with or without square brackets. When using
915 * square brackets for IPv6 addresses, the port separator (colon) is optional.
916 * If not using square brackets, and in order to avoid any ambiguity with
917 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
918 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
919 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100920 *
921 * If <pfx> is non-null, it is used as a string prefix before any path-based
922 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100923 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200924 * if <fqdn> is non-null, it will be filled with :
925 * - a pointer to the FQDN of the server name to resolve if there's one, and
926 * that the caller will have to free(),
927 * - NULL if there was an explicit address that doesn't require resolution.
928 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200929 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
930 * still honored so it is possible for the caller to know whether a resolution
931 * failed by clearing this flag and checking if <fqdn> was filled, indicating
932 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200933 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100934 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200935 * the address when cast to sockaddr_in and the address family is
936 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200937 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200938 * The matching protocol will be set into <proto> if non-null.
939 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200940 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
941 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100942 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200943struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
944 struct protocol **proto, char **err,
945 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100946{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100947 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100948 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200949 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100950 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100951 char *port1, *port2;
952 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200953 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200954 int new_fd = -1;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200955 enum proto_type proto_type;
956 int ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100957
958 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200959 if (fqdn)
960 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200961
Willy Tarreaudad36a32013-03-11 01:20:04 +0100962 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100963 if (str2 == NULL) {
964 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100965 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100966 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200967
Willy Tarreau9f69f462015-09-08 16:01:25 +0200968 if (!*str2) {
969 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
970 goto out;
971 }
972
Willy Tarreau24709282013-03-10 21:32:12 +0100973 memset(&ss, 0, sizeof(ss));
974
Willy Tarreaue835bd82020-09-16 11:35:47 +0200975 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100976 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
Willy Tarreaue3b45182021-10-27 17:28:55 +0200977 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM))) {
978 proto_type = PROTO_TYPE_DGRAM;
979 ctrl_type = SOCK_DGRAM;
980 } else {
981 proto_type = PROTO_TYPE_STREAM;
982 ctrl_type = SOCK_STREAM;
983 }
Willy Tarreaue835bd82020-09-16 11:35:47 +0200984
985 if (strncmp(str2, "stream+", 7) == 0) {
986 str2 += 7;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200987 proto_type = PROTO_TYPE_STREAM;
988 ctrl_type = SOCK_STREAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200989 }
990 else if (strncmp(str2, "dgram+", 6) == 0) {
991 str2 += 6;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200992 proto_type = PROTO_TYPE_DGRAM;
993 ctrl_type = SOCK_DGRAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200994 }
995
Willy Tarreau24709282013-03-10 21:32:12 +0100996 if (strncmp(str2, "unix@", 5) == 0) {
997 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200998 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100999 ss.ss_family = AF_UNIX;
1000 }
Emeric Brunce325c42021-04-02 17:05:09 +02001001 else if (strncmp(str2, "uxdg@", 5) == 0) {
1002 str2 += 5;
1003 abstract = 0;
1004 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001005 proto_type = PROTO_TYPE_DGRAM;
1006 ctrl_type = SOCK_DGRAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001007 }
1008 else if (strncmp(str2, "uxst@", 5) == 0) {
1009 str2 += 5;
1010 abstract = 0;
1011 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001012 proto_type = PROTO_TYPE_STREAM;
1013 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001014 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001015 else if (strncmp(str2, "abns@", 5) == 0) {
1016 str2 += 5;
1017 abstract = 1;
1018 ss.ss_family = AF_UNIX;
1019 }
Emeric Brunce325c42021-04-02 17:05:09 +02001020 else if (strncmp(str2, "ip@", 3) == 0) {
1021 str2 += 3;
1022 ss.ss_family = AF_UNSPEC;
1023 }
Willy Tarreau24709282013-03-10 21:32:12 +01001024 else if (strncmp(str2, "ipv4@", 5) == 0) {
1025 str2 += 5;
1026 ss.ss_family = AF_INET;
1027 }
1028 else if (strncmp(str2, "ipv6@", 5) == 0) {
1029 str2 += 5;
1030 ss.ss_family = AF_INET6;
1031 }
Emeric Brunce325c42021-04-02 17:05:09 +02001032 else if (strncmp(str2, "tcp4@", 5) == 0) {
1033 str2 += 5;
1034 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001035 proto_type = PROTO_TYPE_STREAM;
1036 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001037 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001038 else if (strncmp(str2, "udp4@", 5) == 0) {
1039 str2 += 5;
1040 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001041 proto_type = PROTO_TYPE_DGRAM;
1042 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001043 }
Emeric Brunce325c42021-04-02 17:05:09 +02001044 else if (strncmp(str2, "tcp6@", 5) == 0) {
1045 str2 += 5;
1046 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001047 proto_type = PROTO_TYPE_STREAM;
1048 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001049 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001050 else if (strncmp(str2, "udp6@", 5) == 0) {
1051 str2 += 5;
1052 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001053 proto_type = PROTO_TYPE_DGRAM;
1054 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001055 }
Emeric Brunce325c42021-04-02 17:05:09 +02001056 else if (strncmp(str2, "tcp@", 4) == 0) {
1057 str2 += 4;
1058 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001059 proto_type = PROTO_TYPE_STREAM;
1060 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001061 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001062 else if (strncmp(str2, "udp@", 4) == 0) {
1063 str2 += 4;
1064 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001065 proto_type = PROTO_TYPE_DGRAM;
1066 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001067 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001068 else if (strncmp(str2, "quic4@", 6) == 0) {
1069 str2 += 6;
1070 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001071 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001072 ctrl_type = SOCK_STREAM;
1073 }
1074 else if (strncmp(str2, "quic6@", 6) == 0) {
1075 str2 += 6;
1076 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001077 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001078 ctrl_type = SOCK_STREAM;
1079 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001080 else if (strncmp(str2, "fd@", 3) == 0) {
1081 str2 += 3;
1082 ss.ss_family = AF_CUST_EXISTING_FD;
1083 }
1084 else if (strncmp(str2, "sockpair@", 9) == 0) {
1085 str2 += 9;
1086 ss.ss_family = AF_CUST_SOCKPAIR;
1087 }
Willy Tarreau24709282013-03-10 21:32:12 +01001088 else if (*str2 == '/') {
1089 ss.ss_family = AF_UNIX;
1090 }
1091 else
1092 ss.ss_family = AF_UNSPEC;
1093
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001094 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001095 struct sockaddr_storage ss2;
1096 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001097 char *endptr;
1098
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001099 new_fd = strtol(str2, &endptr, 10);
1100 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001101 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1102 goto out;
1103 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001104
Willy Tarreaua215be22020-09-16 10:14:16 +02001105 /* just verify that it's a socket */
1106 addr_len = sizeof(ss2);
1107 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1108 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1109 goto out;
1110 }
1111
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001112 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1113 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001114 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001115 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001116 char *endptr;
1117
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001118 new_fd = strtol(str2, &endptr, 10);
1119 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001120 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001121 goto out;
1122 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001123
Willy Tarreau6edc7222020-09-15 17:41:56 +02001124 if (opts & PA_O_SOCKET_FD) {
1125 socklen_t addr_len;
1126 int type;
1127
1128 addr_len = sizeof(ss);
1129 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1130 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1131 goto out;
1132 }
1133
1134 addr_len = sizeof(type);
1135 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue3b45182021-10-27 17:28:55 +02001136 (type == SOCK_STREAM) != (proto_type == PROTO_TYPE_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001137 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1138 goto out;
1139 }
1140
1141 porta = portl = porth = get_host_port(&ss);
1142 } else if (opts & PA_O_RAW_FD) {
1143 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1144 ((struct sockaddr_in *)&ss)->sin_port = 0;
1145 } else {
1146 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1147 goto out;
1148 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001149 }
1150 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001151 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001152 int prefix_path_len;
1153 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001154 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001155
1156 /* complete unix socket path name during startup or soft-restart is
1157 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1158 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001159 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001160 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001161 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001162
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001163 adr_len = strlen(str2);
1164 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001165 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1166 goto out;
1167 }
1168
Willy Tarreauccfccef2014-05-10 01:49:15 +02001169 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001170 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001171 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001172 memcpy(un->sun_path, pfx, prefix_path_len);
1173 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001174 }
Willy Tarreau24709282013-03-10 21:32:12 +01001175 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001176 char *end = str2 + strlen(str2);
1177 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001178
mildisff5d5102015-10-26 18:50:08 +01001179 /* search for : or ] whatever comes first */
1180 for (chr = end-1; chr > str2; chr--) {
1181 if (*chr == ']' || *chr == ':')
1182 break;
1183 }
1184
1185 if (*chr == ':') {
1186 /* Found a colon before a closing-bracket, must be a port separator.
1187 * This guarantee backward compatibility.
1188 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001189 if (!(opts & PA_O_PORT_OK)) {
1190 memprintf(err, "port specification not permitted here in '%s'", str);
1191 goto out;
1192 }
mildisff5d5102015-10-26 18:50:08 +01001193 *chr++ = '\0';
1194 port1 = chr;
1195 }
1196 else {
1197 /* Either no colon and no closing-bracket
1198 * or directly ending with a closing-bracket.
1199 * However, no port.
1200 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001201 if (opts & PA_O_PORT_MAND) {
1202 memprintf(err, "missing port specification in '%s'", str);
1203 goto out;
1204 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001205 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001206 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001207
Willy Tarreau90807112020-02-25 08:16:33 +01001208 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001209 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001210 if (port2) {
1211 if (!(opts & PA_O_PORT_RANGE)) {
1212 memprintf(err, "port range not permitted here in '%s'", str);
1213 goto out;
1214 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001215 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001216 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001217 else
1218 port2 = port1;
1219 portl = atoi(port1);
1220 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001221
1222 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1223 memprintf(err, "invalid port '%s'", port1);
1224 goto out;
1225 }
1226
1227 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1228 memprintf(err, "invalid port '%s'", port2);
1229 goto out;
1230 }
1231
1232 if (portl > porth) {
1233 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1234 goto out;
1235 }
1236
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001237 porta = portl;
1238 }
1239 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001240 if (!(opts & PA_O_PORT_OFS)) {
1241 memprintf(err, "port offset not permitted here in '%s'", str);
1242 goto out;
1243 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001244 portl = atoi(port1 + 1);
1245 porta = -portl;
1246 }
1247 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001248 if (!(opts & PA_O_PORT_OFS)) {
1249 memprintf(err, "port offset not permitted here in '%s'", str);
1250 goto out;
1251 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001252 porth = atoi(port1 + 1);
1253 porta = porth;
1254 }
1255 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001256 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001257 goto out;
1258 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001259 else if (opts & PA_O_PORT_MAND) {
1260 memprintf(err, "missing port specification in '%s'", str);
1261 goto out;
1262 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001263
1264 /* first try to parse the IP without resolving. If it fails, it
1265 * tells us we need to keep a copy of the FQDN to resolve later
1266 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001267 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001268 */
1269 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001270 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1271 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001272 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1273 goto out;
1274 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001275
Willy Tarreauceccdd72016-11-02 22:27:10 +01001276 if (fqdn) {
1277 if (str2 != back)
1278 memmove(back, str2, strlen(str2) + 1);
1279 *fqdn = back;
1280 back = NULL;
1281 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001282 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001283 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001284 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001285
Willy Tarreaue835bd82020-09-16 11:35:47 +02001286 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001287 memprintf(err, "stream-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001288 goto out;
1289 }
1290 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
Willy Tarreau8d31ab02022-05-09 16:18:26 +02001291 memprintf(err, "dgram-type address not acceptable in '%s'\n", str);
Willy Tarreaue835bd82020-09-16 11:35:47 +02001292 goto out;
1293 }
1294
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001295 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001296 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001297 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1298 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001299 * in which case the address is not known yet (this is only
1300 * for servers actually).
1301 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001302 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreaue3b45182021-10-27 17:28:55 +02001303 proto_type,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001304 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001305
Emeric Brun26754902021-04-07 14:26:44 +02001306 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001307 memprintf(err, "unsupported %s protocol for %s family %d address '%s'%s",
Willy Tarreau2b049b82022-05-20 17:28:30 +02001308 (ctrl_type == SOCK_DGRAM) ? "datagram" : "stream",
1309 (proto_type == PROTO_TYPE_DGRAM) ? "datagram" : "stream",
1310 ss.ss_family,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001311 str,
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001312#ifndef USE_QUIC
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001313 (ctrl_type == SOCK_STREAM && proto_type == PROTO_TYPE_DGRAM)
1314 ? "; QUIC is not compiled in if this is what you were looking for."
1315 : ""
Willy Tarreau3d7b4682022-05-20 17:32:35 +02001316#else
1317 ""
1318#endif
Tim Duesterhus147eeb22022-05-22 12:40:58 +02001319 );
Willy Tarreau5fc93282020-09-16 18:25:03 +02001320 goto out;
1321 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001322
1323 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1324 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1325 goto out;
1326 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001327 }
1328
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001329 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001330 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001331 if (port)
1332 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001333 if (low)
1334 *low = portl;
1335 if (high)
1336 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001337 if (fd)
1338 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001339 if (proto)
1340 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001341 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001342 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001343}
1344
Thayne McCombs92149f92020-11-20 01:28:26 -07001345/* converts <addr> and <port> into a string representation of the address and port. This is sort
1346 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1347 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1348 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1349 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1350 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1351 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1352 *
1353 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1354 */
1355char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1356{
1357 char buffer[INET6_ADDRSTRLEN];
1358 char *out = NULL;
1359 const void *ptr;
1360 const char *path;
1361
1362 switch (addr->ss_family) {
1363 case AF_INET:
1364 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1365 break;
1366 case AF_INET6:
1367 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1368 break;
1369 case AF_UNIX:
1370 path = ((struct sockaddr_un *)addr)->sun_path;
1371 if (path[0] == '\0') {
1372 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1373 return memprintf(&out, "abns@%.*s", max_length, path+1);
1374 } else {
1375 return strdup(path);
1376 }
1377 case AF_CUST_SOCKPAIR:
1378 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1379 default:
1380 return NULL;
1381 }
Tim Duesterhus22535a52022-05-23 09:30:49 +02001382 if (inet_ntop(addr->ss_family, ptr, buffer, sizeof(buffer)) == NULL) {
1383 BUG_ON(errno == ENOSPC);
1384 return NULL;
1385 }
Thayne McCombs92149f92020-11-20 01:28:26 -07001386 if (map_ports)
1387 return memprintf(&out, "%s:%+d", buffer, port);
1388 else
1389 return memprintf(&out, "%s:%d", buffer, port);
1390}
1391
1392
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001393/* converts <str> to a struct in_addr containing a network mask. It can be
1394 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001395 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001396 */
1397int str2mask(const char *str, struct in_addr *mask)
1398{
1399 if (strchr(str, '.') != NULL) { /* dotted notation */
1400 if (!inet_pton(AF_INET, str, mask))
1401 return 0;
1402 }
1403 else { /* mask length */
1404 char *err;
1405 unsigned long len = strtol(str, &err, 10);
1406
1407 if (!*str || (err && *err) || (unsigned)len > 32)
1408 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001409
1410 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001411 }
1412 return 1;
1413}
1414
Tim Duesterhus47185172018-01-25 16:24:49 +01001415/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001416 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001417 * if the conversion succeeds otherwise zero.
1418 */
1419int str2mask6(const char *str, struct in6_addr *mask)
1420{
1421 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1422 if (!inet_pton(AF_INET6, str, mask))
1423 return 0;
1424 }
1425 else { /* mask length */
1426 char *err;
1427 unsigned long len = strtol(str, &err, 10);
1428
1429 if (!*str || (err && *err) || (unsigned)len > 128)
1430 return 0;
1431
1432 len2mask6(len, mask);
1433 }
1434 return 1;
1435}
1436
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001437/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1438 * succeeds otherwise zero.
1439 */
1440int cidr2dotted(int cidr, struct in_addr *mask) {
1441
1442 if (cidr < 0 || cidr > 32)
1443 return 0;
1444
1445 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1446 return 1;
1447}
1448
Thierry Fournier70473a52016-02-17 17:12:14 +01001449/* Convert mask from bit length form to in_addr form.
1450 * This function never fails.
1451 */
1452void len2mask4(int len, struct in_addr *addr)
1453{
1454 if (len >= 32) {
1455 addr->s_addr = 0xffffffff;
1456 return;
1457 }
1458 if (len <= 0) {
1459 addr->s_addr = 0x00000000;
1460 return;
1461 }
1462 addr->s_addr = 0xffffffff << (32 - len);
1463 addr->s_addr = htonl(addr->s_addr);
1464}
1465
1466/* Convert mask from bit length form to in6_addr form.
1467 * This function never fails.
1468 */
1469void len2mask6(int len, struct in6_addr *addr)
1470{
1471 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1472 len -= 32;
1473 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1474 len -= 32;
1475 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1476 len -= 32;
1477 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1478}
1479
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001480/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001481 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001482 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001483 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001484 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1485 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001486int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001487{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001488 __label__ out_free, out_err;
1489 char *c, *s;
1490 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001491
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001492 s = strdup(str);
1493 if (!s)
1494 return 0;
1495
Willy Tarreaubaaee002006-06-26 02:48:02 +02001496 memset(mask, 0, sizeof(*mask));
1497 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001498
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001499 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001500 *c++ = '\0';
1501 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001502 if (!str2mask(c, mask))
1503 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001504 }
1505 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001506 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001507 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001508 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001509 struct hostent *he;
1510
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001511 if (!resolve)
1512 goto out_err;
1513
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001514 if ((he = gethostbyname(s)) == NULL) {
1515 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001516 }
1517 else
1518 *addr = *(struct in_addr *) *(he->h_addr_list);
1519 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001520
1521 ret_val = 1;
1522 out_free:
1523 free(s);
1524 return ret_val;
1525 out_err:
1526 ret_val = 0;
1527 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001528}
1529
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001530
1531/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001532 * converts <str> to two struct in6_addr* which must be pre-allocated.
1533 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001534 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001535 * Returns 1 if OK, 0 if error.
1536 */
1537int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1538{
1539 char *c, *s;
1540 int ret_val = 0;
1541 char *err;
1542 unsigned long len = 128;
1543
1544 s = strdup(str);
1545 if (!s)
1546 return 0;
1547
1548 memset(mask, 0, sizeof(*mask));
1549 memset(addr, 0, sizeof(*addr));
1550
1551 if ((c = strrchr(s, '/')) != NULL) {
1552 *c++ = '\0'; /* c points to the mask */
1553 if (!*c)
1554 goto out_free;
1555
1556 len = strtoul(c, &err, 10);
1557 if ((err && *err) || (unsigned)len > 128)
1558 goto out_free;
1559 }
1560 *mask = len; /* OK we have a valid mask in <len> */
1561
1562 if (!inet_pton(AF_INET6, s, addr))
1563 goto out_free;
1564
1565 ret_val = 1;
1566 out_free:
1567 free(s);
1568 return ret_val;
1569}
1570
1571
1572/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001573 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1574 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1575 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001576 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001577int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001578{
1579 int saw_digit, octets, ch;
1580 u_char tmp[4], *tp;
1581 const char *cp = addr;
1582
1583 saw_digit = 0;
1584 octets = 0;
1585 *(tp = tmp) = 0;
1586
1587 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001588 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001589 if (digit > 9 && ch != '.')
1590 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001591 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001592 if (digit <= 9) {
1593 u_int new = *tp * 10 + digit;
1594 if (new > 255)
1595 return 0;
1596 *tp = new;
1597 if (!saw_digit) {
1598 if (++octets > 4)
1599 return 0;
1600 saw_digit = 1;
1601 }
1602 } else if (ch == '.' && saw_digit) {
1603 if (octets == 4)
1604 return 0;
1605 *++tp = 0;
1606 saw_digit = 0;
1607 } else
1608 return 0;
1609 }
1610
1611 if (octets < 4)
1612 return 0;
1613
1614 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001615 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001616}
1617
1618/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001619 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001620 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001621 * the hostname. Actually only http and https are supported. <out> can be NULL.
1622 * This function returns the consumed length. It is useful if you parse complete
1623 * url like http://host:port/path, because the consumed length corresponds to
1624 * the first character of the path. If the conversion fails, it returns -1.
1625 *
1626 * This function tries to resolve the DNS name if haproxy is in starting mode.
1627 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001628 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001629int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001630{
1631 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001632 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001633 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001634 unsigned long long int http_code = 0;
1635 int default_port;
1636 struct hostent *he;
1637 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001638
1639 /* Firstly, try to find :// pattern */
1640 while (curr < url+ulen && url_code != 0x3a2f2f) {
1641 url_code = ((url_code & 0xffff) << 8);
1642 url_code += (unsigned char)*curr++;
1643 }
1644
1645 /* Secondly, if :// pattern is found, verify parsed stuff
1646 * before pattern is matching our http pattern.
1647 * If so parse ip address and port in uri.
1648 *
1649 * WARNING: Current code doesn't support dynamic async dns resolver.
1650 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001651 if (url_code != 0x3a2f2f)
1652 return -1;
1653
1654 /* Copy scheme, and utrn to lower case. */
1655 while (cp < curr - 3)
1656 http_code = (http_code << 8) + *cp++;
1657 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001658
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001659 /* HTTP or HTTPS url matching */
1660 if (http_code == 0x2020202068747470ULL) {
1661 default_port = 80;
1662 if (out)
1663 out->scheme = SCH_HTTP;
1664 }
1665 else if (http_code == 0x2020206874747073ULL) {
1666 default_port = 443;
1667 if (out)
1668 out->scheme = SCH_HTTPS;
1669 }
1670 else
1671 return -1;
1672
1673 /* If the next char is '[', the host address is IPv6. */
1674 if (*curr == '[') {
1675 curr++;
1676
1677 /* Check trash size */
1678 if (trash.size < ulen)
1679 return -1;
1680
1681 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001682 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001683 for (end = curr;
1684 end < url + ulen && *end != ']';
1685 end++, p++)
1686 *p = *end;
1687 if (*end != ']')
1688 return -1;
1689 *p = '\0';
1690
1691 /* Update out. */
1692 if (out) {
1693 out->host = curr;
1694 out->host_len = end - curr;
1695 }
1696
1697 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001698 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001699 return -1;
1700 end++;
1701
1702 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001703 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001704 end++;
1705 default_port = read_uint(&end, url + ulen);
1706 }
1707 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1708 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1709 return end - url;
1710 }
1711 else {
William Lallemand8a913742022-02-18 16:13:12 +01001712 /* we need to copy the string into the trash because url2ipv4
1713 * needs a \0 at the end of the string */
1714 if (trash.size < ulen)
1715 return -1;
1716
1717 memcpy(trash.area, curr, ulen - (curr - url));
1718 trash.area[ulen - (curr - url)] = '\0';
1719
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001720 /* We are looking for IP address. If you want to parse and
1721 * resolve hostname found in url, you can use str2sa_range(), but
1722 * be warned this can slow down global daemon performances
1723 * while handling lagging dns responses.
1724 */
William Lallemand8a913742022-02-18 16:13:12 +01001725 ret = url2ipv4(trash.area, &((struct sockaddr_in *)addr)->sin_addr);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001726 if (ret) {
1727 /* Update out. */
1728 if (out) {
1729 out->host = curr;
1730 out->host_len = ret;
1731 }
1732
William Lallemandb938b772022-03-24 21:59:03 +01001733 curr += ret;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001734
1735 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001736 if (curr < url + ulen && *curr == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001737 curr++;
1738 default_port = read_uint(&curr, url + ulen);
1739 }
1740 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1741
1742 /* Set family. */
1743 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1744 return curr - url;
1745 }
1746 else if (global.mode & MODE_STARTING) {
1747 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1748 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001749 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001750
1751 /* look for : or / or end */
1752 for (end = curr;
1753 end < url + ulen && *end != '/' && *end != ':';
1754 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001755 memcpy(trash.area, curr, end - curr);
1756 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001757
1758 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001759 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001760 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001761 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001762
1763 /* Update out. */
1764 if (out) {
1765 out->host = curr;
1766 out->host_len = end - curr;
1767 }
1768
1769 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001770 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001771 end++;
1772 default_port = read_uint(&end, url + ulen);
1773 }
1774
1775 /* Copy IP address, set port and family. */
1776 switch (he->h_addrtype) {
1777 case AF_INET:
1778 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1779 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1780 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1781 return end - url;
1782
1783 case AF_INET6:
1784 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1785 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1786 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1787 return end - url;
1788 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001789 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001790 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001791 return -1;
1792}
1793
Willy Tarreau631f01c2011-09-05 00:36:48 +02001794/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1795 * address family is returned so that it's easy for the caller to adapt to the
1796 * output format. Zero is returned if the address family is not supported. -1
1797 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1798 * supported.
1799 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001800int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001801{
1802
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001803 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001804
1805 if (size < 5)
1806 return 0;
1807 *str = '\0';
1808
1809 switch (addr->ss_family) {
1810 case AF_INET:
1811 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1812 break;
1813 case AF_INET6:
1814 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1815 break;
1816 case AF_UNIX:
1817 memcpy(str, "unix", 5);
1818 return addr->ss_family;
1819 default:
1820 return 0;
1821 }
1822
1823 if (inet_ntop(addr->ss_family, ptr, str, size))
1824 return addr->ss_family;
1825
1826 /* failed */
1827 return -1;
1828}
1829
Simon Horman75ab8bd2014-06-16 09:39:41 +09001830/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1831 * address family is returned so that it's easy for the caller to adapt to the
1832 * output format. Zero is returned if the address family is not supported. -1
1833 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1834 * supported.
1835 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001836int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001837{
1838
1839 uint16_t port;
1840
1841
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001842 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001843 return 0;
1844 *str = '\0';
1845
1846 switch (addr->ss_family) {
1847 case AF_INET:
1848 port = ((struct sockaddr_in *)addr)->sin_port;
1849 break;
1850 case AF_INET6:
1851 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1852 break;
1853 case AF_UNIX:
1854 memcpy(str, "unix", 5);
1855 return addr->ss_family;
1856 default:
1857 return 0;
1858 }
1859
1860 snprintf(str, size, "%u", ntohs(port));
1861 return addr->ss_family;
1862}
1863
Willy Tarreau16e01562016-08-09 16:46:18 +02001864/* check if the given address is local to the system or not. It will return
1865 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1866 * it is. We don't want to iterate over all interfaces for this (and it is not
1867 * portable). So instead we try to bind in UDP to this address on a free non
1868 * privileged port and to connect to the same address, port 0 (connect doesn't
1869 * care). If it succeeds, we own the address. Note that non-inet addresses are
1870 * considered local since they're most likely AF_UNIX.
1871 */
1872int addr_is_local(const struct netns_entry *ns,
1873 const struct sockaddr_storage *orig)
1874{
1875 struct sockaddr_storage addr;
1876 int result;
1877 int fd;
1878
1879 if (!is_inet_addr(orig))
1880 return 1;
1881
1882 memcpy(&addr, orig, sizeof(addr));
1883 set_host_port(&addr, 0);
1884
1885 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1886 if (fd < 0)
1887 return -1;
1888
1889 result = -1;
1890 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1891 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1892 result = 0; // fail, non-local address
1893 else
1894 result = 1; // success, local address
1895 }
1896 else {
1897 if (errno == EADDRNOTAVAIL)
1898 result = 0; // definitely not local :-)
1899 }
1900 close(fd);
1901
1902 return result;
1903}
1904
Willy Tarreaubaaee002006-06-26 02:48:02 +02001905/* will try to encode the string <string> replacing all characters tagged in
1906 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1907 * prefixed by <escape>, and will store the result between <start> (included)
1908 * and <stop> (excluded), and will always terminate the string with a '\0'
1909 * before <stop>. The position of the '\0' is returned if the conversion
1910 * completes. If bytes are missing between <start> and <stop>, then the
1911 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1912 * cannot even be stored so we return <start> without writing the 0.
1913 * The input string must also be zero-terminated.
1914 */
1915const char hextab[16] = "0123456789ABCDEF";
1916char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001917 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001918 const char *string)
1919{
1920 if (start < stop) {
1921 stop--; /* reserve one byte for the final '\0' */
1922 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001923 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001924 *start++ = *string;
1925 else {
1926 if (start + 3 >= stop)
1927 break;
1928 *start++ = escape;
1929 *start++ = hextab[(*string >> 4) & 15];
1930 *start++ = hextab[*string & 15];
1931 }
1932 string++;
1933 }
1934 *start = '\0';
1935 }
1936 return start;
1937}
1938
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001939/*
1940 * Same behavior as encode_string() above, except that it encodes chunk
1941 * <chunk> instead of a string.
1942 */
1943char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001944 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001945 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001946{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001947 char *str = chunk->area;
1948 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001949
1950 if (start < stop) {
1951 stop--; /* reserve one byte for the final '\0' */
1952 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001953 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001954 *start++ = *str;
1955 else {
1956 if (start + 3 >= stop)
1957 break;
1958 *start++ = escape;
1959 *start++ = hextab[(*str >> 4) & 15];
1960 *start++ = hextab[*str & 15];
1961 }
1962 str++;
1963 }
1964 *start = '\0';
1965 }
1966 return start;
1967}
1968
Dragan Dosen0edd1092016-02-12 13:23:02 +01001969/*
1970 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001971 * character. The input <string> must be zero-terminated. The result will
1972 * be stored between <start> (included) and <stop> (excluded). This
1973 * function will always try to terminate the resulting string with a '\0'
1974 * before <stop>, and will return its position if the conversion
1975 * completes.
1976 */
1977char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001978 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001979 const char *string)
1980{
1981 if (start < stop) {
1982 stop--; /* reserve one byte for the final '\0' */
1983 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001984 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001985 *start++ = *string;
1986 else {
1987 if (start + 2 >= stop)
1988 break;
1989 *start++ = escape;
1990 *start++ = *string;
1991 }
1992 string++;
1993 }
1994 *start = '\0';
1995 }
1996 return start;
1997}
1998
1999/*
2000 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01002001 * character. <chunk> contains the input to be escaped. The result will be
2002 * stored between <start> (included) and <stop> (excluded). The function
2003 * will always try to terminate the resulting string with a '\0' before
2004 * <stop>, and will return its position if the conversion completes.
2005 */
2006char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02002007 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02002008 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01002009{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002010 char *str = chunk->area;
2011 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01002012
2013 if (start < stop) {
2014 stop--; /* reserve one byte for the final '\0' */
2015 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02002016 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01002017 *start++ = *str;
2018 else {
2019 if (start + 2 >= stop)
2020 break;
2021 *start++ = escape;
2022 *start++ = *str;
2023 }
2024 str++;
2025 }
2026 *start = '\0';
2027 }
2028 return start;
2029}
2030
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002031/* Check a string for using it in a CSV output format. If the string contains
2032 * one of the following four char <">, <,>, CR or LF, the string is
2033 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2034 * <str> is the input string to be escaped. The function assumes that
2035 * the input string is null-terminated.
2036 *
2037 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002038 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002039 * format.
2040 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002041 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002042 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002043 * If <quote> is 1, the converter puts the quotes only if any reserved character
2044 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002045 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002046 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002047 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002048 * The function returns the converted string on its output. If an error
2049 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002050 * for using the function directly as printf() argument.
2051 *
2052 * If the output buffer is too short to contain the input string, the result
2053 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002054 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002055 * This function appends the encoding to the existing output chunk, and it
2056 * guarantees that it starts immediately at the first available character of
2057 * the chunk. Please use csv_enc() instead if you want to replace the output
2058 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002059 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002060const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002061{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002062 char *end = output->area + output->size;
2063 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002064 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002065
Willy Tarreaub631c292016-01-08 10:04:08 +01002066 if (quote == 1) {
2067 /* automatic quoting: first verify if we'll have to quote the string */
2068 if (!strpbrk(str, "\n\r,\""))
2069 quote = 0;
2070 }
2071
2072 if (quote)
2073 *ptr++ = '"';
2074
Willy Tarreau898529b2016-01-06 18:07:04 +01002075 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2076 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002077 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002078 ptr++;
2079 if (ptr >= end - 2) {
2080 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002081 break;
2082 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002083 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002084 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002085 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002086 str++;
2087 }
2088
Willy Tarreaub631c292016-01-08 10:04:08 +01002089 if (quote)
2090 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002091
Willy Tarreau898529b2016-01-06 18:07:04 +01002092 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002093 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002094 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002095}
2096
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002097/* Decode an URL-encoded string in-place. The resulting string might
2098 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002099 * aborted, the string is truncated before the issue and a negative value is
2100 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002101 * If the 'in_form' argument is non-nul the string is assumed to be part of
2102 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2103 * turned to a space. If it's zero, this will only be done after a question
2104 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002105 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002106int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002107{
2108 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002109 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002110
2111 in = string;
2112 out = string;
2113 while (*in) {
2114 switch (*in) {
2115 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002116 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002117 break;
2118 case '%' :
2119 if (!ishex(in[1]) || !ishex(in[2]))
2120 goto end;
2121 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2122 in += 2;
2123 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002124 case '?':
2125 in_form = 1;
2126 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002127 default:
2128 *out++ = *in;
2129 break;
2130 }
2131 in++;
2132 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002133 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002134 end:
2135 *out = 0;
2136 return ret;
2137}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002138
Willy Tarreau6911fa42007-03-04 18:06:08 +01002139unsigned int str2ui(const char *s)
2140{
2141 return __str2ui(s);
2142}
2143
2144unsigned int str2uic(const char *s)
2145{
2146 return __str2uic(s);
2147}
2148
2149unsigned int strl2ui(const char *s, int len)
2150{
2151 return __strl2ui(s, len);
2152}
2153
2154unsigned int strl2uic(const char *s, int len)
2155{
2156 return __strl2uic(s, len);
2157}
2158
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002159unsigned int read_uint(const char **s, const char *end)
2160{
2161 return __read_uint(s, end);
2162}
2163
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002164/* This function reads an unsigned integer from the string pointed to by <s> and
2165 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2166 * function automatically stops at <end>. If the number overflows, the 2^64-1
2167 * value is returned.
2168 */
2169unsigned long long int read_uint64(const char **s, const char *end)
2170{
2171 const char *ptr = *s;
2172 unsigned long long int i = 0, tmp;
2173 unsigned int j;
2174
2175 while (ptr < end) {
2176
2177 /* read next char */
2178 j = *ptr - '0';
2179 if (j > 9)
2180 goto read_uint64_end;
2181
2182 /* add char to the number and check overflow. */
2183 tmp = i * 10;
2184 if (tmp / 10 != i) {
2185 i = ULLONG_MAX;
2186 goto read_uint64_eat;
2187 }
2188 if (ULLONG_MAX - tmp < j) {
2189 i = ULLONG_MAX;
2190 goto read_uint64_eat;
2191 }
2192 i = tmp + j;
2193 ptr++;
2194 }
2195read_uint64_eat:
2196 /* eat each numeric char */
2197 while (ptr < end) {
2198 if ((unsigned int)(*ptr - '0') > 9)
2199 break;
2200 ptr++;
2201 }
2202read_uint64_end:
2203 *s = ptr;
2204 return i;
2205}
2206
2207/* This function reads an integer from the string pointed to by <s> and returns
2208 * it. The <s> pointer is adjusted to point to the first unread char. The function
2209 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2210 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2211 * returned.
2212 */
2213long long int read_int64(const char **s, const char *end)
2214{
2215 unsigned long long int i = 0;
2216 int neg = 0;
2217
2218 /* Look for minus char. */
2219 if (**s == '-') {
2220 neg = 1;
2221 (*s)++;
2222 }
2223 else if (**s == '+')
2224 (*s)++;
2225
2226 /* convert as positive number. */
2227 i = read_uint64(s, end);
2228
2229 if (neg) {
2230 if (i > 0x8000000000000000ULL)
2231 return LLONG_MIN;
2232 return -i;
2233 }
2234 if (i > 0x7fffffffffffffffULL)
2235 return LLONG_MAX;
2236 return i;
2237}
2238
Willy Tarreau6911fa42007-03-04 18:06:08 +01002239/* This one is 7 times faster than strtol() on athlon with checks.
2240 * It returns the value of the number composed of all valid digits read,
2241 * and can process negative numbers too.
2242 */
2243int strl2ic(const char *s, int len)
2244{
2245 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002246 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002247
2248 if (len > 0) {
2249 if (*s != '-') {
2250 /* positive number */
2251 while (len-- > 0) {
2252 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002253 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002254 if (j > 9)
2255 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002256 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002257 }
2258 } else {
2259 /* negative number */
2260 s++;
2261 while (--len > 0) {
2262 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002263 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002264 if (j > 9)
2265 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002266 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002267 }
2268 }
2269 }
2270 return i;
2271}
2272
2273
2274/* This function reads exactly <len> chars from <s> and converts them to a
2275 * signed integer which it stores into <ret>. It accurately detects any error
2276 * (truncated string, invalid chars, overflows). It is meant to be used in
2277 * applications designed for hostile environments. It returns zero when the
2278 * number has successfully been converted, non-zero otherwise. When an error
2279 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2280 * faster than strtol().
2281 */
2282int strl2irc(const char *s, int len, int *ret)
2283{
2284 int i = 0;
2285 int j;
2286
2287 if (!len)
2288 return 1;
2289
2290 if (*s != '-') {
2291 /* positive number */
2292 while (len-- > 0) {
2293 j = (*s++) - '0';
2294 if (j > 9) return 1; /* invalid char */
2295 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2296 i = i * 10;
2297 if (i + j < i) return 1; /* check for addition overflow */
2298 i = i + j;
2299 }
2300 } else {
2301 /* negative number */
2302 s++;
2303 while (--len > 0) {
2304 j = (*s++) - '0';
2305 if (j > 9) return 1; /* invalid char */
2306 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2307 i = i * 10;
2308 if (i - j > i) return 1; /* check for subtract overflow */
2309 i = i - j;
2310 }
2311 }
2312 *ret = i;
2313 return 0;
2314}
2315
2316
2317/* This function reads exactly <len> chars from <s> and converts them to a
2318 * signed integer which it stores into <ret>. It accurately detects any error
2319 * (truncated string, invalid chars, overflows). It is meant to be used in
2320 * applications designed for hostile environments. It returns zero when the
2321 * number has successfully been converted, non-zero otherwise. When an error
2322 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002323 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002324 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002325
2326int strl2llrc(const char *s, int len, long long *ret)
2327{
2328 long long i = 0;
2329 int j;
2330
2331 if (!len)
2332 return 1;
2333
2334 if (*s != '-') {
2335 /* positive number */
2336 while (len-- > 0) {
2337 j = (*s++) - '0';
2338 if (j > 9) return 1; /* invalid char */
2339 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2340 i = i * 10LL;
2341 if (i + j < i) return 1; /* check for addition overflow */
2342 i = i + j;
2343 }
2344 } else {
2345 /* negative number */
2346 s++;
2347 while (--len > 0) {
2348 j = (*s++) - '0';
2349 if (j > 9) return 1; /* invalid char */
2350 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2351 i = i * 10LL;
2352 if (i - j > i) return 1; /* check for subtract overflow */
2353 i = i - j;
2354 }
2355 }
2356 *ret = i;
2357 return 0;
2358}
2359
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002360/* This function is used with pat_parse_dotted_ver(). It converts a string
2361 * composed by two number separated by a dot. Each part must contain in 16 bits
2362 * because internally they will be represented as a 32-bit quantity stored in
2363 * a 64-bit integer. It returns zero when the number has successfully been
2364 * converted, non-zero otherwise. When an error is returned, the <ret> value
2365 * is left untouched.
2366 *
2367 * "1.3" -> 0x0000000000010003
2368 * "65535.65535" -> 0x00000000ffffffff
2369 */
2370int strl2llrc_dotted(const char *text, int len, long long *ret)
2371{
2372 const char *end = &text[len];
2373 const char *p;
2374 long long major, minor;
2375
2376 /* Look for dot. */
2377 for (p = text; p < end; p++)
2378 if (*p == '.')
2379 break;
2380
2381 /* Convert major. */
2382 if (strl2llrc(text, p - text, &major) != 0)
2383 return 1;
2384
2385 /* Check major. */
2386 if (major >= 65536)
2387 return 1;
2388
2389 /* Convert minor. */
2390 minor = 0;
2391 if (p < end)
2392 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2393 return 1;
2394
2395 /* Check minor. */
2396 if (minor >= 65536)
2397 return 1;
2398
2399 /* Compose value. */
2400 *ret = (major << 16) | (minor & 0xffff);
2401 return 0;
2402}
2403
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002404/* This function parses a time value optionally followed by a unit suffix among
2405 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2406 * expected by the caller. The computation does its best to avoid overflows.
2407 * The value is returned in <ret> if everything is fine, and a NULL is returned
2408 * by the function. In case of error, a pointer to the error is returned and
2409 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002410 * Values resulting in values larger than or equal to 2^31 after conversion are
2411 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2412 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002413 */
2414const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2415{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002416 unsigned long long imult, idiv;
2417 unsigned long long omult, odiv;
2418 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002419 const char *str = text;
2420
2421 if (!isdigit((unsigned char)*text))
2422 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002423
2424 omult = odiv = 1;
2425
2426 switch (unit_flags & TIME_UNIT_MASK) {
2427 case TIME_UNIT_US: omult = 1000000; break;
2428 case TIME_UNIT_MS: omult = 1000; break;
2429 case TIME_UNIT_S: break;
2430 case TIME_UNIT_MIN: odiv = 60; break;
2431 case TIME_UNIT_HOUR: odiv = 3600; break;
2432 case TIME_UNIT_DAY: odiv = 86400; break;
2433 default: break;
2434 }
2435
2436 value = 0;
2437
2438 while (1) {
2439 unsigned int j;
2440
2441 j = *text - '0';
2442 if (j > 9)
2443 break;
2444 text++;
2445 value *= 10;
2446 value += j;
2447 }
2448
2449 imult = idiv = 1;
2450 switch (*text) {
2451 case '\0': /* no unit = default unit */
2452 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002453 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002454 case 's': /* second = unscaled unit */
2455 break;
2456 case 'u': /* microsecond : "us" */
2457 if (text[1] == 's') {
2458 idiv = 1000000;
2459 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002460 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002461 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002462 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002463 case 'm': /* millisecond : "ms" or minute: "m" */
2464 if (text[1] == 's') {
2465 idiv = 1000;
2466 text++;
2467 } else
2468 imult = 60;
2469 break;
2470 case 'h': /* hour : "h" */
2471 imult = 3600;
2472 break;
2473 case 'd': /* day : "d" */
2474 imult = 86400;
2475 break;
2476 default:
2477 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002478 }
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 Tarreau0dc9e6d2022-08-01 11:55:57 +02002766/* dump the full tree to <file> in DOT format for debugging purposes. Will
2767 * optionally highlight node <subj> if found, depending on operation <op> :
2768 * 0 : nothing
2769 * >0 : insertion, node/leaf are surrounded in red
2770 * <0 : removal, node/leaf are dashed with no background
2771 * Will optionally add "desc" as a label on the graph if set and non-null. The
2772 * key is printed as a u32 hex value. A full-sized hex dump would be better but
2773 * is left to be implemented.
2774 */
2775void ebmb_to_file(FILE *file, struct eb_root *root, const struct ebmb_node *subj, int op, const char *desc)
2776{
2777 struct ebmb_node *node;
2778
2779 fprintf(file, "digraph ebtree {\n");
2780
2781 if (desc && *desc) {
2782 fprintf(file,
2783 " fontname=\"fixed\";\n"
2784 " fontsize=8;\n"
2785 " label=\"%s\";\n", desc);
2786 }
2787
2788 fprintf(file,
2789 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2790 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
2791 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2792 );
2793
2794 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2795 (long)eb_root_to_node(root),
2796 (long)eb_root_to_node(eb_clrtag(root->b[0])),
2797 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2798
2799 node = ebmb_first(root);
2800 while (node) {
2801 if (node->node.node_p) {
2802 /* node part is used */
2803 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%#x\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2804 (long)node, (long)node, read_u32(node->key), node->node.bit,
2805 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2806
2807 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2808 (long)node,
2809 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
2810 eb_gettag(node->node.node_p) ? 'R' : 'L');
2811
2812 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
2813 (long)node,
2814 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
2815 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2816
2817 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
2818 (long)node,
2819 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
2820 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2821 }
2822
2823 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%#x\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2824 (long)node, (long)node, read_u32(node->key), node->node.pfx,
2825 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
2826
2827 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
2828 (long)node,
2829 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
2830 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
2831 node = ebmb_next(node);
2832 }
2833 fprintf(file, "}\n");
2834}
2835
Willy Tarreau348238b2010-01-18 15:05:57 +01002836/* This function compares a sample word possibly followed by blanks to another
2837 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2838 * otherwise zero. This intends to be used when checking HTTP headers for some
2839 * values. Note that it validates a word followed only by blanks but does not
2840 * validate a word followed by blanks then other chars.
2841 */
2842int word_match(const char *sample, int slen, const char *word, int wlen)
2843{
2844 if (slen < wlen)
2845 return 0;
2846
2847 while (wlen) {
2848 char c = *sample ^ *word;
2849 if (c && c != ('A' ^ 'a'))
2850 return 0;
2851 sample++;
2852 word++;
2853 slen--;
2854 wlen--;
2855 }
2856
2857 while (slen) {
2858 if (*sample != ' ' && *sample != '\t')
2859 return 0;
2860 sample++;
2861 slen--;
2862 }
2863 return 1;
2864}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002865
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002866/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2867 * is particularly fast because it avoids expensive operations such as
2868 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002869 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002870 */
2871unsigned int inetaddr_host(const char *text)
2872{
2873 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2874 register unsigned int dig100, dig10, dig1;
2875 int s;
2876 const char *p, *d;
2877
2878 dig1 = dig10 = dig100 = ascii_zero;
2879 s = 24;
2880
2881 p = text;
2882 while (1) {
2883 if (((unsigned)(*p - '0')) <= 9) {
2884 p++;
2885 continue;
2886 }
2887
2888 /* here, we have a complete byte between <text> and <p> (exclusive) */
2889 if (p == text)
2890 goto end;
2891
2892 d = p - 1;
2893 dig1 |= (unsigned int)(*d << s);
2894 if (d == text)
2895 goto end;
2896
2897 d--;
2898 dig10 |= (unsigned int)(*d << s);
2899 if (d == text)
2900 goto end;
2901
2902 d--;
2903 dig100 |= (unsigned int)(*d << s);
2904 end:
2905 if (!s || *p != '.')
2906 break;
2907
2908 s -= 8;
2909 text = ++p;
2910 }
2911
2912 dig100 -= ascii_zero;
2913 dig10 -= ascii_zero;
2914 dig1 -= ascii_zero;
2915 return ((dig100 * 10) + dig10) * 10 + dig1;
2916}
2917
2918/*
2919 * Idem except the first unparsed character has to be passed in <stop>.
2920 */
2921unsigned int inetaddr_host_lim(const char *text, const char *stop)
2922{
2923 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2924 register unsigned int dig100, dig10, dig1;
2925 int s;
2926 const char *p, *d;
2927
2928 dig1 = dig10 = dig100 = ascii_zero;
2929 s = 24;
2930
2931 p = text;
2932 while (1) {
2933 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2934 p++;
2935 continue;
2936 }
2937
2938 /* here, we have a complete byte between <text> and <p> (exclusive) */
2939 if (p == text)
2940 goto end;
2941
2942 d = p - 1;
2943 dig1 |= (unsigned int)(*d << s);
2944 if (d == text)
2945 goto end;
2946
2947 d--;
2948 dig10 |= (unsigned int)(*d << s);
2949 if (d == text)
2950 goto end;
2951
2952 d--;
2953 dig100 |= (unsigned int)(*d << s);
2954 end:
2955 if (!s || p == stop || *p != '.')
2956 break;
2957
2958 s -= 8;
2959 text = ++p;
2960 }
2961
2962 dig100 -= ascii_zero;
2963 dig10 -= ascii_zero;
2964 dig1 -= ascii_zero;
2965 return ((dig100 * 10) + dig10) * 10 + dig1;
2966}
2967
2968/*
2969 * Idem except the pointer to first unparsed byte is returned into <ret> which
2970 * must not be NULL.
2971 */
Willy Tarreau74172752010-10-15 23:21:42 +02002972unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002973{
2974 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2975 register unsigned int dig100, dig10, dig1;
2976 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002977 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002978
2979 dig1 = dig10 = dig100 = ascii_zero;
2980 s = 24;
2981
2982 p = text;
2983 while (1) {
2984 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2985 p++;
2986 continue;
2987 }
2988
2989 /* here, we have a complete byte between <text> and <p> (exclusive) */
2990 if (p == text)
2991 goto end;
2992
2993 d = p - 1;
2994 dig1 |= (unsigned int)(*d << s);
2995 if (d == text)
2996 goto end;
2997
2998 d--;
2999 dig10 |= (unsigned int)(*d << s);
3000 if (d == text)
3001 goto end;
3002
3003 d--;
3004 dig100 |= (unsigned int)(*d << s);
3005 end:
3006 if (!s || p == stop || *p != '.')
3007 break;
3008
3009 s -= 8;
3010 text = ++p;
3011 }
3012
3013 *ret = p;
3014 dig100 -= ascii_zero;
3015 dig10 -= ascii_zero;
3016 dig1 -= ascii_zero;
3017 return ((dig100 * 10) + dig10) * 10 + dig1;
3018}
3019
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02003020/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
3021 * or the number of chars read in case of success. Maybe this could be replaced
3022 * by one of the functions above. Also, apparently this function does not support
3023 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01003024 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02003025 */
3026int buf2ip(const char *buf, size_t len, struct in_addr *dst)
3027{
3028 const char *addr;
3029 int saw_digit, octets, ch;
3030 u_char tmp[4], *tp;
3031 const char *cp = buf;
3032
3033 saw_digit = 0;
3034 octets = 0;
3035 *(tp = tmp) = 0;
3036
3037 for (addr = buf; addr - buf < len; addr++) {
3038 unsigned char digit = (ch = *addr) - '0';
3039
3040 if (digit > 9 && ch != '.')
3041 break;
3042
3043 if (digit <= 9) {
3044 u_int new = *tp * 10 + digit;
3045
3046 if (new > 255)
3047 return 0;
3048
3049 *tp = new;
3050
3051 if (!saw_digit) {
3052 if (++octets > 4)
3053 return 0;
3054 saw_digit = 1;
3055 }
3056 } else if (ch == '.' && saw_digit) {
3057 if (octets == 4)
3058 return 0;
3059
3060 *++tp = 0;
3061 saw_digit = 0;
3062 } else
3063 return 0;
3064 }
3065
3066 if (octets < 4)
3067 return 0;
3068
3069 memcpy(&dst->s_addr, tmp, 4);
3070 return addr - cp;
3071}
3072
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003073/* This function converts the string in <buf> of the len <len> to
3074 * struct in6_addr <dst> which must be allocated by the caller.
3075 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01003076 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003077 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003078int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
3079{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003080 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01003081 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003082
Thierry FOURNIERcd659912013-12-11 12:33:54 +01003083 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003084 return 0;
3085
3086 memcpy(null_term_ip6, buf, len);
3087 null_term_ip6[len] = '\0';
3088
Willy Tarreau075415a2013-12-12 11:29:39 +01003089 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003090 return 0;
3091
Willy Tarreau075415a2013-12-12 11:29:39 +01003092 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003093 return 1;
3094}
3095
Willy Tarreauacf95772010-06-14 19:09:21 +02003096/* To be used to quote config arg positions. Returns the short string at <ptr>
3097 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
3098 * if ptr is NULL or empty. The string is locally allocated.
3099 */
3100const char *quote_arg(const char *ptr)
3101{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003102 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003103 int i;
3104
3105 if (!ptr || !*ptr)
3106 return "end of line";
3107 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003108 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003109 val[i] = *ptr++;
3110 val[i++] = '\'';
3111 val[i] = '\0';
3112 return val;
3113}
3114
Willy Tarreau5b180202010-07-18 10:40:48 +02003115/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3116int get_std_op(const char *str)
3117{
3118 int ret = -1;
3119
3120 if (*str == 'e' && str[1] == 'q')
3121 ret = STD_OP_EQ;
3122 else if (*str == 'n' && str[1] == 'e')
3123 ret = STD_OP_NE;
3124 else if (*str == 'l') {
3125 if (str[1] == 'e') ret = STD_OP_LE;
3126 else if (str[1] == 't') ret = STD_OP_LT;
3127 }
3128 else if (*str == 'g') {
3129 if (str[1] == 'e') ret = STD_OP_GE;
3130 else if (str[1] == 't') ret = STD_OP_GT;
3131 }
3132
3133 if (ret == -1 || str[2] != '\0')
3134 return -1;
3135 return ret;
3136}
3137
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003138/* hash a 32-bit integer to another 32-bit integer */
3139unsigned int full_hash(unsigned int a)
3140{
3141 return __full_hash(a);
3142}
3143
Willy Tarreauf3241112019-02-26 09:56:22 +01003144/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3145 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3146 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3147 * a popcount variant and is described here :
3148 * https://graphics.stanford.edu/~seander/bithacks.html
3149 */
3150unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3151{
3152 unsigned long a, b, c, d;
3153 unsigned int s;
3154 unsigned int t;
3155
3156 a = m - ((m >> 1) & ~0UL/3);
3157 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3158 c = (b + (b >> 4)) & ~0UL/0x11;
3159 d = (c + (c >> 8)) & ~0UL/0x101;
3160
3161 r++; // make r be 1..64
3162
3163 t = 0;
3164 s = LONGBITS;
3165 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003166 unsigned long d2 = (d >> 16) >> 16;
3167 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003168 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3169 }
3170
3171 t = (d >> (s - 16)) & 0xff;
3172 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3173 t = (c >> (s - 8)) & 0xf;
3174 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3175 t = (b >> (s - 4)) & 0x7;
3176 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3177 t = (a >> (s - 2)) & 0x3;
3178 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3179 t = (m >> (s - 1)) & 0x1;
3180 s -= ((t - r) & 256) >> 8;
3181
3182 return s - 1;
3183}
3184
3185/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3186 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3187 * using mask_prep_rank_map() below.
3188 */
3189unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3190 unsigned long a, unsigned long b,
3191 unsigned long c, unsigned long d)
3192{
3193 unsigned int s;
3194 unsigned int t;
3195
3196 r++; // make r be 1..64
3197
3198 t = 0;
3199 s = LONGBITS;
3200 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003201 unsigned long d2 = (d >> 16) >> 16;
3202 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003203 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3204 }
3205
3206 t = (d >> (s - 16)) & 0xff;
3207 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3208 t = (c >> (s - 8)) & 0xf;
3209 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3210 t = (b >> (s - 4)) & 0x7;
3211 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3212 t = (a >> (s - 2)) & 0x3;
3213 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3214 t = (m >> (s - 1)) & 0x1;
3215 s -= ((t - r) & 256) >> 8;
3216
3217 return s - 1;
3218}
3219
3220/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3221 * above.
3222 */
3223void mask_prep_rank_map(unsigned long m,
3224 unsigned long *a, unsigned long *b,
3225 unsigned long *c, unsigned long *d)
3226{
3227 *a = m - ((m >> 1) & ~0UL/3);
3228 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3229 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3230 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3231}
3232
Willy Tarreauc7a8a3c2022-06-21 20:19:54 +02003233/* Returns the position of one bit set in <v>, starting at position <bit>, and
3234 * searching in other halves if not found. This is intended to be used to
3235 * report the position of one bit set among several based on a counter or a
3236 * random generator while preserving a relatively good distribution so that
3237 * values made of holes in the middle do not see one of the bits around the
3238 * hole being returned much more often than the other one. It can be seen as a
3239 * disturbed ffsl() where the initial search starts at bit <bit>. The look up
3240 * is performed in O(logN) time for N bit words, yielding a bit among 64 in
3241 * about 16 cycles. Its usage differs from the rank find function in that the
3242 * bit passed doesn't need to be limited to the value's popcount, making the
3243 * function easier to use for random picking, and twice as fast. Passing value
3244 * 0 for <v> makes no sense and -1 is returned in this case.
3245 */
3246int one_among_mask(unsigned long v, int bit)
3247{
3248 /* note, these masks may be produced by ~0UL/((1UL<<scale)+1) but
3249 * that's more expensive.
3250 */
3251 static const unsigned long halves[] = {
3252 (unsigned long)0x5555555555555555ULL,
3253 (unsigned long)0x3333333333333333ULL,
3254 (unsigned long)0x0F0F0F0F0F0F0F0FULL,
3255 (unsigned long)0x00FF00FF00FF00FFULL,
3256 (unsigned long)0x0000FFFF0000FFFFULL,
3257 (unsigned long)0x00000000FFFFFFFFULL
3258 };
3259 unsigned long halfword = ~0UL;
3260 int scope = 0;
3261 int mirror;
3262 int scale;
3263
3264 if (!v)
3265 return -1;
3266
3267 /* we check if the exact bit is set or if it's present in a mirror
3268 * position based on the current scale we're checking, in which case
3269 * it's returned with its current (or mirrored) value. Otherwise we'll
3270 * make sure there's at least one bit in the half we're in, and will
3271 * scale down to a smaller scope and try again, until we find the
3272 * closest bit.
3273 */
3274 for (scale = (sizeof(long) > 4) ? 5 : 4; scale >= 0; scale--) {
3275 halfword >>= (1UL << scale);
3276 scope |= (1UL << scale);
3277 mirror = bit ^ (1UL << scale);
3278 if (v & ((1UL << bit) | (1UL << mirror)))
3279 return (v & (1UL << bit)) ? bit : mirror;
3280
3281 if (!((v >> (bit & scope)) & halves[scale] & halfword))
3282 bit = mirror;
3283 }
3284 return bit;
3285}
3286
David du Colombier4f92d322011-03-24 11:09:31 +01003287/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003288 * otherwise zero. Note that <addr> may not necessarily be aligned
3289 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003290 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003291int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003292{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003293 struct in_addr addr_copy;
3294
3295 memcpy(&addr_copy, addr, sizeof(addr_copy));
3296 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003297}
3298
3299/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003300 * otherwise zero. Note that <addr> may not necessarily be aligned
3301 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003302 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003303int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003304{
3305 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003306 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003307
Willy Tarreaueec1d382016-07-13 11:59:39 +02003308 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003309 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003310 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003311 (((int *)net)[i] & ((int *)mask)[i]))
3312 return 0;
3313 return 1;
3314}
3315
3316/* RFC 4291 prefix */
3317const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3318 0x00, 0x00, 0x00, 0x00,
3319 0x00, 0x00, 0xFF, 0xFF };
3320
Joseph Herlant32b83272018-11-15 11:58:28 -08003321/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003322 * Input and output may overlap.
3323 */
David du Colombier4f92d322011-03-24 11:09:31 +01003324void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3325{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003326 struct in_addr tmp_addr;
3327
3328 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003329 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003330 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003331}
3332
Joseph Herlant32b83272018-11-15 11:58:28 -08003333/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003334 * Return true if conversion is possible and false otherwise.
3335 */
3336int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3337{
3338 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3339 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3340 sizeof(struct in_addr));
3341 return 1;
3342 }
3343
3344 return 0;
3345}
3346
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003347/* compare two struct sockaddr_storage and return:
3348 * 0 (true) if the addr is the same in both
3349 * 1 (false) if the addr is not the same in both
3350 * -1 (unable) if one of the addr is not AF_INET*
3351 */
3352int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3353{
3354 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3355 return -1;
3356
3357 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3358 return -1;
3359
3360 if (ss1->ss_family != ss2->ss_family)
3361 return 1;
3362
3363 switch (ss1->ss_family) {
3364 case AF_INET:
3365 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3366 &((struct sockaddr_in *)ss2)->sin_addr,
3367 sizeof(struct in_addr)) != 0;
3368 case AF_INET6:
3369 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3370 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3371 sizeof(struct in6_addr)) != 0;
3372 }
3373
3374 return 1;
3375}
3376
Christopher Faulet9553de72021-02-26 09:12:50 +01003377/* compare a struct sockaddr_storage to a struct net_addr and return :
3378 * 0 (true) if <addr> is matching <net>
3379 * 1 (false) if <addr> is not matching <net>
3380 * -1 (unable) if <addr> or <net> is not AF_INET*
3381 */
3382int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3383{
3384 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3385 return -1;
3386
3387 if ((net->family != AF_INET) && (net->family != AF_INET6))
3388 return -1;
3389
3390 if (addr->ss_family != net->family)
3391 return 1;
3392
3393 if (addr->ss_family == AF_INET &&
3394 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3395 return 0;
3396 else {
3397 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3398 const struct in6_addr *nip6 = &net->addr.v6.ip;
3399 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3400
3401 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3402 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3403 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3404 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3405 return 0;
3406 }
3407
3408 return 1;
3409}
3410
Baptiste Assmann08396c82016-01-31 00:27:17 +01003411/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003412 * The caller must allocate and clear <dest> before calling.
3413 * The source must be in either AF_INET or AF_INET6 family, or the destination
3414 * address will be undefined. If the destination address used to hold a port,
3415 * it is preserved, so that this function can be used to switch to another
3416 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003417 */
3418struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3419{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003420 int prev_port;
3421
3422 prev_port = get_net_port(dest);
3423 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003424 dest->ss_family = source->ss_family;
3425
3426 /* copy new addr and apply it */
3427 switch (source->ss_family) {
3428 case AF_INET:
3429 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003430 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003431 break;
3432 case AF_INET6:
3433 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 +01003434 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003435 break;
3436 }
3437
3438 return dest;
3439}
3440
William Lallemand421f5b52012-02-06 18:15:57 +01003441char *human_time(int t, short hz_div) {
3442 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3443 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003444 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003445 int cnt=2; // print two numbers
3446
3447 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003448 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003449 return rv;
3450 }
3451
3452 if (unlikely(hz_div > 1))
3453 t /= hz_div;
3454
3455 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003456 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003457 cnt--;
3458 }
3459
3460 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003461 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003462 cnt--;
3463 }
3464
3465 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003466 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003467 cnt--;
3468 }
3469
3470 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003471 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003472
3473 return rv;
3474}
3475
3476const char *monthname[12] = {
3477 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3478 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3479};
3480
3481/* date2str_log: write a date in the format :
3482 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3483 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3484 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3485 *
3486 * without using sprintf. return a pointer to the last char written (\0) or
3487 * NULL if there isn't enough space.
3488 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003489char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003490{
3491
3492 if (size < 25) /* the size is fixed: 24 chars + \0 */
3493 return NULL;
3494
3495 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003496 if (!dst)
3497 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003498 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003499
William Lallemand421f5b52012-02-06 18:15:57 +01003500 memcpy(dst, monthname[tm->tm_mon], 3); // month
3501 dst += 3;
3502 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003503
William Lallemand421f5b52012-02-06 18:15:57 +01003504 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003505 if (!dst)
3506 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003507 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003508
William Lallemand421f5b52012-02-06 18:15:57 +01003509 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003510 if (!dst)
3511 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003512 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003513
William Lallemand421f5b52012-02-06 18:15:57 +01003514 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003515 if (!dst)
3516 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003517 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003518
William Lallemand421f5b52012-02-06 18:15:57 +01003519 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003520 if (!dst)
3521 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003522 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003523
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003524 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003525 if (!dst)
3526 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003527 *dst = '\0';
3528
3529 return dst;
3530}
3531
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003532/* Base year used to compute leap years */
3533#define TM_YEAR_BASE 1900
3534
3535/* Return the difference in seconds between two times (leap seconds are ignored).
3536 * Retrieved from glibc 2.18 source code.
3537 */
3538static int my_tm_diff(const struct tm *a, const struct tm *b)
3539{
3540 /* Compute intervening leap days correctly even if year is negative.
3541 * Take care to avoid int overflow in leap day calculations,
3542 * but it's OK to assume that A and B are close to each other.
3543 */
3544 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3545 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3546 int a100 = a4 / 25 - (a4 % 25 < 0);
3547 int b100 = b4 / 25 - (b4 % 25 < 0);
3548 int a400 = a100 >> 2;
3549 int b400 = b100 >> 2;
3550 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3551 int years = a->tm_year - b->tm_year;
3552 int days = (365 * years + intervening_leap_days
3553 + (a->tm_yday - b->tm_yday));
3554 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3555 + (a->tm_min - b->tm_min))
3556 + (a->tm_sec - b->tm_sec));
3557}
3558
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003559/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003560 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003561 * The string returned has the same format as returned by strftime(... "%z", tm).
3562 * Offsets are kept in an internal cache for better performances.
3563 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003564const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003565{
3566 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003567 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003568
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003569 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003570 struct tm tm_gmt;
3571 int diff;
3572 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003573
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003574 /* Pretend DST not active if its status is unknown */
3575 if (isdst < 0)
3576 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003577
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003578 /* Fetch the offset and initialize it if needed */
3579 gmt_offset = gmt_offsets[isdst & 0x01];
3580 if (unlikely(!*gmt_offset)) {
3581 get_gmtime(t, &tm_gmt);
3582 diff = my_tm_diff(tm, &tm_gmt);
3583 if (diff < 0) {
3584 diff = -diff;
3585 *gmt_offset = '-';
3586 } else {
3587 *gmt_offset = '+';
3588 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003589 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003590 diff /= 60; /* Convert to minutes */
3591 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3592 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003593
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003594 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003595}
3596
William Lallemand421f5b52012-02-06 18:15:57 +01003597/* gmt2str_log: write a date in the format :
3598 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3599 * return a pointer to the last char written (\0) or
3600 * NULL if there isn't enough space.
3601 */
3602char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3603{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003604 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003605 return NULL;
3606
3607 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003608 if (!dst)
3609 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003610 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003611
William Lallemand421f5b52012-02-06 18:15:57 +01003612 memcpy(dst, monthname[tm->tm_mon], 3); // month
3613 dst += 3;
3614 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003615
William Lallemand421f5b52012-02-06 18:15:57 +01003616 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003617 if (!dst)
3618 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003619 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003620
William Lallemand421f5b52012-02-06 18:15:57 +01003621 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003622 if (!dst)
3623 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003624 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003625
William Lallemand421f5b52012-02-06 18:15:57 +01003626 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003627 if (!dst)
3628 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003629 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003630
William Lallemand421f5b52012-02-06 18:15:57 +01003631 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003632 if (!dst)
3633 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003634 *dst++ = ' ';
3635 *dst++ = '+';
3636 *dst++ = '0';
3637 *dst++ = '0';
3638 *dst++ = '0';
3639 *dst++ = '0';
3640 *dst = '\0';
3641
3642 return dst;
3643}
3644
Yuxans Yao4e25b012012-10-19 10:36:09 +08003645/* localdate2str_log: write a date in the format :
3646 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003647 * Both t and tm must represent the same time.
3648 * return a pointer to the last char written (\0) or
3649 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003650 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003651char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003652{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003653 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003654 if (size < 27) /* the size is fixed: 26 chars + \0 */
3655 return NULL;
3656
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003657 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003658
Yuxans Yao4e25b012012-10-19 10:36:09 +08003659 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003660 if (!dst)
3661 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003662 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003663
Yuxans Yao4e25b012012-10-19 10:36:09 +08003664 memcpy(dst, monthname[tm->tm_mon], 3); // month
3665 dst += 3;
3666 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003667
Yuxans Yao4e25b012012-10-19 10:36:09 +08003668 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003669 if (!dst)
3670 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003671 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003672
Yuxans Yao4e25b012012-10-19 10:36:09 +08003673 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003674 if (!dst)
3675 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003676 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003677
Yuxans Yao4e25b012012-10-19 10:36:09 +08003678 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003679 if (!dst)
3680 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003681 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003682
Yuxans Yao4e25b012012-10-19 10:36:09 +08003683 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003684 if (!dst)
3685 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003686 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003687
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003688 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003689 dst += 5;
3690 *dst = '\0';
3691
3692 return dst;
3693}
3694
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003695/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3696 * It is meant as a portable replacement for timegm() for use with valid inputs.
3697 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3698 */
3699time_t my_timegm(const struct tm *tm)
3700{
3701 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3702 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3703 * sum of the extra N days for elapsed months. The sum of all these N
3704 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3705 * in a 5-bit word. This means that with 60 bits we can represent a
3706 * matrix of all these values at once, which is fast and efficient to
3707 * access. The extra February day for leap years is not counted here.
3708 *
3709 * Jan : none = 0 (0)
3710 * Feb : Jan = 3 (3)
3711 * Mar : Jan..Feb = 3 (3 + 0)
3712 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3713 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3714 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3715 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3716 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3717 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3718 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3719 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3720 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3721 */
3722 uint64_t extra =
3723 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3724 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3725 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3726 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3727
3728 unsigned int y = tm->tm_year + 1900;
3729 unsigned int m = tm->tm_mon;
3730 unsigned long days = 0;
3731
3732 /* days since 1/1/1970 for full years */
3733 days += days_since_zero(y) - days_since_zero(1970);
3734
3735 /* days for full months in the current year */
3736 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3737
3738 /* count + 1 after March for leap years. A leap year is a year multiple
3739 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3740 * is leap, 1900 isn't, 1904 is.
3741 */
3742 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3743 days++;
3744
3745 days += tm->tm_mday - 1;
3746 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3747}
3748
Thierry Fournier93127942016-01-20 18:49:45 +01003749/* This function check a char. It returns true and updates
3750 * <date> and <len> pointer to the new position if the
3751 * character is found.
3752 */
3753static inline int parse_expect_char(const char **date, int *len, char c)
3754{
3755 if (*len < 1 || **date != c)
3756 return 0;
3757 (*len)--;
3758 (*date)++;
3759 return 1;
3760}
3761
3762/* This function expects a string <str> of len <l>. It return true and updates.
3763 * <date> and <len> if the string matches, otherwise, it returns false.
3764 */
3765static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3766{
3767 if (*len < l || strncmp(*date, str, l) != 0)
3768 return 0;
3769 (*len) -= l;
3770 (*date) += l;
3771 return 1;
3772}
3773
3774/* This macro converts 3 chars name in integer. */
3775#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3776
3777/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3778 * / %x54.75.65 ; "Tue", case-sensitive
3779 * / %x57.65.64 ; "Wed", case-sensitive
3780 * / %x54.68.75 ; "Thu", case-sensitive
3781 * / %x46.72.69 ; "Fri", case-sensitive
3782 * / %x53.61.74 ; "Sat", case-sensitive
3783 * / %x53.75.6E ; "Sun", case-sensitive
3784 *
3785 * This array must be alphabetically sorted
3786 */
3787static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3788{
3789 if (*len < 3)
3790 return 0;
3791 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3792 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3793 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3794 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3795 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3796 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3797 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3798 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3799 default: return 0;
3800 }
3801 *len -= 3;
3802 *date += 3;
3803 return 1;
3804}
3805
3806/* month = %x4A.61.6E ; "Jan", case-sensitive
3807 * / %x46.65.62 ; "Feb", case-sensitive
3808 * / %x4D.61.72 ; "Mar", case-sensitive
3809 * / %x41.70.72 ; "Apr", case-sensitive
3810 * / %x4D.61.79 ; "May", case-sensitive
3811 * / %x4A.75.6E ; "Jun", case-sensitive
3812 * / %x4A.75.6C ; "Jul", case-sensitive
3813 * / %x41.75.67 ; "Aug", case-sensitive
3814 * / %x53.65.70 ; "Sep", case-sensitive
3815 * / %x4F.63.74 ; "Oct", case-sensitive
3816 * / %x4E.6F.76 ; "Nov", case-sensitive
3817 * / %x44.65.63 ; "Dec", case-sensitive
3818 *
3819 * This array must be alphabetically sorted
3820 */
3821static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3822{
3823 if (*len < 3)
3824 return 0;
3825 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3826 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3827 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3828 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3829 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3830 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3831 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3832 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3833 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3834 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3835 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3836 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3837 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3838 default: return 0;
3839 }
3840 *len -= 3;
3841 *date += 3;
3842 return 1;
3843}
3844
3845/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3846 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3847 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3848 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3849 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3850 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3851 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3852 *
3853 * This array must be alphabetically sorted
3854 */
3855static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3856{
3857 if (*len < 6) /* Minimum length. */
3858 return 0;
3859 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3860 case STR2I3('M','o','n'):
3861 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3862 tm->tm_wday = 1;
3863 return 1;
3864 case STR2I3('T','u','e'):
3865 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3866 tm->tm_wday = 2;
3867 return 1;
3868 case STR2I3('W','e','d'):
3869 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3870 tm->tm_wday = 3;
3871 return 1;
3872 case STR2I3('T','h','u'):
3873 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3874 tm->tm_wday = 4;
3875 return 1;
3876 case STR2I3('F','r','i'):
3877 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3878 tm->tm_wday = 5;
3879 return 1;
3880 case STR2I3('S','a','t'):
3881 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3882 tm->tm_wday = 6;
3883 return 1;
3884 case STR2I3('S','u','n'):
3885 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3886 tm->tm_wday = 7;
3887 return 1;
3888 }
3889 return 0;
3890}
3891
3892/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3893static inline int parse_digit(const char **date, int *len, int *digit)
3894{
3895 if (*len < 1 || **date < '0' || **date > '9')
3896 return 0;
3897 *digit = (**date - '0');
3898 (*date)++;
3899 (*len)--;
3900 return 1;
3901}
3902
3903/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3904static inline int parse_2digit(const char **date, int *len, int *digit)
3905{
3906 int value;
3907
3908 RET0_UNLESS(parse_digit(date, len, &value));
3909 (*digit) = value * 10;
3910 RET0_UNLESS(parse_digit(date, len, &value));
3911 (*digit) += value;
3912
3913 return 1;
3914}
3915
3916/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3917static inline int parse_4digit(const char **date, int *len, int *digit)
3918{
3919 int value;
3920
3921 RET0_UNLESS(parse_digit(date, len, &value));
3922 (*digit) = value * 1000;
3923
3924 RET0_UNLESS(parse_digit(date, len, &value));
3925 (*digit) += value * 100;
3926
3927 RET0_UNLESS(parse_digit(date, len, &value));
3928 (*digit) += value * 10;
3929
3930 RET0_UNLESS(parse_digit(date, len, &value));
3931 (*digit) += value;
3932
3933 return 1;
3934}
3935
3936/* time-of-day = hour ":" minute ":" second
3937 * ; 00:00:00 - 23:59:60 (leap second)
3938 *
3939 * hour = 2DIGIT
3940 * minute = 2DIGIT
3941 * second = 2DIGIT
3942 */
3943static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3944{
3945 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3946 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3947 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3948 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3949 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3950 return 1;
3951}
3952
3953/* From RFC7231
3954 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3955 *
3956 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3957 * ; fixed length/zone/capitalization subset of the format
3958 * ; see Section 3.3 of [RFC5322]
3959 *
3960 *
3961 * date1 = day SP month SP year
3962 * ; e.g., 02 Jun 1982
3963 *
3964 * day = 2DIGIT
3965 * year = 4DIGIT
3966 *
3967 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3968 *
3969 * time-of-day = hour ":" minute ":" second
3970 * ; 00:00:00 - 23:59:60 (leap second)
3971 *
3972 * hour = 2DIGIT
3973 * minute = 2DIGIT
3974 * second = 2DIGIT
3975 *
3976 * DIGIT = decimal 0-9
3977 */
3978int parse_imf_date(const char *date, int len, struct tm *tm)
3979{
David Carlier327298c2016-11-20 10:42:38 +00003980 /* tm_gmtoff, if present, ought to be zero'ed */
3981 memset(tm, 0, sizeof(*tm));
3982
Thierry Fournier93127942016-01-20 18:49:45 +01003983 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3984 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3985 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3986 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3987 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3988 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3989 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3990 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3991 tm->tm_year -= 1900;
3992 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3993 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3994 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3995 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3996 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003997 return 1;
3998}
3999
4000/* From RFC7231
4001 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4002 *
4003 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
4004 * date2 = day "-" month "-" 2DIGIT
4005 * ; e.g., 02-Jun-82
4006 *
4007 * day = 2DIGIT
4008 */
4009int parse_rfc850_date(const char *date, int len, struct tm *tm)
4010{
4011 int year;
4012
David Carlier327298c2016-11-20 10:42:38 +00004013 /* tm_gmtoff, if present, ought to be zero'ed */
4014 memset(tm, 0, sizeof(*tm));
4015
Thierry Fournier93127942016-01-20 18:49:45 +01004016 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
4017 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
4018 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4019 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
4020 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
4021 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
4022 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
4023
4024 /* year = 2DIGIT
4025 *
4026 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
4027 * two-digit year, MUST interpret a timestamp that appears to be more
4028 * than 50 years in the future as representing the most recent year in
4029 * the past that had the same last two digits.
4030 */
4031 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
4032
4033 /* expect SP */
4034 if (!parse_expect_char(&date, &len, ' ')) {
4035 /* Maybe we have the date with 4 digits. */
4036 RET0_UNLESS(parse_2digit(&date, &len, &year));
4037 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
4038 /* expect SP */
4039 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
4040 } else {
4041 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
4042 * tm_year is the number of year since 1900, so for +1900, we
4043 * do nothing, and for +2000, we add 100.
4044 */
4045 if (tm->tm_year <= 60)
4046 tm->tm_year += 100;
4047 }
4048
4049 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4050 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4051 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
4052 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004053
4054 return 1;
4055}
4056
4057/* From RFC7231
4058 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4059 *
4060 * asctime-date = day-name SP date3 SP time-of-day SP year
4061 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
4062 * ; e.g., Jun 2
4063 *
4064 * HTTP-date is case sensitive. A sender MUST NOT generate additional
4065 * whitespace in an HTTP-date beyond that specifically included as SP in
4066 * the grammar.
4067 */
4068int parse_asctime_date(const char *date, int len, struct tm *tm)
4069{
David Carlier327298c2016-11-20 10:42:38 +00004070 /* tm_gmtoff, if present, ought to be zero'ed */
4071 memset(tm, 0, sizeof(*tm));
4072
Thierry Fournier93127942016-01-20 18:49:45 +01004073 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
4074 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4075 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
4076 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4077
4078 /* expect SP and 1DIGIT or 2DIGIT */
4079 if (parse_expect_char(&date, &len, ' '))
4080 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
4081 else
4082 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
4083
4084 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4085 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
4086 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
4087 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
4088 tm->tm_year -= 1900;
4089 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01004090 return 1;
4091}
4092
4093/* From RFC7231
4094 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
4095 *
4096 * HTTP-date = IMF-fixdate / obs-date
4097 * obs-date = rfc850-date / asctime-date
4098 *
4099 * parses an HTTP date in the RFC format and is accepted
4100 * alternatives. <date> is the strinf containing the date,
4101 * len is the len of the string. <tm> is filled with the
4102 * parsed time. We must considers this time as GMT.
4103 */
4104int parse_http_date(const char *date, int len, struct tm *tm)
4105{
4106 if (parse_imf_date(date, len, tm))
4107 return 1;
4108
4109 if (parse_rfc850_date(date, len, tm))
4110 return 1;
4111
4112 if (parse_asctime_date(date, len, tm))
4113 return 1;
4114
4115 return 0;
4116}
4117
Willy Tarreau4deeb102021-01-29 10:47:52 +01004118/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
4119 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
4120 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
4121 * surrounded by <pfx> and <sfx> respectively if not NULL.
4122 */
4123int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
4124{
4125 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
4126 const char *unit;
4127
4128 if (!pfx)
4129 pfx = "";
4130 if (!sfx)
4131 sfx = "";
4132
4133 do {
4134 unit = " - "; if (val <= 0.0) break;
4135 unit = "ns"; if (val < 1000.0) break;
4136 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
4137 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
4138 unit = "s "; val /= 1000.0; if (val < 60.0) break;
4139 unit = "m "; val /= 60.0; if (val < 60.0) break;
4140 unit = "h "; val /= 60.0; if (val < 24.0) break;
4141 unit = "d "; val /= 24.0; if (val < 365.0) break;
4142 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
4143 unit = " inf "; val = 0.0; break;
4144 } while (0);
4145
4146 if (val <= 0.0)
4147 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
4148 else if (val < 10.0)
4149 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
4150 else if (val < 100.0)
4151 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
4152 else
4153 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4154}
4155
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004156/* Dynamically allocates a string of the proper length to hold the formatted
4157 * output. NULL is returned on error. The caller is responsible for freeing the
4158 * memory area using free(). The resulting string is returned in <out> if the
4159 * pointer is not NULL. A previous version of <out> might be used to build the
4160 * new string, and it will be freed before returning if it is not NULL, which
4161 * makes it possible to build complex strings from iterative calls without
4162 * having to care about freeing intermediate values, as in the example below :
4163 *
4164 * memprintf(&err, "invalid argument: '%s'", arg);
4165 * ...
4166 * memprintf(&err, "parser said : <%s>\n", *err);
4167 * ...
4168 * free(*err);
4169 *
4170 * This means that <err> must be initialized to NULL before first invocation.
4171 * The return value also holds the allocated string, which eases error checking
4172 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004173 * passed instead and it will be ignored. The returned message will then also
4174 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004175 *
4176 * It is also convenient to use it without any free except the last one :
4177 * err = NULL;
4178 * if (!fct1(err)) report(*err);
4179 * if (!fct2(err)) report(*err);
4180 * if (!fct3(err)) report(*err);
4181 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004182 *
4183 * memprintf relies on memvprintf. This last version can be called from any
4184 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004185 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004186char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004187{
4188 va_list args;
4189 char *ret = NULL;
4190 int allocated = 0;
4191 int needed = 0;
4192
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004193 if (!out)
4194 return NULL;
4195
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004196 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004197 char buf1;
4198
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004199 /* vsnprintf() will return the required length even when the
4200 * target buffer is NULL. We do this in a loop just in case
4201 * intermediate evaluations get wrong.
4202 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004203 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004204 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004205 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004206 if (needed < allocated) {
4207 /* Note: on Solaris 8, the first iteration always
4208 * returns -1 if allocated is zero, so we force a
4209 * retry.
4210 */
4211 if (!allocated)
4212 needed = 0;
4213 else
4214 break;
4215 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004216
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004217 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004218 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004219 } while (ret);
4220
4221 if (needed < 0) {
4222 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004223 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004224 }
4225
4226 if (out) {
4227 free(*out);
4228 *out = ret;
4229 }
4230
4231 return ret;
4232}
William Lallemand421f5b52012-02-06 18:15:57 +01004233
Christopher Faulet93a518f2017-10-24 11:25:33 +02004234char *memprintf(char **out, const char *format, ...)
4235{
4236 va_list args;
4237 char *ret = NULL;
4238
4239 va_start(args, format);
4240 ret = memvprintf(out, format, args);
4241 va_end(args);
4242
4243 return ret;
4244}
4245
Willy Tarreau21c705b2012-09-14 11:40:36 +02004246/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4247 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004248 * freed by the caller. It also supports being passed a NULL which results in the same
4249 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004250 * Example of use :
4251 * parse(cmd, &err); (callee: memprintf(&err, ...))
4252 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4253 * free(err);
4254 */
4255char *indent_msg(char **out, int level)
4256{
4257 char *ret, *in, *p;
4258 int needed = 0;
4259 int lf = 0;
4260 int lastlf = 0;
4261 int len;
4262
Willy Tarreau70eec382012-10-10 08:56:47 +02004263 if (!out || !*out)
4264 return NULL;
4265
Willy Tarreau21c705b2012-09-14 11:40:36 +02004266 in = *out - 1;
4267 while ((in = strchr(in + 1, '\n')) != NULL) {
4268 lastlf = in - *out;
4269 lf++;
4270 }
4271
4272 if (!lf) /* single line, no LF, return it as-is */
4273 return *out;
4274
4275 len = strlen(*out);
4276
4277 if (lf == 1 && lastlf == len - 1) {
4278 /* single line, LF at end, strip it and return as-is */
4279 (*out)[lastlf] = 0;
4280 return *out;
4281 }
4282
4283 /* OK now we have at least one LF, we need to process the whole string
4284 * as a multi-line string. What we'll do :
4285 * - prefix with an LF if there is none
4286 * - add <level> spaces before each line
4287 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4288 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4289 */
4290
4291 needed = 1 + level * (lf + 1) + len + 1;
4292 p = ret = malloc(needed);
4293 in = *out;
4294
4295 /* skip initial LFs */
4296 while (*in == '\n')
4297 in++;
4298
4299 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4300 while (*in) {
4301 *p++ = '\n';
4302 memset(p, ' ', level);
4303 p += level;
4304 do {
4305 *p++ = *in++;
4306 } while (*in && *in != '\n');
4307 if (*in)
4308 in++;
4309 }
4310 *p = 0;
4311
4312 free(*out);
4313 *out = ret;
4314
4315 return ret;
4316}
4317
Willy Tarreaua2c99112019-08-21 13:17:37 +02004318/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4319 * and end of lines replaced with <eol> if not 0. The first line to indent has
4320 * to be indicated in <first> (starts at zero), so that it is possible to skip
4321 * indenting the first line if it has to be appended after an existing message.
4322 * Empty strings are never indented, and NULL strings are considered empty both
4323 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4324 * character, non-zero otherwise.
4325 */
4326int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4327{
4328 int bol, lf;
4329 int pfxlen = pfx ? strlen(pfx) : 0;
4330
4331 if (!in)
4332 return 0;
4333
4334 bol = 1;
4335 lf = 0;
4336 while (*in) {
4337 if (bol && pfxlen) {
4338 if (first > 0)
4339 first--;
4340 else
4341 b_putblk(out, pfx, pfxlen);
4342 bol = 0;
4343 }
4344
4345 lf = (*in == '\n');
4346 bol |= lf;
4347 b_putchr(out, (lf && eol) ? eol : *in);
4348 in++;
4349 }
4350 return lf;
4351}
4352
Willy Tarreau9d22e562019-03-29 18:49:09 +01004353/* removes environment variable <name> from the environment as found in
4354 * environ. This is only provided as an alternative for systems without
4355 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004356 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004357 * <name> and to replace the matching pointers with the last pointer of
4358 * the array (since variables are not ordered).
4359 * It always returns 0 (success).
4360 */
4361int my_unsetenv(const char *name)
4362{
4363 extern char **environ;
4364 char **p = environ;
4365 int vars;
4366 int next;
4367 int len;
4368
4369 len = strlen(name);
4370 for (vars = 0; p[vars]; vars++)
4371 ;
4372 next = 0;
4373 while (next < vars) {
4374 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4375 next++;
4376 continue;
4377 }
4378 if (next < vars - 1)
4379 p[next] = p[vars - 1];
4380 p[--vars] = NULL;
4381 }
4382 return 0;
4383}
4384
Willy Tarreaudad36a32013-03-11 01:20:04 +01004385/* Convert occurrences of environment variables in the input string to their
4386 * corresponding value. A variable is identified as a series of alphanumeric
4387 * characters or underscores following a '$' sign. The <in> string must be
4388 * free()able. NULL returns NULL. The resulting string might be reallocated if
4389 * some expansion is made. Variable names may also be enclosed into braces if
4390 * needed (eg: to concatenate alphanum characters).
4391 */
4392char *env_expand(char *in)
4393{
4394 char *txt_beg;
4395 char *out;
4396 char *txt_end;
4397 char *var_beg;
4398 char *var_end;
4399 char *value;
4400 char *next;
4401 int out_len;
4402 int val_len;
4403
4404 if (!in)
4405 return in;
4406
4407 value = out = NULL;
4408 out_len = 0;
4409
4410 txt_beg = in;
4411 do {
4412 /* look for next '$' sign in <in> */
4413 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4414
4415 if (!*txt_end && !out) /* end and no expansion performed */
4416 return in;
4417
4418 val_len = 0;
4419 next = txt_end;
4420 if (*txt_end == '$') {
4421 char save;
4422
4423 var_beg = txt_end + 1;
4424 if (*var_beg == '{')
4425 var_beg++;
4426
4427 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004428 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004429 var_end++;
4430 }
4431
4432 next = var_end;
4433 if (*var_end == '}' && (var_beg > txt_end + 1))
4434 next++;
4435
4436 /* get value of the variable name at this location */
4437 save = *var_end;
4438 *var_end = '\0';
4439 value = getenv(var_beg);
4440 *var_end = save;
4441 val_len = value ? strlen(value) : 0;
4442 }
4443
Hubert Verstraete831962e2016-06-28 22:44:26 +02004444 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004445 if (txt_end > txt_beg) {
4446 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4447 out_len += txt_end - txt_beg;
4448 }
4449 if (val_len) {
4450 memcpy(out + out_len, value, val_len);
4451 out_len += val_len;
4452 }
4453 out[out_len] = 0;
4454 txt_beg = next;
4455 } while (*txt_beg);
4456
4457 /* here we know that <out> was allocated and that we don't need <in> anymore */
4458 free(in);
4459 return out;
4460}
4461
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004462
4463/* same as strstr() but case-insensitive and with limit length */
4464const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4465{
4466 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004467 unsigned int slen, plen;
4468 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004469
4470 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4471 return NULL;
4472
4473 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4474 return str1;
4475
4476 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4477 return NULL;
4478
4479 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 +02004480 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004481 start++;
4482 slen--;
4483 tmp1++;
4484
4485 if (tmp1 >= len_str1)
4486 return NULL;
4487
4488 /* if pattern longer than string */
4489 if (slen < plen)
4490 return NULL;
4491 }
4492
4493 sptr = start;
4494 pptr = (char *)str2;
4495
4496 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004497 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004498 sptr++;
4499 pptr++;
4500 tmp2++;
4501
4502 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4503 return start;
4504 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4505 return NULL;
4506 }
4507 }
4508 return NULL;
4509}
4510
Willy Tarreau3ff476e2022-03-30 10:02:56 +02004511/* Returns true if s1 < s2 < s3 otherwise zero. Both s1 and s3 may be NULL and
4512 * in this case only non-null strings are compared. This allows to pass initial
4513 * values in iterators and in sort functions.
4514 */
4515int strordered(const char *s1, const char *s2, const char *s3)
4516{
4517 return (!s1 || strcmp(s1, s2) < 0) && (!s3 || strcmp(s2, s3) < 0);
4518}
4519
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004520/* This function read the next valid utf8 char.
4521 * <s> is the byte srray to be decode, <len> is its length.
4522 * The function returns decoded char encoded like this:
4523 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4524 * are the length read. The decoded character is stored in <c>.
4525 */
4526unsigned char utf8_next(const char *s, int len, unsigned int *c)
4527{
4528 const unsigned char *p = (unsigned char *)s;
4529 int dec;
4530 unsigned char code = UTF8_CODE_OK;
4531
4532 if (len < 1)
4533 return UTF8_CODE_OK;
4534
4535 /* Check the type of UTF8 sequence
4536 *
4537 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4538 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4539 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4540 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4541 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4542 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4543 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4544 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4545 */
4546 switch (*p) {
4547 case 0x00 ... 0x7f:
4548 *c = *p;
4549 return UTF8_CODE_OK | 1;
4550
4551 case 0x80 ... 0xbf:
4552 *c = *p;
4553 return UTF8_CODE_BADSEQ | 1;
4554
4555 case 0xc0 ... 0xdf:
4556 if (len < 2) {
4557 *c = *p;
4558 return UTF8_CODE_BADSEQ | 1;
4559 }
4560 *c = *p & 0x1f;
4561 dec = 1;
4562 break;
4563
4564 case 0xe0 ... 0xef:
4565 if (len < 3) {
4566 *c = *p;
4567 return UTF8_CODE_BADSEQ | 1;
4568 }
4569 *c = *p & 0x0f;
4570 dec = 2;
4571 break;
4572
4573 case 0xf0 ... 0xf7:
4574 if (len < 4) {
4575 *c = *p;
4576 return UTF8_CODE_BADSEQ | 1;
4577 }
4578 *c = *p & 0x07;
4579 dec = 3;
4580 break;
4581
4582 case 0xf8 ... 0xfb:
4583 if (len < 5) {
4584 *c = *p;
4585 return UTF8_CODE_BADSEQ | 1;
4586 }
4587 *c = *p & 0x03;
4588 dec = 4;
4589 break;
4590
4591 case 0xfc ... 0xfd:
4592 if (len < 6) {
4593 *c = *p;
4594 return UTF8_CODE_BADSEQ | 1;
4595 }
4596 *c = *p & 0x01;
4597 dec = 5;
4598 break;
4599
4600 case 0xfe ... 0xff:
4601 default:
4602 *c = *p;
4603 return UTF8_CODE_BADSEQ | 1;
4604 }
4605
4606 p++;
4607
4608 while (dec > 0) {
4609
4610 /* need 0x10 for the 2 first bits */
4611 if ( ( *p & 0xc0 ) != 0x80 )
4612 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4613
4614 /* add data at char */
4615 *c = ( *c << 6 ) | ( *p & 0x3f );
4616
4617 dec--;
4618 p++;
4619 }
4620
4621 /* Check ovelong encoding.
4622 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4623 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4624 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4625 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004626 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004627 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4628 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4629 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4630 code |= UTF8_CODE_OVERLONG;
4631
4632 /* Check invalid UTF8 range. */
4633 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4634 (*c >= 0xfffe && *c <= 0xffff))
4635 code |= UTF8_CODE_INVRANGE;
4636
4637 return code | ((p-(unsigned char *)s)&0x0f);
4638}
4639
Maxime de Roucydc887852016-05-13 23:52:54 +02004640/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4641 * On failure : return 0 and <err> filled with an error message.
4642 * The caller is responsible for freeing the <err> and <str> copy
4643 * memory area using free()
4644 */
4645int list_append_word(struct list *li, const char *str, char **err)
4646{
4647 struct wordlist *wl;
4648
4649 wl = calloc(1, sizeof(*wl));
4650 if (!wl) {
4651 memprintf(err, "out of memory");
4652 goto fail_wl;
4653 }
4654
4655 wl->s = strdup(str);
4656 if (!wl->s) {
4657 memprintf(err, "out of memory");
4658 goto fail_wl_s;
4659 }
4660
Willy Tarreau2b718102021-04-21 07:32:39 +02004661 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004662
4663 return 1;
4664
4665fail_wl_s:
4666 free(wl->s);
4667fail_wl:
4668 free(wl);
4669 return 0;
4670}
4671
Willy Tarreau37101052019-05-20 16:48:20 +02004672/* indicates if a memory location may safely be read or not. The trick consists
4673 * in performing a harmless syscall using this location as an input and letting
4674 * the operating system report whether it's OK or not. For this we have the
4675 * stat() syscall, which will return EFAULT when the memory location supposed
4676 * to contain the file name is not readable. If it is readable it will then
4677 * either return 0 if the area contains an existing file name, or -1 with
4678 * another code. This must not be abused, and some audit systems might detect
4679 * this as abnormal activity. It's used only for unsafe dumps.
4680 */
4681int may_access(const void *ptr)
4682{
4683 struct stat buf;
4684
4685 if (stat(ptr, &buf) == 0)
4686 return 1;
4687 if (errno == EFAULT)
4688 return 0;
4689 return 1;
4690}
4691
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004692/* print a string of text buffer to <out>. The format is :
4693 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4694 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4695 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4696 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004697int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004698{
4699 unsigned char c;
Tim Duesterhus18795d42021-08-29 00:58:22 +02004700 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004701
Tim Duesterhus18795d42021-08-29 00:58:22 +02004702 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004703 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004704 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004705 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004706 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004707 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004708 }
4709 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004710 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004711 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004712 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004713 switch (c) {
4714 case ' ': c = ' '; break;
4715 case '\t': c = 't'; break;
4716 case '\n': c = 'n'; break;
4717 case '\r': c = 'r'; break;
4718 case '\e': c = 'e'; break;
4719 case '\\': c = '\\'; break;
4720 case '=': c = '='; break;
4721 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004722 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004723 }
4724 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004725 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004726 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004727 out->area[out->data++] = '\\';
4728 out->area[out->data++] = 'x';
4729 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4730 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004731 }
4732 ptr++;
4733 }
4734
4735 return ptr;
4736}
4737
4738/* print a buffer in hexa.
4739 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4740 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004741int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004742{
4743 unsigned char c;
4744 int ptr = 0;
4745
4746 while (ptr < bsize) {
4747 c = buf[ptr];
4748
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004749 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004750 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004751 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4752 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004753
4754 ptr++;
4755 }
4756 return ptr;
4757}
4758
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004759/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4760 * prepending each line with prefix <pfx>. The output is *not* initialized.
4761 * The output will not wrap pas the buffer's end so it is more optimal if the
4762 * caller makes sure the buffer is aligned first. A trailing zero will always
4763 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004764 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4765 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004766 */
Willy Tarreau37101052019-05-20 16:48:20 +02004767void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004768{
4769 const unsigned char *d = buf;
4770 int i, j, start;
4771
4772 d = (const unsigned char *)(((unsigned long)buf) & -16);
4773 start = ((unsigned long)buf) & 15;
4774
4775 for (i = 0; i < start + len; i += 16) {
4776 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4777
Willy Tarreau37101052019-05-20 16:48:20 +02004778 // 0: unchecked, 1: checked safe, 2: danger
4779 unsafe = !!unsafe;
4780 if (unsafe && !may_access(d + i))
4781 unsafe = 2;
4782
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004783 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004784 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004785 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004786 else if (unsafe > 1)
4787 chunk_strcat(out, "** ");
4788 else
4789 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004790
4791 if (j == 7)
4792 chunk_strcat(out, "- ");
4793 }
4794 chunk_strcat(out, " ");
4795 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004796 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004797 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004798 else if (unsafe > 1)
4799 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004800 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004801 chunk_appendf(out, "%c", d[i + j]);
4802 else
4803 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004804 }
4805 chunk_strcat(out, "\n");
4806 }
4807}
4808
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004809/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4810 * enclosed in brackets after the address itself, formatted on 14 chars
4811 * including the "0x" prefix. This is meant to be used as a prefix for code
4812 * areas. For example:
4813 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4814 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4815 * is emitted. A NULL <pfx> will be considered empty.
4816 */
4817void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4818{
4819 int ok = 0;
4820 int i;
4821
4822 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4823
4824 for (i = 0; i < n; i++) {
4825 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4826 ok = may_access(addr + i);
4827 if (ok)
4828 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4829 else
4830 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4831 }
4832}
4833
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004834/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4835 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4836 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4837 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4838 * lines are respected within the limit of 70 output chars. Lines that are
4839 * continuation of a previous truncated line begin with "+" instead of " "
4840 * after the offset. The new pointer is returned.
4841 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004842int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004843 int *line, int ptr)
4844{
4845 int end;
4846 unsigned char c;
4847
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004848 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004849 if (end > out->size)
4850 return ptr;
4851
4852 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4853
4854 while (ptr < len && ptr < bsize) {
4855 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004856 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004857 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004858 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004859 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004860 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004861 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004862 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004863 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004864 switch (c) {
4865 case '\t': c = 't'; break;
4866 case '\n': c = 'n'; break;
4867 case '\r': c = 'r'; break;
4868 case '\e': c = 'e'; break;
4869 case '\\': c = '\\'; break;
4870 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004871 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004872 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004873 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004874 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004875 out->area[out->data++] = '\\';
4876 out->area[out->data++] = 'x';
4877 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4878 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004879 }
4880 if (buf[ptr++] == '\n') {
4881 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004882 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004883 *line = ptr;
4884 return ptr;
4885 }
4886 }
4887 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004888 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004889 return ptr;
4890}
4891
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004892/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004893 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4894 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004895 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004896void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4897 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004898{
Willy Tarreau73459792017-04-11 07:58:08 +02004899 unsigned int i;
4900 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004901
4902 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4903 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004904 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004905 for (j = 0; j < 8; j++) {
4906 if (b + j >= 0 && b + j < len)
4907 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4908 else
4909 fprintf(out, " ");
4910 }
4911
4912 if (b + j >= 0 && b + j < len)
4913 fputc('-', out);
4914 else
4915 fputc(' ', out);
4916
4917 for (j = 8; j < 16; j++) {
4918 if (b + j >= 0 && b + j < len)
4919 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4920 else
4921 fprintf(out, " ");
4922 }
4923
4924 fprintf(out, " ");
4925 for (j = 0; j < 16; j++) {
4926 if (b + j >= 0 && b + j < len) {
4927 if (isprint((unsigned char)buf[b + j]))
4928 fputc((unsigned char)buf[b + j], out);
4929 else
4930 fputc('.', out);
4931 }
4932 else
4933 fputc(' ', out);
4934 }
4935 fputc('\n', out);
4936 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004937}
4938
Willy Tarreaubb869862020-04-16 10:52:41 +02004939/* Tries to report the executable path name on platforms supporting this. If
4940 * not found or not possible, returns NULL.
4941 */
4942const char *get_exec_path()
4943{
4944 const char *ret = NULL;
4945
David Carlier43a56852022-03-04 15:50:48 +00004946#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004947 long execfn = getauxval(AT_EXECFN);
4948
4949 if (execfn && execfn != ENOENT)
4950 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004951#elif defined(__FreeBSD__)
4952 Elf_Auxinfo *auxv;
4953 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4954 if (auxv->a_type == AT_EXECPATH) {
4955 ret = (const char *)auxv->a_un.a_ptr;
4956 break;
4957 }
4958 }
David Carlierbd2cced2021-08-17 08:44:25 +01004959#elif defined(__NetBSD__)
4960 AuxInfo *auxv;
4961 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4962 if (auxv->a_type == AT_SUN_EXECNAME) {
4963 ret = (const char *)auxv->a_v;
4964 break;
4965 }
4966 }
David Carlier7198c702022-05-14 17:15:49 +01004967#elif defined(__sun)
4968 ret = getexecname();
Willy Tarreaubb869862020-04-16 10:52:41 +02004969#endif
4970 return ret;
4971}
4972
Baruch Siache1651b22020-07-24 07:52:20 +03004973#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004974/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4975 * also returns the symbol size in <size>, otherwise returns 0 there.
4976 */
4977static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4978{
4979 int ret;
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004980#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreauf3d5c4b2022-01-28 09:42:29 +01004981 const ElfW(Sym) *sym __attribute__((may_alias));
Willy Tarreau9133e482020-03-04 10:19:36 +01004982
4983 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4984 if (ret)
4985 *size = sym ? sym->st_size : 0;
4986#else
David Carlierae5c42f2021-12-31 08:15:29 +00004987#if defined(__sun)
4988 ret = dladdr((void *)addr, dli);
4989#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004990 ret = dladdr(addr, dli);
David Carlierae5c42f2021-12-31 08:15:29 +00004991#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004992 *size = 0;
4993#endif
4994 return ret;
4995}
Willy Tarreau64192392021-05-05 09:06:21 +02004996
Willy Tarreau5b3cd952022-07-18 13:58:17 +02004997/* Sets build_is_static to true if we detect a static build. Some older glibcs
4998 * tend to crash inside dlsym() in static builds, but tests show that at least
4999 * dladdr() still works (and will fail to resolve anything of course). Thus we
5000 * try to determine if we're on a static build to avoid calling dlsym() in this
5001 * case.
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005002 */
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005003void check_if_static_build()
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005004{
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005005 Dl_info dli = { };
5006 size_t size = 0;
5007
5008 /* Now let's try to be smarter */
5009 if (!dladdr_and_size(&main, &dli, &size))
5010 build_is_static = 1;
5011 else
5012 build_is_static = 0;
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005013}
5014
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005015INITCALL0(STG_PREPARE, check_if_static_build);
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005016
Willy Tarreau64192392021-05-05 09:06:21 +02005017/* Tries to retrieve the address of the first occurrence symbol <name>.
5018 * Note that NULL in return is not always an error as a symbol may have that
5019 * address in special situations.
5020 */
5021void *get_sym_curr_addr(const char *name)
5022{
5023 void *ptr = NULL;
5024
5025#ifdef RTLD_DEFAULT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005026 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005027 ptr = dlsym(RTLD_DEFAULT, name);
Willy Tarreau64192392021-05-05 09:06:21 +02005028#endif
5029 return ptr;
5030}
5031
5032
5033/* Tries to retrieve the address of the next occurrence of symbol <name>
5034 * Note that NULL in return is not always an error as a symbol may have that
5035 * address in special situations.
5036 */
5037void *get_sym_next_addr(const char *name)
5038{
5039 void *ptr = NULL;
5040
5041#ifdef RTLD_NEXT
Willy Tarreau5b3cd952022-07-18 13:58:17 +02005042 if (!build_is_static)
Willy Tarreau288dc1d2022-07-16 13:49:34 +02005043 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01005044#endif
Willy Tarreau64192392021-05-05 09:06:21 +02005045 return ptr;
5046}
5047
5048#else /* elf & linux & dl */
5049
5050/* no possible resolving on other platforms at the moment */
5051void *get_sym_curr_addr(const char *name)
5052{
5053 return NULL;
5054}
5055
5056void *get_sym_next_addr(const char *name)
5057{
5058 return NULL;
5059}
5060
5061#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01005062
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005063/* Tries to append to buffer <buf> some indications about the symbol at address
5064 * <addr> using the following form:
5065 * lib:+0xoffset (unresolvable address from lib's base)
5066 * main+0xoffset (unresolvable address from main (+/-))
5067 * lib:main+0xoffset (unresolvable lib address from main (+/-))
5068 * name (resolved exact exec address)
5069 * lib:name (resolved exact lib address)
5070 * name+0xoffset/0xsize (resolved address within exec symbol)
5071 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
5072 *
5073 * The file name (lib or executable) is limited to what lies between the last
5074 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
5075 * 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 +03005076 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005077 *
5078 * The symbol's base address is returned, or NULL when unresolved, in order to
5079 * allow the caller to match it against known ones.
5080 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01005081const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005082{
5083 const struct {
5084 const void *func;
5085 const char *name;
5086 } fcts[] = {
5087 { .func = process_stream, .name = "process_stream" },
5088 { .func = task_run_applet, .name = "task_run_applet" },
Willy Tarreau462b9892022-05-18 18:06:53 +02005089 { .func = sc_conn_io_cb, .name = "sc_conn_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01005090 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005091 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
5092 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01005093 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005094 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
5095 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01005096 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01005097#ifdef USE_THREAD
5098 { .func = accept_queue_process, .name = "accept_queue_process" },
5099#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005100#ifdef USE_LUA
5101 { .func = hlua_process_task, .name = "hlua_process_task" },
5102#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05005103#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005104 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
5105 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
5106#endif
5107 };
5108
Baruch Siache1651b22020-07-24 07:52:20 +03005109#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005110 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01005111 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005112 const char *fname, *p;
5113#endif
5114 int i;
5115
5116 if (pfx)
5117 chunk_appendf(buf, "%s", pfx);
5118
5119 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
5120 if (addr == fcts[i].func) {
5121 chunk_appendf(buf, "%s", fcts[i].name);
5122 return addr;
5123 }
5124 }
5125
Baruch Siache1651b22020-07-24 07:52:20 +03005126#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005127 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01005128 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005129 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005130
5131 /* 1. prefix the library name if it's not the same object as the one
5132 * that contains the main function. The name is picked between last '/'
5133 * and first following '.'.
5134 */
5135 if (!dladdr(main, &dli_main))
5136 dli_main.dli_fbase = NULL;
5137
5138 if (dli_main.dli_fbase != dli.dli_fbase) {
5139 fname = dli.dli_fname;
5140 p = strrchr(fname, '/');
5141 if (p++)
5142 fname = p;
5143 p = strchr(fname, '.');
5144 if (!p)
5145 p = fname + strlen(fname);
5146
5147 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
5148 }
5149
5150 /* 2. symbol name */
5151 if (dli.dli_sname) {
5152 /* known, dump it and return symbol's address (exact or relative) */
5153 chunk_appendf(buf, "%s", dli.dli_sname);
5154 if (addr != dli.dli_saddr) {
5155 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01005156 if (size)
5157 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005158 }
5159 return dli.dli_saddr;
5160 }
5161 else if (dli_main.dli_fbase != dli.dli_fbase) {
5162 /* unresolved symbol from a known library, report relative offset */
5163 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
5164 return NULL;
5165 }
Baruch Siache1651b22020-07-24 07:52:20 +03005166#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01005167 unknown:
5168 /* unresolved symbol from the main file, report relative offset to main */
5169 if ((void*)addr < (void*)main)
5170 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
5171 else
5172 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
5173 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01005174}
5175
Willy Tarreau6ab7b212021-12-28 09:57:10 +01005176/* On systems where this is supported, let's provide a possibility to enumerate
5177 * the list of object files. The output is appended to a buffer initialized by
5178 * the caller, with one name per line. A trailing zero is always emitted if data
5179 * are written. Only real objects are dumped (executable and .so libs). The
5180 * function returns non-zero if it dumps anything. These functions do not make
5181 * use of the trash so that it is possible for the caller to call them with the
5182 * trash on input. The output format may be platform-specific but at least one
5183 * version must emit raw object file names when argument is zero.
5184 */
5185#if defined(HA_HAVE_DUMP_LIBS)
5186# if defined(HA_HAVE_DL_ITERATE_PHDR)
5187/* the private <data> we pass below is a dump context initialized like this */
5188struct dl_dump_ctx {
5189 struct buffer *buf;
5190 int with_addr;
5191};
5192
5193static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5194{
5195 struct dl_dump_ctx *ctx = data;
5196 const char *fname;
5197 size_t p1, p2, beg, end;
5198 int idx;
5199
5200 if (!info || !info->dlpi_name)
5201 goto leave;
5202
5203 if (!*info->dlpi_name)
5204 fname = get_exec_path();
5205 else if (strchr(info->dlpi_name, '/'))
5206 fname = info->dlpi_name;
5207 else
5208 /* else it's a VDSO or similar and we're not interested */
5209 goto leave;
5210
5211 if (!ctx->with_addr)
5212 goto dump_name;
5213
5214 /* virtual addresses are relative to the load address and are per
5215 * pseudo-header, so we have to scan them all to find the furthest
5216 * one from the beginning. In this case we only dump entries if
5217 * they have at least one section.
5218 */
5219 beg = ~0; end = 0;
5220 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5221 if (!info->dlpi_phdr[idx].p_memsz)
5222 continue;
5223 p1 = info->dlpi_phdr[idx].p_vaddr;
5224 if (p1 < beg)
5225 beg = p1;
5226 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5227 if (p2 > end)
5228 end = p2;
5229 }
5230
5231 if (!idx)
5232 goto leave;
5233
5234 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5235 (ullong)info->dlpi_addr + beg,
5236 (ullong)info->dlpi_addr + end,
5237 (ullong)(end - beg + 1));
5238 dump_name:
5239 chunk_appendf(ctx->buf, "%s\n", fname);
5240 leave:
5241 return 0;
5242}
5243
5244/* dumps lib names and optionally address ranges */
5245int dump_libs(struct buffer *output, int with_addr)
5246{
5247 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5248 size_t old_data = output->data;
5249
5250 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5251 return output->data != old_data;
5252}
5253# else // no DL_ITERATE_PHDR
5254# error "No dump_libs() function for this platform"
5255# endif
5256#else // no HA_HAVE_DUMP_LIBS
5257
5258/* unsupported platform: do not dump anything */
5259int dump_libs(struct buffer *output, int with_addr)
5260{
5261 return 0;
5262}
5263
5264#endif // HA_HAVE_DUMP_LIBS
5265
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005266/*
5267 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005268 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005269 *
5270 * First, initializes the value with <sz> as address to 0 and initializes the
5271 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5272 * address updating <sz> pointed value to the size of this array.
5273 *
5274 * Returns 1 if succeeded, 0 if not.
5275 */
5276int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5277{
5278 unsigned int *n;
5279 const char *s, *end;
5280
5281 s = str;
5282 *sz = 0;
5283 end = str + strlen(str);
5284 *nums = n = NULL;
5285
5286 while (1) {
5287 unsigned int r;
5288
5289 if (s >= end)
5290 break;
5291
5292 r = read_uint(&s, end);
5293 /* Expected characters after having read an uint: '\0' or '.',
5294 * if '.', must not be terminal.
5295 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005296 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5297 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005298 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005299 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005300
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005301 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005302 if (!n)
5303 return 0;
5304
5305 n[(*sz)++] = r;
5306 }
5307 *nums = n;
5308
5309 return 1;
5310}
5311
Willy Tarreau4d589e72019-08-23 19:02:26 +02005312
5313/* returns the number of bytes needed to encode <v> as a varint. An inline
5314 * version exists for use with constants (__varint_bytes()).
5315 */
5316int varint_bytes(uint64_t v)
5317{
5318 int len = 1;
5319
5320 if (v >= 240) {
5321 v = (v - 240) >> 4;
5322 while (1) {
5323 len++;
5324 if (v < 128)
5325 break;
5326 v = (v - 128) >> 7;
5327 }
5328 }
5329 return len;
5330}
5331
Willy Tarreau52bf8392020-03-08 00:42:37 +01005332
5333/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005334static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005335
5336/* This is a thread-safe implementation of xoroshiro128** described below:
5337 * http://prng.di.unimi.it/
5338 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5339 * supports fast jumps and passes all common quality tests. It is thread-safe,
5340 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5341 * local lock on other ones.
5342 */
5343uint64_t ha_random64()
5344{
Willy Tarreau1544c142020-03-12 00:31:18 +01005345 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5346 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005347
5348#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5349 static HA_SPINLOCK_T rand_lock;
5350
5351 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5352#endif
5353
5354 old[0] = ha_random_state[0];
5355 old[1] = ha_random_state[1];
5356
5357#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5358 do {
5359#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005360 new[1] = old[0] ^ old[1];
5361 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5362 new[1] = rotl64(new[1], 37); // c
5363
5364#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5365 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5366#else
5367 ha_random_state[0] = new[0];
5368 ha_random_state[1] = new[1];
5369#if defined(USE_THREAD)
5370 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5371#endif
5372#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005373 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005374}
5375
5376/* seeds the random state using up to <len> bytes from <seed>, starting with
5377 * the first non-zero byte.
5378 */
5379void ha_random_seed(const unsigned char *seed, size_t len)
5380{
5381 size_t pos;
5382
5383 /* the seed must not be all zeroes, so we pre-fill it with alternating
5384 * bits and overwrite part of them with the block starting at the first
5385 * non-zero byte from the seed.
5386 */
5387 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5388
5389 for (pos = 0; pos < len; pos++)
5390 if (seed[pos] != 0)
5391 break;
5392
5393 if (pos == len)
5394 return;
5395
5396 seed += pos;
5397 len -= pos;
5398
5399 if (len > sizeof(ha_random_state))
5400 len = sizeof(ha_random_state);
5401
5402 memcpy(ha_random_state, seed, len);
5403}
5404
5405/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5406 * and is equivalent to calling ha_random64() as many times. It is used to
5407 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5408 * different generators (i.e. different processes after a fork). The <dist>
5409 * argument is the distance to jump to and is used in a loop so it rather not
5410 * be too large if the processing time is a concern.
5411 *
5412 * BEWARE: this function is NOT thread-safe and must not be called during
5413 * concurrent accesses to ha_random64().
5414 */
5415void ha_random_jump96(uint32_t dist)
5416{
5417 while (dist--) {
5418 uint64_t s0 = 0;
5419 uint64_t s1 = 0;
5420 int b;
5421
5422 for (b = 0; b < 64; b++) {
5423 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5424 s0 ^= ha_random_state[0];
5425 s1 ^= ha_random_state[1];
5426 }
5427 ha_random64();
5428 }
5429
5430 for (b = 0; b < 64; b++) {
5431 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5432 s0 ^= ha_random_state[0];
5433 s1 ^= ha_random_state[1];
5434 }
5435 ha_random64();
5436 }
5437 ha_random_state[0] = s0;
5438 ha_random_state[1] = s1;
5439 }
5440}
5441
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005442/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5443 * bytes large.
5444 */
5445void ha_generate_uuid(struct buffer *output)
5446{
5447 uint32_t rnd[4];
5448 uint64_t last;
5449
5450 last = ha_random64();
5451 rnd[0] = last;
5452 rnd[1] = last >> 32;
5453
5454 last = ha_random64();
5455 rnd[2] = last;
5456 rnd[3] = last >> 32;
5457
5458 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5459 rnd[0],
5460 rnd[1] & 0xFFFF,
5461 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5462 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5463 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5464}
5465
5466
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005467/* only used by parse_line() below. It supports writing in place provided that
5468 * <in> is updated to the next location before calling it. In that case, the
5469 * char at <in> may be overwritten.
5470 */
5471#define EMIT_CHAR(x) \
5472 do { \
5473 char __c = (char)(x); \
5474 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5475 err |= PARSE_ERR_OVERLAP; \
5476 if (outpos >= outmax) \
5477 err |= PARSE_ERR_TOOLARGE; \
5478 if (!err) \
5479 out[outpos] = __c; \
5480 outpos++; \
5481 } while (0)
5482
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005483/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005484 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5485 * extraneous ones are not emitted but <outlen> is updated so that the caller
5486 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5487 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005488 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5489 * it is guaranteed that at least one arg will point to the zero. It is safe
5490 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005491 *
5492 * <out> may overlap with <in> provided that it never goes further, in which
5493 * case the parser will accept to perform in-place parsing and unquoting/
5494 * unescaping but only if environment variables do not lead to expansion that
5495 * causes overlapping, otherwise the input string being destroyed, the error
5496 * will not be recoverable. Note that even during out-of-place <in> will
5497 * experience temporary modifications in-place for variable resolution and must
5498 * be writable, and will also receive zeroes to delimit words when using
5499 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5500 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5501 * starting point of the first invalid character sequence or unmatched
5502 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5503 * error reporting might be difficult since zeroes will have been inserted into
5504 * the string. One solution for the caller may consist in replacing all args
5505 * delimiters with spaces in this case.
5506 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005507uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, const char **errptr)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005508{
5509 char *quote = NULL;
5510 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005511 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005512 unsigned char hex1, hex2;
5513 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005514 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005515 size_t outpos = 0;
5516 int squote = 0;
5517 int dquote = 0;
5518 int arg = 0;
5519 uint32_t err = 0;
5520
5521 *nbargs = 0;
5522 *outlen = 0;
5523
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005524 /* argsmax may be -1 here, protecting args[] from any write */
5525 if (arg < argsmax)
5526 args[arg] = out;
5527
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005528 while (1) {
5529 if (*in >= '-' && *in != '\\') {
5530 /* speedup: directly send all regular chars starting
5531 * with '-', '.', '/', alnum etc...
5532 */
5533 EMIT_CHAR(*in++);
5534 continue;
5535 }
5536 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5537 /* end of line */
5538 break;
5539 }
5540 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5541 /* comment */
5542 break;
5543 }
5544 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5545 if (dquote) {
5546 dquote = 0;
5547 quote = NULL;
5548 }
5549 else {
5550 dquote = 1;
5551 quote = in;
5552 }
5553 in++;
5554 continue;
5555 }
5556 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5557 if (squote) {
5558 squote = 0;
5559 quote = NULL;
5560 }
5561 else {
5562 squote = 1;
5563 quote = in;
5564 }
5565 in++;
5566 continue;
5567 }
5568 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5569 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5570 * C equivalent value but only when they have a special meaning and within
5571 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5572 */
5573 char tosend = *in;
5574
5575 switch (in[1]) {
5576 case ' ':
5577 case '\\':
5578 tosend = in[1];
5579 in++;
5580 break;
5581
5582 case 't':
5583 tosend = '\t';
5584 in++;
5585 break;
5586
5587 case 'n':
5588 tosend = '\n';
5589 in++;
5590 break;
5591
5592 case 'r':
5593 tosend = '\r';
5594 in++;
5595 break;
5596
5597 case '#':
5598 /* escaping of "#" only if comments are supported */
5599 if (opts & PARSE_OPT_SHARP)
5600 in++;
5601 tosend = *in;
5602 break;
5603
5604 case '\'':
5605 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5606 if (opts & PARSE_OPT_SQUOTE && !squote)
5607 in++;
5608 tosend = *in;
5609 break;
5610
5611 case '"':
5612 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5613 if (opts & PARSE_OPT_DQUOTE && !squote)
5614 in++;
5615 tosend = *in;
5616 break;
5617
5618 case '$':
5619 /* escaping of '$' only inside double quotes and only if env supported */
5620 if (opts & PARSE_OPT_ENV && dquote)
5621 in++;
5622 tosend = *in;
5623 break;
5624
5625 case 'x':
5626 if (!ishex(in[2]) || !ishex(in[3])) {
5627 /* invalid or incomplete hex sequence */
5628 err |= PARSE_ERR_HEX;
5629 if (errptr)
5630 *errptr = in;
5631 goto leave;
5632 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005633 hex1 = toupper((unsigned char)in[2]) - '0';
5634 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005635 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5636 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5637 tosend = (hex1 << 4) + hex2;
5638 in += 3;
5639 break;
5640
5641 default:
5642 /* other combinations are not escape sequences */
5643 break;
5644 }
5645
5646 in++;
5647 EMIT_CHAR(tosend);
5648 }
5649 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5650 /* a non-escaped space is an argument separator */
5651 while (isspace((unsigned char)*in))
5652 in++;
5653 EMIT_CHAR(0);
5654 arg++;
5655 if (arg < argsmax)
5656 args[arg] = out + outpos;
5657 else
5658 err |= PARSE_ERR_TOOMANY;
5659 }
5660 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5661 /* environment variables are evaluated anywhere, or only
5662 * inside double quotes if they are supported.
5663 */
5664 char *var_name;
5665 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005666 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005667
5668 in++;
5669
5670 if (*in == '{')
5671 brace = in++;
5672
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005673 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005674 /* unacceptable character in variable name */
5675 err |= PARSE_ERR_VARNAME;
5676 if (errptr)
5677 *errptr = in;
5678 goto leave;
5679 }
5680
5681 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005682 if (*in == '.')
5683 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005684 while (isalnum((unsigned char)*in) || *in == '_')
5685 in++;
5686
5687 save_char = *in;
5688 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005689 if (unlikely(*var_name == '.')) {
5690 /* internal pseudo-variables */
5691 if (strcmp(var_name, ".LINE") == 0)
5692 value = ultoa(global.cfg_curr_line);
5693 else if (strcmp(var_name, ".FILE") == 0)
5694 value = global.cfg_curr_file;
5695 else if (strcmp(var_name, ".SECTION") == 0)
5696 value = global.cfg_curr_section;
5697 else {
5698 /* unsupported internal variable name */
5699 err |= PARSE_ERR_VARNAME;
5700 if (errptr)
5701 *errptr = var_name;
5702 goto leave;
5703 }
5704 } else {
5705 value = getenv(var_name);
5706 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005707 *in = save_char;
5708
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005709 /* support for '[*]' sequence to force word expansion,
5710 * only available inside braces */
5711 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5712 word_expand = in++;
5713
5714 if (*in++ != '*' || *in++ != ']') {
5715 err |= PARSE_ERR_WRONG_EXPAND;
5716 if (errptr)
5717 *errptr = word_expand;
5718 goto leave;
5719 }
5720 }
5721
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005722 if (brace) {
Willy Tarreauec347b12021-11-18 17:42:50 +01005723 if (*in == '-') {
5724 /* default value starts just after the '-' */
5725 if (!value)
5726 value = in + 1;
5727
5728 while (*in && *in != '}')
5729 in++;
5730 if (!*in)
5731 goto no_brace;
5732 *in = 0; // terminate the default value
5733 }
5734 else if (*in != '}') {
5735 no_brace:
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005736 /* unmatched brace */
5737 err |= PARSE_ERR_BRACE;
5738 if (errptr)
5739 *errptr = brace;
5740 goto leave;
5741 }
Willy Tarreauec347b12021-11-18 17:42:50 +01005742
5743 /* brace found, skip it */
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005744 in++;
5745 brace = NULL;
5746 }
5747
5748 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005749 while (*value) {
5750 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005751 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005752 EMIT_CHAR(0);
5753 ++arg;
5754 if (arg < argsmax)
5755 args[arg] = out + outpos;
5756 else
5757 err |= PARSE_ERR_TOOMANY;
5758
5759 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005760 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005761 ;
5762 } else {
5763 EMIT_CHAR(*value++);
5764 }
5765 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005766 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005767 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005768 }
5769 else {
5770 /* any other regular char */
5771 EMIT_CHAR(*in++);
5772 }
5773 }
5774
5775 /* end of output string */
5776 EMIT_CHAR(0);
5777 arg++;
5778
5779 if (quote) {
5780 /* unmatched quote */
5781 err |= PARSE_ERR_QUOTE;
5782 if (errptr)
5783 *errptr = quote;
5784 goto leave;
5785 }
5786 leave:
5787 *nbargs = arg;
5788 *outlen = outpos;
5789
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005790 /* empty all trailing args by making them point to the trailing zero,
5791 * at least the last one in any case.
5792 */
5793 if (arg > argsmax)
5794 arg = argsmax;
5795
5796 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005797 args[arg++] = out + outpos - 1;
5798
5799 return err;
5800}
5801#undef EMIT_CHAR
5802
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005803/* This is used to sanitize an input line that's about to be used for error reporting.
5804 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5805 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5806 * If non-printable chars are present in the output. It returns the new offset <pos>
5807 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5808 * be at least 6 to support two "..." otherwise the result is undefined. The line
5809 * itself must have at least 7 chars allocated for the same reason.
5810 */
5811size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5812{
5813 size_t shift = 0;
5814 char *out = line;
5815 char *in = line;
5816 char *end = line + width;
5817
5818 if (pos >= width) {
5819 /* if we have to shift, we'll be out of context, so let's
5820 * try to put <pos> at the center of width.
5821 */
5822 shift = pos - width / 2;
5823 in += shift + 3;
5824 end = out + width - 3;
5825 out[0] = out[1] = out[2] = '.';
5826 out += 3;
5827 }
5828
5829 while (out < end && *in) {
5830 if (isspace((unsigned char)*in))
5831 *out++ = ' ';
5832 else if (isprint((unsigned char)*in))
5833 *out++ = *in;
5834 else
5835 *out++ = '?';
5836 in++;
5837 }
5838
5839 if (end < line + width) {
5840 out[0] = out[1] = out[2] = '.';
5841 out += 3;
5842 }
5843
5844 *out++ = 0;
5845 return pos - shift;
5846}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005847
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005848/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005849 * transitions between characters. <fp> is a 1024-entries array indexed as
5850 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005851 * 1..26=letter, 27=digit, 28=other/begin/end.
5852 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005853 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005854void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005855{
5856 const char *p;
5857 int from, to;
5858 int c;
5859
Willy Tarreauba2c4452021-03-12 09:01:52 +01005860 from = 28; // begin
5861 for (p = word; *p; p++) {
5862 c = tolower(*p);
5863 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005864 case 'a'...'z': to = c - 'a' + 1; break;
5865 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5866 case '0'...'9': to = 27; break;
5867 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005868 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005869 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005870 fp[32 * from + to]++;
5871 from = to;
5872 }
5873 to = 28; // end
5874 fp[32 * from + to]++;
5875}
5876
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005877/* Initialize array <fp> with the fingerprint of word <word> by counting the
5878 * transitions between characters. <fp> is a 1024-entries array indexed as
5879 * 32*from+to. Positions for 'from' and 'to' are:
5880 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5881 */
5882void make_word_fingerprint(uint8_t *fp, const char *word)
5883{
5884 memset(fp, 0, 1024);
5885 update_word_fingerprint(fp, word);
5886}
5887
Willy Tarreauba2c4452021-03-12 09:01:52 +01005888/* Return the distance between two word fingerprints created by function
5889 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005890 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005891 */
5892int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5893{
5894 int i, k, dist = 0;
5895
5896 for (i = 0; i < 1024; i++) {
5897 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005898 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005899 }
5900 return dist;
5901}
5902
William Lallemand3aeb3f92021-08-21 23:59:56 +02005903/*
5904 * This function compares the loaded openssl version with a string <version>
5905 * This function use the same return code as compare_current_version:
5906 *
5907 * -1 : the version in argument is older than the current openssl version
5908 * 0 : the version in argument is the same as the current openssl version
5909 * 1 : the version in argument is newer than the current openssl version
5910 *
5911 * Or some errors:
5912 * -2 : openssl is not available on this process
5913 * -3 : the version in argument is not parsable
5914 */
5915int openssl_compare_current_version(const char *version)
5916{
5917#ifdef USE_OPENSSL
5918 int numversion;
5919
5920 numversion = openssl_version_parser(version);
5921 if (numversion == 0)
5922 return -3;
5923
5924 if (numversion < OPENSSL_VERSION_NUMBER)
5925 return -1;
5926 else if (numversion > OPENSSL_VERSION_NUMBER)
5927 return 1;
5928 else
5929 return 0;
5930#else
5931 return -2;
5932#endif
5933}
5934
Remi Tricot-Le Bretonb01179a2021-10-11 15:34:12 +02005935/*
5936 * This function compares the loaded openssl name with a string <name>
5937 * This function returns 0 if the OpenSSL name starts like the passed parameter,
5938 * 1 otherwise.
5939 */
5940int openssl_compare_current_name(const char *name)
5941{
5942#ifdef USE_OPENSSL
5943 int name_len = 0;
5944 const char *openssl_version = OpenSSL_version(OPENSSL_VERSION);
5945
5946 if (name) {
5947 name_len = strlen(name);
5948 if (strlen(name) <= strlen(openssl_version))
5949 return strncmp(openssl_version, name, name_len);
5950 }
5951#endif
5952 return 1;
5953}
5954
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005955#if defined(RTLD_DEFAULT) || defined(RTLD_NEXT)
5956/* redefine dlopen() so that we can detect unexpected replacement of some
5957 * critical symbols, typically init/alloc/free functions coming from alternate
5958 * libraries. When called, a tainted flag is set (TAINTED_SHARED_LIBS).
5959 */
5960void *dlopen(const char *filename, int flags)
5961{
5962 static void *(*_dlopen)(const char *filename, int flags);
Willy Tarreau177aed52022-06-19 16:49:51 +02005963 struct {
5964 const char *name;
5965 void *curr, *next;
5966 } check_syms[] = {
5967 { .name = "malloc", },
5968 { .name = "free", },
5969 { .name = "SSL_library_init", },
5970 { .name = "X509_free", },
5971 /* insert only above, 0 must be the last one */
5972 { 0 },
5973 };
5974 const char *trace;
5975 void *addr;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005976 void *ret;
Willy Tarreau177aed52022-06-19 16:49:51 +02005977 int sym = 0;
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005978
5979 if (!_dlopen) {
5980 _dlopen = get_sym_next_addr("dlopen");
5981 if (!_dlopen || _dlopen == dlopen) {
5982 _dlopen = NULL;
5983 return NULL;
5984 }
5985 }
5986
Willy Tarreau177aed52022-06-19 16:49:51 +02005987 /* save a few pointers to critical symbols. We keep a copy of both the
5988 * current and the next value, because we might already have replaced
5989 * some of them (e.g. malloc/free with DEBUG_MEM_STATS), and we're only
5990 * interested in verifying that a loaded library doesn't come with a
5991 * completely different definition that would be incompatible.
5992 */
5993 for (sym = 0; check_syms[sym].name; sym++) {
5994 check_syms[sym].curr = get_sym_curr_addr(check_syms[sym].name);
5995 check_syms[sym].next = get_sym_next_addr(check_syms[sym].name);
5996 }
Willy Tarreau40dde2d2022-06-19 16:41:59 +02005997
5998 /* now open the requested lib */
5999 ret = _dlopen(filename, flags);
6000 if (!ret)
6001 return ret;
6002
6003 mark_tainted(TAINTED_SHARED_LIBS);
6004
Willy Tarreau177aed52022-06-19 16:49:51 +02006005 /* and check that critical symbols didn't change */
6006 for (sym = 0; check_syms[sym].name; sym++) {
6007 if (!check_syms[sym].curr && !check_syms[sym].next)
6008 continue;
6009
6010 addr = dlsym(ret, check_syms[sym].name);
6011 if (!addr || addr == check_syms[sym].curr || addr == check_syms[sym].next)
6012 continue;
6013
6014 /* OK it's clear that this symbol was redefined */
6015 mark_tainted(TAINTED_REDEFINITION);
6016
6017 trace = hlua_show_current_location("\n ");
6018 ha_warning("dlopen(): shared library '%s' brings a different definition of symbol '%s'. The process cannot be trusted anymore!%s%s\n",
6019 filename, check_syms[sym].name,
6020 trace ? " Suspected call location: \n " : "",
6021 trace ? trace : "");
6022 }
6023
Willy Tarreau40dde2d2022-06-19 16:41:59 +02006024 return ret;
6025}
6026#endif
6027
Willy Tarreau06e69b52021-03-02 14:01:35 +01006028static int init_tools_per_thread()
6029{
6030 /* Let's make each thread start from a different position */
6031 statistical_prng_state += tid * MAX_THREADS;
6032 if (!statistical_prng_state)
6033 statistical_prng_state++;
6034 return 1;
6035}
6036REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02006037
Willy Tarreaubaaee002006-06-26 02:48:02 +02006038/*
6039 * Local variables:
6040 * c-indent-level: 8
6041 * c-basic-offset: 8
6042 * End:
6043 */