blob: 4f536efc3ee4bafc22a58e08416b91096cac8cc4 [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
Willy Tarreau30053062020-08-20 16:39:14 +020046#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
47#include <sys/auxv.h>
48#endif
49
Willy Tarreau48fbcae2020-06-03 18:09:46 +020050#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020052
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020053#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020054#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020055#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020056#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020057#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020058#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020059#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010060#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020061#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010062#include <haproxy/resolvers.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010063#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020064#include <haproxy/ssl_sock.h>
William Lallemand3aeb3f92021-08-21 23:59:56 +020065#include <haproxy/ssl_utils.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020066#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020067#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020068#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010069
Thierry Fournier93127942016-01-20 18:49:45 +010070/* This macro returns false if the test __x is false. Many
71 * of the following parsing function must be abort the processing
72 * if it returns 0, so this macro is useful for writing light code.
73 */
74#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
75
Willy Tarreau56adcf22012-12-23 18:00:29 +010076/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020077 * 2^64-1 = 18446744073709551615 or
78 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020079 *
80 * The HTML version needs room for adding the 25 characters
81 * '<span class="rls"></span>' around digits at positions 3N+1 in order
82 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020083 */
Christopher Faulet99bca652017-11-14 16:47:26 +010084THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
85THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020086
Willy Tarreau588297f2014-06-16 15:16:40 +020087/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
88 * to quote strings larger than a max configuration line.
89 */
Christopher Faulet99bca652017-11-14 16:47:26 +010090THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
91THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020092
Willy Tarreau06e69b52021-03-02 14:01:35 +010093/* thread-local PRNG state. It's modified to start from a different sequence
94 * on all threads upon startup. It must not be used or anything beyond getting
95 * statistical values as it's 100% predictable.
96 */
97THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
98
Willy Tarreaubaaee002006-06-26 02:48:02 +020099/*
William Lallemande7340ec2012-01-24 11:15:39 +0100100 * unsigned long long ASCII representation
101 *
102 * return the last char '\0' or NULL if no enough
103 * space in dst
104 */
105char *ulltoa(unsigned long long n, char *dst, size_t size)
106{
107 int i = 0;
108 char *res;
109
110 switch(n) {
111 case 1ULL ... 9ULL:
112 i = 0;
113 break;
114
115 case 10ULL ... 99ULL:
116 i = 1;
117 break;
118
119 case 100ULL ... 999ULL:
120 i = 2;
121 break;
122
123 case 1000ULL ... 9999ULL:
124 i = 3;
125 break;
126
127 case 10000ULL ... 99999ULL:
128 i = 4;
129 break;
130
131 case 100000ULL ... 999999ULL:
132 i = 5;
133 break;
134
135 case 1000000ULL ... 9999999ULL:
136 i = 6;
137 break;
138
139 case 10000000ULL ... 99999999ULL:
140 i = 7;
141 break;
142
143 case 100000000ULL ... 999999999ULL:
144 i = 8;
145 break;
146
147 case 1000000000ULL ... 9999999999ULL:
148 i = 9;
149 break;
150
151 case 10000000000ULL ... 99999999999ULL:
152 i = 10;
153 break;
154
155 case 100000000000ULL ... 999999999999ULL:
156 i = 11;
157 break;
158
159 case 1000000000000ULL ... 9999999999999ULL:
160 i = 12;
161 break;
162
163 case 10000000000000ULL ... 99999999999999ULL:
164 i = 13;
165 break;
166
167 case 100000000000000ULL ... 999999999999999ULL:
168 i = 14;
169 break;
170
171 case 1000000000000000ULL ... 9999999999999999ULL:
172 i = 15;
173 break;
174
175 case 10000000000000000ULL ... 99999999999999999ULL:
176 i = 16;
177 break;
178
179 case 100000000000000000ULL ... 999999999999999999ULL:
180 i = 17;
181 break;
182
183 case 1000000000000000000ULL ... 9999999999999999999ULL:
184 i = 18;
185 break;
186
187 case 10000000000000000000ULL ... ULLONG_MAX:
188 i = 19;
189 break;
190 }
191 if (i + 2 > size) // (i + 1) + '\0'
192 return NULL; // too long
193 res = dst + i + 1;
194 *res = '\0';
195 for (; i >= 0; i--) {
196 dst[i] = n % 10ULL + '0';
197 n /= 10ULL;
198 }
199 return res;
200}
201
202/*
203 * unsigned long ASCII representation
204 *
205 * return the last char '\0' or NULL if no enough
206 * space in dst
207 */
208char *ultoa_o(unsigned long n, char *dst, size_t size)
209{
210 int i = 0;
211 char *res;
212
213 switch (n) {
214 case 0U ... 9UL:
215 i = 0;
216 break;
217
218 case 10U ... 99UL:
219 i = 1;
220 break;
221
222 case 100U ... 999UL:
223 i = 2;
224 break;
225
226 case 1000U ... 9999UL:
227 i = 3;
228 break;
229
230 case 10000U ... 99999UL:
231 i = 4;
232 break;
233
234 case 100000U ... 999999UL:
235 i = 5;
236 break;
237
238 case 1000000U ... 9999999UL:
239 i = 6;
240 break;
241
242 case 10000000U ... 99999999UL:
243 i = 7;
244 break;
245
246 case 100000000U ... 999999999UL:
247 i = 8;
248 break;
249#if __WORDSIZE == 32
250
251 case 1000000000ULL ... ULONG_MAX:
252 i = 9;
253 break;
254
255#elif __WORDSIZE == 64
256
257 case 1000000000ULL ... 9999999999UL:
258 i = 9;
259 break;
260
261 case 10000000000ULL ... 99999999999UL:
262 i = 10;
263 break;
264
265 case 100000000000ULL ... 999999999999UL:
266 i = 11;
267 break;
268
269 case 1000000000000ULL ... 9999999999999UL:
270 i = 12;
271 break;
272
273 case 10000000000000ULL ... 99999999999999UL:
274 i = 13;
275 break;
276
277 case 100000000000000ULL ... 999999999999999UL:
278 i = 14;
279 break;
280
281 case 1000000000000000ULL ... 9999999999999999UL:
282 i = 15;
283 break;
284
285 case 10000000000000000ULL ... 99999999999999999UL:
286 i = 16;
287 break;
288
289 case 100000000000000000ULL ... 999999999999999999UL:
290 i = 17;
291 break;
292
293 case 1000000000000000000ULL ... 9999999999999999999UL:
294 i = 18;
295 break;
296
297 case 10000000000000000000ULL ... ULONG_MAX:
298 i = 19;
299 break;
300
301#endif
302 }
303 if (i + 2 > size) // (i + 1) + '\0'
304 return NULL; // too long
305 res = dst + i + 1;
306 *res = '\0';
307 for (; i >= 0; i--) {
308 dst[i] = n % 10U + '0';
309 n /= 10U;
310 }
311 return res;
312}
313
314/*
315 * signed long ASCII representation
316 *
317 * return the last char '\0' or NULL if no enough
318 * space in dst
319 */
320char *ltoa_o(long int n, char *dst, size_t size)
321{
322 char *pos = dst;
323
324 if (n < 0) {
325 if (size < 3)
326 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
327 *pos = '-';
328 pos++;
329 dst = ultoa_o(-n, pos, size - 1);
330 } else {
331 dst = ultoa_o(n, dst, size);
332 }
333 return dst;
334}
335
336/*
337 * signed long long ASCII representation
338 *
339 * return the last char '\0' or NULL if no enough
340 * space in dst
341 */
342char *lltoa(long long n, char *dst, size_t size)
343{
344 char *pos = dst;
345
346 if (n < 0) {
347 if (size < 3)
348 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
349 *pos = '-';
350 pos++;
351 dst = ulltoa(-n, pos, size - 1);
352 } else {
353 dst = ulltoa(n, dst, size);
354 }
355 return dst;
356}
357
358/*
359 * write a ascii representation of a unsigned into dst,
360 * return a pointer to the last character
361 * Pad the ascii representation with '0', using size.
362 */
363char *utoa_pad(unsigned int n, char *dst, size_t size)
364{
365 int i = 0;
366 char *ret;
367
368 switch(n) {
369 case 0U ... 9U:
370 i = 0;
371 break;
372
373 case 10U ... 99U:
374 i = 1;
375 break;
376
377 case 100U ... 999U:
378 i = 2;
379 break;
380
381 case 1000U ... 9999U:
382 i = 3;
383 break;
384
385 case 10000U ... 99999U:
386 i = 4;
387 break;
388
389 case 100000U ... 999999U:
390 i = 5;
391 break;
392
393 case 1000000U ... 9999999U:
394 i = 6;
395 break;
396
397 case 10000000U ... 99999999U:
398 i = 7;
399 break;
400
401 case 100000000U ... 999999999U:
402 i = 8;
403 break;
404
405 case 1000000000U ... 4294967295U:
406 i = 9;
407 break;
408 }
409 if (i + 2 > size) // (i + 1) + '\0'
410 return NULL; // too long
411 if (i < size)
412 i = size - 2; // padding - '\0'
413
414 ret = dst + i + 1;
415 *ret = '\0';
416 for (; i >= 0; i--) {
417 dst[i] = n % 10U + '0';
418 n /= 10U;
419 }
420 return ret;
421}
422
423/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200424 * copies at most <size-1> chars from <src> to <dst>. Last char is always
425 * set to 0, unless <size> is 0. The number of chars copied is returned
426 * (excluding the terminating zero).
427 * This code has been optimized for size and speed : on x86, it's 45 bytes
428 * long, uses only registers, and consumes only 4 cycles per char.
429 */
430int strlcpy2(char *dst, const char *src, int size)
431{
432 char *orig = dst;
433 if (size) {
434 while (--size && (*dst = *src)) {
435 src++; dst++;
436 }
437 *dst = 0;
438 }
439 return dst - orig;
440}
441
442/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200443 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200444 * the ascii representation for number 'n' in decimal.
445 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100446char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200447{
448 char *pos;
449
Willy Tarreau72d759c2007-10-25 12:14:10 +0200450 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200451 *pos-- = '\0';
452
453 do {
454 *pos-- = '0' + n % 10;
455 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200456 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200457 return pos + 1;
458}
459
Willy Tarreau91092e52007-10-25 16:58:42 +0200460/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200461 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200462 * the ascii representation for number 'n' in decimal.
463 */
464char *lltoa_r(long long int in, char *buffer, int size)
465{
466 char *pos;
467 int neg = 0;
468 unsigned long long int n;
469
470 pos = buffer + size - 1;
471 *pos-- = '\0';
472
473 if (in < 0) {
474 neg = 1;
475 n = -in;
476 }
477 else
478 n = in;
479
480 do {
481 *pos-- = '0' + n % 10;
482 n /= 10;
483 } while (n && pos >= buffer);
484 if (neg && pos > buffer)
485 *pos-- = '-';
486 return pos + 1;
487}
488
489/*
490 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200491 * the ascii representation for signed number 'n' in decimal.
492 */
493char *sltoa_r(long n, char *buffer, int size)
494{
495 char *pos;
496
497 if (n >= 0)
498 return ultoa_r(n, buffer, size);
499
500 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
501 *pos = '-';
502 return pos;
503}
504
505/*
506 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200507 * the ascii representation for number 'n' in decimal, formatted for
508 * HTML output with tags to create visual grouping by 3 digits. The
509 * output needs to support at least 171 characters.
510 */
511const char *ulltoh_r(unsigned long long n, char *buffer, int size)
512{
513 char *start;
514 int digit = 0;
515
516 start = buffer + size;
517 *--start = '\0';
518
519 do {
520 if (digit == 3 && start >= buffer + 7)
521 memcpy(start -= 7, "</span>", 7);
522
523 if (start >= buffer + 1) {
524 *--start = '0' + n % 10;
525 n /= 10;
526 }
527
528 if (digit == 3 && start >= buffer + 18)
529 memcpy(start -= 18, "<span class=\"rls\">", 18);
530
531 if (digit++ == 3)
532 digit = 1;
533 } while (n && start > buffer);
534 return start;
535}
536
537/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200538 * This function simply returns a locally allocated string containing the ascii
539 * representation for number 'n' in decimal, unless n is 0 in which case it
540 * returns the alternate string (or an empty string if the alternate string is
541 * NULL). It use is intended for limits reported in reports, where it's
542 * desirable not to display anything if there is no limit. Warning! it shares
543 * the same vector as ultoa_r().
544 */
545const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
546{
547 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
548}
549
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200550/* Trims the first "%f" float in a string to its minimum number of digits after
551 * the decimal point by trimming trailing zeroes, even dropping the decimal
552 * point if not needed. The string is in <buffer> of length <len>, and the
553 * number is expected to start at or after position <num_start> (the first
554 * point appearing there is considered). A NUL character is always placed at
555 * the end if some trimming occurs. The new buffer length is returned.
556 */
557size_t flt_trim(char *buffer, size_t num_start, size_t len)
558{
559 char *end = buffer + len;
560 char *p = buffer + num_start;
561 char *trim;
562
563 do {
564 if (p >= end)
565 return len;
566 trim = p++;
567 } while (*trim != '.');
568
569 /* For now <trim> is on the decimal point. Let's look for any other
570 * meaningful digit after it.
571 */
572 while (p < end) {
573 if (*p++ != '0')
574 trim = p;
575 }
576
577 if (trim < end)
578 *trim = 0;
579
580 return trim - buffer;
581}
582
Willy Tarreauae03d262021-05-08 07:35:00 +0200583/*
584 * This function simply returns a locally allocated string containing
585 * the ascii representation for number 'n' in decimal with useless trailing
586 * zeroes trimmed.
587 */
588char *ftoa_r(double n, char *buffer, int size)
589{
590 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
591 return buffer;
592}
593
Willy Tarreau588297f2014-06-16 15:16:40 +0200594/* returns a locally allocated string containing the quoted encoding of the
595 * input string. The output may be truncated to QSTR_SIZE chars, but it is
596 * guaranteed that the string will always be properly terminated. Quotes are
597 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
598 * always be at least 4 chars.
599 */
600const char *qstr(const char *str)
601{
602 char *ret = quoted_str[quoted_idx];
603 char *p, *end;
604
605 if (++quoted_idx >= NB_QSTR)
606 quoted_idx = 0;
607
608 p = ret;
609 end = ret + QSTR_SIZE;
610
611 *p++ = '"';
612
613 /* always keep 3 chars to support passing "" and the ending " */
614 while (*str && p < end - 3) {
615 if (*str == '"') {
616 *p++ = '"';
617 *p++ = '"';
618 }
619 else
620 *p++ = *str;
621 str++;
622 }
623 *p++ = '"';
624 return ret;
625}
626
Robert Tsai81ae1952007-12-05 10:47:29 +0100627/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200628 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
629 *
630 * It looks like this one would be a good candidate for inlining, but this is
631 * not interesting because it around 35 bytes long and often called multiple
632 * times within the same function.
633 */
634int ishex(char s)
635{
636 s -= '0';
637 if ((unsigned char)s <= 9)
638 return 1;
639 s -= 'A' - '0';
640 if ((unsigned char)s <= 5)
641 return 1;
642 s -= 'a' - 'A';
643 if ((unsigned char)s <= 5)
644 return 1;
645 return 0;
646}
647
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100648/* rounds <i> down to the closest value having max 2 digits */
649unsigned int round_2dig(unsigned int i)
650{
651 unsigned int mul = 1;
652
653 while (i >= 100) {
654 i /= 10;
655 mul *= 10;
656 }
657 return i * mul;
658}
659
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100660/*
661 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
662 * invalid character is found, a pointer to it is returned. If everything is
663 * fine, NULL is returned.
664 */
665const char *invalid_char(const char *name)
666{
667 if (!*name)
668 return name;
669
670 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100671 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100672 *name != '_' && *name != '-')
673 return name;
674 name++;
675 }
676 return NULL;
677}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200678
679/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200680 * Checks <name> for invalid characters. Valid chars are [_.-] and those
681 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200682 * If an invalid character is found, a pointer to it is returned.
683 * If everything is fine, NULL is returned.
684 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200685static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200686
687 if (!*name)
688 return name;
689
690 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100691 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200692 *name != '_' && *name != '-')
693 return name;
694
695 name++;
696 }
697
698 return NULL;
699}
700
701/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200702 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
703 * If an invalid character is found, a pointer to it is returned.
704 * If everything is fine, NULL is returned.
705 */
706const char *invalid_domainchar(const char *name) {
707 return __invalid_char(name, isalnum);
708}
709
710/*
711 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
712 * If an invalid character is found, a pointer to it is returned.
713 * If everything is fine, NULL is returned.
714 */
715const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200716 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200717}
718
719/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100720 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100721 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
722 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
723 * the function tries to guess the address family from the syntax. If the
724 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100725 * string is assumed to contain only an address, no port. The address can be a
726 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
727 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
728 * The return address will only have the address family and the address set,
729 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100730 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
731 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100732 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200733 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100734struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200735{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100736 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100737 /* max IPv6 length, including brackets and terminating NULL */
738 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100739 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100740
741 /* check IPv6 with square brackets */
742 if (str[0] == '[') {
743 size_t iplength = strlen(str);
744
745 if (iplength < 4) {
746 /* minimal size is 4 when using brackets "[::]" */
747 goto fail;
748 }
749 else if (iplength >= sizeof(tmpip)) {
750 /* IPv6 literal can not be larger than tmpip */
751 goto fail;
752 }
753 else {
754 if (str[iplength - 1] != ']') {
755 /* if address started with bracket, it should end with bracket */
756 goto fail;
757 }
758 else {
759 memcpy(tmpip, str + 1, iplength - 2);
760 tmpip[iplength - 2] = '\0';
761 str = tmpip;
762 }
763 }
764 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100765
Willy Tarreaufab5a432011-03-04 15:31:53 +0100766 /* Any IPv6 address */
767 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100768 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
769 sa->ss_family = AF_INET6;
770 else if (sa->ss_family != AF_INET6)
771 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100772 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100773 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100774 }
775
Willy Tarreau24709282013-03-10 21:32:12 +0100776 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100777 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100778 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
779 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100780 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100781 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100782 }
783
784 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100785 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
786 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100787 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100788 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100789 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100790 }
791
792 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100793 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
794 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100795 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100796 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100797 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100798 }
799
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100800 if (!resolve)
801 return NULL;
802
Emeric Brund30e9a12020-12-23 18:49:16 +0100803 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200804 return NULL;
805
David du Colombierd5f43282011-03-17 10:40:16 +0100806#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200807 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100808 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100809 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100810
811 memset(&result, 0, sizeof(result));
812 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100813 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100814 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200815 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100816 hints.ai_protocol = 0;
817
818 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100819 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
820 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100821 else if (sa->ss_family != result->ai_family) {
822 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100823 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100824 }
Willy Tarreau24709282013-03-10 21:32:12 +0100825
David du Colombierd5f43282011-03-17 10:40:16 +0100826 switch (result->ai_family) {
827 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100828 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100829 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100830 success = 1;
831 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100832 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100833 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100834 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100835 success = 1;
836 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100837 }
838 }
839
Sean Carey58ea0392013-02-15 23:39:18 +0100840 if (result)
841 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100842
843 if (success)
844 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100845 }
David du Colombierd5f43282011-03-17 10:40:16 +0100846#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200847 /* try to resolve an IPv4/IPv6 hostname */
848 he = gethostbyname(str);
849 if (he) {
850 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
851 sa->ss_family = he->h_addrtype;
852 else if (sa->ss_family != he->h_addrtype)
853 goto fail;
854
855 switch (sa->ss_family) {
856 case AF_INET:
857 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100858 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200859 return sa;
860 case AF_INET6:
861 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100862 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200863 return sa;
864 }
865 }
866
David du Colombierd5f43282011-03-17 10:40:16 +0100867 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100868 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100869 return NULL;
870}
871
872/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100873 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
874 * range or offset consisting in two integers that the caller will have to
875 * check to find the relevant input format. The following format are supported :
876 *
877 * String format | address | port | low | high
878 * addr | <addr> | 0 | 0 | 0
879 * addr: | <addr> | 0 | 0 | 0
880 * addr:port | <addr> | <port> | <port> | <port>
881 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
882 * addr:+port | <addr> | <port> | 0 | <port>
883 * addr:-port | <addr> |-<port> | <port> | 0
884 *
885 * The detection of a port range or increment by the caller is made by
886 * comparing <low> and <high>. If both are equal, then port 0 means no port
887 * was specified. The caller may pass NULL for <low> and <high> if it is not
888 * interested in retrieving port ranges.
889 *
890 * Note that <addr> above may also be :
891 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
892 * - "*" => family will be AF_INET and address will be INADDR_ANY
893 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
894 * - a host name => family and address will depend on host name resolving.
895 *
Willy Tarreau24709282013-03-10 21:32:12 +0100896 * A prefix may be passed in before the address above to force the family :
897 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
898 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
899 * - "unix@" => force address to be a path to a UNIX socket even if the
900 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200901 * - 'abns@' -> force address to belong to the abstract namespace (Linux
902 * only). These sockets are just like Unix sockets but without
903 * the need for an underlying file system. The address is a
904 * string. Technically it's like a Unix socket with a zero in
905 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100906 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100907 *
mildisff5d5102015-10-26 18:50:08 +0100908 * IPv6 addresses can be declared with or without square brackets. When using
909 * square brackets for IPv6 addresses, the port separator (colon) is optional.
910 * If not using square brackets, and in order to avoid any ambiguity with
911 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
912 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
913 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100914 *
915 * If <pfx> is non-null, it is used as a string prefix before any path-based
916 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100917 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200918 * if <fqdn> is non-null, it will be filled with :
919 * - a pointer to the FQDN of the server name to resolve if there's one, and
920 * that the caller will have to free(),
921 * - NULL if there was an explicit address that doesn't require resolution.
922 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200923 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
924 * still honored so it is possible for the caller to know whether a resolution
925 * failed by clearing this flag and checking if <fqdn> was filled, indicating
926 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200927 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100928 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200929 * the address when cast to sockaddr_in and the address family is
930 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200931 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200932 * The matching protocol will be set into <proto> if non-null.
933 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200934 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
935 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100936 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200937struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
938 struct protocol **proto, char **err,
939 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100940{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100941 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100942 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200943 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100944 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100945 char *port1, *port2;
946 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200947 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200948 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200949 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100950
951 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200952 if (fqdn)
953 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200954
Willy Tarreaudad36a32013-03-11 01:20:04 +0100955 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100956 if (str2 == NULL) {
957 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100958 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100959 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200960
Willy Tarreau9f69f462015-09-08 16:01:25 +0200961 if (!*str2) {
962 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
963 goto out;
964 }
965
Willy Tarreau24709282013-03-10 21:32:12 +0100966 memset(&ss, 0, sizeof(ss));
967
Willy Tarreaue835bd82020-09-16 11:35:47 +0200968 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100969 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
970 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM)))
Willy Tarreaue835bd82020-09-16 11:35:47 +0200971 sock_type = ctrl_type = SOCK_DGRAM;
972 else
973 sock_type = ctrl_type = SOCK_STREAM;
974
975 if (strncmp(str2, "stream+", 7) == 0) {
976 str2 += 7;
977 sock_type = ctrl_type = SOCK_STREAM;
978 }
979 else if (strncmp(str2, "dgram+", 6) == 0) {
980 str2 += 6;
981 sock_type = ctrl_type = SOCK_DGRAM;
982 }
983
Willy Tarreau24709282013-03-10 21:32:12 +0100984 if (strncmp(str2, "unix@", 5) == 0) {
985 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200986 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100987 ss.ss_family = AF_UNIX;
988 }
Emeric Brunce325c42021-04-02 17:05:09 +0200989 else if (strncmp(str2, "uxdg@", 5) == 0) {
990 str2 += 5;
991 abstract = 0;
992 ss.ss_family = AF_UNIX;
993 sock_type = ctrl_type = SOCK_DGRAM;
994 }
995 else if (strncmp(str2, "uxst@", 5) == 0) {
996 str2 += 5;
997 abstract = 0;
998 ss.ss_family = AF_UNIX;
999 sock_type = ctrl_type = SOCK_STREAM;
1000 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001001 else if (strncmp(str2, "abns@", 5) == 0) {
1002 str2 += 5;
1003 abstract = 1;
1004 ss.ss_family = AF_UNIX;
1005 }
Emeric Brunce325c42021-04-02 17:05:09 +02001006 else if (strncmp(str2, "ip@", 3) == 0) {
1007 str2 += 3;
1008 ss.ss_family = AF_UNSPEC;
1009 }
Willy Tarreau24709282013-03-10 21:32:12 +01001010 else if (strncmp(str2, "ipv4@", 5) == 0) {
1011 str2 += 5;
1012 ss.ss_family = AF_INET;
1013 }
1014 else if (strncmp(str2, "ipv6@", 5) == 0) {
1015 str2 += 5;
1016 ss.ss_family = AF_INET6;
1017 }
Emeric Brunce325c42021-04-02 17:05:09 +02001018 else if (strncmp(str2, "tcp4@", 5) == 0) {
1019 str2 += 5;
1020 ss.ss_family = AF_INET;
1021 sock_type = ctrl_type = SOCK_STREAM;
1022 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001023 else if (strncmp(str2, "udp4@", 5) == 0) {
1024 str2 += 5;
1025 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001026 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001027 }
Emeric Brunce325c42021-04-02 17:05:09 +02001028 else if (strncmp(str2, "tcp6@", 5) == 0) {
1029 str2 += 5;
1030 ss.ss_family = AF_INET6;
1031 sock_type = ctrl_type = SOCK_STREAM;
1032 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001033 else if (strncmp(str2, "udp6@", 5) == 0) {
1034 str2 += 5;
1035 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001036 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001037 }
Emeric Brunce325c42021-04-02 17:05:09 +02001038 else if (strncmp(str2, "tcp@", 4) == 0) {
1039 str2 += 4;
1040 ss.ss_family = AF_UNSPEC;
1041 sock_type = ctrl_type = SOCK_STREAM;
1042 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001043 else if (strncmp(str2, "udp@", 4) == 0) {
1044 str2 += 4;
1045 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001046 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001047 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001048 else if (strncmp(str2, "quic4@", 6) == 0) {
1049 str2 += 6;
1050 ss.ss_family = AF_INET;
1051 sock_type = SOCK_DGRAM;
1052 ctrl_type = SOCK_STREAM;
1053 }
1054 else if (strncmp(str2, "quic6@", 6) == 0) {
1055 str2 += 6;
1056 ss.ss_family = AF_INET6;
1057 sock_type = SOCK_DGRAM;
1058 ctrl_type = SOCK_STREAM;
1059 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001060 else if (strncmp(str2, "fd@", 3) == 0) {
1061 str2 += 3;
1062 ss.ss_family = AF_CUST_EXISTING_FD;
1063 }
1064 else if (strncmp(str2, "sockpair@", 9) == 0) {
1065 str2 += 9;
1066 ss.ss_family = AF_CUST_SOCKPAIR;
1067 }
Willy Tarreau24709282013-03-10 21:32:12 +01001068 else if (*str2 == '/') {
1069 ss.ss_family = AF_UNIX;
1070 }
1071 else
1072 ss.ss_family = AF_UNSPEC;
1073
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001074 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001075 struct sockaddr_storage ss2;
1076 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001077 char *endptr;
1078
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001079 new_fd = strtol(str2, &endptr, 10);
1080 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001081 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1082 goto out;
1083 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001084
Willy Tarreaua215be22020-09-16 10:14:16 +02001085 /* just verify that it's a socket */
1086 addr_len = sizeof(ss2);
1087 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1088 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1089 goto out;
1090 }
1091
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001092 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1093 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001094 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001095 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001096 char *endptr;
1097
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001098 new_fd = strtol(str2, &endptr, 10);
1099 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001100 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001101 goto out;
1102 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001103
Willy Tarreau6edc7222020-09-15 17:41:56 +02001104 if (opts & PA_O_SOCKET_FD) {
1105 socklen_t addr_len;
1106 int type;
1107
1108 addr_len = sizeof(ss);
1109 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1110 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1111 goto out;
1112 }
1113
1114 addr_len = sizeof(type);
1115 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001116 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001117 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1118 goto out;
1119 }
1120
1121 porta = portl = porth = get_host_port(&ss);
1122 } else if (opts & PA_O_RAW_FD) {
1123 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1124 ((struct sockaddr_in *)&ss)->sin_port = 0;
1125 } else {
1126 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1127 goto out;
1128 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001129 }
1130 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001131 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001132 int prefix_path_len;
1133 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001134 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001135
1136 /* complete unix socket path name during startup or soft-restart is
1137 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1138 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001139 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001140 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001141 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001142
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001143 adr_len = strlen(str2);
1144 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001145 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1146 goto out;
1147 }
1148
Willy Tarreauccfccef2014-05-10 01:49:15 +02001149 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001150 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001151 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001152 memcpy(un->sun_path, pfx, prefix_path_len);
1153 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001154 }
Willy Tarreau24709282013-03-10 21:32:12 +01001155 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001156 char *end = str2 + strlen(str2);
1157 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001158
mildisff5d5102015-10-26 18:50:08 +01001159 /* search for : or ] whatever comes first */
1160 for (chr = end-1; chr > str2; chr--) {
1161 if (*chr == ']' || *chr == ':')
1162 break;
1163 }
1164
1165 if (*chr == ':') {
1166 /* Found a colon before a closing-bracket, must be a port separator.
1167 * This guarantee backward compatibility.
1168 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001169 if (!(opts & PA_O_PORT_OK)) {
1170 memprintf(err, "port specification not permitted here in '%s'", str);
1171 goto out;
1172 }
mildisff5d5102015-10-26 18:50:08 +01001173 *chr++ = '\0';
1174 port1 = chr;
1175 }
1176 else {
1177 /* Either no colon and no closing-bracket
1178 * or directly ending with a closing-bracket.
1179 * However, no port.
1180 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001181 if (opts & PA_O_PORT_MAND) {
1182 memprintf(err, "missing port specification in '%s'", str);
1183 goto out;
1184 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001185 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001186 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001187
Willy Tarreau90807112020-02-25 08:16:33 +01001188 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001189 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001190 if (port2) {
1191 if (!(opts & PA_O_PORT_RANGE)) {
1192 memprintf(err, "port range not permitted here in '%s'", str);
1193 goto out;
1194 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001195 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001196 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001197 else
1198 port2 = port1;
1199 portl = atoi(port1);
1200 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001201
1202 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1203 memprintf(err, "invalid port '%s'", port1);
1204 goto out;
1205 }
1206
1207 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1208 memprintf(err, "invalid port '%s'", port2);
1209 goto out;
1210 }
1211
1212 if (portl > porth) {
1213 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1214 goto out;
1215 }
1216
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001217 porta = portl;
1218 }
1219 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001220 if (!(opts & PA_O_PORT_OFS)) {
1221 memprintf(err, "port offset not permitted here in '%s'", str);
1222 goto out;
1223 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001224 portl = atoi(port1 + 1);
1225 porta = -portl;
1226 }
1227 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001228 if (!(opts & PA_O_PORT_OFS)) {
1229 memprintf(err, "port offset not permitted here in '%s'", str);
1230 goto out;
1231 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001232 porth = atoi(port1 + 1);
1233 porta = porth;
1234 }
1235 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001236 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001237 goto out;
1238 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001239 else if (opts & PA_O_PORT_MAND) {
1240 memprintf(err, "missing port specification in '%s'", str);
1241 goto out;
1242 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001243
1244 /* first try to parse the IP without resolving. If it fails, it
1245 * tells us we need to keep a copy of the FQDN to resolve later
1246 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001247 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001248 */
1249 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001250 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1251 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001252 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1253 goto out;
1254 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001255
Willy Tarreauceccdd72016-11-02 22:27:10 +01001256 if (fqdn) {
1257 if (str2 != back)
1258 memmove(back, str2, strlen(str2) + 1);
1259 *fqdn = back;
1260 back = NULL;
1261 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001262 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001263 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001264 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001265
Willy Tarreaue835bd82020-09-16 11:35:47 +02001266 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1267 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1268 goto out;
1269 }
1270 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1271 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1272 goto out;
1273 }
1274
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001275 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001276 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001277 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1278 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001279 * in which case the address is not known yet (this is only
1280 * for servers actually).
1281 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001282 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001283 sock_type == SOCK_DGRAM,
1284 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001285
Emeric Brun26754902021-04-07 14:26:44 +02001286 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001287 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1288 goto out;
1289 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001290
1291 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1292 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1293 goto out;
1294 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001295 }
1296
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001297 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001298 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001299 if (port)
1300 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001301 if (low)
1302 *low = portl;
1303 if (high)
1304 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001305 if (fd)
1306 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001307 if (proto)
1308 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001309 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001310 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001311}
1312
Thayne McCombs92149f92020-11-20 01:28:26 -07001313/* converts <addr> and <port> into a string representation of the address and port. This is sort
1314 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1315 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1316 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1317 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1318 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1319 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1320 *
1321 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1322 */
1323char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1324{
1325 char buffer[INET6_ADDRSTRLEN];
1326 char *out = NULL;
1327 const void *ptr;
1328 const char *path;
1329
1330 switch (addr->ss_family) {
1331 case AF_INET:
1332 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1333 break;
1334 case AF_INET6:
1335 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1336 break;
1337 case AF_UNIX:
1338 path = ((struct sockaddr_un *)addr)->sun_path;
1339 if (path[0] == '\0') {
1340 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1341 return memprintf(&out, "abns@%.*s", max_length, path+1);
1342 } else {
1343 return strdup(path);
1344 }
1345 case AF_CUST_SOCKPAIR:
1346 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1347 default:
1348 return NULL;
1349 }
1350 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1351 if (map_ports)
1352 return memprintf(&out, "%s:%+d", buffer, port);
1353 else
1354 return memprintf(&out, "%s:%d", buffer, port);
1355}
1356
1357
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001358/* converts <str> to a struct in_addr containing a network mask. It can be
1359 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001360 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001361 */
1362int str2mask(const char *str, struct in_addr *mask)
1363{
1364 if (strchr(str, '.') != NULL) { /* dotted notation */
1365 if (!inet_pton(AF_INET, str, mask))
1366 return 0;
1367 }
1368 else { /* mask length */
1369 char *err;
1370 unsigned long len = strtol(str, &err, 10);
1371
1372 if (!*str || (err && *err) || (unsigned)len > 32)
1373 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001374
1375 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001376 }
1377 return 1;
1378}
1379
Tim Duesterhus47185172018-01-25 16:24:49 +01001380/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001381 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001382 * if the conversion succeeds otherwise zero.
1383 */
1384int str2mask6(const char *str, struct in6_addr *mask)
1385{
1386 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1387 if (!inet_pton(AF_INET6, str, mask))
1388 return 0;
1389 }
1390 else { /* mask length */
1391 char *err;
1392 unsigned long len = strtol(str, &err, 10);
1393
1394 if (!*str || (err && *err) || (unsigned)len > 128)
1395 return 0;
1396
1397 len2mask6(len, mask);
1398 }
1399 return 1;
1400}
1401
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001402/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1403 * succeeds otherwise zero.
1404 */
1405int cidr2dotted(int cidr, struct in_addr *mask) {
1406
1407 if (cidr < 0 || cidr > 32)
1408 return 0;
1409
1410 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1411 return 1;
1412}
1413
Thierry Fournier70473a52016-02-17 17:12:14 +01001414/* Convert mask from bit length form to in_addr form.
1415 * This function never fails.
1416 */
1417void len2mask4(int len, struct in_addr *addr)
1418{
1419 if (len >= 32) {
1420 addr->s_addr = 0xffffffff;
1421 return;
1422 }
1423 if (len <= 0) {
1424 addr->s_addr = 0x00000000;
1425 return;
1426 }
1427 addr->s_addr = 0xffffffff << (32 - len);
1428 addr->s_addr = htonl(addr->s_addr);
1429}
1430
1431/* Convert mask from bit length form to in6_addr form.
1432 * This function never fails.
1433 */
1434void len2mask6(int len, struct in6_addr *addr)
1435{
1436 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1437 len -= 32;
1438 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1439 len -= 32;
1440 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1441 len -= 32;
1442 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1443}
1444
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001445/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001446 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001447 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001448 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001449 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1450 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001451int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001452{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001453 __label__ out_free, out_err;
1454 char *c, *s;
1455 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001456
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001457 s = strdup(str);
1458 if (!s)
1459 return 0;
1460
Willy Tarreaubaaee002006-06-26 02:48:02 +02001461 memset(mask, 0, sizeof(*mask));
1462 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001463
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001464 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001465 *c++ = '\0';
1466 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001467 if (!str2mask(c, mask))
1468 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001469 }
1470 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001471 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001472 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001473 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001474 struct hostent *he;
1475
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001476 if (!resolve)
1477 goto out_err;
1478
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001479 if ((he = gethostbyname(s)) == NULL) {
1480 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001481 }
1482 else
1483 *addr = *(struct in_addr *) *(he->h_addr_list);
1484 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001485
1486 ret_val = 1;
1487 out_free:
1488 free(s);
1489 return ret_val;
1490 out_err:
1491 ret_val = 0;
1492 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001493}
1494
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001495
1496/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001497 * converts <str> to two struct in6_addr* which must be pre-allocated.
1498 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001499 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001500 * Returns 1 if OK, 0 if error.
1501 */
1502int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1503{
1504 char *c, *s;
1505 int ret_val = 0;
1506 char *err;
1507 unsigned long len = 128;
1508
1509 s = strdup(str);
1510 if (!s)
1511 return 0;
1512
1513 memset(mask, 0, sizeof(*mask));
1514 memset(addr, 0, sizeof(*addr));
1515
1516 if ((c = strrchr(s, '/')) != NULL) {
1517 *c++ = '\0'; /* c points to the mask */
1518 if (!*c)
1519 goto out_free;
1520
1521 len = strtoul(c, &err, 10);
1522 if ((err && *err) || (unsigned)len > 128)
1523 goto out_free;
1524 }
1525 *mask = len; /* OK we have a valid mask in <len> */
1526
1527 if (!inet_pton(AF_INET6, s, addr))
1528 goto out_free;
1529
1530 ret_val = 1;
1531 out_free:
1532 free(s);
1533 return ret_val;
1534}
1535
1536
1537/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001538 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1539 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1540 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001541 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001542int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001543{
1544 int saw_digit, octets, ch;
1545 u_char tmp[4], *tp;
1546 const char *cp = addr;
1547
1548 saw_digit = 0;
1549 octets = 0;
1550 *(tp = tmp) = 0;
1551
1552 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001553 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001554 if (digit > 9 && ch != '.')
1555 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001556 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001557 if (digit <= 9) {
1558 u_int new = *tp * 10 + digit;
1559 if (new > 255)
1560 return 0;
1561 *tp = new;
1562 if (!saw_digit) {
1563 if (++octets > 4)
1564 return 0;
1565 saw_digit = 1;
1566 }
1567 } else if (ch == '.' && saw_digit) {
1568 if (octets == 4)
1569 return 0;
1570 *++tp = 0;
1571 saw_digit = 0;
1572 } else
1573 return 0;
1574 }
1575
1576 if (octets < 4)
1577 return 0;
1578
1579 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001580 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001581}
1582
1583/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001584 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001585 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001586 * the hostname. Actually only http and https are supported. <out> can be NULL.
1587 * This function returns the consumed length. It is useful if you parse complete
1588 * url like http://host:port/path, because the consumed length corresponds to
1589 * the first character of the path. If the conversion fails, it returns -1.
1590 *
1591 * This function tries to resolve the DNS name if haproxy is in starting mode.
1592 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001593 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001594int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001595{
1596 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001597 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001598 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001599 unsigned long long int http_code = 0;
1600 int default_port;
1601 struct hostent *he;
1602 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001603
1604 /* Firstly, try to find :// pattern */
1605 while (curr < url+ulen && url_code != 0x3a2f2f) {
1606 url_code = ((url_code & 0xffff) << 8);
1607 url_code += (unsigned char)*curr++;
1608 }
1609
1610 /* Secondly, if :// pattern is found, verify parsed stuff
1611 * before pattern is matching our http pattern.
1612 * If so parse ip address and port in uri.
1613 *
1614 * WARNING: Current code doesn't support dynamic async dns resolver.
1615 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001616 if (url_code != 0x3a2f2f)
1617 return -1;
1618
1619 /* Copy scheme, and utrn to lower case. */
1620 while (cp < curr - 3)
1621 http_code = (http_code << 8) + *cp++;
1622 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001623
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001624 /* HTTP or HTTPS url matching */
1625 if (http_code == 0x2020202068747470ULL) {
1626 default_port = 80;
1627 if (out)
1628 out->scheme = SCH_HTTP;
1629 }
1630 else if (http_code == 0x2020206874747073ULL) {
1631 default_port = 443;
1632 if (out)
1633 out->scheme = SCH_HTTPS;
1634 }
1635 else
1636 return -1;
1637
1638 /* If the next char is '[', the host address is IPv6. */
1639 if (*curr == '[') {
1640 curr++;
1641
1642 /* Check trash size */
1643 if (trash.size < ulen)
1644 return -1;
1645
1646 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001647 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001648 for (end = curr;
1649 end < url + ulen && *end != ']';
1650 end++, p++)
1651 *p = *end;
1652 if (*end != ']')
1653 return -1;
1654 *p = '\0';
1655
1656 /* Update out. */
1657 if (out) {
1658 out->host = curr;
1659 out->host_len = end - curr;
1660 }
1661
1662 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001663 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001664 return -1;
1665 end++;
1666
1667 /* Decode port. */
1668 if (*end == ':') {
1669 end++;
1670 default_port = read_uint(&end, url + ulen);
1671 }
1672 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1673 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1674 return end - url;
1675 }
1676 else {
1677 /* We are looking for IP address. If you want to parse and
1678 * resolve hostname found in url, you can use str2sa_range(), but
1679 * be warned this can slow down global daemon performances
1680 * while handling lagging dns responses.
1681 */
1682 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1683 if (ret) {
1684 /* Update out. */
1685 if (out) {
1686 out->host = curr;
1687 out->host_len = ret;
1688 }
1689
1690 curr += ret;
1691
1692 /* Decode port. */
1693 if (*curr == ':') {
1694 curr++;
1695 default_port = read_uint(&curr, url + ulen);
1696 }
1697 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1698
1699 /* Set family. */
1700 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1701 return curr - url;
1702 }
1703 else if (global.mode & MODE_STARTING) {
1704 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1705 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001706 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001707
1708 /* look for : or / or end */
1709 for (end = curr;
1710 end < url + ulen && *end != '/' && *end != ':';
1711 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001712 memcpy(trash.area, curr, end - curr);
1713 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001714
1715 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001716 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001717 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001718 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001719
1720 /* Update out. */
1721 if (out) {
1722 out->host = curr;
1723 out->host_len = end - curr;
1724 }
1725
1726 /* Decode port. */
1727 if (*end == ':') {
1728 end++;
1729 default_port = read_uint(&end, url + ulen);
1730 }
1731
1732 /* Copy IP address, set port and family. */
1733 switch (he->h_addrtype) {
1734 case AF_INET:
1735 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1736 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1737 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1738 return end - url;
1739
1740 case AF_INET6:
1741 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1742 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1743 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1744 return end - url;
1745 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001746 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001747 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001748 return -1;
1749}
1750
Willy Tarreau631f01c2011-09-05 00:36:48 +02001751/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1752 * address family is returned so that it's easy for the caller to adapt to the
1753 * output format. Zero is returned if the address family is not supported. -1
1754 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1755 * supported.
1756 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001757int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001758{
1759
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001760 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001761
1762 if (size < 5)
1763 return 0;
1764 *str = '\0';
1765
1766 switch (addr->ss_family) {
1767 case AF_INET:
1768 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1769 break;
1770 case AF_INET6:
1771 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1772 break;
1773 case AF_UNIX:
1774 memcpy(str, "unix", 5);
1775 return addr->ss_family;
1776 default:
1777 return 0;
1778 }
1779
1780 if (inet_ntop(addr->ss_family, ptr, str, size))
1781 return addr->ss_family;
1782
1783 /* failed */
1784 return -1;
1785}
1786
Simon Horman75ab8bd2014-06-16 09:39:41 +09001787/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1788 * address family is returned so that it's easy for the caller to adapt to the
1789 * output format. Zero is returned if the address family is not supported. -1
1790 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1791 * supported.
1792 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001793int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001794{
1795
1796 uint16_t port;
1797
1798
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001799 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001800 return 0;
1801 *str = '\0';
1802
1803 switch (addr->ss_family) {
1804 case AF_INET:
1805 port = ((struct sockaddr_in *)addr)->sin_port;
1806 break;
1807 case AF_INET6:
1808 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1809 break;
1810 case AF_UNIX:
1811 memcpy(str, "unix", 5);
1812 return addr->ss_family;
1813 default:
1814 return 0;
1815 }
1816
1817 snprintf(str, size, "%u", ntohs(port));
1818 return addr->ss_family;
1819}
1820
Willy Tarreau16e01562016-08-09 16:46:18 +02001821/* check if the given address is local to the system or not. It will return
1822 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1823 * it is. We don't want to iterate over all interfaces for this (and it is not
1824 * portable). So instead we try to bind in UDP to this address on a free non
1825 * privileged port and to connect to the same address, port 0 (connect doesn't
1826 * care). If it succeeds, we own the address. Note that non-inet addresses are
1827 * considered local since they're most likely AF_UNIX.
1828 */
1829int addr_is_local(const struct netns_entry *ns,
1830 const struct sockaddr_storage *orig)
1831{
1832 struct sockaddr_storage addr;
1833 int result;
1834 int fd;
1835
1836 if (!is_inet_addr(orig))
1837 return 1;
1838
1839 memcpy(&addr, orig, sizeof(addr));
1840 set_host_port(&addr, 0);
1841
1842 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1843 if (fd < 0)
1844 return -1;
1845
1846 result = -1;
1847 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1848 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1849 result = 0; // fail, non-local address
1850 else
1851 result = 1; // success, local address
1852 }
1853 else {
1854 if (errno == EADDRNOTAVAIL)
1855 result = 0; // definitely not local :-)
1856 }
1857 close(fd);
1858
1859 return result;
1860}
1861
Willy Tarreaubaaee002006-06-26 02:48:02 +02001862/* will try to encode the string <string> replacing all characters tagged in
1863 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1864 * prefixed by <escape>, and will store the result between <start> (included)
1865 * and <stop> (excluded), and will always terminate the string with a '\0'
1866 * before <stop>. The position of the '\0' is returned if the conversion
1867 * completes. If bytes are missing between <start> and <stop>, then the
1868 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1869 * cannot even be stored so we return <start> without writing the 0.
1870 * The input string must also be zero-terminated.
1871 */
1872const char hextab[16] = "0123456789ABCDEF";
1873char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001874 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001875 const char *string)
1876{
1877 if (start < stop) {
1878 stop--; /* reserve one byte for the final '\0' */
1879 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001880 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001881 *start++ = *string;
1882 else {
1883 if (start + 3 >= stop)
1884 break;
1885 *start++ = escape;
1886 *start++ = hextab[(*string >> 4) & 15];
1887 *start++ = hextab[*string & 15];
1888 }
1889 string++;
1890 }
1891 *start = '\0';
1892 }
1893 return start;
1894}
1895
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001896/*
1897 * Same behavior as encode_string() above, except that it encodes chunk
1898 * <chunk> instead of a string.
1899 */
1900char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001901 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001902 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001903{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001904 char *str = chunk->area;
1905 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001906
1907 if (start < stop) {
1908 stop--; /* reserve one byte for the final '\0' */
1909 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001910 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001911 *start++ = *str;
1912 else {
1913 if (start + 3 >= stop)
1914 break;
1915 *start++ = escape;
1916 *start++ = hextab[(*str >> 4) & 15];
1917 *start++ = hextab[*str & 15];
1918 }
1919 str++;
1920 }
1921 *start = '\0';
1922 }
1923 return start;
1924}
1925
Dragan Dosen0edd1092016-02-12 13:23:02 +01001926/*
1927 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001928 * character. The input <string> must be zero-terminated. The result will
1929 * be stored between <start> (included) and <stop> (excluded). This
1930 * function will always try to terminate the resulting string with a '\0'
1931 * before <stop>, and will return its position if the conversion
1932 * completes.
1933 */
1934char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001935 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001936 const char *string)
1937{
1938 if (start < stop) {
1939 stop--; /* reserve one byte for the final '\0' */
1940 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001941 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001942 *start++ = *string;
1943 else {
1944 if (start + 2 >= stop)
1945 break;
1946 *start++ = escape;
1947 *start++ = *string;
1948 }
1949 string++;
1950 }
1951 *start = '\0';
1952 }
1953 return start;
1954}
1955
1956/*
1957 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001958 * character. <chunk> contains the input to be escaped. The result will be
1959 * stored between <start> (included) and <stop> (excluded). The function
1960 * will always try to terminate the resulting string with a '\0' before
1961 * <stop>, and will return its position if the conversion completes.
1962 */
1963char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001964 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001965 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001966{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001967 char *str = chunk->area;
1968 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001969
1970 if (start < stop) {
1971 stop--; /* reserve one byte for the final '\0' */
1972 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001973 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001974 *start++ = *str;
1975 else {
1976 if (start + 2 >= stop)
1977 break;
1978 *start++ = escape;
1979 *start++ = *str;
1980 }
1981 str++;
1982 }
1983 *start = '\0';
1984 }
1985 return start;
1986}
1987
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001988/* Check a string for using it in a CSV output format. If the string contains
1989 * one of the following four char <">, <,>, CR or LF, the string is
1990 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1991 * <str> is the input string to be escaped. The function assumes that
1992 * the input string is null-terminated.
1993 *
1994 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001995 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001996 * format.
1997 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001998 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001999 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002000 * If <quote> is 1, the converter puts the quotes only if any reserved character
2001 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002002 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002003 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002004 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002005 * The function returns the converted string on its output. If an error
2006 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002007 * for using the function directly as printf() argument.
2008 *
2009 * If the output buffer is too short to contain the input string, the result
2010 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002011 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002012 * This function appends the encoding to the existing output chunk, and it
2013 * guarantees that it starts immediately at the first available character of
2014 * the chunk. Please use csv_enc() instead if you want to replace the output
2015 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002016 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002017const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002018{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002019 char *end = output->area + output->size;
2020 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002021 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002022
Willy Tarreaub631c292016-01-08 10:04:08 +01002023 if (quote == 1) {
2024 /* automatic quoting: first verify if we'll have to quote the string */
2025 if (!strpbrk(str, "\n\r,\""))
2026 quote = 0;
2027 }
2028
2029 if (quote)
2030 *ptr++ = '"';
2031
Willy Tarreau898529b2016-01-06 18:07:04 +01002032 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2033 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002034 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002035 ptr++;
2036 if (ptr >= end - 2) {
2037 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002038 break;
2039 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002040 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002041 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002042 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002043 str++;
2044 }
2045
Willy Tarreaub631c292016-01-08 10:04:08 +01002046 if (quote)
2047 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002048
Willy Tarreau898529b2016-01-06 18:07:04 +01002049 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002050 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002051 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002052}
2053
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002054/* Decode an URL-encoded string in-place. The resulting string might
2055 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002056 * aborted, the string is truncated before the issue and a negative value is
2057 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002058 * If the 'in_form' argument is non-nul the string is assumed to be part of
2059 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2060 * turned to a space. If it's zero, this will only be done after a question
2061 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002062 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002063int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002064{
2065 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002066 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002067
2068 in = string;
2069 out = string;
2070 while (*in) {
2071 switch (*in) {
2072 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002073 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002074 break;
2075 case '%' :
2076 if (!ishex(in[1]) || !ishex(in[2]))
2077 goto end;
2078 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2079 in += 2;
2080 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002081 case '?':
2082 in_form = 1;
2083 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002084 default:
2085 *out++ = *in;
2086 break;
2087 }
2088 in++;
2089 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002090 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002091 end:
2092 *out = 0;
2093 return ret;
2094}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002095
Willy Tarreau6911fa42007-03-04 18:06:08 +01002096unsigned int str2ui(const char *s)
2097{
2098 return __str2ui(s);
2099}
2100
2101unsigned int str2uic(const char *s)
2102{
2103 return __str2uic(s);
2104}
2105
2106unsigned int strl2ui(const char *s, int len)
2107{
2108 return __strl2ui(s, len);
2109}
2110
2111unsigned int strl2uic(const char *s, int len)
2112{
2113 return __strl2uic(s, len);
2114}
2115
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002116unsigned int read_uint(const char **s, const char *end)
2117{
2118 return __read_uint(s, end);
2119}
2120
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002121/* This function reads an unsigned integer from the string pointed to by <s> and
2122 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2123 * function automatically stops at <end>. If the number overflows, the 2^64-1
2124 * value is returned.
2125 */
2126unsigned long long int read_uint64(const char **s, const char *end)
2127{
2128 const char *ptr = *s;
2129 unsigned long long int i = 0, tmp;
2130 unsigned int j;
2131
2132 while (ptr < end) {
2133
2134 /* read next char */
2135 j = *ptr - '0';
2136 if (j > 9)
2137 goto read_uint64_end;
2138
2139 /* add char to the number and check overflow. */
2140 tmp = i * 10;
2141 if (tmp / 10 != i) {
2142 i = ULLONG_MAX;
2143 goto read_uint64_eat;
2144 }
2145 if (ULLONG_MAX - tmp < j) {
2146 i = ULLONG_MAX;
2147 goto read_uint64_eat;
2148 }
2149 i = tmp + j;
2150 ptr++;
2151 }
2152read_uint64_eat:
2153 /* eat each numeric char */
2154 while (ptr < end) {
2155 if ((unsigned int)(*ptr - '0') > 9)
2156 break;
2157 ptr++;
2158 }
2159read_uint64_end:
2160 *s = ptr;
2161 return i;
2162}
2163
2164/* This function reads an integer from the string pointed to by <s> and returns
2165 * it. The <s> pointer is adjusted to point to the first unread char. The function
2166 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2167 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2168 * returned.
2169 */
2170long long int read_int64(const char **s, const char *end)
2171{
2172 unsigned long long int i = 0;
2173 int neg = 0;
2174
2175 /* Look for minus char. */
2176 if (**s == '-') {
2177 neg = 1;
2178 (*s)++;
2179 }
2180 else if (**s == '+')
2181 (*s)++;
2182
2183 /* convert as positive number. */
2184 i = read_uint64(s, end);
2185
2186 if (neg) {
2187 if (i > 0x8000000000000000ULL)
2188 return LLONG_MIN;
2189 return -i;
2190 }
2191 if (i > 0x7fffffffffffffffULL)
2192 return LLONG_MAX;
2193 return i;
2194}
2195
Willy Tarreau6911fa42007-03-04 18:06:08 +01002196/* This one is 7 times faster than strtol() on athlon with checks.
2197 * It returns the value of the number composed of all valid digits read,
2198 * and can process negative numbers too.
2199 */
2200int strl2ic(const char *s, int len)
2201{
2202 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002203 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002204
2205 if (len > 0) {
2206 if (*s != '-') {
2207 /* positive number */
2208 while (len-- > 0) {
2209 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002210 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002211 if (j > 9)
2212 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002213 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002214 }
2215 } else {
2216 /* negative number */
2217 s++;
2218 while (--len > 0) {
2219 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002220 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002221 if (j > 9)
2222 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002223 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002224 }
2225 }
2226 }
2227 return i;
2228}
2229
2230
2231/* This function reads exactly <len> chars from <s> and converts them to a
2232 * signed integer which it stores into <ret>. It accurately detects any error
2233 * (truncated string, invalid chars, overflows). It is meant to be used in
2234 * applications designed for hostile environments. It returns zero when the
2235 * number has successfully been converted, non-zero otherwise. When an error
2236 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2237 * faster than strtol().
2238 */
2239int strl2irc(const char *s, int len, int *ret)
2240{
2241 int i = 0;
2242 int j;
2243
2244 if (!len)
2245 return 1;
2246
2247 if (*s != '-') {
2248 /* positive number */
2249 while (len-- > 0) {
2250 j = (*s++) - '0';
2251 if (j > 9) return 1; /* invalid char */
2252 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2253 i = i * 10;
2254 if (i + j < i) return 1; /* check for addition overflow */
2255 i = i + j;
2256 }
2257 } else {
2258 /* negative number */
2259 s++;
2260 while (--len > 0) {
2261 j = (*s++) - '0';
2262 if (j > 9) return 1; /* invalid char */
2263 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2264 i = i * 10;
2265 if (i - j > i) return 1; /* check for subtract overflow */
2266 i = i - j;
2267 }
2268 }
2269 *ret = i;
2270 return 0;
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 about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002280 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002281 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002282
2283int strl2llrc(const char *s, int len, long long *ret)
2284{
2285 long long i = 0;
2286 int j;
2287
2288 if (!len)
2289 return 1;
2290
2291 if (*s != '-') {
2292 /* positive number */
2293 while (len-- > 0) {
2294 j = (*s++) - '0';
2295 if (j > 9) return 1; /* invalid char */
2296 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2297 i = i * 10LL;
2298 if (i + j < i) return 1; /* check for addition overflow */
2299 i = i + j;
2300 }
2301 } else {
2302 /* negative number */
2303 s++;
2304 while (--len > 0) {
2305 j = (*s++) - '0';
2306 if (j > 9) return 1; /* invalid char */
2307 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2308 i = i * 10LL;
2309 if (i - j > i) return 1; /* check for subtract overflow */
2310 i = i - j;
2311 }
2312 }
2313 *ret = i;
2314 return 0;
2315}
2316
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002317/* This function is used with pat_parse_dotted_ver(). It converts a string
2318 * composed by two number separated by a dot. Each part must contain in 16 bits
2319 * because internally they will be represented as a 32-bit quantity stored in
2320 * a 64-bit integer. It returns zero when the number has successfully been
2321 * converted, non-zero otherwise. When an error is returned, the <ret> value
2322 * is left untouched.
2323 *
2324 * "1.3" -> 0x0000000000010003
2325 * "65535.65535" -> 0x00000000ffffffff
2326 */
2327int strl2llrc_dotted(const char *text, int len, long long *ret)
2328{
2329 const char *end = &text[len];
2330 const char *p;
2331 long long major, minor;
2332
2333 /* Look for dot. */
2334 for (p = text; p < end; p++)
2335 if (*p == '.')
2336 break;
2337
2338 /* Convert major. */
2339 if (strl2llrc(text, p - text, &major) != 0)
2340 return 1;
2341
2342 /* Check major. */
2343 if (major >= 65536)
2344 return 1;
2345
2346 /* Convert minor. */
2347 minor = 0;
2348 if (p < end)
2349 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2350 return 1;
2351
2352 /* Check minor. */
2353 if (minor >= 65536)
2354 return 1;
2355
2356 /* Compose value. */
2357 *ret = (major << 16) | (minor & 0xffff);
2358 return 0;
2359}
2360
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002361/* This function parses a time value optionally followed by a unit suffix among
2362 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2363 * expected by the caller. The computation does its best to avoid overflows.
2364 * The value is returned in <ret> if everything is fine, and a NULL is returned
2365 * by the function. In case of error, a pointer to the error is returned and
2366 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002367 * Values resulting in values larger than or equal to 2^31 after conversion are
2368 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2369 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002370 */
2371const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2372{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002373 unsigned long long imult, idiv;
2374 unsigned long long omult, odiv;
2375 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002376 const char *str = text;
2377
2378 if (!isdigit((unsigned char)*text))
2379 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002380
2381 omult = odiv = 1;
2382
2383 switch (unit_flags & TIME_UNIT_MASK) {
2384 case TIME_UNIT_US: omult = 1000000; break;
2385 case TIME_UNIT_MS: omult = 1000; break;
2386 case TIME_UNIT_S: break;
2387 case TIME_UNIT_MIN: odiv = 60; break;
2388 case TIME_UNIT_HOUR: odiv = 3600; break;
2389 case TIME_UNIT_DAY: odiv = 86400; break;
2390 default: break;
2391 }
2392
2393 value = 0;
2394
2395 while (1) {
2396 unsigned int j;
2397
2398 j = *text - '0';
2399 if (j > 9)
2400 break;
2401 text++;
2402 value *= 10;
2403 value += j;
2404 }
2405
2406 imult = idiv = 1;
2407 switch (*text) {
2408 case '\0': /* no unit = default unit */
2409 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002410 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002411 case 's': /* second = unscaled unit */
2412 break;
2413 case 'u': /* microsecond : "us" */
2414 if (text[1] == 's') {
2415 idiv = 1000000;
2416 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002417 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002418 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002419 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002420 case 'm': /* millisecond : "ms" or minute: "m" */
2421 if (text[1] == 's') {
2422 idiv = 1000;
2423 text++;
2424 } else
2425 imult = 60;
2426 break;
2427 case 'h': /* hour : "h" */
2428 imult = 3600;
2429 break;
2430 case 'd': /* day : "d" */
2431 imult = 86400;
2432 break;
2433 default:
2434 return text;
2435 break;
2436 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002437 if (*(++text) != '\0') {
2438 ha_warning("unexpected character '%c' after the timer value '%s', only "
2439 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2440 " This will be reported as an error in next versions.\n", *text, str);
2441 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002442
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002443 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002444 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2445 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2446 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2447 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2448
Willy Tarreau9faebe32019-06-07 19:00:37 +02002449 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2450 if (result >= 0x80000000)
2451 return PARSE_TIME_OVER;
2452 if (!result && value)
2453 return PARSE_TIME_UNDER;
2454 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002455 return NULL;
2456}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002457
Emeric Brun39132b22010-01-04 14:57:24 +01002458/* this function converts the string starting at <text> to an unsigned int
2459 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002460 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002461 */
2462const char *parse_size_err(const char *text, unsigned *ret) {
2463 unsigned value = 0;
2464
Christopher Faulet82635a02020-12-11 09:30:45 +01002465 if (!isdigit((unsigned char)*text))
2466 return text;
2467
Emeric Brun39132b22010-01-04 14:57:24 +01002468 while (1) {
2469 unsigned int j;
2470
2471 j = *text - '0';
2472 if (j > 9)
2473 break;
2474 if (value > ~0U / 10)
2475 return text;
2476 value *= 10;
2477 if (value > (value + j))
2478 return text;
2479 value += j;
2480 text++;
2481 }
2482
2483 switch (*text) {
2484 case '\0':
2485 break;
2486 case 'K':
2487 case 'k':
2488 if (value > ~0U >> 10)
2489 return text;
2490 value = value << 10;
2491 break;
2492 case 'M':
2493 case 'm':
2494 if (value > ~0U >> 20)
2495 return text;
2496 value = value << 20;
2497 break;
2498 case 'G':
2499 case 'g':
2500 if (value > ~0U >> 30)
2501 return text;
2502 value = value << 30;
2503 break;
2504 default:
2505 return text;
2506 }
2507
Godbach58048a22015-01-28 17:36:16 +08002508 if (*text != '\0' && *++text != '\0')
2509 return text;
2510
Emeric Brun39132b22010-01-04 14:57:24 +01002511 *ret = value;
2512 return NULL;
2513}
2514
Willy Tarreau126d4062013-12-03 17:50:47 +01002515/*
2516 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002517 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002518 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002519 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002520 */
2521int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2522{
2523 int len;
2524 const char *p = source;
2525 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002526 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002527
2528 len = strlen(source);
2529 if (len % 2) {
2530 memprintf(err, "an even number of hex digit is expected");
2531 return 0;
2532 }
2533
2534 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002535
Willy Tarreau126d4062013-12-03 17:50:47 +01002536 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002537 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002538 if (!*binstr) {
2539 memprintf(err, "out of memory while loading string pattern");
2540 return 0;
2541 }
2542 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002543 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002544 else {
2545 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002546 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002547 len, *binstrlen);
2548 return 0;
2549 }
2550 alloc = 0;
2551 }
2552 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002553
2554 i = j = 0;
2555 while (j < len) {
2556 if (!ishex(p[i++]))
2557 goto bad_input;
2558 if (!ishex(p[i++]))
2559 goto bad_input;
2560 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2561 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002562 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002563
2564bad_input:
2565 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002566 if (alloc)
2567 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002568 return 0;
2569}
2570
Willy Tarreau946ba592009-05-10 15:41:18 +02002571/* copies at most <n> characters from <src> and always terminates with '\0' */
2572char *my_strndup(const char *src, int n)
2573{
2574 int len = 0;
2575 char *ret;
2576
2577 while (len < n && src[len])
2578 len++;
2579
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002580 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002581 if (!ret)
2582 return ret;
2583 memcpy(ret, src, len);
2584 ret[len] = '\0';
2585 return ret;
2586}
2587
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002588/*
2589 * search needle in haystack
2590 * returns the pointer if found, returns NULL otherwise
2591 */
2592const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2593{
2594 const void *c = NULL;
2595 unsigned char f;
2596
2597 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2598 return NULL;
2599
2600 f = *(char *)needle;
2601 c = haystack;
2602 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2603 if ((haystacklen - (c - haystack)) < needlelen)
2604 return NULL;
2605
2606 if (memcmp(c, needle, needlelen) == 0)
2607 return c;
2608 ++c;
2609 }
2610 return NULL;
2611}
2612
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002613/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002614size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2615{
2616 size_t ret = 0;
2617
2618 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2619 str++;
2620 ret++;
2621 }
2622 return ret;
2623}
2624
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002625/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002626size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2627{
2628 size_t ret = 0;
2629
2630 while (ret < len) {
2631 if(memchr(reject, *((int *)str), rejectlen))
2632 return ret;
2633 str++;
2634 ret++;
2635 }
2636 return ret;
2637}
2638
Willy Tarreau482b00d2009-10-04 22:48:42 +02002639/* This function returns the first unused key greater than or equal to <key> in
2640 * ID tree <root>. Zero is returned if no place is found.
2641 */
2642unsigned int get_next_id(struct eb_root *root, unsigned int key)
2643{
2644 struct eb32_node *used;
2645
2646 do {
2647 used = eb32_lookup_ge(root, key);
2648 if (!used || used->key > key)
2649 return key; /* key is available */
2650 key++;
2651 } while (key);
2652 return key;
2653}
2654
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002655/* dump the full tree to <file> in DOT format for debugging purposes. Will
2656 * optionally highlight node <subj> if found, depending on operation <op> :
2657 * 0 : nothing
2658 * >0 : insertion, node/leaf are surrounded in red
2659 * <0 : removal, node/leaf are dashed with no background
2660 * Will optionally add "desc" as a label on the graph if set and non-null.
2661 */
2662void 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 +01002663{
2664 struct eb32sc_node *node;
2665 unsigned long scope = -1;
2666
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002667 fprintf(file, "digraph ebtree {\n");
2668
2669 if (desc && *desc) {
2670 fprintf(file,
2671 " fontname=\"fixed\";\n"
2672 " fontsize=8;\n"
2673 " label=\"%s\";\n", desc);
2674 }
2675
Willy Tarreaued3cda02017-11-15 15:04:05 +01002676 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002677 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2678 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002679 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2680 );
2681
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002682 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002683 (long)eb_root_to_node(root),
2684 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002685 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2686
2687 node = eb32sc_first(root, scope);
2688 while (node) {
2689 if (node->node.node_p) {
2690 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002691 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2692 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2693 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002694
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002695 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002696 (long)node,
2697 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002698 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002699
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002700 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002701 (long)node,
2702 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002703 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2704
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002705 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002706 (long)node,
2707 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002708 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2709 }
2710
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002711 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2712 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2713 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002714
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002715 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002716 (long)node,
2717 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002718 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002719 node = eb32sc_next(node, scope);
2720 }
2721 fprintf(file, "}\n");
2722}
2723
Willy Tarreau348238b2010-01-18 15:05:57 +01002724/* This function compares a sample word possibly followed by blanks to another
2725 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2726 * otherwise zero. This intends to be used when checking HTTP headers for some
2727 * values. Note that it validates a word followed only by blanks but does not
2728 * validate a word followed by blanks then other chars.
2729 */
2730int word_match(const char *sample, int slen, const char *word, int wlen)
2731{
2732 if (slen < wlen)
2733 return 0;
2734
2735 while (wlen) {
2736 char c = *sample ^ *word;
2737 if (c && c != ('A' ^ 'a'))
2738 return 0;
2739 sample++;
2740 word++;
2741 slen--;
2742 wlen--;
2743 }
2744
2745 while (slen) {
2746 if (*sample != ' ' && *sample != '\t')
2747 return 0;
2748 sample++;
2749 slen--;
2750 }
2751 return 1;
2752}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002753
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002754/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2755 * is particularly fast because it avoids expensive operations such as
2756 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002757 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002758 */
2759unsigned int inetaddr_host(const char *text)
2760{
2761 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2762 register unsigned int dig100, dig10, dig1;
2763 int s;
2764 const char *p, *d;
2765
2766 dig1 = dig10 = dig100 = ascii_zero;
2767 s = 24;
2768
2769 p = text;
2770 while (1) {
2771 if (((unsigned)(*p - '0')) <= 9) {
2772 p++;
2773 continue;
2774 }
2775
2776 /* here, we have a complete byte between <text> and <p> (exclusive) */
2777 if (p == text)
2778 goto end;
2779
2780 d = p - 1;
2781 dig1 |= (unsigned int)(*d << s);
2782 if (d == text)
2783 goto end;
2784
2785 d--;
2786 dig10 |= (unsigned int)(*d << s);
2787 if (d == text)
2788 goto end;
2789
2790 d--;
2791 dig100 |= (unsigned int)(*d << s);
2792 end:
2793 if (!s || *p != '.')
2794 break;
2795
2796 s -= 8;
2797 text = ++p;
2798 }
2799
2800 dig100 -= ascii_zero;
2801 dig10 -= ascii_zero;
2802 dig1 -= ascii_zero;
2803 return ((dig100 * 10) + dig10) * 10 + dig1;
2804}
2805
2806/*
2807 * Idem except the first unparsed character has to be passed in <stop>.
2808 */
2809unsigned int inetaddr_host_lim(const char *text, const char *stop)
2810{
2811 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2812 register unsigned int dig100, dig10, dig1;
2813 int s;
2814 const char *p, *d;
2815
2816 dig1 = dig10 = dig100 = ascii_zero;
2817 s = 24;
2818
2819 p = text;
2820 while (1) {
2821 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2822 p++;
2823 continue;
2824 }
2825
2826 /* here, we have a complete byte between <text> and <p> (exclusive) */
2827 if (p == text)
2828 goto end;
2829
2830 d = p - 1;
2831 dig1 |= (unsigned int)(*d << s);
2832 if (d == text)
2833 goto end;
2834
2835 d--;
2836 dig10 |= (unsigned int)(*d << s);
2837 if (d == text)
2838 goto end;
2839
2840 d--;
2841 dig100 |= (unsigned int)(*d << s);
2842 end:
2843 if (!s || p == stop || *p != '.')
2844 break;
2845
2846 s -= 8;
2847 text = ++p;
2848 }
2849
2850 dig100 -= ascii_zero;
2851 dig10 -= ascii_zero;
2852 dig1 -= ascii_zero;
2853 return ((dig100 * 10) + dig10) * 10 + dig1;
2854}
2855
2856/*
2857 * Idem except the pointer to first unparsed byte is returned into <ret> which
2858 * must not be NULL.
2859 */
Willy Tarreau74172752010-10-15 23:21:42 +02002860unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002861{
2862 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2863 register unsigned int dig100, dig10, dig1;
2864 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002865 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002866
2867 dig1 = dig10 = dig100 = ascii_zero;
2868 s = 24;
2869
2870 p = text;
2871 while (1) {
2872 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2873 p++;
2874 continue;
2875 }
2876
2877 /* here, we have a complete byte between <text> and <p> (exclusive) */
2878 if (p == text)
2879 goto end;
2880
2881 d = p - 1;
2882 dig1 |= (unsigned int)(*d << s);
2883 if (d == text)
2884 goto end;
2885
2886 d--;
2887 dig10 |= (unsigned int)(*d << s);
2888 if (d == text)
2889 goto end;
2890
2891 d--;
2892 dig100 |= (unsigned int)(*d << s);
2893 end:
2894 if (!s || p == stop || *p != '.')
2895 break;
2896
2897 s -= 8;
2898 text = ++p;
2899 }
2900
2901 *ret = p;
2902 dig100 -= ascii_zero;
2903 dig10 -= ascii_zero;
2904 dig1 -= ascii_zero;
2905 return ((dig100 * 10) + dig10) * 10 + dig1;
2906}
2907
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002908/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2909 * or the number of chars read in case of success. Maybe this could be replaced
2910 * by one of the functions above. Also, apparently this function does not support
2911 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002912 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002913 */
2914int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2915{
2916 const char *addr;
2917 int saw_digit, octets, ch;
2918 u_char tmp[4], *tp;
2919 const char *cp = buf;
2920
2921 saw_digit = 0;
2922 octets = 0;
2923 *(tp = tmp) = 0;
2924
2925 for (addr = buf; addr - buf < len; addr++) {
2926 unsigned char digit = (ch = *addr) - '0';
2927
2928 if (digit > 9 && ch != '.')
2929 break;
2930
2931 if (digit <= 9) {
2932 u_int new = *tp * 10 + digit;
2933
2934 if (new > 255)
2935 return 0;
2936
2937 *tp = new;
2938
2939 if (!saw_digit) {
2940 if (++octets > 4)
2941 return 0;
2942 saw_digit = 1;
2943 }
2944 } else if (ch == '.' && saw_digit) {
2945 if (octets == 4)
2946 return 0;
2947
2948 *++tp = 0;
2949 saw_digit = 0;
2950 } else
2951 return 0;
2952 }
2953
2954 if (octets < 4)
2955 return 0;
2956
2957 memcpy(&dst->s_addr, tmp, 4);
2958 return addr - cp;
2959}
2960
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002961/* This function converts the string in <buf> of the len <len> to
2962 * struct in6_addr <dst> which must be allocated by the caller.
2963 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002964 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002965 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002966int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2967{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002968 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002969 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002970
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002971 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002972 return 0;
2973
2974 memcpy(null_term_ip6, buf, len);
2975 null_term_ip6[len] = '\0';
2976
Willy Tarreau075415a2013-12-12 11:29:39 +01002977 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002978 return 0;
2979
Willy Tarreau075415a2013-12-12 11:29:39 +01002980 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002981 return 1;
2982}
2983
Willy Tarreauacf95772010-06-14 19:09:21 +02002984/* To be used to quote config arg positions. Returns the short string at <ptr>
2985 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2986 * if ptr is NULL or empty. The string is locally allocated.
2987 */
2988const char *quote_arg(const char *ptr)
2989{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002990 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002991 int i;
2992
2993 if (!ptr || !*ptr)
2994 return "end of line";
2995 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002996 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002997 val[i] = *ptr++;
2998 val[i++] = '\'';
2999 val[i] = '\0';
3000 return val;
3001}
3002
Willy Tarreau5b180202010-07-18 10:40:48 +02003003/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3004int get_std_op(const char *str)
3005{
3006 int ret = -1;
3007
3008 if (*str == 'e' && str[1] == 'q')
3009 ret = STD_OP_EQ;
3010 else if (*str == 'n' && str[1] == 'e')
3011 ret = STD_OP_NE;
3012 else if (*str == 'l') {
3013 if (str[1] == 'e') ret = STD_OP_LE;
3014 else if (str[1] == 't') ret = STD_OP_LT;
3015 }
3016 else if (*str == 'g') {
3017 if (str[1] == 'e') ret = STD_OP_GE;
3018 else if (str[1] == 't') ret = STD_OP_GT;
3019 }
3020
3021 if (ret == -1 || str[2] != '\0')
3022 return -1;
3023 return ret;
3024}
3025
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003026/* hash a 32-bit integer to another 32-bit integer */
3027unsigned int full_hash(unsigned int a)
3028{
3029 return __full_hash(a);
3030}
3031
Willy Tarreauf3241112019-02-26 09:56:22 +01003032/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3033 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3034 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3035 * a popcount variant and is described here :
3036 * https://graphics.stanford.edu/~seander/bithacks.html
3037 */
3038unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3039{
3040 unsigned long a, b, c, d;
3041 unsigned int s;
3042 unsigned int t;
3043
3044 a = m - ((m >> 1) & ~0UL/3);
3045 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3046 c = (b + (b >> 4)) & ~0UL/0x11;
3047 d = (c + (c >> 8)) & ~0UL/0x101;
3048
3049 r++; // make r be 1..64
3050
3051 t = 0;
3052 s = LONGBITS;
3053 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003054 unsigned long d2 = (d >> 16) >> 16;
3055 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003056 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3057 }
3058
3059 t = (d >> (s - 16)) & 0xff;
3060 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3061 t = (c >> (s - 8)) & 0xf;
3062 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3063 t = (b >> (s - 4)) & 0x7;
3064 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3065 t = (a >> (s - 2)) & 0x3;
3066 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3067 t = (m >> (s - 1)) & 0x1;
3068 s -= ((t - r) & 256) >> 8;
3069
3070 return s - 1;
3071}
3072
3073/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3074 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3075 * using mask_prep_rank_map() below.
3076 */
3077unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3078 unsigned long a, unsigned long b,
3079 unsigned long c, unsigned long d)
3080{
3081 unsigned int s;
3082 unsigned int t;
3083
3084 r++; // make r be 1..64
3085
3086 t = 0;
3087 s = LONGBITS;
3088 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003089 unsigned long d2 = (d >> 16) >> 16;
3090 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003091 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3092 }
3093
3094 t = (d >> (s - 16)) & 0xff;
3095 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3096 t = (c >> (s - 8)) & 0xf;
3097 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3098 t = (b >> (s - 4)) & 0x7;
3099 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3100 t = (a >> (s - 2)) & 0x3;
3101 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3102 t = (m >> (s - 1)) & 0x1;
3103 s -= ((t - r) & 256) >> 8;
3104
3105 return s - 1;
3106}
3107
3108/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3109 * above.
3110 */
3111void mask_prep_rank_map(unsigned long m,
3112 unsigned long *a, unsigned long *b,
3113 unsigned long *c, unsigned long *d)
3114{
3115 *a = m - ((m >> 1) & ~0UL/3);
3116 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3117 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3118 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3119}
3120
David du Colombier4f92d322011-03-24 11:09:31 +01003121/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003122 * otherwise zero. Note that <addr> may not necessarily be aligned
3123 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003124 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003125int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003126{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003127 struct in_addr addr_copy;
3128
3129 memcpy(&addr_copy, addr, sizeof(addr_copy));
3130 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003131}
3132
3133/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003134 * otherwise zero. Note that <addr> may not necessarily be aligned
3135 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003136 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003137int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003138{
3139 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003140 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003141
Willy Tarreaueec1d382016-07-13 11:59:39 +02003142 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003143 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003144 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003145 (((int *)net)[i] & ((int *)mask)[i]))
3146 return 0;
3147 return 1;
3148}
3149
3150/* RFC 4291 prefix */
3151const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3152 0x00, 0x00, 0x00, 0x00,
3153 0x00, 0x00, 0xFF, 0xFF };
3154
Joseph Herlant32b83272018-11-15 11:58:28 -08003155/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003156 * Input and output may overlap.
3157 */
David du Colombier4f92d322011-03-24 11:09:31 +01003158void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3159{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003160 struct in_addr tmp_addr;
3161
3162 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003163 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003164 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003165}
3166
Joseph Herlant32b83272018-11-15 11:58:28 -08003167/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003168 * Return true if conversion is possible and false otherwise.
3169 */
3170int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3171{
3172 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3173 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3174 sizeof(struct in_addr));
3175 return 1;
3176 }
3177
3178 return 0;
3179}
3180
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003181/* compare two struct sockaddr_storage and return:
3182 * 0 (true) if the addr is the same in both
3183 * 1 (false) if the addr is not the same in both
3184 * -1 (unable) if one of the addr is not AF_INET*
3185 */
3186int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3187{
3188 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3189 return -1;
3190
3191 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3192 return -1;
3193
3194 if (ss1->ss_family != ss2->ss_family)
3195 return 1;
3196
3197 switch (ss1->ss_family) {
3198 case AF_INET:
3199 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3200 &((struct sockaddr_in *)ss2)->sin_addr,
3201 sizeof(struct in_addr)) != 0;
3202 case AF_INET6:
3203 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3204 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3205 sizeof(struct in6_addr)) != 0;
3206 }
3207
3208 return 1;
3209}
3210
Christopher Faulet9553de72021-02-26 09:12:50 +01003211/* compare a struct sockaddr_storage to a struct net_addr and return :
3212 * 0 (true) if <addr> is matching <net>
3213 * 1 (false) if <addr> is not matching <net>
3214 * -1 (unable) if <addr> or <net> is not AF_INET*
3215 */
3216int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3217{
3218 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3219 return -1;
3220
3221 if ((net->family != AF_INET) && (net->family != AF_INET6))
3222 return -1;
3223
3224 if (addr->ss_family != net->family)
3225 return 1;
3226
3227 if (addr->ss_family == AF_INET &&
3228 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3229 return 0;
3230 else {
3231 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3232 const struct in6_addr *nip6 = &net->addr.v6.ip;
3233 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3234
3235 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3236 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3237 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3238 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3239 return 0;
3240 }
3241
3242 return 1;
3243}
3244
Baptiste Assmann08396c82016-01-31 00:27:17 +01003245/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003246 * The caller must allocate and clear <dest> before calling.
3247 * The source must be in either AF_INET or AF_INET6 family, or the destination
3248 * address will be undefined. If the destination address used to hold a port,
3249 * it is preserved, so that this function can be used to switch to another
3250 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003251 */
3252struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3253{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003254 int prev_port;
3255
3256 prev_port = get_net_port(dest);
3257 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003258 dest->ss_family = source->ss_family;
3259
3260 /* copy new addr and apply it */
3261 switch (source->ss_family) {
3262 case AF_INET:
3263 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003264 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003265 break;
3266 case AF_INET6:
3267 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 +01003268 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003269 break;
3270 }
3271
3272 return dest;
3273}
3274
William Lallemand421f5b52012-02-06 18:15:57 +01003275char *human_time(int t, short hz_div) {
3276 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3277 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003278 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003279 int cnt=2; // print two numbers
3280
3281 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003282 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003283 return rv;
3284 }
3285
3286 if (unlikely(hz_div > 1))
3287 t /= hz_div;
3288
3289 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003290 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003291 cnt--;
3292 }
3293
3294 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003295 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003296 cnt--;
3297 }
3298
3299 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003300 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003301 cnt--;
3302 }
3303
3304 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003305 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003306
3307 return rv;
3308}
3309
3310const char *monthname[12] = {
3311 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3312 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3313};
3314
3315/* date2str_log: write a date in the format :
3316 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3317 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3318 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3319 *
3320 * without using sprintf. return a pointer to the last char written (\0) or
3321 * NULL if there isn't enough space.
3322 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003323char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003324{
3325
3326 if (size < 25) /* the size is fixed: 24 chars + \0 */
3327 return NULL;
3328
3329 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003330 if (!dst)
3331 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003332 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003333
William Lallemand421f5b52012-02-06 18:15:57 +01003334 memcpy(dst, monthname[tm->tm_mon], 3); // month
3335 dst += 3;
3336 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003337
William Lallemand421f5b52012-02-06 18:15:57 +01003338 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003339 if (!dst)
3340 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003341 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003342
William Lallemand421f5b52012-02-06 18:15:57 +01003343 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003344 if (!dst)
3345 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003346 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003347
William Lallemand421f5b52012-02-06 18:15:57 +01003348 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003349 if (!dst)
3350 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003351 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003352
William Lallemand421f5b52012-02-06 18:15:57 +01003353 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003354 if (!dst)
3355 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003356 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003357
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003358 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003359 if (!dst)
3360 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003361 *dst = '\0';
3362
3363 return dst;
3364}
3365
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003366/* Base year used to compute leap years */
3367#define TM_YEAR_BASE 1900
3368
3369/* Return the difference in seconds between two times (leap seconds are ignored).
3370 * Retrieved from glibc 2.18 source code.
3371 */
3372static int my_tm_diff(const struct tm *a, const struct tm *b)
3373{
3374 /* Compute intervening leap days correctly even if year is negative.
3375 * Take care to avoid int overflow in leap day calculations,
3376 * but it's OK to assume that A and B are close to each other.
3377 */
3378 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3379 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3380 int a100 = a4 / 25 - (a4 % 25 < 0);
3381 int b100 = b4 / 25 - (b4 % 25 < 0);
3382 int a400 = a100 >> 2;
3383 int b400 = b100 >> 2;
3384 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3385 int years = a->tm_year - b->tm_year;
3386 int days = (365 * years + intervening_leap_days
3387 + (a->tm_yday - b->tm_yday));
3388 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3389 + (a->tm_min - b->tm_min))
3390 + (a->tm_sec - b->tm_sec));
3391}
3392
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003393/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003394 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003395 * The string returned has the same format as returned by strftime(... "%z", tm).
3396 * Offsets are kept in an internal cache for better performances.
3397 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003398const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003399{
3400 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003401 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003402
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003403 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003404 struct tm tm_gmt;
3405 int diff;
3406 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003407
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003408 /* Pretend DST not active if its status is unknown */
3409 if (isdst < 0)
3410 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003411
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003412 /* Fetch the offset and initialize it if needed */
3413 gmt_offset = gmt_offsets[isdst & 0x01];
3414 if (unlikely(!*gmt_offset)) {
3415 get_gmtime(t, &tm_gmt);
3416 diff = my_tm_diff(tm, &tm_gmt);
3417 if (diff < 0) {
3418 diff = -diff;
3419 *gmt_offset = '-';
3420 } else {
3421 *gmt_offset = '+';
3422 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003423 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003424 diff /= 60; /* Convert to minutes */
3425 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3426 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003427
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003428 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003429}
3430
William Lallemand421f5b52012-02-06 18:15:57 +01003431/* gmt2str_log: write a date in the format :
3432 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3433 * return a pointer to the last char written (\0) or
3434 * NULL if there isn't enough space.
3435 */
3436char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3437{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003438 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003439 return NULL;
3440
3441 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003442 if (!dst)
3443 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003444 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003445
William Lallemand421f5b52012-02-06 18:15:57 +01003446 memcpy(dst, monthname[tm->tm_mon], 3); // month
3447 dst += 3;
3448 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003449
William Lallemand421f5b52012-02-06 18:15:57 +01003450 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003451 if (!dst)
3452 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003453 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003454
William Lallemand421f5b52012-02-06 18:15:57 +01003455 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003456 if (!dst)
3457 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003458 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003459
William Lallemand421f5b52012-02-06 18:15:57 +01003460 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003461 if (!dst)
3462 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003463 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003464
William Lallemand421f5b52012-02-06 18:15:57 +01003465 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003466 if (!dst)
3467 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003468 *dst++ = ' ';
3469 *dst++ = '+';
3470 *dst++ = '0';
3471 *dst++ = '0';
3472 *dst++ = '0';
3473 *dst++ = '0';
3474 *dst = '\0';
3475
3476 return dst;
3477}
3478
Yuxans Yao4e25b012012-10-19 10:36:09 +08003479/* localdate2str_log: write a date in the format :
3480 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003481 * Both t and tm must represent the same time.
3482 * return a pointer to the last char written (\0) or
3483 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003484 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003485char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003486{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003487 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003488 if (size < 27) /* the size is fixed: 26 chars + \0 */
3489 return NULL;
3490
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003491 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003492
Yuxans Yao4e25b012012-10-19 10:36:09 +08003493 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003494 if (!dst)
3495 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003496 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003497
Yuxans Yao4e25b012012-10-19 10:36:09 +08003498 memcpy(dst, monthname[tm->tm_mon], 3); // month
3499 dst += 3;
3500 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003501
Yuxans Yao4e25b012012-10-19 10:36:09 +08003502 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003503 if (!dst)
3504 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003505 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003506
Yuxans Yao4e25b012012-10-19 10:36:09 +08003507 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003508 if (!dst)
3509 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003510 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003511
Yuxans Yao4e25b012012-10-19 10:36:09 +08003512 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003513 if (!dst)
3514 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003515 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003516
Yuxans Yao4e25b012012-10-19 10:36:09 +08003517 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003518 if (!dst)
3519 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003520 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003521
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003522 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003523 dst += 5;
3524 *dst = '\0';
3525
3526 return dst;
3527}
3528
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003529/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3530 * It is meant as a portable replacement for timegm() for use with valid inputs.
3531 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3532 */
3533time_t my_timegm(const struct tm *tm)
3534{
3535 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3536 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3537 * sum of the extra N days for elapsed months. The sum of all these N
3538 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3539 * in a 5-bit word. This means that with 60 bits we can represent a
3540 * matrix of all these values at once, which is fast and efficient to
3541 * access. The extra February day for leap years is not counted here.
3542 *
3543 * Jan : none = 0 (0)
3544 * Feb : Jan = 3 (3)
3545 * Mar : Jan..Feb = 3 (3 + 0)
3546 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3547 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3548 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3549 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3550 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3551 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3552 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3553 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3554 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3555 */
3556 uint64_t extra =
3557 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3558 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3559 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3560 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3561
3562 unsigned int y = tm->tm_year + 1900;
3563 unsigned int m = tm->tm_mon;
3564 unsigned long days = 0;
3565
3566 /* days since 1/1/1970 for full years */
3567 days += days_since_zero(y) - days_since_zero(1970);
3568
3569 /* days for full months in the current year */
3570 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3571
3572 /* count + 1 after March for leap years. A leap year is a year multiple
3573 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3574 * is leap, 1900 isn't, 1904 is.
3575 */
3576 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3577 days++;
3578
3579 days += tm->tm_mday - 1;
3580 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3581}
3582
Thierry Fournier93127942016-01-20 18:49:45 +01003583/* This function check a char. It returns true and updates
3584 * <date> and <len> pointer to the new position if the
3585 * character is found.
3586 */
3587static inline int parse_expect_char(const char **date, int *len, char c)
3588{
3589 if (*len < 1 || **date != c)
3590 return 0;
3591 (*len)--;
3592 (*date)++;
3593 return 1;
3594}
3595
3596/* This function expects a string <str> of len <l>. It return true and updates.
3597 * <date> and <len> if the string matches, otherwise, it returns false.
3598 */
3599static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3600{
3601 if (*len < l || strncmp(*date, str, l) != 0)
3602 return 0;
3603 (*len) -= l;
3604 (*date) += l;
3605 return 1;
3606}
3607
3608/* This macro converts 3 chars name in integer. */
3609#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3610
3611/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3612 * / %x54.75.65 ; "Tue", case-sensitive
3613 * / %x57.65.64 ; "Wed", case-sensitive
3614 * / %x54.68.75 ; "Thu", case-sensitive
3615 * / %x46.72.69 ; "Fri", case-sensitive
3616 * / %x53.61.74 ; "Sat", case-sensitive
3617 * / %x53.75.6E ; "Sun", case-sensitive
3618 *
3619 * This array must be alphabetically sorted
3620 */
3621static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3622{
3623 if (*len < 3)
3624 return 0;
3625 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3626 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3627 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3628 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3629 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3630 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3631 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3632 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3633 default: return 0;
3634 }
3635 *len -= 3;
3636 *date += 3;
3637 return 1;
3638}
3639
3640/* month = %x4A.61.6E ; "Jan", case-sensitive
3641 * / %x46.65.62 ; "Feb", case-sensitive
3642 * / %x4D.61.72 ; "Mar", case-sensitive
3643 * / %x41.70.72 ; "Apr", case-sensitive
3644 * / %x4D.61.79 ; "May", case-sensitive
3645 * / %x4A.75.6E ; "Jun", case-sensitive
3646 * / %x4A.75.6C ; "Jul", case-sensitive
3647 * / %x41.75.67 ; "Aug", case-sensitive
3648 * / %x53.65.70 ; "Sep", case-sensitive
3649 * / %x4F.63.74 ; "Oct", case-sensitive
3650 * / %x4E.6F.76 ; "Nov", case-sensitive
3651 * / %x44.65.63 ; "Dec", case-sensitive
3652 *
3653 * This array must be alphabetically sorted
3654 */
3655static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3656{
3657 if (*len < 3)
3658 return 0;
3659 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3660 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3661 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3662 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3663 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3664 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3665 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3666 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3667 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3668 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3669 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3670 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3671 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3672 default: return 0;
3673 }
3674 *len -= 3;
3675 *date += 3;
3676 return 1;
3677}
3678
3679/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3680 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3681 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3682 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3683 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3684 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3685 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3686 *
3687 * This array must be alphabetically sorted
3688 */
3689static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3690{
3691 if (*len < 6) /* Minimum length. */
3692 return 0;
3693 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3694 case STR2I3('M','o','n'):
3695 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3696 tm->tm_wday = 1;
3697 return 1;
3698 case STR2I3('T','u','e'):
3699 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3700 tm->tm_wday = 2;
3701 return 1;
3702 case STR2I3('W','e','d'):
3703 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3704 tm->tm_wday = 3;
3705 return 1;
3706 case STR2I3('T','h','u'):
3707 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3708 tm->tm_wday = 4;
3709 return 1;
3710 case STR2I3('F','r','i'):
3711 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3712 tm->tm_wday = 5;
3713 return 1;
3714 case STR2I3('S','a','t'):
3715 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3716 tm->tm_wday = 6;
3717 return 1;
3718 case STR2I3('S','u','n'):
3719 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3720 tm->tm_wday = 7;
3721 return 1;
3722 }
3723 return 0;
3724}
3725
3726/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3727static inline int parse_digit(const char **date, int *len, int *digit)
3728{
3729 if (*len < 1 || **date < '0' || **date > '9')
3730 return 0;
3731 *digit = (**date - '0');
3732 (*date)++;
3733 (*len)--;
3734 return 1;
3735}
3736
3737/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3738static inline int parse_2digit(const char **date, int *len, int *digit)
3739{
3740 int value;
3741
3742 RET0_UNLESS(parse_digit(date, len, &value));
3743 (*digit) = value * 10;
3744 RET0_UNLESS(parse_digit(date, len, &value));
3745 (*digit) += value;
3746
3747 return 1;
3748}
3749
3750/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3751static inline int parse_4digit(const char **date, int *len, int *digit)
3752{
3753 int value;
3754
3755 RET0_UNLESS(parse_digit(date, len, &value));
3756 (*digit) = value * 1000;
3757
3758 RET0_UNLESS(parse_digit(date, len, &value));
3759 (*digit) += value * 100;
3760
3761 RET0_UNLESS(parse_digit(date, len, &value));
3762 (*digit) += value * 10;
3763
3764 RET0_UNLESS(parse_digit(date, len, &value));
3765 (*digit) += value;
3766
3767 return 1;
3768}
3769
3770/* time-of-day = hour ":" minute ":" second
3771 * ; 00:00:00 - 23:59:60 (leap second)
3772 *
3773 * hour = 2DIGIT
3774 * minute = 2DIGIT
3775 * second = 2DIGIT
3776 */
3777static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3778{
3779 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3780 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3781 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3782 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3783 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3784 return 1;
3785}
3786
3787/* From RFC7231
3788 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3789 *
3790 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3791 * ; fixed length/zone/capitalization subset of the format
3792 * ; see Section 3.3 of [RFC5322]
3793 *
3794 *
3795 * date1 = day SP month SP year
3796 * ; e.g., 02 Jun 1982
3797 *
3798 * day = 2DIGIT
3799 * year = 4DIGIT
3800 *
3801 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3802 *
3803 * time-of-day = hour ":" minute ":" second
3804 * ; 00:00:00 - 23:59:60 (leap second)
3805 *
3806 * hour = 2DIGIT
3807 * minute = 2DIGIT
3808 * second = 2DIGIT
3809 *
3810 * DIGIT = decimal 0-9
3811 */
3812int parse_imf_date(const char *date, int len, struct tm *tm)
3813{
David Carlier327298c2016-11-20 10:42:38 +00003814 /* tm_gmtoff, if present, ought to be zero'ed */
3815 memset(tm, 0, sizeof(*tm));
3816
Thierry Fournier93127942016-01-20 18:49:45 +01003817 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3818 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3819 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3820 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3821 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3822 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3823 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3824 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3825 tm->tm_year -= 1900;
3826 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3827 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3828 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3829 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3830 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003831 return 1;
3832}
3833
3834/* From RFC7231
3835 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3836 *
3837 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3838 * date2 = day "-" month "-" 2DIGIT
3839 * ; e.g., 02-Jun-82
3840 *
3841 * day = 2DIGIT
3842 */
3843int parse_rfc850_date(const char *date, int len, struct tm *tm)
3844{
3845 int year;
3846
David Carlier327298c2016-11-20 10:42:38 +00003847 /* tm_gmtoff, if present, ought to be zero'ed */
3848 memset(tm, 0, sizeof(*tm));
3849
Thierry Fournier93127942016-01-20 18:49:45 +01003850 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3851 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3852 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3853 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3854 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3855 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3856 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3857
3858 /* year = 2DIGIT
3859 *
3860 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3861 * two-digit year, MUST interpret a timestamp that appears to be more
3862 * than 50 years in the future as representing the most recent year in
3863 * the past that had the same last two digits.
3864 */
3865 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3866
3867 /* expect SP */
3868 if (!parse_expect_char(&date, &len, ' ')) {
3869 /* Maybe we have the date with 4 digits. */
3870 RET0_UNLESS(parse_2digit(&date, &len, &year));
3871 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3872 /* expect SP */
3873 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3874 } else {
3875 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3876 * tm_year is the number of year since 1900, so for +1900, we
3877 * do nothing, and for +2000, we add 100.
3878 */
3879 if (tm->tm_year <= 60)
3880 tm->tm_year += 100;
3881 }
3882
3883 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3884 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3885 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3886 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003887
3888 return 1;
3889}
3890
3891/* From RFC7231
3892 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3893 *
3894 * asctime-date = day-name SP date3 SP time-of-day SP year
3895 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3896 * ; e.g., Jun 2
3897 *
3898 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3899 * whitespace in an HTTP-date beyond that specifically included as SP in
3900 * the grammar.
3901 */
3902int parse_asctime_date(const char *date, int len, struct tm *tm)
3903{
David Carlier327298c2016-11-20 10:42:38 +00003904 /* tm_gmtoff, if present, ought to be zero'ed */
3905 memset(tm, 0, sizeof(*tm));
3906
Thierry Fournier93127942016-01-20 18:49:45 +01003907 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3908 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3909 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3910 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3911
3912 /* expect SP and 1DIGIT or 2DIGIT */
3913 if (parse_expect_char(&date, &len, ' '))
3914 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3915 else
3916 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3917
3918 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3919 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3920 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3921 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3922 tm->tm_year -= 1900;
3923 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003924 return 1;
3925}
3926
3927/* From RFC7231
3928 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3929 *
3930 * HTTP-date = IMF-fixdate / obs-date
3931 * obs-date = rfc850-date / asctime-date
3932 *
3933 * parses an HTTP date in the RFC format and is accepted
3934 * alternatives. <date> is the strinf containing the date,
3935 * len is the len of the string. <tm> is filled with the
3936 * parsed time. We must considers this time as GMT.
3937 */
3938int parse_http_date(const char *date, int len, struct tm *tm)
3939{
3940 if (parse_imf_date(date, len, tm))
3941 return 1;
3942
3943 if (parse_rfc850_date(date, len, tm))
3944 return 1;
3945
3946 if (parse_asctime_date(date, len, tm))
3947 return 1;
3948
3949 return 0;
3950}
3951
Willy Tarreau4deeb102021-01-29 10:47:52 +01003952/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3953 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3954 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3955 * surrounded by <pfx> and <sfx> respectively if not NULL.
3956 */
3957int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3958{
3959 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3960 const char *unit;
3961
3962 if (!pfx)
3963 pfx = "";
3964 if (!sfx)
3965 sfx = "";
3966
3967 do {
3968 unit = " - "; if (val <= 0.0) break;
3969 unit = "ns"; if (val < 1000.0) break;
3970 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3971 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3972 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3973 unit = "m "; val /= 60.0; if (val < 60.0) break;
3974 unit = "h "; val /= 60.0; if (val < 24.0) break;
3975 unit = "d "; val /= 24.0; if (val < 365.0) break;
3976 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3977 unit = " inf "; val = 0.0; break;
3978 } while (0);
3979
3980 if (val <= 0.0)
3981 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
3982 else if (val < 10.0)
3983 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
3984 else if (val < 100.0)
3985 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
3986 else
3987 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
3988}
3989
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003990/* Dynamically allocates a string of the proper length to hold the formatted
3991 * output. NULL is returned on error. The caller is responsible for freeing the
3992 * memory area using free(). The resulting string is returned in <out> if the
3993 * pointer is not NULL. A previous version of <out> might be used to build the
3994 * new string, and it will be freed before returning if it is not NULL, which
3995 * makes it possible to build complex strings from iterative calls without
3996 * having to care about freeing intermediate values, as in the example below :
3997 *
3998 * memprintf(&err, "invalid argument: '%s'", arg);
3999 * ...
4000 * memprintf(&err, "parser said : <%s>\n", *err);
4001 * ...
4002 * free(*err);
4003 *
4004 * This means that <err> must be initialized to NULL before first invocation.
4005 * The return value also holds the allocated string, which eases error checking
4006 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004007 * passed instead and it will be ignored. The returned message will then also
4008 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004009 *
4010 * It is also convenient to use it without any free except the last one :
4011 * err = NULL;
4012 * if (!fct1(err)) report(*err);
4013 * if (!fct2(err)) report(*err);
4014 * if (!fct3(err)) report(*err);
4015 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004016 *
4017 * memprintf relies on memvprintf. This last version can be called from any
4018 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004019 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004020char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004021{
4022 va_list args;
4023 char *ret = NULL;
4024 int allocated = 0;
4025 int needed = 0;
4026
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004027 if (!out)
4028 return NULL;
4029
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004030 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004031 char buf1;
4032
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004033 /* vsnprintf() will return the required length even when the
4034 * target buffer is NULL. We do this in a loop just in case
4035 * intermediate evaluations get wrong.
4036 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004037 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004038 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004039 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004040 if (needed < allocated) {
4041 /* Note: on Solaris 8, the first iteration always
4042 * returns -1 if allocated is zero, so we force a
4043 * retry.
4044 */
4045 if (!allocated)
4046 needed = 0;
4047 else
4048 break;
4049 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004050
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004051 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004052 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004053 } while (ret);
4054
4055 if (needed < 0) {
4056 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004057 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004058 }
4059
4060 if (out) {
4061 free(*out);
4062 *out = ret;
4063 }
4064
4065 return ret;
4066}
William Lallemand421f5b52012-02-06 18:15:57 +01004067
Christopher Faulet93a518f2017-10-24 11:25:33 +02004068char *memprintf(char **out, const char *format, ...)
4069{
4070 va_list args;
4071 char *ret = NULL;
4072
4073 va_start(args, format);
4074 ret = memvprintf(out, format, args);
4075 va_end(args);
4076
4077 return ret;
4078}
4079
Willy Tarreau21c705b2012-09-14 11:40:36 +02004080/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4081 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004082 * freed by the caller. It also supports being passed a NULL which results in the same
4083 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004084 * Example of use :
4085 * parse(cmd, &err); (callee: memprintf(&err, ...))
4086 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4087 * free(err);
4088 */
4089char *indent_msg(char **out, int level)
4090{
4091 char *ret, *in, *p;
4092 int needed = 0;
4093 int lf = 0;
4094 int lastlf = 0;
4095 int len;
4096
Willy Tarreau70eec382012-10-10 08:56:47 +02004097 if (!out || !*out)
4098 return NULL;
4099
Willy Tarreau21c705b2012-09-14 11:40:36 +02004100 in = *out - 1;
4101 while ((in = strchr(in + 1, '\n')) != NULL) {
4102 lastlf = in - *out;
4103 lf++;
4104 }
4105
4106 if (!lf) /* single line, no LF, return it as-is */
4107 return *out;
4108
4109 len = strlen(*out);
4110
4111 if (lf == 1 && lastlf == len - 1) {
4112 /* single line, LF at end, strip it and return as-is */
4113 (*out)[lastlf] = 0;
4114 return *out;
4115 }
4116
4117 /* OK now we have at least one LF, we need to process the whole string
4118 * as a multi-line string. What we'll do :
4119 * - prefix with an LF if there is none
4120 * - add <level> spaces before each line
4121 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4122 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4123 */
4124
4125 needed = 1 + level * (lf + 1) + len + 1;
4126 p = ret = malloc(needed);
4127 in = *out;
4128
4129 /* skip initial LFs */
4130 while (*in == '\n')
4131 in++;
4132
4133 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4134 while (*in) {
4135 *p++ = '\n';
4136 memset(p, ' ', level);
4137 p += level;
4138 do {
4139 *p++ = *in++;
4140 } while (*in && *in != '\n');
4141 if (*in)
4142 in++;
4143 }
4144 *p = 0;
4145
4146 free(*out);
4147 *out = ret;
4148
4149 return ret;
4150}
4151
Willy Tarreaua2c99112019-08-21 13:17:37 +02004152/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4153 * and end of lines replaced with <eol> if not 0. The first line to indent has
4154 * to be indicated in <first> (starts at zero), so that it is possible to skip
4155 * indenting the first line if it has to be appended after an existing message.
4156 * Empty strings are never indented, and NULL strings are considered empty both
4157 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4158 * character, non-zero otherwise.
4159 */
4160int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4161{
4162 int bol, lf;
4163 int pfxlen = pfx ? strlen(pfx) : 0;
4164
4165 if (!in)
4166 return 0;
4167
4168 bol = 1;
4169 lf = 0;
4170 while (*in) {
4171 if (bol && pfxlen) {
4172 if (first > 0)
4173 first--;
4174 else
4175 b_putblk(out, pfx, pfxlen);
4176 bol = 0;
4177 }
4178
4179 lf = (*in == '\n');
4180 bol |= lf;
4181 b_putchr(out, (lf && eol) ? eol : *in);
4182 in++;
4183 }
4184 return lf;
4185}
4186
Willy Tarreau9d22e562019-03-29 18:49:09 +01004187/* removes environment variable <name> from the environment as found in
4188 * environ. This is only provided as an alternative for systems without
4189 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004190 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004191 * <name> and to replace the matching pointers with the last pointer of
4192 * the array (since variables are not ordered).
4193 * It always returns 0 (success).
4194 */
4195int my_unsetenv(const char *name)
4196{
4197 extern char **environ;
4198 char **p = environ;
4199 int vars;
4200 int next;
4201 int len;
4202
4203 len = strlen(name);
4204 for (vars = 0; p[vars]; vars++)
4205 ;
4206 next = 0;
4207 while (next < vars) {
4208 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4209 next++;
4210 continue;
4211 }
4212 if (next < vars - 1)
4213 p[next] = p[vars - 1];
4214 p[--vars] = NULL;
4215 }
4216 return 0;
4217}
4218
Willy Tarreaudad36a32013-03-11 01:20:04 +01004219/* Convert occurrences of environment variables in the input string to their
4220 * corresponding value. A variable is identified as a series of alphanumeric
4221 * characters or underscores following a '$' sign. The <in> string must be
4222 * free()able. NULL returns NULL. The resulting string might be reallocated if
4223 * some expansion is made. Variable names may also be enclosed into braces if
4224 * needed (eg: to concatenate alphanum characters).
4225 */
4226char *env_expand(char *in)
4227{
4228 char *txt_beg;
4229 char *out;
4230 char *txt_end;
4231 char *var_beg;
4232 char *var_end;
4233 char *value;
4234 char *next;
4235 int out_len;
4236 int val_len;
4237
4238 if (!in)
4239 return in;
4240
4241 value = out = NULL;
4242 out_len = 0;
4243
4244 txt_beg = in;
4245 do {
4246 /* look for next '$' sign in <in> */
4247 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4248
4249 if (!*txt_end && !out) /* end and no expansion performed */
4250 return in;
4251
4252 val_len = 0;
4253 next = txt_end;
4254 if (*txt_end == '$') {
4255 char save;
4256
4257 var_beg = txt_end + 1;
4258 if (*var_beg == '{')
4259 var_beg++;
4260
4261 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004262 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004263 var_end++;
4264 }
4265
4266 next = var_end;
4267 if (*var_end == '}' && (var_beg > txt_end + 1))
4268 next++;
4269
4270 /* get value of the variable name at this location */
4271 save = *var_end;
4272 *var_end = '\0';
4273 value = getenv(var_beg);
4274 *var_end = save;
4275 val_len = value ? strlen(value) : 0;
4276 }
4277
Hubert Verstraete831962e2016-06-28 22:44:26 +02004278 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004279 if (txt_end > txt_beg) {
4280 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4281 out_len += txt_end - txt_beg;
4282 }
4283 if (val_len) {
4284 memcpy(out + out_len, value, val_len);
4285 out_len += val_len;
4286 }
4287 out[out_len] = 0;
4288 txt_beg = next;
4289 } while (*txt_beg);
4290
4291 /* here we know that <out> was allocated and that we don't need <in> anymore */
4292 free(in);
4293 return out;
4294}
4295
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004296
4297/* same as strstr() but case-insensitive and with limit length */
4298const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4299{
4300 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004301 unsigned int slen, plen;
4302 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004303
4304 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4305 return NULL;
4306
4307 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4308 return str1;
4309
4310 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4311 return NULL;
4312
4313 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 +02004314 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004315 start++;
4316 slen--;
4317 tmp1++;
4318
4319 if (tmp1 >= len_str1)
4320 return NULL;
4321
4322 /* if pattern longer than string */
4323 if (slen < plen)
4324 return NULL;
4325 }
4326
4327 sptr = start;
4328 pptr = (char *)str2;
4329
4330 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004331 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004332 sptr++;
4333 pptr++;
4334 tmp2++;
4335
4336 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4337 return start;
4338 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4339 return NULL;
4340 }
4341 }
4342 return NULL;
4343}
4344
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004345/* This function read the next valid utf8 char.
4346 * <s> is the byte srray to be decode, <len> is its length.
4347 * The function returns decoded char encoded like this:
4348 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4349 * are the length read. The decoded character is stored in <c>.
4350 */
4351unsigned char utf8_next(const char *s, int len, unsigned int *c)
4352{
4353 const unsigned char *p = (unsigned char *)s;
4354 int dec;
4355 unsigned char code = UTF8_CODE_OK;
4356
4357 if (len < 1)
4358 return UTF8_CODE_OK;
4359
4360 /* Check the type of UTF8 sequence
4361 *
4362 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4363 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4364 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4365 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4366 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4367 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4368 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4369 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4370 */
4371 switch (*p) {
4372 case 0x00 ... 0x7f:
4373 *c = *p;
4374 return UTF8_CODE_OK | 1;
4375
4376 case 0x80 ... 0xbf:
4377 *c = *p;
4378 return UTF8_CODE_BADSEQ | 1;
4379
4380 case 0xc0 ... 0xdf:
4381 if (len < 2) {
4382 *c = *p;
4383 return UTF8_CODE_BADSEQ | 1;
4384 }
4385 *c = *p & 0x1f;
4386 dec = 1;
4387 break;
4388
4389 case 0xe0 ... 0xef:
4390 if (len < 3) {
4391 *c = *p;
4392 return UTF8_CODE_BADSEQ | 1;
4393 }
4394 *c = *p & 0x0f;
4395 dec = 2;
4396 break;
4397
4398 case 0xf0 ... 0xf7:
4399 if (len < 4) {
4400 *c = *p;
4401 return UTF8_CODE_BADSEQ | 1;
4402 }
4403 *c = *p & 0x07;
4404 dec = 3;
4405 break;
4406
4407 case 0xf8 ... 0xfb:
4408 if (len < 5) {
4409 *c = *p;
4410 return UTF8_CODE_BADSEQ | 1;
4411 }
4412 *c = *p & 0x03;
4413 dec = 4;
4414 break;
4415
4416 case 0xfc ... 0xfd:
4417 if (len < 6) {
4418 *c = *p;
4419 return UTF8_CODE_BADSEQ | 1;
4420 }
4421 *c = *p & 0x01;
4422 dec = 5;
4423 break;
4424
4425 case 0xfe ... 0xff:
4426 default:
4427 *c = *p;
4428 return UTF8_CODE_BADSEQ | 1;
4429 }
4430
4431 p++;
4432
4433 while (dec > 0) {
4434
4435 /* need 0x10 for the 2 first bits */
4436 if ( ( *p & 0xc0 ) != 0x80 )
4437 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4438
4439 /* add data at char */
4440 *c = ( *c << 6 ) | ( *p & 0x3f );
4441
4442 dec--;
4443 p++;
4444 }
4445
4446 /* Check ovelong encoding.
4447 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4448 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4449 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4450 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004451 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004452 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4453 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4454 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4455 code |= UTF8_CODE_OVERLONG;
4456
4457 /* Check invalid UTF8 range. */
4458 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4459 (*c >= 0xfffe && *c <= 0xffff))
4460 code |= UTF8_CODE_INVRANGE;
4461
4462 return code | ((p-(unsigned char *)s)&0x0f);
4463}
4464
Maxime de Roucydc887852016-05-13 23:52:54 +02004465/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4466 * On failure : return 0 and <err> filled with an error message.
4467 * The caller is responsible for freeing the <err> and <str> copy
4468 * memory area using free()
4469 */
4470int list_append_word(struct list *li, const char *str, char **err)
4471{
4472 struct wordlist *wl;
4473
4474 wl = calloc(1, sizeof(*wl));
4475 if (!wl) {
4476 memprintf(err, "out of memory");
4477 goto fail_wl;
4478 }
4479
4480 wl->s = strdup(str);
4481 if (!wl->s) {
4482 memprintf(err, "out of memory");
4483 goto fail_wl_s;
4484 }
4485
Willy Tarreau2b718102021-04-21 07:32:39 +02004486 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004487
4488 return 1;
4489
4490fail_wl_s:
4491 free(wl->s);
4492fail_wl:
4493 free(wl);
4494 return 0;
4495}
4496
Willy Tarreau37101052019-05-20 16:48:20 +02004497/* indicates if a memory location may safely be read or not. The trick consists
4498 * in performing a harmless syscall using this location as an input and letting
4499 * the operating system report whether it's OK or not. For this we have the
4500 * stat() syscall, which will return EFAULT when the memory location supposed
4501 * to contain the file name is not readable. If it is readable it will then
4502 * either return 0 if the area contains an existing file name, or -1 with
4503 * another code. This must not be abused, and some audit systems might detect
4504 * this as abnormal activity. It's used only for unsafe dumps.
4505 */
4506int may_access(const void *ptr)
4507{
4508 struct stat buf;
4509
4510 if (stat(ptr, &buf) == 0)
4511 return 1;
4512 if (errno == EFAULT)
4513 return 0;
4514 return 1;
4515}
4516
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004517/* print a string of text buffer to <out>. The format is :
4518 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4519 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4520 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4521 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004522int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004523{
4524 unsigned char c;
4525 int ptr = 0;
4526
4527 while (buf[ptr] && ptr < bsize) {
4528 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004529 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004530 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004531 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004532 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004533 }
4534 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004535 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004536 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004537 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004538 switch (c) {
4539 case ' ': c = ' '; break;
4540 case '\t': c = 't'; break;
4541 case '\n': c = 'n'; break;
4542 case '\r': c = 'r'; break;
4543 case '\e': c = 'e'; break;
4544 case '\\': c = '\\'; break;
4545 case '=': c = '='; break;
4546 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004547 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004548 }
4549 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004550 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004551 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004552 out->area[out->data++] = '\\';
4553 out->area[out->data++] = 'x';
4554 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4555 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004556 }
4557 ptr++;
4558 }
4559
4560 return ptr;
4561}
4562
4563/* print a buffer in hexa.
4564 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4565 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004566int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004567{
4568 unsigned char c;
4569 int ptr = 0;
4570
4571 while (ptr < bsize) {
4572 c = buf[ptr];
4573
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004574 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004575 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004576 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4577 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004578
4579 ptr++;
4580 }
4581 return ptr;
4582}
4583
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004584/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4585 * prepending each line with prefix <pfx>. The output is *not* initialized.
4586 * The output will not wrap pas the buffer's end so it is more optimal if the
4587 * caller makes sure the buffer is aligned first. A trailing zero will always
4588 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004589 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4590 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004591 */
Willy Tarreau37101052019-05-20 16:48:20 +02004592void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004593{
4594 const unsigned char *d = buf;
4595 int i, j, start;
4596
4597 d = (const unsigned char *)(((unsigned long)buf) & -16);
4598 start = ((unsigned long)buf) & 15;
4599
4600 for (i = 0; i < start + len; i += 16) {
4601 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4602
Willy Tarreau37101052019-05-20 16:48:20 +02004603 // 0: unchecked, 1: checked safe, 2: danger
4604 unsafe = !!unsafe;
4605 if (unsafe && !may_access(d + i))
4606 unsafe = 2;
4607
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004608 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004609 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004610 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004611 else if (unsafe > 1)
4612 chunk_strcat(out, "** ");
4613 else
4614 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004615
4616 if (j == 7)
4617 chunk_strcat(out, "- ");
4618 }
4619 chunk_strcat(out, " ");
4620 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004621 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004622 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004623 else if (unsafe > 1)
4624 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004625 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004626 chunk_appendf(out, "%c", d[i + j]);
4627 else
4628 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004629 }
4630 chunk_strcat(out, "\n");
4631 }
4632}
4633
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004634/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4635 * enclosed in brackets after the address itself, formatted on 14 chars
4636 * including the "0x" prefix. This is meant to be used as a prefix for code
4637 * areas. For example:
4638 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4639 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4640 * is emitted. A NULL <pfx> will be considered empty.
4641 */
4642void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4643{
4644 int ok = 0;
4645 int i;
4646
4647 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4648
4649 for (i = 0; i < n; i++) {
4650 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4651 ok = may_access(addr + i);
4652 if (ok)
4653 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4654 else
4655 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4656 }
4657}
4658
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004659/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4660 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4661 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4662 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4663 * lines are respected within the limit of 70 output chars. Lines that are
4664 * continuation of a previous truncated line begin with "+" instead of " "
4665 * after the offset. The new pointer is returned.
4666 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004667int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004668 int *line, int ptr)
4669{
4670 int end;
4671 unsigned char c;
4672
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004673 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004674 if (end > out->size)
4675 return ptr;
4676
4677 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4678
4679 while (ptr < len && ptr < bsize) {
4680 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004681 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004682 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004683 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004684 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004685 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004686 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004687 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004688 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004689 switch (c) {
4690 case '\t': c = 't'; break;
4691 case '\n': c = 'n'; break;
4692 case '\r': c = 'r'; break;
4693 case '\e': c = 'e'; break;
4694 case '\\': c = '\\'; break;
4695 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004696 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004697 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004698 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004699 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004700 out->area[out->data++] = '\\';
4701 out->area[out->data++] = 'x';
4702 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4703 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004704 }
4705 if (buf[ptr++] == '\n') {
4706 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004707 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004708 *line = ptr;
4709 return ptr;
4710 }
4711 }
4712 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004713 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004714 return ptr;
4715}
4716
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004717/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004718 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4719 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004720 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004721void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4722 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004723{
Willy Tarreau73459792017-04-11 07:58:08 +02004724 unsigned int i;
4725 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004726
4727 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4728 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004729 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004730 for (j = 0; j < 8; j++) {
4731 if (b + j >= 0 && b + j < len)
4732 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4733 else
4734 fprintf(out, " ");
4735 }
4736
4737 if (b + j >= 0 && b + j < len)
4738 fputc('-', out);
4739 else
4740 fputc(' ', out);
4741
4742 for (j = 8; j < 16; j++) {
4743 if (b + j >= 0 && b + j < len)
4744 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4745 else
4746 fprintf(out, " ");
4747 }
4748
4749 fprintf(out, " ");
4750 for (j = 0; j < 16; j++) {
4751 if (b + j >= 0 && b + j < len) {
4752 if (isprint((unsigned char)buf[b + j]))
4753 fputc((unsigned char)buf[b + j], out);
4754 else
4755 fputc('.', out);
4756 }
4757 else
4758 fputc(' ', out);
4759 }
4760 fputc('\n', out);
4761 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004762}
4763
Willy Tarreaubb869862020-04-16 10:52:41 +02004764/* Tries to report the executable path name on platforms supporting this. If
4765 * not found or not possible, returns NULL.
4766 */
4767const char *get_exec_path()
4768{
4769 const char *ret = NULL;
4770
4771#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4772 long execfn = getauxval(AT_EXECFN);
4773
4774 if (execfn && execfn != ENOENT)
4775 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004776#elif defined(__FreeBSD__)
4777 Elf_Auxinfo *auxv;
4778 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4779 if (auxv->a_type == AT_EXECPATH) {
4780 ret = (const char *)auxv->a_un.a_ptr;
4781 break;
4782 }
4783 }
David Carlierbd2cced2021-08-17 08:44:25 +01004784#elif defined(__NetBSD__)
4785 AuxInfo *auxv;
4786 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4787 if (auxv->a_type == AT_SUN_EXECNAME) {
4788 ret = (const char *)auxv->a_v;
4789 break;
4790 }
4791 }
Willy Tarreaubb869862020-04-16 10:52:41 +02004792#endif
4793 return ret;
4794}
4795
Baruch Siache1651b22020-07-24 07:52:20 +03004796#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004797/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4798 * also returns the symbol size in <size>, otherwise returns 0 there.
4799 */
4800static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4801{
4802 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004803#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004804 const ElfW(Sym) *sym;
4805
4806 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4807 if (ret)
4808 *size = sym ? sym->st_size : 0;
4809#else
4810 ret = dladdr(addr, dli);
4811 *size = 0;
4812#endif
4813 return ret;
4814}
Willy Tarreau64192392021-05-05 09:06:21 +02004815
4816/* Tries to retrieve the address of the first occurrence symbol <name>.
4817 * Note that NULL in return is not always an error as a symbol may have that
4818 * address in special situations.
4819 */
4820void *get_sym_curr_addr(const char *name)
4821{
4822 void *ptr = NULL;
4823
4824#ifdef RTLD_DEFAULT
4825 ptr = dlsym(RTLD_DEFAULT, name);
4826#endif
4827 return ptr;
4828}
4829
4830
4831/* Tries to retrieve the address of the next occurrence of symbol <name>
4832 * Note that NULL in return is not always an error as a symbol may have that
4833 * address in special situations.
4834 */
4835void *get_sym_next_addr(const char *name)
4836{
4837 void *ptr = NULL;
4838
4839#ifdef RTLD_NEXT
4840 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004841#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004842 return ptr;
4843}
4844
4845#else /* elf & linux & dl */
4846
4847/* no possible resolving on other platforms at the moment */
4848void *get_sym_curr_addr(const char *name)
4849{
4850 return NULL;
4851}
4852
4853void *get_sym_next_addr(const char *name)
4854{
4855 return NULL;
4856}
4857
4858#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004859
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004860/* Tries to append to buffer <buf> some indications about the symbol at address
4861 * <addr> using the following form:
4862 * lib:+0xoffset (unresolvable address from lib's base)
4863 * main+0xoffset (unresolvable address from main (+/-))
4864 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4865 * name (resolved exact exec address)
4866 * lib:name (resolved exact lib address)
4867 * name+0xoffset/0xsize (resolved address within exec symbol)
4868 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4869 *
4870 * The file name (lib or executable) is limited to what lies between the last
4871 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4872 * 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 +03004873 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004874 *
4875 * The symbol's base address is returned, or NULL when unresolved, in order to
4876 * allow the caller to match it against known ones.
4877 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004878const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004879{
4880 const struct {
4881 const void *func;
4882 const char *name;
4883 } fcts[] = {
4884 { .func = process_stream, .name = "process_stream" },
4885 { .func = task_run_applet, .name = "task_run_applet" },
4886 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004887 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004888 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4889 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004890 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004891 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4892 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004893 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004894#ifdef USE_THREAD
4895 { .func = accept_queue_process, .name = "accept_queue_process" },
4896#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004897#ifdef USE_LUA
4898 { .func = hlua_process_task, .name = "hlua_process_task" },
4899#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004900#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004901 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4902 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4903#endif
4904 };
4905
Baruch Siache1651b22020-07-24 07:52:20 +03004906#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004907 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004908 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004909 const char *fname, *p;
4910#endif
4911 int i;
4912
4913 if (pfx)
4914 chunk_appendf(buf, "%s", pfx);
4915
4916 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4917 if (addr == fcts[i].func) {
4918 chunk_appendf(buf, "%s", fcts[i].name);
4919 return addr;
4920 }
4921 }
4922
Baruch Siache1651b22020-07-24 07:52:20 +03004923#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004924 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004925 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004926 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004927
4928 /* 1. prefix the library name if it's not the same object as the one
4929 * that contains the main function. The name is picked between last '/'
4930 * and first following '.'.
4931 */
4932 if (!dladdr(main, &dli_main))
4933 dli_main.dli_fbase = NULL;
4934
4935 if (dli_main.dli_fbase != dli.dli_fbase) {
4936 fname = dli.dli_fname;
4937 p = strrchr(fname, '/');
4938 if (p++)
4939 fname = p;
4940 p = strchr(fname, '.');
4941 if (!p)
4942 p = fname + strlen(fname);
4943
4944 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4945 }
4946
4947 /* 2. symbol name */
4948 if (dli.dli_sname) {
4949 /* known, dump it and return symbol's address (exact or relative) */
4950 chunk_appendf(buf, "%s", dli.dli_sname);
4951 if (addr != dli.dli_saddr) {
4952 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004953 if (size)
4954 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004955 }
4956 return dli.dli_saddr;
4957 }
4958 else if (dli_main.dli_fbase != dli.dli_fbase) {
4959 /* unresolved symbol from a known library, report relative offset */
4960 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4961 return NULL;
4962 }
Baruch Siache1651b22020-07-24 07:52:20 +03004963#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004964 unknown:
4965 /* unresolved symbol from the main file, report relative offset to main */
4966 if ((void*)addr < (void*)main)
4967 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4968 else
4969 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4970 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004971}
4972
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004973/*
4974 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004975 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004976 *
4977 * First, initializes the value with <sz> as address to 0 and initializes the
4978 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4979 * address updating <sz> pointed value to the size of this array.
4980 *
4981 * Returns 1 if succeeded, 0 if not.
4982 */
4983int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4984{
4985 unsigned int *n;
4986 const char *s, *end;
4987
4988 s = str;
4989 *sz = 0;
4990 end = str + strlen(str);
4991 *nums = n = NULL;
4992
4993 while (1) {
4994 unsigned int r;
4995
4996 if (s >= end)
4997 break;
4998
4999 r = read_uint(&s, end);
5000 /* Expected characters after having read an uint: '\0' or '.',
5001 * if '.', must not be terminal.
5002 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005003 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5004 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005005 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005006 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005007
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005008 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005009 if (!n)
5010 return 0;
5011
5012 n[(*sz)++] = r;
5013 }
5014 *nums = n;
5015
5016 return 1;
5017}
5018
Willy Tarreau4d589e72019-08-23 19:02:26 +02005019
5020/* returns the number of bytes needed to encode <v> as a varint. An inline
5021 * version exists for use with constants (__varint_bytes()).
5022 */
5023int varint_bytes(uint64_t v)
5024{
5025 int len = 1;
5026
5027 if (v >= 240) {
5028 v = (v - 240) >> 4;
5029 while (1) {
5030 len++;
5031 if (v < 128)
5032 break;
5033 v = (v - 128) >> 7;
5034 }
5035 }
5036 return len;
5037}
5038
Willy Tarreau52bf8392020-03-08 00:42:37 +01005039
5040/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005041static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005042
5043/* This is a thread-safe implementation of xoroshiro128** described below:
5044 * http://prng.di.unimi.it/
5045 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5046 * supports fast jumps and passes all common quality tests. It is thread-safe,
5047 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5048 * local lock on other ones.
5049 */
5050uint64_t ha_random64()
5051{
Willy Tarreau1544c142020-03-12 00:31:18 +01005052 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5053 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005054
5055#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5056 static HA_SPINLOCK_T rand_lock;
5057
5058 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5059#endif
5060
5061 old[0] = ha_random_state[0];
5062 old[1] = ha_random_state[1];
5063
5064#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5065 do {
5066#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005067 new[1] = old[0] ^ old[1];
5068 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5069 new[1] = rotl64(new[1], 37); // c
5070
5071#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5072 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5073#else
5074 ha_random_state[0] = new[0];
5075 ha_random_state[1] = new[1];
5076#if defined(USE_THREAD)
5077 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5078#endif
5079#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005080 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005081}
5082
5083/* seeds the random state using up to <len> bytes from <seed>, starting with
5084 * the first non-zero byte.
5085 */
5086void ha_random_seed(const unsigned char *seed, size_t len)
5087{
5088 size_t pos;
5089
5090 /* the seed must not be all zeroes, so we pre-fill it with alternating
5091 * bits and overwrite part of them with the block starting at the first
5092 * non-zero byte from the seed.
5093 */
5094 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5095
5096 for (pos = 0; pos < len; pos++)
5097 if (seed[pos] != 0)
5098 break;
5099
5100 if (pos == len)
5101 return;
5102
5103 seed += pos;
5104 len -= pos;
5105
5106 if (len > sizeof(ha_random_state))
5107 len = sizeof(ha_random_state);
5108
5109 memcpy(ha_random_state, seed, len);
5110}
5111
5112/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5113 * and is equivalent to calling ha_random64() as many times. It is used to
5114 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5115 * different generators (i.e. different processes after a fork). The <dist>
5116 * argument is the distance to jump to and is used in a loop so it rather not
5117 * be too large if the processing time is a concern.
5118 *
5119 * BEWARE: this function is NOT thread-safe and must not be called during
5120 * concurrent accesses to ha_random64().
5121 */
5122void ha_random_jump96(uint32_t dist)
5123{
5124 while (dist--) {
5125 uint64_t s0 = 0;
5126 uint64_t s1 = 0;
5127 int b;
5128
5129 for (b = 0; b < 64; b++) {
5130 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5131 s0 ^= ha_random_state[0];
5132 s1 ^= ha_random_state[1];
5133 }
5134 ha_random64();
5135 }
5136
5137 for (b = 0; b < 64; b++) {
5138 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5139 s0 ^= ha_random_state[0];
5140 s1 ^= ha_random_state[1];
5141 }
5142 ha_random64();
5143 }
5144 ha_random_state[0] = s0;
5145 ha_random_state[1] = s1;
5146 }
5147}
5148
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005149/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5150 * bytes large.
5151 */
5152void ha_generate_uuid(struct buffer *output)
5153{
5154 uint32_t rnd[4];
5155 uint64_t last;
5156
5157 last = ha_random64();
5158 rnd[0] = last;
5159 rnd[1] = last >> 32;
5160
5161 last = ha_random64();
5162 rnd[2] = last;
5163 rnd[3] = last >> 32;
5164
5165 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5166 rnd[0],
5167 rnd[1] & 0xFFFF,
5168 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5169 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5170 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5171}
5172
5173
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005174/* only used by parse_line() below. It supports writing in place provided that
5175 * <in> is updated to the next location before calling it. In that case, the
5176 * char at <in> may be overwritten.
5177 */
5178#define EMIT_CHAR(x) \
5179 do { \
5180 char __c = (char)(x); \
5181 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5182 err |= PARSE_ERR_OVERLAP; \
5183 if (outpos >= outmax) \
5184 err |= PARSE_ERR_TOOLARGE; \
5185 if (!err) \
5186 out[outpos] = __c; \
5187 outpos++; \
5188 } while (0)
5189
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005190/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005191 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5192 * extraneous ones are not emitted but <outlen> is updated so that the caller
5193 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5194 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005195 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5196 * it is guaranteed that at least one arg will point to the zero. It is safe
5197 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005198 *
5199 * <out> may overlap with <in> provided that it never goes further, in which
5200 * case the parser will accept to perform in-place parsing and unquoting/
5201 * unescaping but only if environment variables do not lead to expansion that
5202 * causes overlapping, otherwise the input string being destroyed, the error
5203 * will not be recoverable. Note that even during out-of-place <in> will
5204 * experience temporary modifications in-place for variable resolution and must
5205 * be writable, and will also receive zeroes to delimit words when using
5206 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5207 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5208 * starting point of the first invalid character sequence or unmatched
5209 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5210 * error reporting might be difficult since zeroes will have been inserted into
5211 * the string. One solution for the caller may consist in replacing all args
5212 * delimiters with spaces in this case.
5213 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005214uint32_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 +02005215{
5216 char *quote = NULL;
5217 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005218 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005219 unsigned char hex1, hex2;
5220 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005221 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005222 size_t outpos = 0;
5223 int squote = 0;
5224 int dquote = 0;
5225 int arg = 0;
5226 uint32_t err = 0;
5227
5228 *nbargs = 0;
5229 *outlen = 0;
5230
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005231 /* argsmax may be -1 here, protecting args[] from any write */
5232 if (arg < argsmax)
5233 args[arg] = out;
5234
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005235 while (1) {
5236 if (*in >= '-' && *in != '\\') {
5237 /* speedup: directly send all regular chars starting
5238 * with '-', '.', '/', alnum etc...
5239 */
5240 EMIT_CHAR(*in++);
5241 continue;
5242 }
5243 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5244 /* end of line */
5245 break;
5246 }
5247 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5248 /* comment */
5249 break;
5250 }
5251 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5252 if (dquote) {
5253 dquote = 0;
5254 quote = NULL;
5255 }
5256 else {
5257 dquote = 1;
5258 quote = in;
5259 }
5260 in++;
5261 continue;
5262 }
5263 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5264 if (squote) {
5265 squote = 0;
5266 quote = NULL;
5267 }
5268 else {
5269 squote = 1;
5270 quote = in;
5271 }
5272 in++;
5273 continue;
5274 }
5275 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5276 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5277 * C equivalent value but only when they have a special meaning and within
5278 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5279 */
5280 char tosend = *in;
5281
5282 switch (in[1]) {
5283 case ' ':
5284 case '\\':
5285 tosend = in[1];
5286 in++;
5287 break;
5288
5289 case 't':
5290 tosend = '\t';
5291 in++;
5292 break;
5293
5294 case 'n':
5295 tosend = '\n';
5296 in++;
5297 break;
5298
5299 case 'r':
5300 tosend = '\r';
5301 in++;
5302 break;
5303
5304 case '#':
5305 /* escaping of "#" only if comments are supported */
5306 if (opts & PARSE_OPT_SHARP)
5307 in++;
5308 tosend = *in;
5309 break;
5310
5311 case '\'':
5312 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5313 if (opts & PARSE_OPT_SQUOTE && !squote)
5314 in++;
5315 tosend = *in;
5316 break;
5317
5318 case '"':
5319 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5320 if (opts & PARSE_OPT_DQUOTE && !squote)
5321 in++;
5322 tosend = *in;
5323 break;
5324
5325 case '$':
5326 /* escaping of '$' only inside double quotes and only if env supported */
5327 if (opts & PARSE_OPT_ENV && dquote)
5328 in++;
5329 tosend = *in;
5330 break;
5331
5332 case 'x':
5333 if (!ishex(in[2]) || !ishex(in[3])) {
5334 /* invalid or incomplete hex sequence */
5335 err |= PARSE_ERR_HEX;
5336 if (errptr)
5337 *errptr = in;
5338 goto leave;
5339 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005340 hex1 = toupper((unsigned char)in[2]) - '0';
5341 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005342 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5343 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5344 tosend = (hex1 << 4) + hex2;
5345 in += 3;
5346 break;
5347
5348 default:
5349 /* other combinations are not escape sequences */
5350 break;
5351 }
5352
5353 in++;
5354 EMIT_CHAR(tosend);
5355 }
5356 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5357 /* a non-escaped space is an argument separator */
5358 while (isspace((unsigned char)*in))
5359 in++;
5360 EMIT_CHAR(0);
5361 arg++;
5362 if (arg < argsmax)
5363 args[arg] = out + outpos;
5364 else
5365 err |= PARSE_ERR_TOOMANY;
5366 }
5367 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5368 /* environment variables are evaluated anywhere, or only
5369 * inside double quotes if they are supported.
5370 */
5371 char *var_name;
5372 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005373 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005374
5375 in++;
5376
5377 if (*in == '{')
5378 brace = in++;
5379
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005380 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005381 /* unacceptable character in variable name */
5382 err |= PARSE_ERR_VARNAME;
5383 if (errptr)
5384 *errptr = in;
5385 goto leave;
5386 }
5387
5388 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005389 if (*in == '.')
5390 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005391 while (isalnum((unsigned char)*in) || *in == '_')
5392 in++;
5393
5394 save_char = *in;
5395 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005396 if (unlikely(*var_name == '.')) {
5397 /* internal pseudo-variables */
5398 if (strcmp(var_name, ".LINE") == 0)
5399 value = ultoa(global.cfg_curr_line);
5400 else if (strcmp(var_name, ".FILE") == 0)
5401 value = global.cfg_curr_file;
5402 else if (strcmp(var_name, ".SECTION") == 0)
5403 value = global.cfg_curr_section;
5404 else {
5405 /* unsupported internal variable name */
5406 err |= PARSE_ERR_VARNAME;
5407 if (errptr)
5408 *errptr = var_name;
5409 goto leave;
5410 }
5411 } else {
5412 value = getenv(var_name);
5413 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005414 *in = save_char;
5415
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005416 /* support for '[*]' sequence to force word expansion,
5417 * only available inside braces */
5418 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5419 word_expand = in++;
5420
5421 if (*in++ != '*' || *in++ != ']') {
5422 err |= PARSE_ERR_WRONG_EXPAND;
5423 if (errptr)
5424 *errptr = word_expand;
5425 goto leave;
5426 }
5427 }
5428
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005429 if (brace) {
5430 if (*in != '}') {
5431 /* unmatched brace */
5432 err |= PARSE_ERR_BRACE;
5433 if (errptr)
5434 *errptr = brace;
5435 goto leave;
5436 }
5437 in++;
5438 brace = NULL;
5439 }
5440
5441 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005442 while (*value) {
5443 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005444 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005445 EMIT_CHAR(0);
5446 ++arg;
5447 if (arg < argsmax)
5448 args[arg] = out + outpos;
5449 else
5450 err |= PARSE_ERR_TOOMANY;
5451
5452 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005453 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005454 ;
5455 } else {
5456 EMIT_CHAR(*value++);
5457 }
5458 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005459 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005460 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005461 }
5462 else {
5463 /* any other regular char */
5464 EMIT_CHAR(*in++);
5465 }
5466 }
5467
5468 /* end of output string */
5469 EMIT_CHAR(0);
5470 arg++;
5471
5472 if (quote) {
5473 /* unmatched quote */
5474 err |= PARSE_ERR_QUOTE;
5475 if (errptr)
5476 *errptr = quote;
5477 goto leave;
5478 }
5479 leave:
5480 *nbargs = arg;
5481 *outlen = outpos;
5482
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005483 /* empty all trailing args by making them point to the trailing zero,
5484 * at least the last one in any case.
5485 */
5486 if (arg > argsmax)
5487 arg = argsmax;
5488
5489 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005490 args[arg++] = out + outpos - 1;
5491
5492 return err;
5493}
5494#undef EMIT_CHAR
5495
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005496/* This is used to sanitize an input line that's about to be used for error reporting.
5497 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5498 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5499 * If non-printable chars are present in the output. It returns the new offset <pos>
5500 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5501 * be at least 6 to support two "..." otherwise the result is undefined. The line
5502 * itself must have at least 7 chars allocated for the same reason.
5503 */
5504size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5505{
5506 size_t shift = 0;
5507 char *out = line;
5508 char *in = line;
5509 char *end = line + width;
5510
5511 if (pos >= width) {
5512 /* if we have to shift, we'll be out of context, so let's
5513 * try to put <pos> at the center of width.
5514 */
5515 shift = pos - width / 2;
5516 in += shift + 3;
5517 end = out + width - 3;
5518 out[0] = out[1] = out[2] = '.';
5519 out += 3;
5520 }
5521
5522 while (out < end && *in) {
5523 if (isspace((unsigned char)*in))
5524 *out++ = ' ';
5525 else if (isprint((unsigned char)*in))
5526 *out++ = *in;
5527 else
5528 *out++ = '?';
5529 in++;
5530 }
5531
5532 if (end < line + width) {
5533 out[0] = out[1] = out[2] = '.';
5534 out += 3;
5535 }
5536
5537 *out++ = 0;
5538 return pos - shift;
5539}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005540
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005541/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005542 * transitions between characters. <fp> is a 1024-entries array indexed as
5543 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005544 * 1..26=letter, 27=digit, 28=other/begin/end.
5545 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005546 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005547void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005548{
5549 const char *p;
5550 int from, to;
5551 int c;
5552
Willy Tarreauba2c4452021-03-12 09:01:52 +01005553 from = 28; // begin
5554 for (p = word; *p; p++) {
5555 c = tolower(*p);
5556 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005557 case 'a'...'z': to = c - 'a' + 1; break;
5558 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5559 case '0'...'9': to = 27; break;
5560 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005561 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005562 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005563 fp[32 * from + to]++;
5564 from = to;
5565 }
5566 to = 28; // end
5567 fp[32 * from + to]++;
5568}
5569
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005570/* Initialize array <fp> with the fingerprint of word <word> by counting the
5571 * transitions between characters. <fp> is a 1024-entries array indexed as
5572 * 32*from+to. Positions for 'from' and 'to' are:
5573 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5574 */
5575void make_word_fingerprint(uint8_t *fp, const char *word)
5576{
5577 memset(fp, 0, 1024);
5578 update_word_fingerprint(fp, word);
5579}
5580
Willy Tarreauba2c4452021-03-12 09:01:52 +01005581/* Return the distance between two word fingerprints created by function
5582 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005583 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005584 */
5585int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5586{
5587 int i, k, dist = 0;
5588
5589 for (i = 0; i < 1024; i++) {
5590 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005591 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005592 }
5593 return dist;
5594}
5595
William Lallemand3aeb3f92021-08-21 23:59:56 +02005596/*
5597 * This function compares the loaded openssl version with a string <version>
5598 * This function use the same return code as compare_current_version:
5599 *
5600 * -1 : the version in argument is older than the current openssl version
5601 * 0 : the version in argument is the same as the current openssl version
5602 * 1 : the version in argument is newer than the current openssl version
5603 *
5604 * Or some errors:
5605 * -2 : openssl is not available on this process
5606 * -3 : the version in argument is not parsable
5607 */
5608int openssl_compare_current_version(const char *version)
5609{
5610#ifdef USE_OPENSSL
5611 int numversion;
5612
5613 numversion = openssl_version_parser(version);
5614 if (numversion == 0)
5615 return -3;
5616
5617 if (numversion < OPENSSL_VERSION_NUMBER)
5618 return -1;
5619 else if (numversion > OPENSSL_VERSION_NUMBER)
5620 return 1;
5621 else
5622 return 0;
5623#else
5624 return -2;
5625#endif
5626}
5627
Willy Tarreau06e69b52021-03-02 14:01:35 +01005628static int init_tools_per_thread()
5629{
5630 /* Let's make each thread start from a different position */
5631 statistical_prng_state += tid * MAX_THREADS;
5632 if (!statistical_prng_state)
5633 statistical_prng_state++;
5634 return 1;
5635}
5636REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005637
Willy Tarreaubaaee002006-06-26 02:48:02 +02005638/*
5639 * Local variables:
5640 * c-indent-level: 8
5641 * c-basic-offset: 8
5642 * End:
5643 */