blob: bdf78ffb5b798171db65f01a5ca2cc35af80c7ba [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
devnexen@gmail.com49a32282021-08-17 12:55:49 +010019#if defined(__FreeBSD__)
20#include <elf.h>
21#include <dlfcn.h>
22extern void *__elf_aux_vector;
23#endif
24
David Carlier1b9d57d2021-08-17 08:44:25 +010025#if defined(__NetBSD__)
26#include <sys/exec_elf.h>
27#include <dlfcn.h>
28#endif
29
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010030#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020033#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020034#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035#include <stdlib.h>
36#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010037#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020038#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010039#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020040#include <sys/stat.h>
41#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010042#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020043#include <netinet/in.h>
44#include <arpa/inet.h>
45
Willy Tarreau1ee71dd2021-08-30 10:15:35 +020046#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreau30053062020-08-20 16:39:14 +020047#include <sys/auxv.h>
48#endif
49
Willy Tarreau48fbcae2020-06-03 18:09:46 +020050#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020052
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020053#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020054#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020055#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020056#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020057#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020058#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020059#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010060#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020061#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010062#include <haproxy/resolvers.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010063#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020064#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020065#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020066#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020067#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010068
Thierry Fournier93127942016-01-20 18:49:45 +010069/* This macro returns false if the test __x is false. Many
70 * of the following parsing function must be abort the processing
71 * if it returns 0, so this macro is useful for writing light code.
72 */
73#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
74
Willy Tarreau56adcf22012-12-23 18:00:29 +010075/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020076 * 2^64-1 = 18446744073709551615 or
77 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020078 *
79 * The HTML version needs room for adding the 25 characters
80 * '<span class="rls"></span>' around digits at positions 3N+1 in order
81 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020082 */
Christopher Faulet99bca652017-11-14 16:47:26 +010083THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
84THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020085
Willy Tarreau588297f2014-06-16 15:16:40 +020086/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
87 * to quote strings larger than a max configuration line.
88 */
Christopher Faulet99bca652017-11-14 16:47:26 +010089THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
90THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020091
Willy Tarreau06e69b52021-03-02 14:01:35 +010092/* thread-local PRNG state. It's modified to start from a different sequence
93 * on all threads upon startup. It must not be used or anything beyond getting
94 * statistical values as it's 100% predictable.
95 */
96THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
97
Willy Tarreaubaaee002006-06-26 02:48:02 +020098/*
William Lallemande7340ec2012-01-24 11:15:39 +010099 * unsigned long long ASCII representation
100 *
101 * return the last char '\0' or NULL if no enough
102 * space in dst
103 */
104char *ulltoa(unsigned long long n, char *dst, size_t size)
105{
106 int i = 0;
107 char *res;
108
109 switch(n) {
110 case 1ULL ... 9ULL:
111 i = 0;
112 break;
113
114 case 10ULL ... 99ULL:
115 i = 1;
116 break;
117
118 case 100ULL ... 999ULL:
119 i = 2;
120 break;
121
122 case 1000ULL ... 9999ULL:
123 i = 3;
124 break;
125
126 case 10000ULL ... 99999ULL:
127 i = 4;
128 break;
129
130 case 100000ULL ... 999999ULL:
131 i = 5;
132 break;
133
134 case 1000000ULL ... 9999999ULL:
135 i = 6;
136 break;
137
138 case 10000000ULL ... 99999999ULL:
139 i = 7;
140 break;
141
142 case 100000000ULL ... 999999999ULL:
143 i = 8;
144 break;
145
146 case 1000000000ULL ... 9999999999ULL:
147 i = 9;
148 break;
149
150 case 10000000000ULL ... 99999999999ULL:
151 i = 10;
152 break;
153
154 case 100000000000ULL ... 999999999999ULL:
155 i = 11;
156 break;
157
158 case 1000000000000ULL ... 9999999999999ULL:
159 i = 12;
160 break;
161
162 case 10000000000000ULL ... 99999999999999ULL:
163 i = 13;
164 break;
165
166 case 100000000000000ULL ... 999999999999999ULL:
167 i = 14;
168 break;
169
170 case 1000000000000000ULL ... 9999999999999999ULL:
171 i = 15;
172 break;
173
174 case 10000000000000000ULL ... 99999999999999999ULL:
175 i = 16;
176 break;
177
178 case 100000000000000000ULL ... 999999999999999999ULL:
179 i = 17;
180 break;
181
182 case 1000000000000000000ULL ... 9999999999999999999ULL:
183 i = 18;
184 break;
185
186 case 10000000000000000000ULL ... ULLONG_MAX:
187 i = 19;
188 break;
189 }
190 if (i + 2 > size) // (i + 1) + '\0'
191 return NULL; // too long
192 res = dst + i + 1;
193 *res = '\0';
194 for (; i >= 0; i--) {
195 dst[i] = n % 10ULL + '0';
196 n /= 10ULL;
197 }
198 return res;
199}
200
201/*
202 * unsigned long ASCII representation
203 *
204 * return the last char '\0' or NULL if no enough
205 * space in dst
206 */
207char *ultoa_o(unsigned long n, char *dst, size_t size)
208{
209 int i = 0;
210 char *res;
211
212 switch (n) {
213 case 0U ... 9UL:
214 i = 0;
215 break;
216
217 case 10U ... 99UL:
218 i = 1;
219 break;
220
221 case 100U ... 999UL:
222 i = 2;
223 break;
224
225 case 1000U ... 9999UL:
226 i = 3;
227 break;
228
229 case 10000U ... 99999UL:
230 i = 4;
231 break;
232
233 case 100000U ... 999999UL:
234 i = 5;
235 break;
236
237 case 1000000U ... 9999999UL:
238 i = 6;
239 break;
240
241 case 10000000U ... 99999999UL:
242 i = 7;
243 break;
244
245 case 100000000U ... 999999999UL:
246 i = 8;
247 break;
248#if __WORDSIZE == 32
249
250 case 1000000000ULL ... ULONG_MAX:
251 i = 9;
252 break;
253
254#elif __WORDSIZE == 64
255
256 case 1000000000ULL ... 9999999999UL:
257 i = 9;
258 break;
259
260 case 10000000000ULL ... 99999999999UL:
261 i = 10;
262 break;
263
264 case 100000000000ULL ... 999999999999UL:
265 i = 11;
266 break;
267
268 case 1000000000000ULL ... 9999999999999UL:
269 i = 12;
270 break;
271
272 case 10000000000000ULL ... 99999999999999UL:
273 i = 13;
274 break;
275
276 case 100000000000000ULL ... 999999999999999UL:
277 i = 14;
278 break;
279
280 case 1000000000000000ULL ... 9999999999999999UL:
281 i = 15;
282 break;
283
284 case 10000000000000000ULL ... 99999999999999999UL:
285 i = 16;
286 break;
287
288 case 100000000000000000ULL ... 999999999999999999UL:
289 i = 17;
290 break;
291
292 case 1000000000000000000ULL ... 9999999999999999999UL:
293 i = 18;
294 break;
295
296 case 10000000000000000000ULL ... ULONG_MAX:
297 i = 19;
298 break;
299
300#endif
301 }
302 if (i + 2 > size) // (i + 1) + '\0'
303 return NULL; // too long
304 res = dst + i + 1;
305 *res = '\0';
306 for (; i >= 0; i--) {
307 dst[i] = n % 10U + '0';
308 n /= 10U;
309 }
310 return res;
311}
312
313/*
314 * signed long ASCII representation
315 *
316 * return the last char '\0' or NULL if no enough
317 * space in dst
318 */
319char *ltoa_o(long int n, char *dst, size_t size)
320{
321 char *pos = dst;
322
323 if (n < 0) {
324 if (size < 3)
325 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
326 *pos = '-';
327 pos++;
328 dst = ultoa_o(-n, pos, size - 1);
329 } else {
330 dst = ultoa_o(n, dst, size);
331 }
332 return dst;
333}
334
335/*
336 * signed long long ASCII representation
337 *
338 * return the last char '\0' or NULL if no enough
339 * space in dst
340 */
341char *lltoa(long long n, char *dst, size_t size)
342{
343 char *pos = dst;
344
345 if (n < 0) {
346 if (size < 3)
347 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
348 *pos = '-';
349 pos++;
350 dst = ulltoa(-n, pos, size - 1);
351 } else {
352 dst = ulltoa(n, dst, size);
353 }
354 return dst;
355}
356
357/*
358 * write a ascii representation of a unsigned into dst,
359 * return a pointer to the last character
360 * Pad the ascii representation with '0', using size.
361 */
362char *utoa_pad(unsigned int n, char *dst, size_t size)
363{
364 int i = 0;
365 char *ret;
366
367 switch(n) {
368 case 0U ... 9U:
369 i = 0;
370 break;
371
372 case 10U ... 99U:
373 i = 1;
374 break;
375
376 case 100U ... 999U:
377 i = 2;
378 break;
379
380 case 1000U ... 9999U:
381 i = 3;
382 break;
383
384 case 10000U ... 99999U:
385 i = 4;
386 break;
387
388 case 100000U ... 999999U:
389 i = 5;
390 break;
391
392 case 1000000U ... 9999999U:
393 i = 6;
394 break;
395
396 case 10000000U ... 99999999U:
397 i = 7;
398 break;
399
400 case 100000000U ... 999999999U:
401 i = 8;
402 break;
403
404 case 1000000000U ... 4294967295U:
405 i = 9;
406 break;
407 }
408 if (i + 2 > size) // (i + 1) + '\0'
409 return NULL; // too long
410 if (i < size)
411 i = size - 2; // padding - '\0'
412
413 ret = dst + i + 1;
414 *ret = '\0';
415 for (; i >= 0; i--) {
416 dst[i] = n % 10U + '0';
417 n /= 10U;
418 }
419 return ret;
420}
421
422/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200423 * copies at most <size-1> chars from <src> to <dst>. Last char is always
424 * set to 0, unless <size> is 0. The number of chars copied is returned
425 * (excluding the terminating zero).
426 * This code has been optimized for size and speed : on x86, it's 45 bytes
427 * long, uses only registers, and consumes only 4 cycles per char.
428 */
429int strlcpy2(char *dst, const char *src, int size)
430{
431 char *orig = dst;
432 if (size) {
433 while (--size && (*dst = *src)) {
434 src++; dst++;
435 }
436 *dst = 0;
437 }
438 return dst - orig;
439}
440
441/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200442 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200443 * the ascii representation for number 'n' in decimal.
444 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100445char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200446{
447 char *pos;
448
Willy Tarreau72d759c2007-10-25 12:14:10 +0200449 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200450 *pos-- = '\0';
451
452 do {
453 *pos-- = '0' + n % 10;
454 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200455 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200456 return pos + 1;
457}
458
Willy Tarreau91092e52007-10-25 16:58:42 +0200459/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200460 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200461 * the ascii representation for number 'n' in decimal.
462 */
463char *lltoa_r(long long int in, char *buffer, int size)
464{
465 char *pos;
466 int neg = 0;
467 unsigned long long int n;
468
469 pos = buffer + size - 1;
470 *pos-- = '\0';
471
472 if (in < 0) {
473 neg = 1;
474 n = -in;
475 }
476 else
477 n = in;
478
479 do {
480 *pos-- = '0' + n % 10;
481 n /= 10;
482 } while (n && pos >= buffer);
483 if (neg && pos > buffer)
484 *pos-- = '-';
485 return pos + 1;
486}
487
488/*
489 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200490 * the ascii representation for signed number 'n' in decimal.
491 */
492char *sltoa_r(long n, char *buffer, int size)
493{
494 char *pos;
495
496 if (n >= 0)
497 return ultoa_r(n, buffer, size);
498
499 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
500 *pos = '-';
501 return pos;
502}
503
504/*
505 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200506 * the ascii representation for number 'n' in decimal, formatted for
507 * HTML output with tags to create visual grouping by 3 digits. The
508 * output needs to support at least 171 characters.
509 */
510const char *ulltoh_r(unsigned long long n, char *buffer, int size)
511{
512 char *start;
513 int digit = 0;
514
515 start = buffer + size;
516 *--start = '\0';
517
518 do {
519 if (digit == 3 && start >= buffer + 7)
520 memcpy(start -= 7, "</span>", 7);
521
522 if (start >= buffer + 1) {
523 *--start = '0' + n % 10;
524 n /= 10;
525 }
526
527 if (digit == 3 && start >= buffer + 18)
528 memcpy(start -= 18, "<span class=\"rls\">", 18);
529
530 if (digit++ == 3)
531 digit = 1;
532 } while (n && start > buffer);
533 return start;
534}
535
536/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200537 * This function simply returns a locally allocated string containing the ascii
538 * representation for number 'n' in decimal, unless n is 0 in which case it
539 * returns the alternate string (or an empty string if the alternate string is
540 * NULL). It use is intended for limits reported in reports, where it's
541 * desirable not to display anything if there is no limit. Warning! it shares
542 * the same vector as ultoa_r().
543 */
544const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
545{
546 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
547}
548
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200549/* Trims the first "%f" float in a string to its minimum number of digits after
550 * the decimal point by trimming trailing zeroes, even dropping the decimal
551 * point if not needed. The string is in <buffer> of length <len>, and the
552 * number is expected to start at or after position <num_start> (the first
553 * point appearing there is considered). A NUL character is always placed at
554 * the end if some trimming occurs. The new buffer length is returned.
555 */
556size_t flt_trim(char *buffer, size_t num_start, size_t len)
557{
558 char *end = buffer + len;
559 char *p = buffer + num_start;
560 char *trim;
561
562 do {
563 if (p >= end)
564 return len;
565 trim = p++;
566 } while (*trim != '.');
567
568 /* For now <trim> is on the decimal point. Let's look for any other
569 * meaningful digit after it.
570 */
571 while (p < end) {
572 if (*p++ != '0')
573 trim = p;
574 }
575
576 if (trim < end)
577 *trim = 0;
578
579 return trim - buffer;
580}
581
Willy Tarreauae03d262021-05-08 07:35:00 +0200582/*
583 * This function simply returns a locally allocated string containing
584 * the ascii representation for number 'n' in decimal with useless trailing
585 * zeroes trimmed.
586 */
587char *ftoa_r(double n, char *buffer, int size)
588{
589 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
590 return buffer;
591}
592
Willy Tarreau588297f2014-06-16 15:16:40 +0200593/* returns a locally allocated string containing the quoted encoding of the
594 * input string. The output may be truncated to QSTR_SIZE chars, but it is
595 * guaranteed that the string will always be properly terminated. Quotes are
596 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
597 * always be at least 4 chars.
598 */
599const char *qstr(const char *str)
600{
601 char *ret = quoted_str[quoted_idx];
602 char *p, *end;
603
604 if (++quoted_idx >= NB_QSTR)
605 quoted_idx = 0;
606
607 p = ret;
608 end = ret + QSTR_SIZE;
609
610 *p++ = '"';
611
612 /* always keep 3 chars to support passing "" and the ending " */
613 while (*str && p < end - 3) {
614 if (*str == '"') {
615 *p++ = '"';
616 *p++ = '"';
617 }
618 else
619 *p++ = *str;
620 str++;
621 }
622 *p++ = '"';
623 return ret;
624}
625
Robert Tsai81ae1952007-12-05 10:47:29 +0100626/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200627 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
628 *
629 * It looks like this one would be a good candidate for inlining, but this is
630 * not interesting because it around 35 bytes long and often called multiple
631 * times within the same function.
632 */
633int ishex(char s)
634{
635 s -= '0';
636 if ((unsigned char)s <= 9)
637 return 1;
638 s -= 'A' - '0';
639 if ((unsigned char)s <= 5)
640 return 1;
641 s -= 'a' - 'A';
642 if ((unsigned char)s <= 5)
643 return 1;
644 return 0;
645}
646
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100647/* rounds <i> down to the closest value having max 2 digits */
648unsigned int round_2dig(unsigned int i)
649{
650 unsigned int mul = 1;
651
652 while (i >= 100) {
653 i /= 10;
654 mul *= 10;
655 }
656 return i * mul;
657}
658
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100659/*
660 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
661 * invalid character is found, a pointer to it is returned. If everything is
662 * fine, NULL is returned.
663 */
664const char *invalid_char(const char *name)
665{
666 if (!*name)
667 return name;
668
669 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100670 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100671 *name != '_' && *name != '-')
672 return name;
673 name++;
674 }
675 return NULL;
676}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200677
678/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200679 * Checks <name> for invalid characters. Valid chars are [_.-] and those
680 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200681 * If an invalid character is found, a pointer to it is returned.
682 * If everything is fine, NULL is returned.
683 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200684static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200685
686 if (!*name)
687 return name;
688
689 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100690 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200691 *name != '_' && *name != '-')
692 return name;
693
694 name++;
695 }
696
697 return NULL;
698}
699
700/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200701 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
702 * If an invalid character is found, a pointer to it is returned.
703 * If everything is fine, NULL is returned.
704 */
705const char *invalid_domainchar(const char *name) {
706 return __invalid_char(name, isalnum);
707}
708
709/*
710 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
711 * If an invalid character is found, a pointer to it is returned.
712 * If everything is fine, NULL is returned.
713 */
714const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200715 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200716}
717
718/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100719 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100720 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
721 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
722 * the function tries to guess the address family from the syntax. If the
723 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100724 * string is assumed to contain only an address, no port. The address can be a
725 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
726 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
727 * The return address will only have the address family and the address set,
728 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100729 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
730 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100731 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200732 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100733struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200734{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100735 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100736 /* max IPv6 length, including brackets and terminating NULL */
737 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100738 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100739
740 /* check IPv6 with square brackets */
741 if (str[0] == '[') {
742 size_t iplength = strlen(str);
743
744 if (iplength < 4) {
745 /* minimal size is 4 when using brackets "[::]" */
746 goto fail;
747 }
748 else if (iplength >= sizeof(tmpip)) {
749 /* IPv6 literal can not be larger than tmpip */
750 goto fail;
751 }
752 else {
753 if (str[iplength - 1] != ']') {
754 /* if address started with bracket, it should end with bracket */
755 goto fail;
756 }
757 else {
758 memcpy(tmpip, str + 1, iplength - 2);
759 tmpip[iplength - 2] = '\0';
760 str = tmpip;
761 }
762 }
763 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100764
Willy Tarreaufab5a432011-03-04 15:31:53 +0100765 /* Any IPv6 address */
766 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100767 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
768 sa->ss_family = AF_INET6;
769 else if (sa->ss_family != AF_INET6)
770 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100771 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100772 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100773 }
774
Willy Tarreau24709282013-03-10 21:32:12 +0100775 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100776 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100777 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
778 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100779 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100780 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100781 }
782
783 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100784 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
785 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100786 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100787 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100788 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100789 }
790
791 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100792 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
793 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100794 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100795 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100796 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100797 }
798
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100799 if (!resolve)
800 return NULL;
801
Emeric Brund30e9a12020-12-23 18:49:16 +0100802 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200803 return NULL;
804
David du Colombierd5f43282011-03-17 10:40:16 +0100805#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200806 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100807 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100808 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100809
810 memset(&result, 0, sizeof(result));
811 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100812 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100813 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200814 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100815 hints.ai_protocol = 0;
816
817 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100818 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
819 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100820 else if (sa->ss_family != result->ai_family) {
821 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100822 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100823 }
Willy Tarreau24709282013-03-10 21:32:12 +0100824
David du Colombierd5f43282011-03-17 10:40:16 +0100825 switch (result->ai_family) {
826 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100827 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100828 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100829 success = 1;
830 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100831 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100832 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100833 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100834 success = 1;
835 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100836 }
837 }
838
Sean Carey58ea0392013-02-15 23:39:18 +0100839 if (result)
840 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100841
842 if (success)
843 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100844 }
David du Colombierd5f43282011-03-17 10:40:16 +0100845#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200846 /* try to resolve an IPv4/IPv6 hostname */
847 he = gethostbyname(str);
848 if (he) {
849 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
850 sa->ss_family = he->h_addrtype;
851 else if (sa->ss_family != he->h_addrtype)
852 goto fail;
853
854 switch (sa->ss_family) {
855 case AF_INET:
856 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100857 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200858 return sa;
859 case AF_INET6:
860 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100861 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200862 return sa;
863 }
864 }
865
David du Colombierd5f43282011-03-17 10:40:16 +0100866 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100867 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100868 return NULL;
869}
870
871/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100872 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
873 * range or offset consisting in two integers that the caller will have to
874 * check to find the relevant input format. The following format are supported :
875 *
876 * String format | address | port | low | high
877 * addr | <addr> | 0 | 0 | 0
878 * addr: | <addr> | 0 | 0 | 0
879 * addr:port | <addr> | <port> | <port> | <port>
880 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
881 * addr:+port | <addr> | <port> | 0 | <port>
882 * addr:-port | <addr> |-<port> | <port> | 0
883 *
884 * The detection of a port range or increment by the caller is made by
885 * comparing <low> and <high>. If both are equal, then port 0 means no port
886 * was specified. The caller may pass NULL for <low> and <high> if it is not
887 * interested in retrieving port ranges.
888 *
889 * Note that <addr> above may also be :
890 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
891 * - "*" => family will be AF_INET and address will be INADDR_ANY
892 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
893 * - a host name => family and address will depend on host name resolving.
894 *
Willy Tarreau24709282013-03-10 21:32:12 +0100895 * A prefix may be passed in before the address above to force the family :
896 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
897 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
898 * - "unix@" => force address to be a path to a UNIX socket even if the
899 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200900 * - 'abns@' -> force address to belong to the abstract namespace (Linux
901 * only). These sockets are just like Unix sockets but without
902 * the need for an underlying file system. The address is a
903 * string. Technically it's like a Unix socket with a zero in
904 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100905 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100906 *
mildisff5d5102015-10-26 18:50:08 +0100907 * IPv6 addresses can be declared with or without square brackets. When using
908 * square brackets for IPv6 addresses, the port separator (colon) is optional.
909 * If not using square brackets, and in order to avoid any ambiguity with
910 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
911 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
912 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100913 *
914 * If <pfx> is non-null, it is used as a string prefix before any path-based
915 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100916 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200917 * if <fqdn> is non-null, it will be filled with :
918 * - a pointer to the FQDN of the server name to resolve if there's one, and
919 * that the caller will have to free(),
920 * - NULL if there was an explicit address that doesn't require resolution.
921 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200922 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
923 * still honored so it is possible for the caller to know whether a resolution
924 * failed by clearing this flag and checking if <fqdn> was filled, indicating
925 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200926 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100927 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200928 * the address when cast to sockaddr_in and the address family is
929 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200930 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200931 * The matching protocol will be set into <proto> if non-null.
932 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200933 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
934 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100935 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200936struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
937 struct protocol **proto, char **err,
938 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100939{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100940 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100941 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200942 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100943 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100944 char *port1, *port2;
945 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200946 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200947 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200948 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100949
950 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200951 if (fqdn)
952 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200953
Willy Tarreaudad36a32013-03-11 01:20:04 +0100954 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100955 if (str2 == NULL) {
956 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100957 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100958 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200959
Willy Tarreau9f69f462015-09-08 16:01:25 +0200960 if (!*str2) {
961 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
962 goto out;
963 }
964
Willy Tarreau24709282013-03-10 21:32:12 +0100965 memset(&ss, 0, sizeof(ss));
966
Willy Tarreaue835bd82020-09-16 11:35:47 +0200967 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100968 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
969 ((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 +0200970 sock_type = ctrl_type = SOCK_DGRAM;
971 else
972 sock_type = ctrl_type = SOCK_STREAM;
973
974 if (strncmp(str2, "stream+", 7) == 0) {
975 str2 += 7;
976 sock_type = ctrl_type = SOCK_STREAM;
977 }
978 else if (strncmp(str2, "dgram+", 6) == 0) {
979 str2 += 6;
980 sock_type = ctrl_type = SOCK_DGRAM;
981 }
982
Willy Tarreau24709282013-03-10 21:32:12 +0100983 if (strncmp(str2, "unix@", 5) == 0) {
984 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200985 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100986 ss.ss_family = AF_UNIX;
987 }
Emeric Brunce325c42021-04-02 17:05:09 +0200988 else if (strncmp(str2, "uxdg@", 5) == 0) {
989 str2 += 5;
990 abstract = 0;
991 ss.ss_family = AF_UNIX;
992 sock_type = ctrl_type = SOCK_DGRAM;
993 }
994 else if (strncmp(str2, "uxst@", 5) == 0) {
995 str2 += 5;
996 abstract = 0;
997 ss.ss_family = AF_UNIX;
998 sock_type = ctrl_type = SOCK_STREAM;
999 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001000 else if (strncmp(str2, "abns@", 5) == 0) {
1001 str2 += 5;
1002 abstract = 1;
1003 ss.ss_family = AF_UNIX;
1004 }
Emeric Brunce325c42021-04-02 17:05:09 +02001005 else if (strncmp(str2, "ip@", 3) == 0) {
1006 str2 += 3;
1007 ss.ss_family = AF_UNSPEC;
1008 }
Willy Tarreau24709282013-03-10 21:32:12 +01001009 else if (strncmp(str2, "ipv4@", 5) == 0) {
1010 str2 += 5;
1011 ss.ss_family = AF_INET;
1012 }
1013 else if (strncmp(str2, "ipv6@", 5) == 0) {
1014 str2 += 5;
1015 ss.ss_family = AF_INET6;
1016 }
Emeric Brunce325c42021-04-02 17:05:09 +02001017 else if (strncmp(str2, "tcp4@", 5) == 0) {
1018 str2 += 5;
1019 ss.ss_family = AF_INET;
1020 sock_type = ctrl_type = SOCK_STREAM;
1021 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001022 else if (strncmp(str2, "udp4@", 5) == 0) {
1023 str2 += 5;
1024 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001025 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001026 }
Emeric Brunce325c42021-04-02 17:05:09 +02001027 else if (strncmp(str2, "tcp6@", 5) == 0) {
1028 str2 += 5;
1029 ss.ss_family = AF_INET6;
1030 sock_type = ctrl_type = SOCK_STREAM;
1031 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001032 else if (strncmp(str2, "udp6@", 5) == 0) {
1033 str2 += 5;
1034 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001035 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001036 }
Emeric Brunce325c42021-04-02 17:05:09 +02001037 else if (strncmp(str2, "tcp@", 4) == 0) {
1038 str2 += 4;
1039 ss.ss_family = AF_UNSPEC;
1040 sock_type = ctrl_type = SOCK_STREAM;
1041 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001042 else if (strncmp(str2, "udp@", 4) == 0) {
1043 str2 += 4;
1044 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001045 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001046 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001047 else if (strncmp(str2, "quic4@", 6) == 0) {
1048 str2 += 6;
1049 ss.ss_family = AF_INET;
1050 sock_type = SOCK_DGRAM;
1051 ctrl_type = SOCK_STREAM;
1052 }
1053 else if (strncmp(str2, "quic6@", 6) == 0) {
1054 str2 += 6;
1055 ss.ss_family = AF_INET6;
1056 sock_type = SOCK_DGRAM;
1057 ctrl_type = SOCK_STREAM;
1058 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001059 else if (strncmp(str2, "fd@", 3) == 0) {
1060 str2 += 3;
1061 ss.ss_family = AF_CUST_EXISTING_FD;
1062 }
1063 else if (strncmp(str2, "sockpair@", 9) == 0) {
1064 str2 += 9;
1065 ss.ss_family = AF_CUST_SOCKPAIR;
1066 }
Willy Tarreau24709282013-03-10 21:32:12 +01001067 else if (*str2 == '/') {
1068 ss.ss_family = AF_UNIX;
1069 }
1070 else
1071 ss.ss_family = AF_UNSPEC;
1072
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001073 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001074 struct sockaddr_storage ss2;
1075 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001076 char *endptr;
1077
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001078 new_fd = strtol(str2, &endptr, 10);
1079 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001080 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1081 goto out;
1082 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001083
Willy Tarreaua215be22020-09-16 10:14:16 +02001084 /* just verify that it's a socket */
1085 addr_len = sizeof(ss2);
1086 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1087 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1088 goto out;
1089 }
1090
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001091 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1092 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001093 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001094 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001095 char *endptr;
1096
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001097 new_fd = strtol(str2, &endptr, 10);
1098 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001099 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001100 goto out;
1101 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001102
Willy Tarreau6edc7222020-09-15 17:41:56 +02001103 if (opts & PA_O_SOCKET_FD) {
1104 socklen_t addr_len;
1105 int type;
1106
1107 addr_len = sizeof(ss);
1108 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1109 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1110 goto out;
1111 }
1112
1113 addr_len = sizeof(type);
1114 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001115 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001116 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1117 goto out;
1118 }
1119
1120 porta = portl = porth = get_host_port(&ss);
1121 } else if (opts & PA_O_RAW_FD) {
1122 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1123 ((struct sockaddr_in *)&ss)->sin_port = 0;
1124 } else {
1125 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1126 goto out;
1127 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001128 }
1129 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001130 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001131 int prefix_path_len;
1132 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001133 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001134
1135 /* complete unix socket path name during startup or soft-restart is
1136 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1137 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001138 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001139 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001140 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001141
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001142 adr_len = strlen(str2);
1143 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001144 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1145 goto out;
1146 }
1147
Willy Tarreauccfccef2014-05-10 01:49:15 +02001148 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001149 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001150 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001151 memcpy(un->sun_path, pfx, prefix_path_len);
1152 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001153 }
Willy Tarreau24709282013-03-10 21:32:12 +01001154 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001155 char *end = str2 + strlen(str2);
1156 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001157
mildisff5d5102015-10-26 18:50:08 +01001158 /* search for : or ] whatever comes first */
1159 for (chr = end-1; chr > str2; chr--) {
1160 if (*chr == ']' || *chr == ':')
1161 break;
1162 }
1163
1164 if (*chr == ':') {
1165 /* Found a colon before a closing-bracket, must be a port separator.
1166 * This guarantee backward compatibility.
1167 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001168 if (!(opts & PA_O_PORT_OK)) {
1169 memprintf(err, "port specification not permitted here in '%s'", str);
1170 goto out;
1171 }
mildisff5d5102015-10-26 18:50:08 +01001172 *chr++ = '\0';
1173 port1 = chr;
1174 }
1175 else {
1176 /* Either no colon and no closing-bracket
1177 * or directly ending with a closing-bracket.
1178 * However, no port.
1179 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001180 if (opts & PA_O_PORT_MAND) {
1181 memprintf(err, "missing port specification in '%s'", str);
1182 goto out;
1183 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001184 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001185 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001186
Willy Tarreau90807112020-02-25 08:16:33 +01001187 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001188 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001189 if (port2) {
1190 if (!(opts & PA_O_PORT_RANGE)) {
1191 memprintf(err, "port range not permitted here in '%s'", str);
1192 goto out;
1193 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001194 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001195 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001196 else
1197 port2 = port1;
1198 portl = atoi(port1);
1199 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001200
1201 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1202 memprintf(err, "invalid port '%s'", port1);
1203 goto out;
1204 }
1205
1206 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1207 memprintf(err, "invalid port '%s'", port2);
1208 goto out;
1209 }
1210
1211 if (portl > porth) {
1212 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1213 goto out;
1214 }
1215
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001216 porta = portl;
1217 }
1218 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001219 if (!(opts & PA_O_PORT_OFS)) {
1220 memprintf(err, "port offset not permitted here in '%s'", str);
1221 goto out;
1222 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001223 portl = atoi(port1 + 1);
1224 porta = -portl;
1225 }
1226 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001227 if (!(opts & PA_O_PORT_OFS)) {
1228 memprintf(err, "port offset not permitted here in '%s'", str);
1229 goto out;
1230 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001231 porth = atoi(port1 + 1);
1232 porta = porth;
1233 }
1234 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001235 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001236 goto out;
1237 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001238 else if (opts & PA_O_PORT_MAND) {
1239 memprintf(err, "missing port specification in '%s'", str);
1240 goto out;
1241 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001242
1243 /* first try to parse the IP without resolving. If it fails, it
1244 * tells us we need to keep a copy of the FQDN to resolve later
1245 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001246 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001247 */
1248 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001249 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1250 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001251 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1252 goto out;
1253 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001254
Willy Tarreauceccdd72016-11-02 22:27:10 +01001255 if (fqdn) {
1256 if (str2 != back)
1257 memmove(back, str2, strlen(str2) + 1);
1258 *fqdn = back;
1259 back = NULL;
1260 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001261 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001262 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001263 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001264
Willy Tarreaue835bd82020-09-16 11:35:47 +02001265 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1266 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1267 goto out;
1268 }
1269 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1270 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1271 goto out;
1272 }
1273
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001274 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001275 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001276 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1277 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001278 * in which case the address is not known yet (this is only
1279 * for servers actually).
1280 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001281 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001282 sock_type == SOCK_DGRAM,
1283 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001284
Emeric Brun26754902021-04-07 14:26:44 +02001285 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001286 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1287 goto out;
1288 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001289
1290 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1291 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1292 goto out;
1293 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001294 }
1295
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001296 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001297 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001298 if (port)
1299 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001300 if (low)
1301 *low = portl;
1302 if (high)
1303 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001304 if (fd)
1305 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001306 if (proto)
1307 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001308 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001309 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001310}
1311
Thayne McCombs92149f92020-11-20 01:28:26 -07001312/* converts <addr> and <port> into a string representation of the address and port. This is sort
1313 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1314 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1315 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1316 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1317 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1318 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1319 *
1320 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1321 */
1322char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1323{
1324 char buffer[INET6_ADDRSTRLEN];
1325 char *out = NULL;
1326 const void *ptr;
1327 const char *path;
1328
1329 switch (addr->ss_family) {
1330 case AF_INET:
1331 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1332 break;
1333 case AF_INET6:
1334 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1335 break;
1336 case AF_UNIX:
1337 path = ((struct sockaddr_un *)addr)->sun_path;
1338 if (path[0] == '\0') {
1339 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1340 return memprintf(&out, "abns@%.*s", max_length, path+1);
1341 } else {
1342 return strdup(path);
1343 }
1344 case AF_CUST_SOCKPAIR:
1345 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1346 default:
1347 return NULL;
1348 }
1349 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1350 if (map_ports)
1351 return memprintf(&out, "%s:%+d", buffer, port);
1352 else
1353 return memprintf(&out, "%s:%d", buffer, port);
1354}
1355
1356
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001357/* converts <str> to a struct in_addr containing a network mask. It can be
1358 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001359 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001360 */
1361int str2mask(const char *str, struct in_addr *mask)
1362{
1363 if (strchr(str, '.') != NULL) { /* dotted notation */
1364 if (!inet_pton(AF_INET, str, mask))
1365 return 0;
1366 }
1367 else { /* mask length */
1368 char *err;
1369 unsigned long len = strtol(str, &err, 10);
1370
1371 if (!*str || (err && *err) || (unsigned)len > 32)
1372 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001373
1374 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001375 }
1376 return 1;
1377}
1378
Tim Duesterhus47185172018-01-25 16:24:49 +01001379/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001380 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001381 * if the conversion succeeds otherwise zero.
1382 */
1383int str2mask6(const char *str, struct in6_addr *mask)
1384{
1385 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1386 if (!inet_pton(AF_INET6, str, mask))
1387 return 0;
1388 }
1389 else { /* mask length */
1390 char *err;
1391 unsigned long len = strtol(str, &err, 10);
1392
1393 if (!*str || (err && *err) || (unsigned)len > 128)
1394 return 0;
1395
1396 len2mask6(len, mask);
1397 }
1398 return 1;
1399}
1400
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001401/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1402 * succeeds otherwise zero.
1403 */
1404int cidr2dotted(int cidr, struct in_addr *mask) {
1405
1406 if (cidr < 0 || cidr > 32)
1407 return 0;
1408
1409 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1410 return 1;
1411}
1412
Thierry Fournier70473a52016-02-17 17:12:14 +01001413/* Convert mask from bit length form to in_addr form.
1414 * This function never fails.
1415 */
1416void len2mask4(int len, struct in_addr *addr)
1417{
1418 if (len >= 32) {
1419 addr->s_addr = 0xffffffff;
1420 return;
1421 }
1422 if (len <= 0) {
1423 addr->s_addr = 0x00000000;
1424 return;
1425 }
1426 addr->s_addr = 0xffffffff << (32 - len);
1427 addr->s_addr = htonl(addr->s_addr);
1428}
1429
1430/* Convert mask from bit length form to in6_addr form.
1431 * This function never fails.
1432 */
1433void len2mask6(int len, struct in6_addr *addr)
1434{
1435 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1436 len -= 32;
1437 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1438 len -= 32;
1439 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1440 len -= 32;
1441 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1442}
1443
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001444/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001445 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001446 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001447 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001448 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1449 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001450int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001451{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001452 __label__ out_free, out_err;
1453 char *c, *s;
1454 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001455
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001456 s = strdup(str);
1457 if (!s)
1458 return 0;
1459
Willy Tarreaubaaee002006-06-26 02:48:02 +02001460 memset(mask, 0, sizeof(*mask));
1461 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001462
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001463 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001464 *c++ = '\0';
1465 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001466 if (!str2mask(c, mask))
1467 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001468 }
1469 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001470 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001471 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001472 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001473 struct hostent *he;
1474
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001475 if (!resolve)
1476 goto out_err;
1477
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001478 if ((he = gethostbyname(s)) == NULL) {
1479 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001480 }
1481 else
1482 *addr = *(struct in_addr *) *(he->h_addr_list);
1483 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001484
1485 ret_val = 1;
1486 out_free:
1487 free(s);
1488 return ret_val;
1489 out_err:
1490 ret_val = 0;
1491 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001492}
1493
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001494
1495/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001496 * converts <str> to two struct in6_addr* which must be pre-allocated.
1497 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001498 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001499 * Returns 1 if OK, 0 if error.
1500 */
1501int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1502{
1503 char *c, *s;
1504 int ret_val = 0;
1505 char *err;
1506 unsigned long len = 128;
1507
1508 s = strdup(str);
1509 if (!s)
1510 return 0;
1511
1512 memset(mask, 0, sizeof(*mask));
1513 memset(addr, 0, sizeof(*addr));
1514
1515 if ((c = strrchr(s, '/')) != NULL) {
1516 *c++ = '\0'; /* c points to the mask */
1517 if (!*c)
1518 goto out_free;
1519
1520 len = strtoul(c, &err, 10);
1521 if ((err && *err) || (unsigned)len > 128)
1522 goto out_free;
1523 }
1524 *mask = len; /* OK we have a valid mask in <len> */
1525
1526 if (!inet_pton(AF_INET6, s, addr))
1527 goto out_free;
1528
1529 ret_val = 1;
1530 out_free:
1531 free(s);
1532 return ret_val;
1533}
1534
1535
1536/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001537 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1538 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1539 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001540 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001541int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001542{
1543 int saw_digit, octets, ch;
1544 u_char tmp[4], *tp;
1545 const char *cp = addr;
1546
1547 saw_digit = 0;
1548 octets = 0;
1549 *(tp = tmp) = 0;
1550
1551 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001552 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001553 if (digit > 9 && ch != '.')
1554 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001555 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001556 if (digit <= 9) {
1557 u_int new = *tp * 10 + digit;
1558 if (new > 255)
1559 return 0;
1560 *tp = new;
1561 if (!saw_digit) {
1562 if (++octets > 4)
1563 return 0;
1564 saw_digit = 1;
1565 }
1566 } else if (ch == '.' && saw_digit) {
1567 if (octets == 4)
1568 return 0;
1569 *++tp = 0;
1570 saw_digit = 0;
1571 } else
1572 return 0;
1573 }
1574
1575 if (octets < 4)
1576 return 0;
1577
1578 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001579 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001580}
1581
1582/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001583 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001584 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001585 * the hostname. Actually only http and https are supported. <out> can be NULL.
1586 * This function returns the consumed length. It is useful if you parse complete
1587 * url like http://host:port/path, because the consumed length corresponds to
1588 * the first character of the path. If the conversion fails, it returns -1.
1589 *
1590 * This function tries to resolve the DNS name if haproxy is in starting mode.
1591 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001592 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001593int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001594{
1595 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001596 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001597 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001598 unsigned long long int http_code = 0;
1599 int default_port;
1600 struct hostent *he;
1601 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001602
1603 /* Firstly, try to find :// pattern */
1604 while (curr < url+ulen && url_code != 0x3a2f2f) {
1605 url_code = ((url_code & 0xffff) << 8);
1606 url_code += (unsigned char)*curr++;
1607 }
1608
1609 /* Secondly, if :// pattern is found, verify parsed stuff
1610 * before pattern is matching our http pattern.
1611 * If so parse ip address and port in uri.
1612 *
1613 * WARNING: Current code doesn't support dynamic async dns resolver.
1614 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001615 if (url_code != 0x3a2f2f)
1616 return -1;
1617
1618 /* Copy scheme, and utrn to lower case. */
1619 while (cp < curr - 3)
1620 http_code = (http_code << 8) + *cp++;
1621 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001622
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001623 /* HTTP or HTTPS url matching */
1624 if (http_code == 0x2020202068747470ULL) {
1625 default_port = 80;
1626 if (out)
1627 out->scheme = SCH_HTTP;
1628 }
1629 else if (http_code == 0x2020206874747073ULL) {
1630 default_port = 443;
1631 if (out)
1632 out->scheme = SCH_HTTPS;
1633 }
1634 else
1635 return -1;
1636
1637 /* If the next char is '[', the host address is IPv6. */
1638 if (*curr == '[') {
1639 curr++;
1640
1641 /* Check trash size */
1642 if (trash.size < ulen)
1643 return -1;
1644
1645 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001646 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001647 for (end = curr;
1648 end < url + ulen && *end != ']';
1649 end++, p++)
1650 *p = *end;
1651 if (*end != ']')
1652 return -1;
1653 *p = '\0';
1654
1655 /* Update out. */
1656 if (out) {
1657 out->host = curr;
1658 out->host_len = end - curr;
1659 }
1660
1661 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001662 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001663 return -1;
1664 end++;
1665
1666 /* Decode port. */
1667 if (*end == ':') {
1668 end++;
1669 default_port = read_uint(&end, url + ulen);
1670 }
1671 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1672 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1673 return end - url;
1674 }
1675 else {
William Lallemand12e3b252022-02-18 16:13:12 +01001676 /* we need to copy the string into the trash because url2ipv4
1677 * needs a \0 at the end of the string */
1678 if (trash.size < ulen)
1679 return -1;
1680
1681 memcpy(trash.area, curr, ulen - (curr - url));
1682 trash.area[ulen - (curr - url)] = '\0';
1683
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001684 /* We are looking for IP address. If you want to parse and
1685 * resolve hostname found in url, you can use str2sa_range(), but
1686 * be warned this can slow down global daemon performances
1687 * while handling lagging dns responses.
1688 */
William Lallemand12e3b252022-02-18 16:13:12 +01001689 ret = url2ipv4(trash.area, &((struct sockaddr_in *)addr)->sin_addr);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001690 if (ret) {
1691 /* Update out. */
1692 if (out) {
1693 out->host = curr;
1694 out->host_len = ret;
1695 }
1696
William Lallemand12e3b252022-02-18 16:13:12 +01001697 /* we need to assign again curr and end from the trash */
1698 url = trash.area;
1699 curr = trash.area + ret;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001700
1701 /* Decode port. */
1702 if (*curr == ':') {
1703 curr++;
1704 default_port = read_uint(&curr, url + ulen);
1705 }
1706 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1707
1708 /* Set family. */
1709 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1710 return curr - url;
1711 }
1712 else if (global.mode & MODE_STARTING) {
1713 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1714 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001715 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001716
1717 /* look for : or / or end */
1718 for (end = curr;
1719 end < url + ulen && *end != '/' && *end != ':';
1720 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001721 memcpy(trash.area, curr, end - curr);
1722 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001723
1724 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001725 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001726 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001727 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001728
1729 /* Update out. */
1730 if (out) {
1731 out->host = curr;
1732 out->host_len = end - curr;
1733 }
1734
1735 /* Decode port. */
1736 if (*end == ':') {
1737 end++;
1738 default_port = read_uint(&end, url + ulen);
1739 }
1740
1741 /* Copy IP address, set port and family. */
1742 switch (he->h_addrtype) {
1743 case AF_INET:
1744 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1745 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1746 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1747 return end - url;
1748
1749 case AF_INET6:
1750 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1751 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1752 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1753 return end - url;
1754 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001755 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001756 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001757 return -1;
1758}
1759
Willy Tarreau631f01c2011-09-05 00:36:48 +02001760/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1761 * address family is returned so that it's easy for the caller to adapt to the
1762 * output format. Zero is returned if the address family is not supported. -1
1763 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1764 * supported.
1765 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001766int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001767{
1768
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001769 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001770
1771 if (size < 5)
1772 return 0;
1773 *str = '\0';
1774
1775 switch (addr->ss_family) {
1776 case AF_INET:
1777 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1778 break;
1779 case AF_INET6:
1780 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1781 break;
1782 case AF_UNIX:
1783 memcpy(str, "unix", 5);
1784 return addr->ss_family;
1785 default:
1786 return 0;
1787 }
1788
1789 if (inet_ntop(addr->ss_family, ptr, str, size))
1790 return addr->ss_family;
1791
1792 /* failed */
1793 return -1;
1794}
1795
Simon Horman75ab8bd2014-06-16 09:39:41 +09001796/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1797 * address family is returned so that it's easy for the caller to adapt to the
1798 * output format. Zero is returned if the address family is not supported. -1
1799 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1800 * supported.
1801 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001802int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001803{
1804
1805 uint16_t port;
1806
1807
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001808 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001809 return 0;
1810 *str = '\0';
1811
1812 switch (addr->ss_family) {
1813 case AF_INET:
1814 port = ((struct sockaddr_in *)addr)->sin_port;
1815 break;
1816 case AF_INET6:
1817 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1818 break;
1819 case AF_UNIX:
1820 memcpy(str, "unix", 5);
1821 return addr->ss_family;
1822 default:
1823 return 0;
1824 }
1825
1826 snprintf(str, size, "%u", ntohs(port));
1827 return addr->ss_family;
1828}
1829
Willy Tarreau16e01562016-08-09 16:46:18 +02001830/* check if the given address is local to the system or not. It will return
1831 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1832 * it is. We don't want to iterate over all interfaces for this (and it is not
1833 * portable). So instead we try to bind in UDP to this address on a free non
1834 * privileged port and to connect to the same address, port 0 (connect doesn't
1835 * care). If it succeeds, we own the address. Note that non-inet addresses are
1836 * considered local since they're most likely AF_UNIX.
1837 */
1838int addr_is_local(const struct netns_entry *ns,
1839 const struct sockaddr_storage *orig)
1840{
1841 struct sockaddr_storage addr;
1842 int result;
1843 int fd;
1844
1845 if (!is_inet_addr(orig))
1846 return 1;
1847
1848 memcpy(&addr, orig, sizeof(addr));
1849 set_host_port(&addr, 0);
1850
1851 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1852 if (fd < 0)
1853 return -1;
1854
1855 result = -1;
1856 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1857 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1858 result = 0; // fail, non-local address
1859 else
1860 result = 1; // success, local address
1861 }
1862 else {
1863 if (errno == EADDRNOTAVAIL)
1864 result = 0; // definitely not local :-)
1865 }
1866 close(fd);
1867
1868 return result;
1869}
1870
Willy Tarreaubaaee002006-06-26 02:48:02 +02001871/* will try to encode the string <string> replacing all characters tagged in
1872 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1873 * prefixed by <escape>, and will store the result between <start> (included)
1874 * and <stop> (excluded), and will always terminate the string with a '\0'
1875 * before <stop>. The position of the '\0' is returned if the conversion
1876 * completes. If bytes are missing between <start> and <stop>, then the
1877 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1878 * cannot even be stored so we return <start> without writing the 0.
1879 * The input string must also be zero-terminated.
1880 */
1881const char hextab[16] = "0123456789ABCDEF";
1882char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001883 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001884 const char *string)
1885{
1886 if (start < stop) {
1887 stop--; /* reserve one byte for the final '\0' */
1888 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001889 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001890 *start++ = *string;
1891 else {
1892 if (start + 3 >= stop)
1893 break;
1894 *start++ = escape;
1895 *start++ = hextab[(*string >> 4) & 15];
1896 *start++ = hextab[*string & 15];
1897 }
1898 string++;
1899 }
1900 *start = '\0';
1901 }
1902 return start;
1903}
1904
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001905/*
1906 * Same behavior as encode_string() above, except that it encodes chunk
1907 * <chunk> instead of a string.
1908 */
1909char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001910 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001911 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001912{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001913 char *str = chunk->area;
1914 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001915
1916 if (start < stop) {
1917 stop--; /* reserve one byte for the final '\0' */
1918 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001919 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001920 *start++ = *str;
1921 else {
1922 if (start + 3 >= stop)
1923 break;
1924 *start++ = escape;
1925 *start++ = hextab[(*str >> 4) & 15];
1926 *start++ = hextab[*str & 15];
1927 }
1928 str++;
1929 }
1930 *start = '\0';
1931 }
1932 return start;
1933}
1934
Dragan Dosen0edd1092016-02-12 13:23:02 +01001935/*
1936 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001937 * character. The input <string> must be zero-terminated. The result will
1938 * be stored between <start> (included) and <stop> (excluded). This
1939 * function will always try to terminate the resulting string with a '\0'
1940 * before <stop>, and will return its position if the conversion
1941 * completes.
1942 */
1943char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001944 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001945 const char *string)
1946{
1947 if (start < stop) {
1948 stop--; /* reserve one byte for the final '\0' */
1949 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001950 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001951 *start++ = *string;
1952 else {
1953 if (start + 2 >= stop)
1954 break;
1955 *start++ = escape;
1956 *start++ = *string;
1957 }
1958 string++;
1959 }
1960 *start = '\0';
1961 }
1962 return start;
1963}
1964
1965/*
1966 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001967 * character. <chunk> contains the input to be escaped. The result will be
1968 * stored between <start> (included) and <stop> (excluded). The function
1969 * will always try to terminate the resulting string with a '\0' before
1970 * <stop>, and will return its position if the conversion completes.
1971 */
1972char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001973 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001974 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001975{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001976 char *str = chunk->area;
1977 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001978
1979 if (start < stop) {
1980 stop--; /* reserve one byte for the final '\0' */
1981 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001982 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001983 *start++ = *str;
1984 else {
1985 if (start + 2 >= stop)
1986 break;
1987 *start++ = escape;
1988 *start++ = *str;
1989 }
1990 str++;
1991 }
1992 *start = '\0';
1993 }
1994 return start;
1995}
1996
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001997/* Check a string for using it in a CSV output format. If the string contains
1998 * one of the following four char <">, <,>, CR or LF, the string is
1999 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2000 * <str> is the input string to be escaped. The function assumes that
2001 * the input string is null-terminated.
2002 *
2003 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002004 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002005 * format.
2006 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002007 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002008 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002009 * If <quote> is 1, the converter puts the quotes only if any reserved character
2010 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002011 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002012 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002013 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002014 * The function returns the converted string on its output. If an error
2015 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002016 * for using the function directly as printf() argument.
2017 *
2018 * If the output buffer is too short to contain the input string, the result
2019 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002020 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002021 * This function appends the encoding to the existing output chunk, and it
2022 * guarantees that it starts immediately at the first available character of
2023 * the chunk. Please use csv_enc() instead if you want to replace the output
2024 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002025 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002026const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002027{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002028 char *end = output->area + output->size;
2029 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002030 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002031
Willy Tarreaub631c292016-01-08 10:04:08 +01002032 if (quote == 1) {
2033 /* automatic quoting: first verify if we'll have to quote the string */
2034 if (!strpbrk(str, "\n\r,\""))
2035 quote = 0;
2036 }
2037
2038 if (quote)
2039 *ptr++ = '"';
2040
Willy Tarreau898529b2016-01-06 18:07:04 +01002041 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2042 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002043 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002044 ptr++;
2045 if (ptr >= end - 2) {
2046 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002047 break;
2048 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002049 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002050 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002051 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002052 str++;
2053 }
2054
Willy Tarreaub631c292016-01-08 10:04:08 +01002055 if (quote)
2056 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002057
Willy Tarreau898529b2016-01-06 18:07:04 +01002058 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002059 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002060 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002061}
2062
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002063/* Decode an URL-encoded string in-place. The resulting string might
2064 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002065 * aborted, the string is truncated before the issue and a negative value is
2066 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002067 * If the 'in_form' argument is non-nul the string is assumed to be part of
2068 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2069 * turned to a space. If it's zero, this will only be done after a question
2070 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002071 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002072int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002073{
2074 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002075 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002076
2077 in = string;
2078 out = string;
2079 while (*in) {
2080 switch (*in) {
2081 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002082 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002083 break;
2084 case '%' :
2085 if (!ishex(in[1]) || !ishex(in[2]))
2086 goto end;
2087 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2088 in += 2;
2089 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002090 case '?':
2091 in_form = 1;
2092 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002093 default:
2094 *out++ = *in;
2095 break;
2096 }
2097 in++;
2098 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002099 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002100 end:
2101 *out = 0;
2102 return ret;
2103}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002104
Willy Tarreau6911fa42007-03-04 18:06:08 +01002105unsigned int str2ui(const char *s)
2106{
2107 return __str2ui(s);
2108}
2109
2110unsigned int str2uic(const char *s)
2111{
2112 return __str2uic(s);
2113}
2114
2115unsigned int strl2ui(const char *s, int len)
2116{
2117 return __strl2ui(s, len);
2118}
2119
2120unsigned int strl2uic(const char *s, int len)
2121{
2122 return __strl2uic(s, len);
2123}
2124
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002125unsigned int read_uint(const char **s, const char *end)
2126{
2127 return __read_uint(s, end);
2128}
2129
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002130/* This function reads an unsigned integer from the string pointed to by <s> and
2131 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2132 * function automatically stops at <end>. If the number overflows, the 2^64-1
2133 * value is returned.
2134 */
2135unsigned long long int read_uint64(const char **s, const char *end)
2136{
2137 const char *ptr = *s;
2138 unsigned long long int i = 0, tmp;
2139 unsigned int j;
2140
2141 while (ptr < end) {
2142
2143 /* read next char */
2144 j = *ptr - '0';
2145 if (j > 9)
2146 goto read_uint64_end;
2147
2148 /* add char to the number and check overflow. */
2149 tmp = i * 10;
2150 if (tmp / 10 != i) {
2151 i = ULLONG_MAX;
2152 goto read_uint64_eat;
2153 }
2154 if (ULLONG_MAX - tmp < j) {
2155 i = ULLONG_MAX;
2156 goto read_uint64_eat;
2157 }
2158 i = tmp + j;
2159 ptr++;
2160 }
2161read_uint64_eat:
2162 /* eat each numeric char */
2163 while (ptr < end) {
2164 if ((unsigned int)(*ptr - '0') > 9)
2165 break;
2166 ptr++;
2167 }
2168read_uint64_end:
2169 *s = ptr;
2170 return i;
2171}
2172
2173/* This function reads an integer from the string pointed to by <s> and returns
2174 * it. The <s> pointer is adjusted to point to the first unread char. The function
2175 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2176 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2177 * returned.
2178 */
2179long long int read_int64(const char **s, const char *end)
2180{
2181 unsigned long long int i = 0;
2182 int neg = 0;
2183
2184 /* Look for minus char. */
2185 if (**s == '-') {
2186 neg = 1;
2187 (*s)++;
2188 }
2189 else if (**s == '+')
2190 (*s)++;
2191
2192 /* convert as positive number. */
2193 i = read_uint64(s, end);
2194
2195 if (neg) {
2196 if (i > 0x8000000000000000ULL)
2197 return LLONG_MIN;
2198 return -i;
2199 }
2200 if (i > 0x7fffffffffffffffULL)
2201 return LLONG_MAX;
2202 return i;
2203}
2204
Willy Tarreau6911fa42007-03-04 18:06:08 +01002205/* This one is 7 times faster than strtol() on athlon with checks.
2206 * It returns the value of the number composed of all valid digits read,
2207 * and can process negative numbers too.
2208 */
2209int strl2ic(const char *s, int len)
2210{
2211 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002212 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002213
2214 if (len > 0) {
2215 if (*s != '-') {
2216 /* positive number */
2217 while (len-- > 0) {
2218 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002219 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002220 if (j > 9)
2221 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002222 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002223 }
2224 } else {
2225 /* negative number */
2226 s++;
2227 while (--len > 0) {
2228 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002229 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002230 if (j > 9)
2231 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002232 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002233 }
2234 }
2235 }
2236 return i;
2237}
2238
2239
2240/* This function reads exactly <len> chars from <s> and converts them to a
2241 * signed integer which it stores into <ret>. It accurately detects any error
2242 * (truncated string, invalid chars, overflows). It is meant to be used in
2243 * applications designed for hostile environments. It returns zero when the
2244 * number has successfully been converted, non-zero otherwise. When an error
2245 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2246 * faster than strtol().
2247 */
2248int strl2irc(const char *s, int len, int *ret)
2249{
2250 int i = 0;
2251 int j;
2252
2253 if (!len)
2254 return 1;
2255
2256 if (*s != '-') {
2257 /* positive number */
2258 while (len-- > 0) {
2259 j = (*s++) - '0';
2260 if (j > 9) return 1; /* invalid char */
2261 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2262 i = i * 10;
2263 if (i + j < i) return 1; /* check for addition overflow */
2264 i = i + j;
2265 }
2266 } else {
2267 /* negative number */
2268 s++;
2269 while (--len > 0) {
2270 j = (*s++) - '0';
2271 if (j > 9) return 1; /* invalid char */
2272 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2273 i = i * 10;
2274 if (i - j > i) return 1; /* check for subtract overflow */
2275 i = i - j;
2276 }
2277 }
2278 *ret = i;
2279 return 0;
2280}
2281
2282
2283/* This function reads exactly <len> chars from <s> and converts them to a
2284 * signed integer which it stores into <ret>. It accurately detects any error
2285 * (truncated string, invalid chars, overflows). It is meant to be used in
2286 * applications designed for hostile environments. It returns zero when the
2287 * number has successfully been converted, non-zero otherwise. When an error
2288 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002289 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002290 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002291
2292int strl2llrc(const char *s, int len, long long *ret)
2293{
2294 long long i = 0;
2295 int j;
2296
2297 if (!len)
2298 return 1;
2299
2300 if (*s != '-') {
2301 /* positive number */
2302 while (len-- > 0) {
2303 j = (*s++) - '0';
2304 if (j > 9) return 1; /* invalid char */
2305 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2306 i = i * 10LL;
2307 if (i + j < i) return 1; /* check for addition overflow */
2308 i = i + j;
2309 }
2310 } else {
2311 /* negative number */
2312 s++;
2313 while (--len > 0) {
2314 j = (*s++) - '0';
2315 if (j > 9) return 1; /* invalid char */
2316 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2317 i = i * 10LL;
2318 if (i - j > i) return 1; /* check for subtract overflow */
2319 i = i - j;
2320 }
2321 }
2322 *ret = i;
2323 return 0;
2324}
2325
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002326/* This function is used with pat_parse_dotted_ver(). It converts a string
2327 * composed by two number separated by a dot. Each part must contain in 16 bits
2328 * because internally they will be represented as a 32-bit quantity stored in
2329 * a 64-bit integer. It returns zero when the number has successfully been
2330 * converted, non-zero otherwise. When an error is returned, the <ret> value
2331 * is left untouched.
2332 *
2333 * "1.3" -> 0x0000000000010003
2334 * "65535.65535" -> 0x00000000ffffffff
2335 */
2336int strl2llrc_dotted(const char *text, int len, long long *ret)
2337{
2338 const char *end = &text[len];
2339 const char *p;
2340 long long major, minor;
2341
2342 /* Look for dot. */
2343 for (p = text; p < end; p++)
2344 if (*p == '.')
2345 break;
2346
2347 /* Convert major. */
2348 if (strl2llrc(text, p - text, &major) != 0)
2349 return 1;
2350
2351 /* Check major. */
2352 if (major >= 65536)
2353 return 1;
2354
2355 /* Convert minor. */
2356 minor = 0;
2357 if (p < end)
2358 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2359 return 1;
2360
2361 /* Check minor. */
2362 if (minor >= 65536)
2363 return 1;
2364
2365 /* Compose value. */
2366 *ret = (major << 16) | (minor & 0xffff);
2367 return 0;
2368}
2369
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002370/* This function parses a time value optionally followed by a unit suffix among
2371 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2372 * expected by the caller. The computation does its best to avoid overflows.
2373 * The value is returned in <ret> if everything is fine, and a NULL is returned
2374 * by the function. In case of error, a pointer to the error is returned and
2375 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002376 * Values resulting in values larger than or equal to 2^31 after conversion are
2377 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2378 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002379 */
2380const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2381{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002382 unsigned long long imult, idiv;
2383 unsigned long long omult, odiv;
2384 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002385 const char *str = text;
2386
2387 if (!isdigit((unsigned char)*text))
2388 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002389
2390 omult = odiv = 1;
2391
2392 switch (unit_flags & TIME_UNIT_MASK) {
2393 case TIME_UNIT_US: omult = 1000000; break;
2394 case TIME_UNIT_MS: omult = 1000; break;
2395 case TIME_UNIT_S: break;
2396 case TIME_UNIT_MIN: odiv = 60; break;
2397 case TIME_UNIT_HOUR: odiv = 3600; break;
2398 case TIME_UNIT_DAY: odiv = 86400; break;
2399 default: break;
2400 }
2401
2402 value = 0;
2403
2404 while (1) {
2405 unsigned int j;
2406
2407 j = *text - '0';
2408 if (j > 9)
2409 break;
2410 text++;
2411 value *= 10;
2412 value += j;
2413 }
2414
2415 imult = idiv = 1;
2416 switch (*text) {
2417 case '\0': /* no unit = default unit */
2418 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002419 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002420 case 's': /* second = unscaled unit */
2421 break;
2422 case 'u': /* microsecond : "us" */
2423 if (text[1] == 's') {
2424 idiv = 1000000;
2425 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002426 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002427 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002428 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002429 case 'm': /* millisecond : "ms" or minute: "m" */
2430 if (text[1] == 's') {
2431 idiv = 1000;
2432 text++;
2433 } else
2434 imult = 60;
2435 break;
2436 case 'h': /* hour : "h" */
2437 imult = 3600;
2438 break;
2439 case 'd': /* day : "d" */
2440 imult = 86400;
2441 break;
2442 default:
2443 return text;
2444 break;
2445 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002446 if (*(++text) != '\0') {
2447 ha_warning("unexpected character '%c' after the timer value '%s', only "
2448 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2449 " This will be reported as an error in next versions.\n", *text, str);
2450 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002451
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002452 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002453 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2454 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2455 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2456 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2457
Willy Tarreau9faebe32019-06-07 19:00:37 +02002458 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2459 if (result >= 0x80000000)
2460 return PARSE_TIME_OVER;
2461 if (!result && value)
2462 return PARSE_TIME_UNDER;
2463 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002464 return NULL;
2465}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002466
Emeric Brun39132b22010-01-04 14:57:24 +01002467/* this function converts the string starting at <text> to an unsigned int
2468 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002469 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002470 */
2471const char *parse_size_err(const char *text, unsigned *ret) {
2472 unsigned value = 0;
2473
Christopher Faulet82635a02020-12-11 09:30:45 +01002474 if (!isdigit((unsigned char)*text))
2475 return text;
2476
Emeric Brun39132b22010-01-04 14:57:24 +01002477 while (1) {
2478 unsigned int j;
2479
2480 j = *text - '0';
2481 if (j > 9)
2482 break;
2483 if (value > ~0U / 10)
2484 return text;
2485 value *= 10;
2486 if (value > (value + j))
2487 return text;
2488 value += j;
2489 text++;
2490 }
2491
2492 switch (*text) {
2493 case '\0':
2494 break;
2495 case 'K':
2496 case 'k':
2497 if (value > ~0U >> 10)
2498 return text;
2499 value = value << 10;
2500 break;
2501 case 'M':
2502 case 'm':
2503 if (value > ~0U >> 20)
2504 return text;
2505 value = value << 20;
2506 break;
2507 case 'G':
2508 case 'g':
2509 if (value > ~0U >> 30)
2510 return text;
2511 value = value << 30;
2512 break;
2513 default:
2514 return text;
2515 }
2516
Godbach58048a22015-01-28 17:36:16 +08002517 if (*text != '\0' && *++text != '\0')
2518 return text;
2519
Emeric Brun39132b22010-01-04 14:57:24 +01002520 *ret = value;
2521 return NULL;
2522}
2523
Willy Tarreau126d4062013-12-03 17:50:47 +01002524/*
2525 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002526 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002527 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002528 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002529 */
2530int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2531{
2532 int len;
2533 const char *p = source;
2534 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002535 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002536
2537 len = strlen(source);
2538 if (len % 2) {
2539 memprintf(err, "an even number of hex digit is expected");
2540 return 0;
2541 }
2542
2543 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002544
Willy Tarreau126d4062013-12-03 17:50:47 +01002545 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002546 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002547 if (!*binstr) {
2548 memprintf(err, "out of memory while loading string pattern");
2549 return 0;
2550 }
2551 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002552 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002553 else {
2554 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002555 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002556 len, *binstrlen);
2557 return 0;
2558 }
2559 alloc = 0;
2560 }
2561 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002562
2563 i = j = 0;
2564 while (j < len) {
2565 if (!ishex(p[i++]))
2566 goto bad_input;
2567 if (!ishex(p[i++]))
2568 goto bad_input;
2569 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2570 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002571 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002572
2573bad_input:
2574 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002575 if (alloc)
2576 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002577 return 0;
2578}
2579
Willy Tarreau946ba592009-05-10 15:41:18 +02002580/* copies at most <n> characters from <src> and always terminates with '\0' */
2581char *my_strndup(const char *src, int n)
2582{
2583 int len = 0;
2584 char *ret;
2585
2586 while (len < n && src[len])
2587 len++;
2588
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002589 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002590 if (!ret)
2591 return ret;
2592 memcpy(ret, src, len);
2593 ret[len] = '\0';
2594 return ret;
2595}
2596
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002597/*
2598 * search needle in haystack
2599 * returns the pointer if found, returns NULL otherwise
2600 */
2601const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2602{
2603 const void *c = NULL;
2604 unsigned char f;
2605
2606 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2607 return NULL;
2608
2609 f = *(char *)needle;
2610 c = haystack;
2611 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2612 if ((haystacklen - (c - haystack)) < needlelen)
2613 return NULL;
2614
2615 if (memcmp(c, needle, needlelen) == 0)
2616 return c;
2617 ++c;
2618 }
2619 return NULL;
2620}
2621
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002622/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002623size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2624{
2625 size_t ret = 0;
2626
2627 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2628 str++;
2629 ret++;
2630 }
2631 return ret;
2632}
2633
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002634/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002635size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2636{
2637 size_t ret = 0;
2638
2639 while (ret < len) {
2640 if(memchr(reject, *((int *)str), rejectlen))
2641 return ret;
2642 str++;
2643 ret++;
2644 }
2645 return ret;
2646}
2647
Willy Tarreau482b00d2009-10-04 22:48:42 +02002648/* This function returns the first unused key greater than or equal to <key> in
2649 * ID tree <root>. Zero is returned if no place is found.
2650 */
2651unsigned int get_next_id(struct eb_root *root, unsigned int key)
2652{
2653 struct eb32_node *used;
2654
2655 do {
2656 used = eb32_lookup_ge(root, key);
2657 if (!used || used->key > key)
2658 return key; /* key is available */
2659 key++;
2660 } while (key);
2661 return key;
2662}
2663
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002664/* dump the full tree to <file> in DOT format for debugging purposes. Will
2665 * optionally highlight node <subj> if found, depending on operation <op> :
2666 * 0 : nothing
2667 * >0 : insertion, node/leaf are surrounded in red
2668 * <0 : removal, node/leaf are dashed with no background
2669 * Will optionally add "desc" as a label on the graph if set and non-null.
2670 */
2671void 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 +01002672{
2673 struct eb32sc_node *node;
2674 unsigned long scope = -1;
2675
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002676 fprintf(file, "digraph ebtree {\n");
2677
2678 if (desc && *desc) {
2679 fprintf(file,
2680 " fontname=\"fixed\";\n"
2681 " fontsize=8;\n"
2682 " label=\"%s\";\n", desc);
2683 }
2684
Willy Tarreaued3cda02017-11-15 15:04:05 +01002685 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002686 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2687 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002688 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2689 );
2690
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002691 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002692 (long)eb_root_to_node(root),
2693 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002694 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2695
2696 node = eb32sc_first(root, scope);
2697 while (node) {
2698 if (node->node.node_p) {
2699 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002700 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2701 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2702 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002703
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002704 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002705 (long)node,
2706 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002707 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002708
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002709 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002710 (long)node,
2711 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002712 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2713
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002714 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002715 (long)node,
2716 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002717 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2718 }
2719
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002720 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2721 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2722 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002723
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002724 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002725 (long)node,
2726 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002727 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002728 node = eb32sc_next(node, scope);
2729 }
2730 fprintf(file, "}\n");
2731}
2732
Willy Tarreau348238b2010-01-18 15:05:57 +01002733/* This function compares a sample word possibly followed by blanks to another
2734 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2735 * otherwise zero. This intends to be used when checking HTTP headers for some
2736 * values. Note that it validates a word followed only by blanks but does not
2737 * validate a word followed by blanks then other chars.
2738 */
2739int word_match(const char *sample, int slen, const char *word, int wlen)
2740{
2741 if (slen < wlen)
2742 return 0;
2743
2744 while (wlen) {
2745 char c = *sample ^ *word;
2746 if (c && c != ('A' ^ 'a'))
2747 return 0;
2748 sample++;
2749 word++;
2750 slen--;
2751 wlen--;
2752 }
2753
2754 while (slen) {
2755 if (*sample != ' ' && *sample != '\t')
2756 return 0;
2757 sample++;
2758 slen--;
2759 }
2760 return 1;
2761}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002762
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002763/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2764 * is particularly fast because it avoids expensive operations such as
2765 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002766 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002767 */
2768unsigned int inetaddr_host(const char *text)
2769{
2770 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2771 register unsigned int dig100, dig10, dig1;
2772 int s;
2773 const char *p, *d;
2774
2775 dig1 = dig10 = dig100 = ascii_zero;
2776 s = 24;
2777
2778 p = text;
2779 while (1) {
2780 if (((unsigned)(*p - '0')) <= 9) {
2781 p++;
2782 continue;
2783 }
2784
2785 /* here, we have a complete byte between <text> and <p> (exclusive) */
2786 if (p == text)
2787 goto end;
2788
2789 d = p - 1;
2790 dig1 |= (unsigned int)(*d << s);
2791 if (d == text)
2792 goto end;
2793
2794 d--;
2795 dig10 |= (unsigned int)(*d << s);
2796 if (d == text)
2797 goto end;
2798
2799 d--;
2800 dig100 |= (unsigned int)(*d << s);
2801 end:
2802 if (!s || *p != '.')
2803 break;
2804
2805 s -= 8;
2806 text = ++p;
2807 }
2808
2809 dig100 -= ascii_zero;
2810 dig10 -= ascii_zero;
2811 dig1 -= ascii_zero;
2812 return ((dig100 * 10) + dig10) * 10 + dig1;
2813}
2814
2815/*
2816 * Idem except the first unparsed character has to be passed in <stop>.
2817 */
2818unsigned int inetaddr_host_lim(const char *text, const char *stop)
2819{
2820 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2821 register unsigned int dig100, dig10, dig1;
2822 int s;
2823 const char *p, *d;
2824
2825 dig1 = dig10 = dig100 = ascii_zero;
2826 s = 24;
2827
2828 p = text;
2829 while (1) {
2830 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2831 p++;
2832 continue;
2833 }
2834
2835 /* here, we have a complete byte between <text> and <p> (exclusive) */
2836 if (p == text)
2837 goto end;
2838
2839 d = p - 1;
2840 dig1 |= (unsigned int)(*d << s);
2841 if (d == text)
2842 goto end;
2843
2844 d--;
2845 dig10 |= (unsigned int)(*d << s);
2846 if (d == text)
2847 goto end;
2848
2849 d--;
2850 dig100 |= (unsigned int)(*d << s);
2851 end:
2852 if (!s || p == stop || *p != '.')
2853 break;
2854
2855 s -= 8;
2856 text = ++p;
2857 }
2858
2859 dig100 -= ascii_zero;
2860 dig10 -= ascii_zero;
2861 dig1 -= ascii_zero;
2862 return ((dig100 * 10) + dig10) * 10 + dig1;
2863}
2864
2865/*
2866 * Idem except the pointer to first unparsed byte is returned into <ret> which
2867 * must not be NULL.
2868 */
Willy Tarreau74172752010-10-15 23:21:42 +02002869unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002870{
2871 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2872 register unsigned int dig100, dig10, dig1;
2873 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002874 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002875
2876 dig1 = dig10 = dig100 = ascii_zero;
2877 s = 24;
2878
2879 p = text;
2880 while (1) {
2881 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2882 p++;
2883 continue;
2884 }
2885
2886 /* here, we have a complete byte between <text> and <p> (exclusive) */
2887 if (p == text)
2888 goto end;
2889
2890 d = p - 1;
2891 dig1 |= (unsigned int)(*d << s);
2892 if (d == text)
2893 goto end;
2894
2895 d--;
2896 dig10 |= (unsigned int)(*d << s);
2897 if (d == text)
2898 goto end;
2899
2900 d--;
2901 dig100 |= (unsigned int)(*d << s);
2902 end:
2903 if (!s || p == stop || *p != '.')
2904 break;
2905
2906 s -= 8;
2907 text = ++p;
2908 }
2909
2910 *ret = p;
2911 dig100 -= ascii_zero;
2912 dig10 -= ascii_zero;
2913 dig1 -= ascii_zero;
2914 return ((dig100 * 10) + dig10) * 10 + dig1;
2915}
2916
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002917/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2918 * or the number of chars read in case of success. Maybe this could be replaced
2919 * by one of the functions above. Also, apparently this function does not support
2920 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002921 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002922 */
2923int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2924{
2925 const char *addr;
2926 int saw_digit, octets, ch;
2927 u_char tmp[4], *tp;
2928 const char *cp = buf;
2929
2930 saw_digit = 0;
2931 octets = 0;
2932 *(tp = tmp) = 0;
2933
2934 for (addr = buf; addr - buf < len; addr++) {
2935 unsigned char digit = (ch = *addr) - '0';
2936
2937 if (digit > 9 && ch != '.')
2938 break;
2939
2940 if (digit <= 9) {
2941 u_int new = *tp * 10 + digit;
2942
2943 if (new > 255)
2944 return 0;
2945
2946 *tp = new;
2947
2948 if (!saw_digit) {
2949 if (++octets > 4)
2950 return 0;
2951 saw_digit = 1;
2952 }
2953 } else if (ch == '.' && saw_digit) {
2954 if (octets == 4)
2955 return 0;
2956
2957 *++tp = 0;
2958 saw_digit = 0;
2959 } else
2960 return 0;
2961 }
2962
2963 if (octets < 4)
2964 return 0;
2965
2966 memcpy(&dst->s_addr, tmp, 4);
2967 return addr - cp;
2968}
2969
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002970/* This function converts the string in <buf> of the len <len> to
2971 * struct in6_addr <dst> which must be allocated by the caller.
2972 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002973 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002974 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002975int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2976{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002977 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002978 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002979
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002980 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002981 return 0;
2982
2983 memcpy(null_term_ip6, buf, len);
2984 null_term_ip6[len] = '\0';
2985
Willy Tarreau075415a2013-12-12 11:29:39 +01002986 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002987 return 0;
2988
Willy Tarreau075415a2013-12-12 11:29:39 +01002989 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002990 return 1;
2991}
2992
Willy Tarreauacf95772010-06-14 19:09:21 +02002993/* To be used to quote config arg positions. Returns the short string at <ptr>
2994 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2995 * if ptr is NULL or empty. The string is locally allocated.
2996 */
2997const char *quote_arg(const char *ptr)
2998{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002999 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003000 int i;
3001
3002 if (!ptr || !*ptr)
3003 return "end of line";
3004 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003005 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003006 val[i] = *ptr++;
3007 val[i++] = '\'';
3008 val[i] = '\0';
3009 return val;
3010}
3011
Willy Tarreau5b180202010-07-18 10:40:48 +02003012/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3013int get_std_op(const char *str)
3014{
3015 int ret = -1;
3016
3017 if (*str == 'e' && str[1] == 'q')
3018 ret = STD_OP_EQ;
3019 else if (*str == 'n' && str[1] == 'e')
3020 ret = STD_OP_NE;
3021 else if (*str == 'l') {
3022 if (str[1] == 'e') ret = STD_OP_LE;
3023 else if (str[1] == 't') ret = STD_OP_LT;
3024 }
3025 else if (*str == 'g') {
3026 if (str[1] == 'e') ret = STD_OP_GE;
3027 else if (str[1] == 't') ret = STD_OP_GT;
3028 }
3029
3030 if (ret == -1 || str[2] != '\0')
3031 return -1;
3032 return ret;
3033}
3034
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003035/* hash a 32-bit integer to another 32-bit integer */
3036unsigned int full_hash(unsigned int a)
3037{
3038 return __full_hash(a);
3039}
3040
Willy Tarreauf3241112019-02-26 09:56:22 +01003041/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3042 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3043 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3044 * a popcount variant and is described here :
3045 * https://graphics.stanford.edu/~seander/bithacks.html
3046 */
3047unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3048{
3049 unsigned long a, b, c, d;
3050 unsigned int s;
3051 unsigned int t;
3052
3053 a = m - ((m >> 1) & ~0UL/3);
3054 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3055 c = (b + (b >> 4)) & ~0UL/0x11;
3056 d = (c + (c >> 8)) & ~0UL/0x101;
3057
3058 r++; // make r be 1..64
3059
3060 t = 0;
3061 s = LONGBITS;
3062 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003063 unsigned long d2 = (d >> 16) >> 16;
3064 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003065 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3066 }
3067
3068 t = (d >> (s - 16)) & 0xff;
3069 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3070 t = (c >> (s - 8)) & 0xf;
3071 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3072 t = (b >> (s - 4)) & 0x7;
3073 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3074 t = (a >> (s - 2)) & 0x3;
3075 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3076 t = (m >> (s - 1)) & 0x1;
3077 s -= ((t - r) & 256) >> 8;
3078
3079 return s - 1;
3080}
3081
3082/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3083 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3084 * using mask_prep_rank_map() below.
3085 */
3086unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3087 unsigned long a, unsigned long b,
3088 unsigned long c, unsigned long d)
3089{
3090 unsigned int s;
3091 unsigned int t;
3092
3093 r++; // make r be 1..64
3094
3095 t = 0;
3096 s = LONGBITS;
3097 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003098 unsigned long d2 = (d >> 16) >> 16;
3099 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003100 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3101 }
3102
3103 t = (d >> (s - 16)) & 0xff;
3104 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3105 t = (c >> (s - 8)) & 0xf;
3106 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3107 t = (b >> (s - 4)) & 0x7;
3108 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3109 t = (a >> (s - 2)) & 0x3;
3110 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3111 t = (m >> (s - 1)) & 0x1;
3112 s -= ((t - r) & 256) >> 8;
3113
3114 return s - 1;
3115}
3116
3117/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3118 * above.
3119 */
3120void mask_prep_rank_map(unsigned long m,
3121 unsigned long *a, unsigned long *b,
3122 unsigned long *c, unsigned long *d)
3123{
3124 *a = m - ((m >> 1) & ~0UL/3);
3125 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3126 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3127 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3128}
3129
David du Colombier4f92d322011-03-24 11:09:31 +01003130/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003131 * otherwise zero. Note that <addr> may not necessarily be aligned
3132 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003133 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003134int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003135{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003136 struct in_addr addr_copy;
3137
3138 memcpy(&addr_copy, addr, sizeof(addr_copy));
3139 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003140}
3141
3142/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003143 * otherwise zero. Note that <addr> may not necessarily be aligned
3144 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003145 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003146int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003147{
3148 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003149 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003150
Willy Tarreaueec1d382016-07-13 11:59:39 +02003151 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003152 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003153 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003154 (((int *)net)[i] & ((int *)mask)[i]))
3155 return 0;
3156 return 1;
3157}
3158
3159/* RFC 4291 prefix */
3160const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3161 0x00, 0x00, 0x00, 0x00,
3162 0x00, 0x00, 0xFF, 0xFF };
3163
Joseph Herlant32b83272018-11-15 11:58:28 -08003164/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003165 * Input and output may overlap.
3166 */
David du Colombier4f92d322011-03-24 11:09:31 +01003167void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3168{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003169 struct in_addr tmp_addr;
3170
3171 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003172 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003173 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003174}
3175
Joseph Herlant32b83272018-11-15 11:58:28 -08003176/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003177 * Return true if conversion is possible and false otherwise.
3178 */
3179int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3180{
3181 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3182 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3183 sizeof(struct in_addr));
3184 return 1;
3185 }
3186
3187 return 0;
3188}
3189
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003190/* compare two struct sockaddr_storage and return:
3191 * 0 (true) if the addr is the same in both
3192 * 1 (false) if the addr is not the same in both
3193 * -1 (unable) if one of the addr is not AF_INET*
3194 */
3195int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3196{
3197 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3198 return -1;
3199
3200 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3201 return -1;
3202
3203 if (ss1->ss_family != ss2->ss_family)
3204 return 1;
3205
3206 switch (ss1->ss_family) {
3207 case AF_INET:
3208 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3209 &((struct sockaddr_in *)ss2)->sin_addr,
3210 sizeof(struct in_addr)) != 0;
3211 case AF_INET6:
3212 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3213 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3214 sizeof(struct in6_addr)) != 0;
3215 }
3216
3217 return 1;
3218}
3219
Christopher Faulet9553de72021-02-26 09:12:50 +01003220/* compare a struct sockaddr_storage to a struct net_addr and return :
3221 * 0 (true) if <addr> is matching <net>
3222 * 1 (false) if <addr> is not matching <net>
3223 * -1 (unable) if <addr> or <net> is not AF_INET*
3224 */
3225int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3226{
3227 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3228 return -1;
3229
3230 if ((net->family != AF_INET) && (net->family != AF_INET6))
3231 return -1;
3232
3233 if (addr->ss_family != net->family)
3234 return 1;
3235
3236 if (addr->ss_family == AF_INET &&
3237 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3238 return 0;
3239 else {
3240 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3241 const struct in6_addr *nip6 = &net->addr.v6.ip;
3242 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3243
3244 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3245 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3246 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3247 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3248 return 0;
3249 }
3250
3251 return 1;
3252}
3253
Baptiste Assmann08396c82016-01-31 00:27:17 +01003254/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003255 * The caller must allocate and clear <dest> before calling.
3256 * The source must be in either AF_INET or AF_INET6 family, or the destination
3257 * address will be undefined. If the destination address used to hold a port,
3258 * it is preserved, so that this function can be used to switch to another
3259 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003260 */
3261struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3262{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003263 int prev_port;
3264
3265 prev_port = get_net_port(dest);
3266 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003267 dest->ss_family = source->ss_family;
3268
3269 /* copy new addr and apply it */
3270 switch (source->ss_family) {
3271 case AF_INET:
3272 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003273 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003274 break;
3275 case AF_INET6:
3276 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 +01003277 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003278 break;
3279 }
3280
3281 return dest;
3282}
3283
William Lallemand421f5b52012-02-06 18:15:57 +01003284char *human_time(int t, short hz_div) {
3285 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3286 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003287 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003288 int cnt=2; // print two numbers
3289
3290 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003291 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003292 return rv;
3293 }
3294
3295 if (unlikely(hz_div > 1))
3296 t /= hz_div;
3297
3298 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003299 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003300 cnt--;
3301 }
3302
3303 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003304 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003305 cnt--;
3306 }
3307
3308 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003309 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003310 cnt--;
3311 }
3312
3313 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003314 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003315
3316 return rv;
3317}
3318
3319const char *monthname[12] = {
3320 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3321 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3322};
3323
3324/* date2str_log: write a date in the format :
3325 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3326 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3327 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3328 *
3329 * without using sprintf. return a pointer to the last char written (\0) or
3330 * NULL if there isn't enough space.
3331 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003332char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003333{
3334
3335 if (size < 25) /* the size is fixed: 24 chars + \0 */
3336 return NULL;
3337
3338 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
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 memcpy(dst, monthname[tm->tm_mon], 3); // month
3344 dst += 3;
3345 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003346
William Lallemand421f5b52012-02-06 18:15:57 +01003347 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003348 if (!dst)
3349 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003350 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003351
William Lallemand421f5b52012-02-06 18:15:57 +01003352 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003353 if (!dst)
3354 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003355 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003356
William Lallemand421f5b52012-02-06 18:15:57 +01003357 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003358 if (!dst)
3359 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003360 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003361
William Lallemand421f5b52012-02-06 18:15:57 +01003362 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003363 if (!dst)
3364 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003365 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003366
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003367 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003368 if (!dst)
3369 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003370 *dst = '\0';
3371
3372 return dst;
3373}
3374
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003375/* Base year used to compute leap years */
3376#define TM_YEAR_BASE 1900
3377
3378/* Return the difference in seconds between two times (leap seconds are ignored).
3379 * Retrieved from glibc 2.18 source code.
3380 */
3381static int my_tm_diff(const struct tm *a, const struct tm *b)
3382{
3383 /* Compute intervening leap days correctly even if year is negative.
3384 * Take care to avoid int overflow in leap day calculations,
3385 * but it's OK to assume that A and B are close to each other.
3386 */
3387 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3388 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3389 int a100 = a4 / 25 - (a4 % 25 < 0);
3390 int b100 = b4 / 25 - (b4 % 25 < 0);
3391 int a400 = a100 >> 2;
3392 int b400 = b100 >> 2;
3393 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3394 int years = a->tm_year - b->tm_year;
3395 int days = (365 * years + intervening_leap_days
3396 + (a->tm_yday - b->tm_yday));
3397 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3398 + (a->tm_min - b->tm_min))
3399 + (a->tm_sec - b->tm_sec));
3400}
3401
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003402/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003403 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003404 * The string returned has the same format as returned by strftime(... "%z", tm).
3405 * Offsets are kept in an internal cache for better performances.
3406 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003407const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003408{
3409 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003410 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003411
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003412 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003413 struct tm tm_gmt;
3414 int diff;
3415 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003416
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003417 /* Pretend DST not active if its status is unknown */
3418 if (isdst < 0)
3419 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003420
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003421 /* Fetch the offset and initialize it if needed */
3422 gmt_offset = gmt_offsets[isdst & 0x01];
3423 if (unlikely(!*gmt_offset)) {
3424 get_gmtime(t, &tm_gmt);
3425 diff = my_tm_diff(tm, &tm_gmt);
3426 if (diff < 0) {
3427 diff = -diff;
3428 *gmt_offset = '-';
3429 } else {
3430 *gmt_offset = '+';
3431 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003432 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003433 diff /= 60; /* Convert to minutes */
3434 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3435 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003436
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003437 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003438}
3439
William Lallemand421f5b52012-02-06 18:15:57 +01003440/* gmt2str_log: write a date in the format :
3441 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3442 * return a pointer to the last char written (\0) or
3443 * NULL if there isn't enough space.
3444 */
3445char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3446{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003447 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003448 return NULL;
3449
3450 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
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 memcpy(dst, monthname[tm->tm_mon], 3); // month
3456 dst += 3;
3457 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003458
William Lallemand421f5b52012-02-06 18:15:57 +01003459 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003460 if (!dst)
3461 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003462 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003463
William Lallemand421f5b52012-02-06 18:15:57 +01003464 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003465 if (!dst)
3466 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003467 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003468
William Lallemand421f5b52012-02-06 18:15:57 +01003469 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003470 if (!dst)
3471 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003472 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003473
William Lallemand421f5b52012-02-06 18:15:57 +01003474 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003475 if (!dst)
3476 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003477 *dst++ = ' ';
3478 *dst++ = '+';
3479 *dst++ = '0';
3480 *dst++ = '0';
3481 *dst++ = '0';
3482 *dst++ = '0';
3483 *dst = '\0';
3484
3485 return dst;
3486}
3487
Yuxans Yao4e25b012012-10-19 10:36:09 +08003488/* localdate2str_log: write a date in the format :
3489 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003490 * Both t and tm must represent the same time.
3491 * return a pointer to the last char written (\0) or
3492 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003493 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003494char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003495{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003496 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003497 if (size < 27) /* the size is fixed: 26 chars + \0 */
3498 return NULL;
3499
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003500 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003501
Yuxans Yao4e25b012012-10-19 10:36:09 +08003502 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
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 memcpy(dst, monthname[tm->tm_mon], 3); // month
3508 dst += 3;
3509 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003510
Yuxans Yao4e25b012012-10-19 10:36:09 +08003511 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003512 if (!dst)
3513 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003514 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003515
Yuxans Yao4e25b012012-10-19 10:36:09 +08003516 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003517 if (!dst)
3518 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003519 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003520
Yuxans Yao4e25b012012-10-19 10:36:09 +08003521 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003522 if (!dst)
3523 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003524 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003525
Yuxans Yao4e25b012012-10-19 10:36:09 +08003526 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003527 if (!dst)
3528 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003529 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003530
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003531 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003532 dst += 5;
3533 *dst = '\0';
3534
3535 return dst;
3536}
3537
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003538/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3539 * It is meant as a portable replacement for timegm() for use with valid inputs.
3540 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3541 */
3542time_t my_timegm(const struct tm *tm)
3543{
3544 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3545 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3546 * sum of the extra N days for elapsed months. The sum of all these N
3547 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3548 * in a 5-bit word. This means that with 60 bits we can represent a
3549 * matrix of all these values at once, which is fast and efficient to
3550 * access. The extra February day for leap years is not counted here.
3551 *
3552 * Jan : none = 0 (0)
3553 * Feb : Jan = 3 (3)
3554 * Mar : Jan..Feb = 3 (3 + 0)
3555 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3556 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3557 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3558 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3559 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3560 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3561 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3562 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3563 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3564 */
3565 uint64_t extra =
3566 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3567 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3568 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3569 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3570
3571 unsigned int y = tm->tm_year + 1900;
3572 unsigned int m = tm->tm_mon;
3573 unsigned long days = 0;
3574
3575 /* days since 1/1/1970 for full years */
3576 days += days_since_zero(y) - days_since_zero(1970);
3577
3578 /* days for full months in the current year */
3579 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3580
3581 /* count + 1 after March for leap years. A leap year is a year multiple
3582 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3583 * is leap, 1900 isn't, 1904 is.
3584 */
3585 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3586 days++;
3587
3588 days += tm->tm_mday - 1;
3589 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3590}
3591
Thierry Fournier93127942016-01-20 18:49:45 +01003592/* This function check a char. It returns true and updates
3593 * <date> and <len> pointer to the new position if the
3594 * character is found.
3595 */
3596static inline int parse_expect_char(const char **date, int *len, char c)
3597{
3598 if (*len < 1 || **date != c)
3599 return 0;
3600 (*len)--;
3601 (*date)++;
3602 return 1;
3603}
3604
3605/* This function expects a string <str> of len <l>. It return true and updates.
3606 * <date> and <len> if the string matches, otherwise, it returns false.
3607 */
3608static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3609{
3610 if (*len < l || strncmp(*date, str, l) != 0)
3611 return 0;
3612 (*len) -= l;
3613 (*date) += l;
3614 return 1;
3615}
3616
3617/* This macro converts 3 chars name in integer. */
3618#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3619
3620/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3621 * / %x54.75.65 ; "Tue", case-sensitive
3622 * / %x57.65.64 ; "Wed", case-sensitive
3623 * / %x54.68.75 ; "Thu", case-sensitive
3624 * / %x46.72.69 ; "Fri", case-sensitive
3625 * / %x53.61.74 ; "Sat", case-sensitive
3626 * / %x53.75.6E ; "Sun", case-sensitive
3627 *
3628 * This array must be alphabetically sorted
3629 */
3630static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3631{
3632 if (*len < 3)
3633 return 0;
3634 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3635 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3636 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3637 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3638 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3639 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3640 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3641 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3642 default: return 0;
3643 }
3644 *len -= 3;
3645 *date += 3;
3646 return 1;
3647}
3648
3649/* month = %x4A.61.6E ; "Jan", case-sensitive
3650 * / %x46.65.62 ; "Feb", case-sensitive
3651 * / %x4D.61.72 ; "Mar", case-sensitive
3652 * / %x41.70.72 ; "Apr", case-sensitive
3653 * / %x4D.61.79 ; "May", case-sensitive
3654 * / %x4A.75.6E ; "Jun", case-sensitive
3655 * / %x4A.75.6C ; "Jul", case-sensitive
3656 * / %x41.75.67 ; "Aug", case-sensitive
3657 * / %x53.65.70 ; "Sep", case-sensitive
3658 * / %x4F.63.74 ; "Oct", case-sensitive
3659 * / %x4E.6F.76 ; "Nov", case-sensitive
3660 * / %x44.65.63 ; "Dec", case-sensitive
3661 *
3662 * This array must be alphabetically sorted
3663 */
3664static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3665{
3666 if (*len < 3)
3667 return 0;
3668 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3669 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3670 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3671 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3672 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3673 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3674 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3675 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3676 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3677 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3678 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3679 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3680 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3681 default: return 0;
3682 }
3683 *len -= 3;
3684 *date += 3;
3685 return 1;
3686}
3687
3688/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3689 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3690 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3691 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3692 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3693 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3694 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3695 *
3696 * This array must be alphabetically sorted
3697 */
3698static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3699{
3700 if (*len < 6) /* Minimum length. */
3701 return 0;
3702 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3703 case STR2I3('M','o','n'):
3704 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3705 tm->tm_wday = 1;
3706 return 1;
3707 case STR2I3('T','u','e'):
3708 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3709 tm->tm_wday = 2;
3710 return 1;
3711 case STR2I3('W','e','d'):
3712 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3713 tm->tm_wday = 3;
3714 return 1;
3715 case STR2I3('T','h','u'):
3716 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3717 tm->tm_wday = 4;
3718 return 1;
3719 case STR2I3('F','r','i'):
3720 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3721 tm->tm_wday = 5;
3722 return 1;
3723 case STR2I3('S','a','t'):
3724 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3725 tm->tm_wday = 6;
3726 return 1;
3727 case STR2I3('S','u','n'):
3728 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3729 tm->tm_wday = 7;
3730 return 1;
3731 }
3732 return 0;
3733}
3734
3735/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3736static inline int parse_digit(const char **date, int *len, int *digit)
3737{
3738 if (*len < 1 || **date < '0' || **date > '9')
3739 return 0;
3740 *digit = (**date - '0');
3741 (*date)++;
3742 (*len)--;
3743 return 1;
3744}
3745
3746/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3747static inline int parse_2digit(const char **date, int *len, int *digit)
3748{
3749 int value;
3750
3751 RET0_UNLESS(parse_digit(date, len, &value));
3752 (*digit) = value * 10;
3753 RET0_UNLESS(parse_digit(date, len, &value));
3754 (*digit) += value;
3755
3756 return 1;
3757}
3758
3759/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3760static inline int parse_4digit(const char **date, int *len, int *digit)
3761{
3762 int value;
3763
3764 RET0_UNLESS(parse_digit(date, len, &value));
3765 (*digit) = value * 1000;
3766
3767 RET0_UNLESS(parse_digit(date, len, &value));
3768 (*digit) += value * 100;
3769
3770 RET0_UNLESS(parse_digit(date, len, &value));
3771 (*digit) += value * 10;
3772
3773 RET0_UNLESS(parse_digit(date, len, &value));
3774 (*digit) += value;
3775
3776 return 1;
3777}
3778
3779/* time-of-day = hour ":" minute ":" second
3780 * ; 00:00:00 - 23:59:60 (leap second)
3781 *
3782 * hour = 2DIGIT
3783 * minute = 2DIGIT
3784 * second = 2DIGIT
3785 */
3786static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3787{
3788 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3789 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3790 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3791 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3792 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3793 return 1;
3794}
3795
3796/* From RFC7231
3797 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3798 *
3799 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3800 * ; fixed length/zone/capitalization subset of the format
3801 * ; see Section 3.3 of [RFC5322]
3802 *
3803 *
3804 * date1 = day SP month SP year
3805 * ; e.g., 02 Jun 1982
3806 *
3807 * day = 2DIGIT
3808 * year = 4DIGIT
3809 *
3810 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3811 *
3812 * time-of-day = hour ":" minute ":" second
3813 * ; 00:00:00 - 23:59:60 (leap second)
3814 *
3815 * hour = 2DIGIT
3816 * minute = 2DIGIT
3817 * second = 2DIGIT
3818 *
3819 * DIGIT = decimal 0-9
3820 */
3821int parse_imf_date(const char *date, int len, struct tm *tm)
3822{
David Carlier327298c2016-11-20 10:42:38 +00003823 /* tm_gmtoff, if present, ought to be zero'ed */
3824 memset(tm, 0, sizeof(*tm));
3825
Thierry Fournier93127942016-01-20 18:49:45 +01003826 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3827 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3828 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3829 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3830 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3831 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3832 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3833 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3834 tm->tm_year -= 1900;
3835 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3836 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3837 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3838 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3839 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003840 return 1;
3841}
3842
3843/* From RFC7231
3844 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3845 *
3846 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3847 * date2 = day "-" month "-" 2DIGIT
3848 * ; e.g., 02-Jun-82
3849 *
3850 * day = 2DIGIT
3851 */
3852int parse_rfc850_date(const char *date, int len, struct tm *tm)
3853{
3854 int year;
3855
David Carlier327298c2016-11-20 10:42:38 +00003856 /* tm_gmtoff, if present, ought to be zero'ed */
3857 memset(tm, 0, sizeof(*tm));
3858
Thierry Fournier93127942016-01-20 18:49:45 +01003859 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3860 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3861 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3862 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3863 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3864 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3865 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3866
3867 /* year = 2DIGIT
3868 *
3869 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3870 * two-digit year, MUST interpret a timestamp that appears to be more
3871 * than 50 years in the future as representing the most recent year in
3872 * the past that had the same last two digits.
3873 */
3874 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3875
3876 /* expect SP */
3877 if (!parse_expect_char(&date, &len, ' ')) {
3878 /* Maybe we have the date with 4 digits. */
3879 RET0_UNLESS(parse_2digit(&date, &len, &year));
3880 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3881 /* expect SP */
3882 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3883 } else {
3884 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3885 * tm_year is the number of year since 1900, so for +1900, we
3886 * do nothing, and for +2000, we add 100.
3887 */
3888 if (tm->tm_year <= 60)
3889 tm->tm_year += 100;
3890 }
3891
3892 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3893 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3894 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3895 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003896
3897 return 1;
3898}
3899
3900/* From RFC7231
3901 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3902 *
3903 * asctime-date = day-name SP date3 SP time-of-day SP year
3904 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3905 * ; e.g., Jun 2
3906 *
3907 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3908 * whitespace in an HTTP-date beyond that specifically included as SP in
3909 * the grammar.
3910 */
3911int parse_asctime_date(const char *date, int len, struct tm *tm)
3912{
David Carlier327298c2016-11-20 10:42:38 +00003913 /* tm_gmtoff, if present, ought to be zero'ed */
3914 memset(tm, 0, sizeof(*tm));
3915
Thierry Fournier93127942016-01-20 18:49:45 +01003916 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3917 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3918 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3919 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3920
3921 /* expect SP and 1DIGIT or 2DIGIT */
3922 if (parse_expect_char(&date, &len, ' '))
3923 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3924 else
3925 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3926
3927 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3928 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3929 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3930 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3931 tm->tm_year -= 1900;
3932 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003933 return 1;
3934}
3935
3936/* From RFC7231
3937 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3938 *
3939 * HTTP-date = IMF-fixdate / obs-date
3940 * obs-date = rfc850-date / asctime-date
3941 *
3942 * parses an HTTP date in the RFC format and is accepted
3943 * alternatives. <date> is the strinf containing the date,
3944 * len is the len of the string. <tm> is filled with the
3945 * parsed time. We must considers this time as GMT.
3946 */
3947int parse_http_date(const char *date, int len, struct tm *tm)
3948{
3949 if (parse_imf_date(date, len, tm))
3950 return 1;
3951
3952 if (parse_rfc850_date(date, len, tm))
3953 return 1;
3954
3955 if (parse_asctime_date(date, len, tm))
3956 return 1;
3957
3958 return 0;
3959}
3960
Willy Tarreau4deeb102021-01-29 10:47:52 +01003961/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3962 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3963 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3964 * surrounded by <pfx> and <sfx> respectively if not NULL.
3965 */
3966int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3967{
3968 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3969 const char *unit;
3970
3971 if (!pfx)
3972 pfx = "";
3973 if (!sfx)
3974 sfx = "";
3975
3976 do {
3977 unit = " - "; if (val <= 0.0) break;
3978 unit = "ns"; if (val < 1000.0) break;
3979 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3980 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3981 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3982 unit = "m "; val /= 60.0; if (val < 60.0) break;
3983 unit = "h "; val /= 60.0; if (val < 24.0) break;
3984 unit = "d "; val /= 24.0; if (val < 365.0) break;
3985 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3986 unit = " inf "; val = 0.0; break;
3987 } while (0);
3988
3989 if (val <= 0.0)
3990 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
3991 else if (val < 10.0)
3992 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
3993 else if (val < 100.0)
3994 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
3995 else
3996 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
3997}
3998
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003999/* Dynamically allocates a string of the proper length to hold the formatted
4000 * output. NULL is returned on error. The caller is responsible for freeing the
4001 * memory area using free(). The resulting string is returned in <out> if the
4002 * pointer is not NULL. A previous version of <out> might be used to build the
4003 * new string, and it will be freed before returning if it is not NULL, which
4004 * makes it possible to build complex strings from iterative calls without
4005 * having to care about freeing intermediate values, as in the example below :
4006 *
4007 * memprintf(&err, "invalid argument: '%s'", arg);
4008 * ...
4009 * memprintf(&err, "parser said : <%s>\n", *err);
4010 * ...
4011 * free(*err);
4012 *
4013 * This means that <err> must be initialized to NULL before first invocation.
4014 * The return value also holds the allocated string, which eases error checking
4015 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004016 * passed instead and it will be ignored. The returned message will then also
4017 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004018 *
4019 * It is also convenient to use it without any free except the last one :
4020 * err = NULL;
4021 * if (!fct1(err)) report(*err);
4022 * if (!fct2(err)) report(*err);
4023 * if (!fct3(err)) report(*err);
4024 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004025 *
4026 * memprintf relies on memvprintf. This last version can be called from any
4027 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004028 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004029char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004030{
4031 va_list args;
4032 char *ret = NULL;
4033 int allocated = 0;
4034 int needed = 0;
4035
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004036 if (!out)
4037 return NULL;
4038
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004039 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004040 char buf1;
4041
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004042 /* vsnprintf() will return the required length even when the
4043 * target buffer is NULL. We do this in a loop just in case
4044 * intermediate evaluations get wrong.
4045 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004046 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004047 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004048 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004049 if (needed < allocated) {
4050 /* Note: on Solaris 8, the first iteration always
4051 * returns -1 if allocated is zero, so we force a
4052 * retry.
4053 */
4054 if (!allocated)
4055 needed = 0;
4056 else
4057 break;
4058 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004059
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004060 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004061 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004062 } while (ret);
4063
4064 if (needed < 0) {
4065 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004066 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004067 }
4068
4069 if (out) {
4070 free(*out);
4071 *out = ret;
4072 }
4073
4074 return ret;
4075}
William Lallemand421f5b52012-02-06 18:15:57 +01004076
Christopher Faulet93a518f2017-10-24 11:25:33 +02004077char *memprintf(char **out, const char *format, ...)
4078{
4079 va_list args;
4080 char *ret = NULL;
4081
4082 va_start(args, format);
4083 ret = memvprintf(out, format, args);
4084 va_end(args);
4085
4086 return ret;
4087}
4088
Willy Tarreau21c705b2012-09-14 11:40:36 +02004089/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4090 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004091 * freed by the caller. It also supports being passed a NULL which results in the same
4092 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004093 * Example of use :
4094 * parse(cmd, &err); (callee: memprintf(&err, ...))
4095 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4096 * free(err);
4097 */
4098char *indent_msg(char **out, int level)
4099{
4100 char *ret, *in, *p;
4101 int needed = 0;
4102 int lf = 0;
4103 int lastlf = 0;
4104 int len;
4105
Willy Tarreau70eec382012-10-10 08:56:47 +02004106 if (!out || !*out)
4107 return NULL;
4108
Willy Tarreau21c705b2012-09-14 11:40:36 +02004109 in = *out - 1;
4110 while ((in = strchr(in + 1, '\n')) != NULL) {
4111 lastlf = in - *out;
4112 lf++;
4113 }
4114
4115 if (!lf) /* single line, no LF, return it as-is */
4116 return *out;
4117
4118 len = strlen(*out);
4119
4120 if (lf == 1 && lastlf == len - 1) {
4121 /* single line, LF at end, strip it and return as-is */
4122 (*out)[lastlf] = 0;
4123 return *out;
4124 }
4125
4126 /* OK now we have at least one LF, we need to process the whole string
4127 * as a multi-line string. What we'll do :
4128 * - prefix with an LF if there is none
4129 * - add <level> spaces before each line
4130 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4131 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4132 */
4133
4134 needed = 1 + level * (lf + 1) + len + 1;
4135 p = ret = malloc(needed);
4136 in = *out;
4137
4138 /* skip initial LFs */
4139 while (*in == '\n')
4140 in++;
4141
4142 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4143 while (*in) {
4144 *p++ = '\n';
4145 memset(p, ' ', level);
4146 p += level;
4147 do {
4148 *p++ = *in++;
4149 } while (*in && *in != '\n');
4150 if (*in)
4151 in++;
4152 }
4153 *p = 0;
4154
4155 free(*out);
4156 *out = ret;
4157
4158 return ret;
4159}
4160
Willy Tarreaua2c99112019-08-21 13:17:37 +02004161/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4162 * and end of lines replaced with <eol> if not 0. The first line to indent has
4163 * to be indicated in <first> (starts at zero), so that it is possible to skip
4164 * indenting the first line if it has to be appended after an existing message.
4165 * Empty strings are never indented, and NULL strings are considered empty both
4166 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4167 * character, non-zero otherwise.
4168 */
4169int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4170{
4171 int bol, lf;
4172 int pfxlen = pfx ? strlen(pfx) : 0;
4173
4174 if (!in)
4175 return 0;
4176
4177 bol = 1;
4178 lf = 0;
4179 while (*in) {
4180 if (bol && pfxlen) {
4181 if (first > 0)
4182 first--;
4183 else
4184 b_putblk(out, pfx, pfxlen);
4185 bol = 0;
4186 }
4187
4188 lf = (*in == '\n');
4189 bol |= lf;
4190 b_putchr(out, (lf && eol) ? eol : *in);
4191 in++;
4192 }
4193 return lf;
4194}
4195
Willy Tarreau9d22e562019-03-29 18:49:09 +01004196/* removes environment variable <name> from the environment as found in
4197 * environ. This is only provided as an alternative for systems without
4198 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004199 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004200 * <name> and to replace the matching pointers with the last pointer of
4201 * the array (since variables are not ordered).
4202 * It always returns 0 (success).
4203 */
4204int my_unsetenv(const char *name)
4205{
4206 extern char **environ;
4207 char **p = environ;
4208 int vars;
4209 int next;
4210 int len;
4211
4212 len = strlen(name);
4213 for (vars = 0; p[vars]; vars++)
4214 ;
4215 next = 0;
4216 while (next < vars) {
4217 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4218 next++;
4219 continue;
4220 }
4221 if (next < vars - 1)
4222 p[next] = p[vars - 1];
4223 p[--vars] = NULL;
4224 }
4225 return 0;
4226}
4227
Willy Tarreaudad36a32013-03-11 01:20:04 +01004228/* Convert occurrences of environment variables in the input string to their
4229 * corresponding value. A variable is identified as a series of alphanumeric
4230 * characters or underscores following a '$' sign. The <in> string must be
4231 * free()able. NULL returns NULL. The resulting string might be reallocated if
4232 * some expansion is made. Variable names may also be enclosed into braces if
4233 * needed (eg: to concatenate alphanum characters).
4234 */
4235char *env_expand(char *in)
4236{
4237 char *txt_beg;
4238 char *out;
4239 char *txt_end;
4240 char *var_beg;
4241 char *var_end;
4242 char *value;
4243 char *next;
4244 int out_len;
4245 int val_len;
4246
4247 if (!in)
4248 return in;
4249
4250 value = out = NULL;
4251 out_len = 0;
4252
4253 txt_beg = in;
4254 do {
4255 /* look for next '$' sign in <in> */
4256 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4257
4258 if (!*txt_end && !out) /* end and no expansion performed */
4259 return in;
4260
4261 val_len = 0;
4262 next = txt_end;
4263 if (*txt_end == '$') {
4264 char save;
4265
4266 var_beg = txt_end + 1;
4267 if (*var_beg == '{')
4268 var_beg++;
4269
4270 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004271 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004272 var_end++;
4273 }
4274
4275 next = var_end;
4276 if (*var_end == '}' && (var_beg > txt_end + 1))
4277 next++;
4278
4279 /* get value of the variable name at this location */
4280 save = *var_end;
4281 *var_end = '\0';
4282 value = getenv(var_beg);
4283 *var_end = save;
4284 val_len = value ? strlen(value) : 0;
4285 }
4286
Hubert Verstraete831962e2016-06-28 22:44:26 +02004287 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004288 if (txt_end > txt_beg) {
4289 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4290 out_len += txt_end - txt_beg;
4291 }
4292 if (val_len) {
4293 memcpy(out + out_len, value, val_len);
4294 out_len += val_len;
4295 }
4296 out[out_len] = 0;
4297 txt_beg = next;
4298 } while (*txt_beg);
4299
4300 /* here we know that <out> was allocated and that we don't need <in> anymore */
4301 free(in);
4302 return out;
4303}
4304
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004305
4306/* same as strstr() but case-insensitive and with limit length */
4307const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4308{
4309 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004310 unsigned int slen, plen;
4311 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004312
4313 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4314 return NULL;
4315
4316 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4317 return str1;
4318
4319 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4320 return NULL;
4321
4322 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 +02004323 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004324 start++;
4325 slen--;
4326 tmp1++;
4327
4328 if (tmp1 >= len_str1)
4329 return NULL;
4330
4331 /* if pattern longer than string */
4332 if (slen < plen)
4333 return NULL;
4334 }
4335
4336 sptr = start;
4337 pptr = (char *)str2;
4338
4339 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004340 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004341 sptr++;
4342 pptr++;
4343 tmp2++;
4344
4345 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4346 return start;
4347 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4348 return NULL;
4349 }
4350 }
4351 return NULL;
4352}
4353
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004354/* This function read the next valid utf8 char.
4355 * <s> is the byte srray to be decode, <len> is its length.
4356 * The function returns decoded char encoded like this:
4357 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4358 * are the length read. The decoded character is stored in <c>.
4359 */
4360unsigned char utf8_next(const char *s, int len, unsigned int *c)
4361{
4362 const unsigned char *p = (unsigned char *)s;
4363 int dec;
4364 unsigned char code = UTF8_CODE_OK;
4365
4366 if (len < 1)
4367 return UTF8_CODE_OK;
4368
4369 /* Check the type of UTF8 sequence
4370 *
4371 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4372 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4373 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4374 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4375 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4376 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4377 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4378 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4379 */
4380 switch (*p) {
4381 case 0x00 ... 0x7f:
4382 *c = *p;
4383 return UTF8_CODE_OK | 1;
4384
4385 case 0x80 ... 0xbf:
4386 *c = *p;
4387 return UTF8_CODE_BADSEQ | 1;
4388
4389 case 0xc0 ... 0xdf:
4390 if (len < 2) {
4391 *c = *p;
4392 return UTF8_CODE_BADSEQ | 1;
4393 }
4394 *c = *p & 0x1f;
4395 dec = 1;
4396 break;
4397
4398 case 0xe0 ... 0xef:
4399 if (len < 3) {
4400 *c = *p;
4401 return UTF8_CODE_BADSEQ | 1;
4402 }
4403 *c = *p & 0x0f;
4404 dec = 2;
4405 break;
4406
4407 case 0xf0 ... 0xf7:
4408 if (len < 4) {
4409 *c = *p;
4410 return UTF8_CODE_BADSEQ | 1;
4411 }
4412 *c = *p & 0x07;
4413 dec = 3;
4414 break;
4415
4416 case 0xf8 ... 0xfb:
4417 if (len < 5) {
4418 *c = *p;
4419 return UTF8_CODE_BADSEQ | 1;
4420 }
4421 *c = *p & 0x03;
4422 dec = 4;
4423 break;
4424
4425 case 0xfc ... 0xfd:
4426 if (len < 6) {
4427 *c = *p;
4428 return UTF8_CODE_BADSEQ | 1;
4429 }
4430 *c = *p & 0x01;
4431 dec = 5;
4432 break;
4433
4434 case 0xfe ... 0xff:
4435 default:
4436 *c = *p;
4437 return UTF8_CODE_BADSEQ | 1;
4438 }
4439
4440 p++;
4441
4442 while (dec > 0) {
4443
4444 /* need 0x10 for the 2 first bits */
4445 if ( ( *p & 0xc0 ) != 0x80 )
4446 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4447
4448 /* add data at char */
4449 *c = ( *c << 6 ) | ( *p & 0x3f );
4450
4451 dec--;
4452 p++;
4453 }
4454
4455 /* Check ovelong encoding.
4456 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4457 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4458 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4459 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004460 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004461 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4462 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4463 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4464 code |= UTF8_CODE_OVERLONG;
4465
4466 /* Check invalid UTF8 range. */
4467 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4468 (*c >= 0xfffe && *c <= 0xffff))
4469 code |= UTF8_CODE_INVRANGE;
4470
4471 return code | ((p-(unsigned char *)s)&0x0f);
4472}
4473
Maxime de Roucydc887852016-05-13 23:52:54 +02004474/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4475 * On failure : return 0 and <err> filled with an error message.
4476 * The caller is responsible for freeing the <err> and <str> copy
4477 * memory area using free()
4478 */
4479int list_append_word(struct list *li, const char *str, char **err)
4480{
4481 struct wordlist *wl;
4482
4483 wl = calloc(1, sizeof(*wl));
4484 if (!wl) {
4485 memprintf(err, "out of memory");
4486 goto fail_wl;
4487 }
4488
4489 wl->s = strdup(str);
4490 if (!wl->s) {
4491 memprintf(err, "out of memory");
4492 goto fail_wl_s;
4493 }
4494
Willy Tarreau2b718102021-04-21 07:32:39 +02004495 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004496
4497 return 1;
4498
4499fail_wl_s:
4500 free(wl->s);
4501fail_wl:
4502 free(wl);
4503 return 0;
4504}
4505
Willy Tarreau37101052019-05-20 16:48:20 +02004506/* indicates if a memory location may safely be read or not. The trick consists
4507 * in performing a harmless syscall using this location as an input and letting
4508 * the operating system report whether it's OK or not. For this we have the
4509 * stat() syscall, which will return EFAULT when the memory location supposed
4510 * to contain the file name is not readable. If it is readable it will then
4511 * either return 0 if the area contains an existing file name, or -1 with
4512 * another code. This must not be abused, and some audit systems might detect
4513 * this as abnormal activity. It's used only for unsafe dumps.
4514 */
4515int may_access(const void *ptr)
4516{
4517 struct stat buf;
4518
4519 if (stat(ptr, &buf) == 0)
4520 return 1;
4521 if (errno == EFAULT)
4522 return 0;
4523 return 1;
4524}
4525
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004526/* print a string of text buffer to <out>. The format is :
4527 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4528 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4529 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4530 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004531int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004532{
4533 unsigned char c;
Tim Duesterhuscd5521e2021-08-29 00:58:22 +02004534 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004535
Tim Duesterhuscd5521e2021-08-29 00:58:22 +02004536 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004537 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004538 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004539 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004540 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004541 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004542 }
4543 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004544 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004545 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004546 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004547 switch (c) {
4548 case ' ': c = ' '; break;
4549 case '\t': c = 't'; break;
4550 case '\n': c = 'n'; break;
4551 case '\r': c = 'r'; break;
4552 case '\e': c = 'e'; break;
4553 case '\\': c = '\\'; break;
4554 case '=': c = '='; break;
4555 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004556 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004557 }
4558 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004559 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004560 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004561 out->area[out->data++] = '\\';
4562 out->area[out->data++] = 'x';
4563 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4564 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004565 }
4566 ptr++;
4567 }
4568
4569 return ptr;
4570}
4571
4572/* print a buffer in hexa.
4573 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4574 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004575int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004576{
4577 unsigned char c;
4578 int ptr = 0;
4579
4580 while (ptr < bsize) {
4581 c = buf[ptr];
4582
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004583 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004584 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004585 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4586 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004587
4588 ptr++;
4589 }
4590 return ptr;
4591}
4592
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004593/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4594 * prepending each line with prefix <pfx>. The output is *not* initialized.
4595 * The output will not wrap pas the buffer's end so it is more optimal if the
4596 * caller makes sure the buffer is aligned first. A trailing zero will always
4597 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004598 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4599 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004600 */
Willy Tarreau37101052019-05-20 16:48:20 +02004601void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004602{
4603 const unsigned char *d = buf;
4604 int i, j, start;
4605
4606 d = (const unsigned char *)(((unsigned long)buf) & -16);
4607 start = ((unsigned long)buf) & 15;
4608
4609 for (i = 0; i < start + len; i += 16) {
4610 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4611
Willy Tarreau37101052019-05-20 16:48:20 +02004612 // 0: unchecked, 1: checked safe, 2: danger
4613 unsafe = !!unsafe;
4614 if (unsafe && !may_access(d + i))
4615 unsafe = 2;
4616
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004617 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004618 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004619 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004620 else if (unsafe > 1)
4621 chunk_strcat(out, "** ");
4622 else
4623 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004624
4625 if (j == 7)
4626 chunk_strcat(out, "- ");
4627 }
4628 chunk_strcat(out, " ");
4629 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004630 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004631 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004632 else if (unsafe > 1)
4633 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004634 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004635 chunk_appendf(out, "%c", d[i + j]);
4636 else
4637 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004638 }
4639 chunk_strcat(out, "\n");
4640 }
4641}
4642
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004643/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4644 * enclosed in brackets after the address itself, formatted on 14 chars
4645 * including the "0x" prefix. This is meant to be used as a prefix for code
4646 * areas. For example:
4647 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4648 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4649 * is emitted. A NULL <pfx> will be considered empty.
4650 */
4651void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4652{
4653 int ok = 0;
4654 int i;
4655
4656 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4657
4658 for (i = 0; i < n; i++) {
4659 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4660 ok = may_access(addr + i);
4661 if (ok)
4662 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4663 else
4664 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4665 }
4666}
4667
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004668/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4669 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4670 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4671 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4672 * lines are respected within the limit of 70 output chars. Lines that are
4673 * continuation of a previous truncated line begin with "+" instead of " "
4674 * after the offset. The new pointer is returned.
4675 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004676int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004677 int *line, int ptr)
4678{
4679 int end;
4680 unsigned char c;
4681
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004682 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004683 if (end > out->size)
4684 return ptr;
4685
4686 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4687
4688 while (ptr < len && ptr < bsize) {
4689 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004690 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004691 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004692 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004693 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004694 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004695 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004696 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004697 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004698 switch (c) {
4699 case '\t': c = 't'; break;
4700 case '\n': c = 'n'; break;
4701 case '\r': c = 'r'; break;
4702 case '\e': c = 'e'; break;
4703 case '\\': c = '\\'; break;
4704 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004705 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004706 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004707 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004708 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004709 out->area[out->data++] = '\\';
4710 out->area[out->data++] = 'x';
4711 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4712 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004713 }
4714 if (buf[ptr++] == '\n') {
4715 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004716 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004717 *line = ptr;
4718 return ptr;
4719 }
4720 }
4721 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004722 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004723 return ptr;
4724}
4725
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004726/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004727 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4728 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004729 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004730void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4731 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004732{
Willy Tarreau73459792017-04-11 07:58:08 +02004733 unsigned int i;
4734 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004735
4736 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4737 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004738 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004739 for (j = 0; j < 8; j++) {
4740 if (b + j >= 0 && b + j < len)
4741 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4742 else
4743 fprintf(out, " ");
4744 }
4745
4746 if (b + j >= 0 && b + j < len)
4747 fputc('-', out);
4748 else
4749 fputc(' ', out);
4750
4751 for (j = 8; j < 16; j++) {
4752 if (b + j >= 0 && b + j < len)
4753 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4754 else
4755 fprintf(out, " ");
4756 }
4757
4758 fprintf(out, " ");
4759 for (j = 0; j < 16; j++) {
4760 if (b + j >= 0 && b + j < len) {
4761 if (isprint((unsigned char)buf[b + j]))
4762 fputc((unsigned char)buf[b + j], out);
4763 else
4764 fputc('.', out);
4765 }
4766 else
4767 fputc(' ', out);
4768 }
4769 fputc('\n', out);
4770 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004771}
4772
Willy Tarreaubb869862020-04-16 10:52:41 +02004773/* Tries to report the executable path name on platforms supporting this. If
4774 * not found or not possible, returns NULL.
4775 */
4776const char *get_exec_path()
4777{
4778 const char *ret = NULL;
4779
Willy Tarreau1ee71dd2021-08-30 10:15:35 +02004780#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004781 long execfn = getauxval(AT_EXECFN);
4782
4783 if (execfn && execfn != ENOENT)
4784 ret = (const char *)execfn;
devnexen@gmail.com49a32282021-08-17 12:55:49 +01004785#elif defined(__FreeBSD__)
4786 Elf_Auxinfo *auxv;
4787 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4788 if (auxv->a_type == AT_EXECPATH) {
4789 ret = (const char *)auxv->a_un.a_ptr;
4790 break;
4791 }
4792 }
David Carlier1b9d57d2021-08-17 08:44:25 +01004793#elif defined(__NetBSD__)
4794 AuxInfo *auxv;
4795 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4796 if (auxv->a_type == AT_SUN_EXECNAME) {
4797 ret = (const char *)auxv->a_v;
4798 break;
4799 }
4800 }
Willy Tarreaubb869862020-04-16 10:52:41 +02004801#endif
4802 return ret;
4803}
4804
Baruch Siache1651b22020-07-24 07:52:20 +03004805#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004806/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4807 * also returns the symbol size in <size>, otherwise returns 0 there.
4808 */
4809static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4810{
4811 int ret;
Willy Tarreau1ee71dd2021-08-30 10:15:35 +02004812#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004813 const ElfW(Sym) *sym;
4814
4815 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4816 if (ret)
4817 *size = sym ? sym->st_size : 0;
4818#else
David Carlier7b6de262021-12-31 08:15:29 +00004819#if defined(__sun)
4820 ret = dladdr((void *)addr, dli);
4821#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004822 ret = dladdr(addr, dli);
David Carlier7b6de262021-12-31 08:15:29 +00004823#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004824 *size = 0;
4825#endif
4826 return ret;
4827}
Willy Tarreau64192392021-05-05 09:06:21 +02004828
4829/* Tries to retrieve the address of the first occurrence symbol <name>.
4830 * Note that NULL in return is not always an error as a symbol may have that
4831 * address in special situations.
4832 */
4833void *get_sym_curr_addr(const char *name)
4834{
4835 void *ptr = NULL;
4836
4837#ifdef RTLD_DEFAULT
4838 ptr = dlsym(RTLD_DEFAULT, name);
4839#endif
4840 return ptr;
4841}
4842
4843
4844/* Tries to retrieve the address of the next occurrence of symbol <name>
4845 * Note that NULL in return is not always an error as a symbol may have that
4846 * address in special situations.
4847 */
4848void *get_sym_next_addr(const char *name)
4849{
4850 void *ptr = NULL;
4851
4852#ifdef RTLD_NEXT
4853 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004854#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004855 return ptr;
4856}
4857
4858#else /* elf & linux & dl */
4859
4860/* no possible resolving on other platforms at the moment */
4861void *get_sym_curr_addr(const char *name)
4862{
4863 return NULL;
4864}
4865
4866void *get_sym_next_addr(const char *name)
4867{
4868 return NULL;
4869}
4870
4871#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004872
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004873/* Tries to append to buffer <buf> some indications about the symbol at address
4874 * <addr> using the following form:
4875 * lib:+0xoffset (unresolvable address from lib's base)
4876 * main+0xoffset (unresolvable address from main (+/-))
4877 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4878 * name (resolved exact exec address)
4879 * lib:name (resolved exact lib address)
4880 * name+0xoffset/0xsize (resolved address within exec symbol)
4881 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4882 *
4883 * The file name (lib or executable) is limited to what lies between the last
4884 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4885 * 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 +03004886 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004887 *
4888 * The symbol's base address is returned, or NULL when unresolved, in order to
4889 * allow the caller to match it against known ones.
4890 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004891const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004892{
4893 const struct {
4894 const void *func;
4895 const char *name;
4896 } fcts[] = {
4897 { .func = process_stream, .name = "process_stream" },
4898 { .func = task_run_applet, .name = "task_run_applet" },
4899 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004900 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004901 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4902 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004903 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004904 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4905 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004906 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004907#ifdef USE_THREAD
4908 { .func = accept_queue_process, .name = "accept_queue_process" },
4909#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004910#ifdef USE_LUA
4911 { .func = hlua_process_task, .name = "hlua_process_task" },
4912#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004913#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004914 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4915 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4916#endif
4917 };
4918
Baruch Siache1651b22020-07-24 07:52:20 +03004919#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004920 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004921 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004922 const char *fname, *p;
4923#endif
4924 int i;
4925
4926 if (pfx)
4927 chunk_appendf(buf, "%s", pfx);
4928
4929 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4930 if (addr == fcts[i].func) {
4931 chunk_appendf(buf, "%s", fcts[i].name);
4932 return addr;
4933 }
4934 }
4935
Baruch Siache1651b22020-07-24 07:52:20 +03004936#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004937 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004938 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004939 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004940
4941 /* 1. prefix the library name if it's not the same object as the one
4942 * that contains the main function. The name is picked between last '/'
4943 * and first following '.'.
4944 */
4945 if (!dladdr(main, &dli_main))
4946 dli_main.dli_fbase = NULL;
4947
4948 if (dli_main.dli_fbase != dli.dli_fbase) {
4949 fname = dli.dli_fname;
4950 p = strrchr(fname, '/');
4951 if (p++)
4952 fname = p;
4953 p = strchr(fname, '.');
4954 if (!p)
4955 p = fname + strlen(fname);
4956
4957 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4958 }
4959
4960 /* 2. symbol name */
4961 if (dli.dli_sname) {
4962 /* known, dump it and return symbol's address (exact or relative) */
4963 chunk_appendf(buf, "%s", dli.dli_sname);
4964 if (addr != dli.dli_saddr) {
4965 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004966 if (size)
4967 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004968 }
4969 return dli.dli_saddr;
4970 }
4971 else if (dli_main.dli_fbase != dli.dli_fbase) {
4972 /* unresolved symbol from a known library, report relative offset */
4973 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4974 return NULL;
4975 }
Baruch Siache1651b22020-07-24 07:52:20 +03004976#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004977 unknown:
4978 /* unresolved symbol from the main file, report relative offset to main */
4979 if ((void*)addr < (void*)main)
4980 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4981 else
4982 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4983 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004984}
4985
Willy Tarreau37857332021-12-28 09:57:10 +01004986/* On systems where this is supported, let's provide a possibility to enumerate
4987 * the list of object files. The output is appended to a buffer initialized by
4988 * the caller, with one name per line. A trailing zero is always emitted if data
4989 * are written. Only real objects are dumped (executable and .so libs). The
4990 * function returns non-zero if it dumps anything. These functions do not make
4991 * use of the trash so that it is possible for the caller to call them with the
4992 * trash on input. The output format may be platform-specific but at least one
4993 * version must emit raw object file names when argument is zero.
4994 */
4995#if defined(HA_HAVE_DUMP_LIBS)
4996# if defined(HA_HAVE_DL_ITERATE_PHDR)
4997/* the private <data> we pass below is a dump context initialized like this */
4998struct dl_dump_ctx {
4999 struct buffer *buf;
5000 int with_addr;
5001};
5002
5003static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5004{
5005 struct dl_dump_ctx *ctx = data;
5006 const char *fname;
5007 size_t p1, p2, beg, end;
5008 int idx;
5009
5010 if (!info || !info->dlpi_name)
5011 goto leave;
5012
5013 if (!*info->dlpi_name)
5014 fname = get_exec_path();
5015 else if (strchr(info->dlpi_name, '/'))
5016 fname = info->dlpi_name;
5017 else
5018 /* else it's a VDSO or similar and we're not interested */
5019 goto leave;
5020
5021 if (!ctx->with_addr)
5022 goto dump_name;
5023
5024 /* virtual addresses are relative to the load address and are per
5025 * pseudo-header, so we have to scan them all to find the furthest
5026 * one from the beginning. In this case we only dump entries if
5027 * they have at least one section.
5028 */
5029 beg = ~0; end = 0;
5030 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5031 if (!info->dlpi_phdr[idx].p_memsz)
5032 continue;
5033 p1 = info->dlpi_phdr[idx].p_vaddr;
5034 if (p1 < beg)
5035 beg = p1;
5036 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5037 if (p2 > end)
5038 end = p2;
5039 }
5040
5041 if (!idx)
5042 goto leave;
5043
5044 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5045 (ullong)info->dlpi_addr + beg,
5046 (ullong)info->dlpi_addr + end,
5047 (ullong)(end - beg + 1));
5048 dump_name:
5049 chunk_appendf(ctx->buf, "%s\n", fname);
5050 leave:
5051 return 0;
5052}
5053
5054/* dumps lib names and optionally address ranges */
5055int dump_libs(struct buffer *output, int with_addr)
5056{
5057 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5058 size_t old_data = output->data;
5059
5060 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5061 return output->data != old_data;
5062}
5063# else // no DL_ITERATE_PHDR
5064# error "No dump_libs() function for this platform"
5065# endif
5066#else // no HA_HAVE_DUMP_LIBS
5067
5068/* unsupported platform: do not dump anything */
5069int dump_libs(struct buffer *output, int with_addr)
5070{
5071 return 0;
5072}
5073
5074#endif // HA_HAVE_DUMP_LIBS
5075
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005076/*
5077 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005078 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005079 *
5080 * First, initializes the value with <sz> as address to 0 and initializes the
5081 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5082 * address updating <sz> pointed value to the size of this array.
5083 *
5084 * Returns 1 if succeeded, 0 if not.
5085 */
5086int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5087{
5088 unsigned int *n;
5089 const char *s, *end;
5090
5091 s = str;
5092 *sz = 0;
5093 end = str + strlen(str);
5094 *nums = n = NULL;
5095
5096 while (1) {
5097 unsigned int r;
5098
5099 if (s >= end)
5100 break;
5101
5102 r = read_uint(&s, end);
5103 /* Expected characters after having read an uint: '\0' or '.',
5104 * if '.', must not be terminal.
5105 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005106 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5107 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005108 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005109 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005110
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005111 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005112 if (!n)
5113 return 0;
5114
5115 n[(*sz)++] = r;
5116 }
5117 *nums = n;
5118
5119 return 1;
5120}
5121
Willy Tarreau4d589e72019-08-23 19:02:26 +02005122
5123/* returns the number of bytes needed to encode <v> as a varint. An inline
5124 * version exists for use with constants (__varint_bytes()).
5125 */
5126int varint_bytes(uint64_t v)
5127{
5128 int len = 1;
5129
5130 if (v >= 240) {
5131 v = (v - 240) >> 4;
5132 while (1) {
5133 len++;
5134 if (v < 128)
5135 break;
5136 v = (v - 128) >> 7;
5137 }
5138 }
5139 return len;
5140}
5141
Willy Tarreau52bf8392020-03-08 00:42:37 +01005142
5143/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005144static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005145
5146/* This is a thread-safe implementation of xoroshiro128** described below:
5147 * http://prng.di.unimi.it/
5148 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5149 * supports fast jumps and passes all common quality tests. It is thread-safe,
5150 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5151 * local lock on other ones.
5152 */
5153uint64_t ha_random64()
5154{
Willy Tarreau1544c142020-03-12 00:31:18 +01005155 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5156 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005157
5158#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5159 static HA_SPINLOCK_T rand_lock;
5160
5161 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5162#endif
5163
5164 old[0] = ha_random_state[0];
5165 old[1] = ha_random_state[1];
5166
5167#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5168 do {
5169#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005170 new[1] = old[0] ^ old[1];
5171 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5172 new[1] = rotl64(new[1], 37); // c
5173
5174#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5175 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5176#else
5177 ha_random_state[0] = new[0];
5178 ha_random_state[1] = new[1];
5179#if defined(USE_THREAD)
5180 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5181#endif
5182#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005183 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005184}
5185
5186/* seeds the random state using up to <len> bytes from <seed>, starting with
5187 * the first non-zero byte.
5188 */
5189void ha_random_seed(const unsigned char *seed, size_t len)
5190{
5191 size_t pos;
5192
5193 /* the seed must not be all zeroes, so we pre-fill it with alternating
5194 * bits and overwrite part of them with the block starting at the first
5195 * non-zero byte from the seed.
5196 */
5197 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5198
5199 for (pos = 0; pos < len; pos++)
5200 if (seed[pos] != 0)
5201 break;
5202
5203 if (pos == len)
5204 return;
5205
5206 seed += pos;
5207 len -= pos;
5208
5209 if (len > sizeof(ha_random_state))
5210 len = sizeof(ha_random_state);
5211
5212 memcpy(ha_random_state, seed, len);
5213}
5214
5215/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5216 * and is equivalent to calling ha_random64() as many times. It is used to
5217 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5218 * different generators (i.e. different processes after a fork). The <dist>
5219 * argument is the distance to jump to and is used in a loop so it rather not
5220 * be too large if the processing time is a concern.
5221 *
5222 * BEWARE: this function is NOT thread-safe and must not be called during
5223 * concurrent accesses to ha_random64().
5224 */
5225void ha_random_jump96(uint32_t dist)
5226{
5227 while (dist--) {
5228 uint64_t s0 = 0;
5229 uint64_t s1 = 0;
5230 int b;
5231
5232 for (b = 0; b < 64; b++) {
5233 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5234 s0 ^= ha_random_state[0];
5235 s1 ^= ha_random_state[1];
5236 }
5237 ha_random64();
5238 }
5239
5240 for (b = 0; b < 64; b++) {
5241 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5242 s0 ^= ha_random_state[0];
5243 s1 ^= ha_random_state[1];
5244 }
5245 ha_random64();
5246 }
5247 ha_random_state[0] = s0;
5248 ha_random_state[1] = s1;
5249 }
5250}
5251
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005252/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5253 * bytes large.
5254 */
5255void ha_generate_uuid(struct buffer *output)
5256{
5257 uint32_t rnd[4];
5258 uint64_t last;
5259
5260 last = ha_random64();
5261 rnd[0] = last;
5262 rnd[1] = last >> 32;
5263
5264 last = ha_random64();
5265 rnd[2] = last;
5266 rnd[3] = last >> 32;
5267
5268 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5269 rnd[0],
5270 rnd[1] & 0xFFFF,
5271 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5272 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5273 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5274}
5275
5276
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005277/* only used by parse_line() below. It supports writing in place provided that
5278 * <in> is updated to the next location before calling it. In that case, the
5279 * char at <in> may be overwritten.
5280 */
5281#define EMIT_CHAR(x) \
5282 do { \
5283 char __c = (char)(x); \
5284 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5285 err |= PARSE_ERR_OVERLAP; \
5286 if (outpos >= outmax) \
5287 err |= PARSE_ERR_TOOLARGE; \
5288 if (!err) \
5289 out[outpos] = __c; \
5290 outpos++; \
5291 } while (0)
5292
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005293/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005294 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5295 * extraneous ones are not emitted but <outlen> is updated so that the caller
5296 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5297 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005298 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5299 * it is guaranteed that at least one arg will point to the zero. It is safe
5300 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005301 *
5302 * <out> may overlap with <in> provided that it never goes further, in which
5303 * case the parser will accept to perform in-place parsing and unquoting/
5304 * unescaping but only if environment variables do not lead to expansion that
5305 * causes overlapping, otherwise the input string being destroyed, the error
5306 * will not be recoverable. Note that even during out-of-place <in> will
5307 * experience temporary modifications in-place for variable resolution and must
5308 * be writable, and will also receive zeroes to delimit words when using
5309 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5310 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5311 * starting point of the first invalid character sequence or unmatched
5312 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5313 * error reporting might be difficult since zeroes will have been inserted into
5314 * the string. One solution for the caller may consist in replacing all args
5315 * delimiters with spaces in this case.
5316 */
5317uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
5318{
5319 char *quote = NULL;
5320 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005321 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005322 unsigned char hex1, hex2;
5323 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005324 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005325 size_t outpos = 0;
5326 int squote = 0;
5327 int dquote = 0;
5328 int arg = 0;
5329 uint32_t err = 0;
5330
5331 *nbargs = 0;
5332 *outlen = 0;
5333
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005334 /* argsmax may be -1 here, protecting args[] from any write */
5335 if (arg < argsmax)
5336 args[arg] = out;
5337
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005338 while (1) {
5339 if (*in >= '-' && *in != '\\') {
5340 /* speedup: directly send all regular chars starting
5341 * with '-', '.', '/', alnum etc...
5342 */
5343 EMIT_CHAR(*in++);
5344 continue;
5345 }
5346 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5347 /* end of line */
5348 break;
5349 }
5350 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5351 /* comment */
5352 break;
5353 }
5354 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5355 if (dquote) {
5356 dquote = 0;
5357 quote = NULL;
5358 }
5359 else {
5360 dquote = 1;
5361 quote = in;
5362 }
5363 in++;
5364 continue;
5365 }
5366 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5367 if (squote) {
5368 squote = 0;
5369 quote = NULL;
5370 }
5371 else {
5372 squote = 1;
5373 quote = in;
5374 }
5375 in++;
5376 continue;
5377 }
5378 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5379 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5380 * C equivalent value but only when they have a special meaning and within
5381 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5382 */
5383 char tosend = *in;
5384
5385 switch (in[1]) {
5386 case ' ':
5387 case '\\':
5388 tosend = in[1];
5389 in++;
5390 break;
5391
5392 case 't':
5393 tosend = '\t';
5394 in++;
5395 break;
5396
5397 case 'n':
5398 tosend = '\n';
5399 in++;
5400 break;
5401
5402 case 'r':
5403 tosend = '\r';
5404 in++;
5405 break;
5406
5407 case '#':
5408 /* escaping of "#" only if comments are supported */
5409 if (opts & PARSE_OPT_SHARP)
5410 in++;
5411 tosend = *in;
5412 break;
5413
5414 case '\'':
5415 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5416 if (opts & PARSE_OPT_SQUOTE && !squote)
5417 in++;
5418 tosend = *in;
5419 break;
5420
5421 case '"':
5422 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5423 if (opts & PARSE_OPT_DQUOTE && !squote)
5424 in++;
5425 tosend = *in;
5426 break;
5427
5428 case '$':
5429 /* escaping of '$' only inside double quotes and only if env supported */
5430 if (opts & PARSE_OPT_ENV && dquote)
5431 in++;
5432 tosend = *in;
5433 break;
5434
5435 case 'x':
5436 if (!ishex(in[2]) || !ishex(in[3])) {
5437 /* invalid or incomplete hex sequence */
5438 err |= PARSE_ERR_HEX;
5439 if (errptr)
5440 *errptr = in;
5441 goto leave;
5442 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005443 hex1 = toupper((unsigned char)in[2]) - '0';
5444 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005445 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5446 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5447 tosend = (hex1 << 4) + hex2;
5448 in += 3;
5449 break;
5450
5451 default:
5452 /* other combinations are not escape sequences */
5453 break;
5454 }
5455
5456 in++;
5457 EMIT_CHAR(tosend);
5458 }
5459 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5460 /* a non-escaped space is an argument separator */
5461 while (isspace((unsigned char)*in))
5462 in++;
5463 EMIT_CHAR(0);
5464 arg++;
5465 if (arg < argsmax)
5466 args[arg] = out + outpos;
5467 else
5468 err |= PARSE_ERR_TOOMANY;
5469 }
5470 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5471 /* environment variables are evaluated anywhere, or only
5472 * inside double quotes if they are supported.
5473 */
5474 char *var_name;
5475 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005476 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005477
5478 in++;
5479
5480 if (*in == '{')
5481 brace = in++;
5482
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005483 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005484 /* unacceptable character in variable name */
5485 err |= PARSE_ERR_VARNAME;
5486 if (errptr)
5487 *errptr = in;
5488 goto leave;
5489 }
5490
5491 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005492 if (*in == '.')
5493 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005494 while (isalnum((unsigned char)*in) || *in == '_')
5495 in++;
5496
5497 save_char = *in;
5498 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005499 if (unlikely(*var_name == '.')) {
5500 /* internal pseudo-variables */
5501 if (strcmp(var_name, ".LINE") == 0)
5502 value = ultoa(global.cfg_curr_line);
5503 else if (strcmp(var_name, ".FILE") == 0)
5504 value = global.cfg_curr_file;
5505 else if (strcmp(var_name, ".SECTION") == 0)
5506 value = global.cfg_curr_section;
5507 else {
5508 /* unsupported internal variable name */
5509 err |= PARSE_ERR_VARNAME;
5510 if (errptr)
5511 *errptr = var_name;
5512 goto leave;
5513 }
5514 } else {
5515 value = getenv(var_name);
5516 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005517 *in = save_char;
5518
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005519 /* support for '[*]' sequence to force word expansion,
5520 * only available inside braces */
5521 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5522 word_expand = in++;
5523
5524 if (*in++ != '*' || *in++ != ']') {
5525 err |= PARSE_ERR_WRONG_EXPAND;
5526 if (errptr)
5527 *errptr = word_expand;
5528 goto leave;
5529 }
5530 }
5531
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005532 if (brace) {
5533 if (*in != '}') {
5534 /* unmatched brace */
5535 err |= PARSE_ERR_BRACE;
5536 if (errptr)
5537 *errptr = brace;
5538 goto leave;
5539 }
5540 in++;
5541 brace = NULL;
5542 }
5543
5544 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005545 while (*value) {
5546 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005547 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005548 EMIT_CHAR(0);
5549 ++arg;
5550 if (arg < argsmax)
5551 args[arg] = out + outpos;
5552 else
5553 err |= PARSE_ERR_TOOMANY;
5554
5555 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005556 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005557 ;
5558 } else {
5559 EMIT_CHAR(*value++);
5560 }
5561 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005562 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005563 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005564 }
5565 else {
5566 /* any other regular char */
5567 EMIT_CHAR(*in++);
5568 }
5569 }
5570
5571 /* end of output string */
5572 EMIT_CHAR(0);
5573 arg++;
5574
5575 if (quote) {
5576 /* unmatched quote */
5577 err |= PARSE_ERR_QUOTE;
5578 if (errptr)
5579 *errptr = quote;
5580 goto leave;
5581 }
5582 leave:
5583 *nbargs = arg;
5584 *outlen = outpos;
5585
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005586 /* empty all trailing args by making them point to the trailing zero,
5587 * at least the last one in any case.
5588 */
5589 if (arg > argsmax)
5590 arg = argsmax;
5591
5592 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005593 args[arg++] = out + outpos - 1;
5594
5595 return err;
5596}
5597#undef EMIT_CHAR
5598
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005599/* This is used to sanitize an input line that's about to be used for error reporting.
5600 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5601 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5602 * If non-printable chars are present in the output. It returns the new offset <pos>
5603 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5604 * be at least 6 to support two "..." otherwise the result is undefined. The line
5605 * itself must have at least 7 chars allocated for the same reason.
5606 */
5607size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5608{
5609 size_t shift = 0;
5610 char *out = line;
5611 char *in = line;
5612 char *end = line + width;
5613
5614 if (pos >= width) {
5615 /* if we have to shift, we'll be out of context, so let's
5616 * try to put <pos> at the center of width.
5617 */
5618 shift = pos - width / 2;
5619 in += shift + 3;
5620 end = out + width - 3;
5621 out[0] = out[1] = out[2] = '.';
5622 out += 3;
5623 }
5624
5625 while (out < end && *in) {
5626 if (isspace((unsigned char)*in))
5627 *out++ = ' ';
5628 else if (isprint((unsigned char)*in))
5629 *out++ = *in;
5630 else
5631 *out++ = '?';
5632 in++;
5633 }
5634
5635 if (end < line + width) {
5636 out[0] = out[1] = out[2] = '.';
5637 out += 3;
5638 }
5639
5640 *out++ = 0;
5641 return pos - shift;
5642}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005643
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005644/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005645 * transitions between characters. <fp> is a 1024-entries array indexed as
5646 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005647 * 1..26=letter, 27=digit, 28=other/begin/end.
5648 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005649 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005650void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005651{
5652 const char *p;
5653 int from, to;
5654 int c;
5655
Willy Tarreauba2c4452021-03-12 09:01:52 +01005656 from = 28; // begin
5657 for (p = word; *p; p++) {
5658 c = tolower(*p);
5659 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005660 case 'a'...'z': to = c - 'a' + 1; break;
5661 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5662 case '0'...'9': to = 27; break;
5663 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005664 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005665 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005666 fp[32 * from + to]++;
5667 from = to;
5668 }
5669 to = 28; // end
5670 fp[32 * from + to]++;
5671}
5672
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005673/* Initialize array <fp> with the fingerprint of word <word> by counting the
5674 * transitions between characters. <fp> is a 1024-entries array indexed as
5675 * 32*from+to. Positions for 'from' and 'to' are:
5676 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5677 */
5678void make_word_fingerprint(uint8_t *fp, const char *word)
5679{
5680 memset(fp, 0, 1024);
5681 update_word_fingerprint(fp, word);
5682}
5683
Willy Tarreauba2c4452021-03-12 09:01:52 +01005684/* Return the distance between two word fingerprints created by function
5685 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005686 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005687 */
5688int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5689{
5690 int i, k, dist = 0;
5691
5692 for (i = 0; i < 1024; i++) {
5693 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005694 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005695 }
5696 return dist;
5697}
5698
Willy Tarreau06e69b52021-03-02 14:01:35 +01005699static int init_tools_per_thread()
5700{
5701 /* Let's make each thread start from a different position */
5702 statistical_prng_state += tid * MAX_THREADS;
5703 if (!statistical_prng_state)
5704 statistical_prng_state++;
5705 return 1;
5706}
5707REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005708
Willy Tarreaubaaee002006-06-26 02:48:02 +02005709/*
5710 * Local variables:
5711 * c-indent-level: 8
5712 * c-basic-offset: 8
5713 * End:
5714 */