blob: 7d2b4ea3dfa3bc5fd7f3b45ed585c2a86a3b4ce5 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
devnexen@gmail.comc4e52322021-08-17 12:55:49 +010019#if defined(__FreeBSD__)
20#include <elf.h>
21#include <dlfcn.h>
22extern void *__elf_aux_vector;
23#endif
24
David Carlierbd2cced2021-08-17 08:44:25 +010025#if defined(__NetBSD__)
26#include <sys/exec_elf.h>
27#include <dlfcn.h>
28#endif
29
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010030#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020033#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020034#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035#include <stdlib.h>
36#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010037#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020038#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010039#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020040#include <sys/stat.h>
41#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010042#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020043#include <netinet/in.h>
44#include <arpa/inet.h>
45
David Carlier43a56852022-03-04 15:50:48 +000046#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreau30053062020-08-20 16:39:14 +020047#include <sys/auxv.h>
48#endif
49
Willy Tarreau48fbcae2020-06-03 18:09:46 +020050#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020052
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020053#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020054#include <haproxy/chunk.h>
Christopher Faulet5e29b762022-04-04 08:58:34 +020055#include <haproxy/conn_stream.h>
56#include <haproxy/cs_utils.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020057#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020058#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020059#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020060#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020061#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010062#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020063#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010064#include <haproxy/resolvers.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010065#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020066#include <haproxy/ssl_sock.h>
William Lallemand3aeb3f92021-08-21 23:59:56 +020067#include <haproxy/ssl_utils.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020068#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020069#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010070
Thierry Fournier93127942016-01-20 18:49:45 +010071/* This macro returns false if the test __x is false. Many
72 * of the following parsing function must be abort the processing
73 * if it returns 0, so this macro is useful for writing light code.
74 */
75#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
76
Willy Tarreau56adcf22012-12-23 18:00:29 +010077/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020078 * 2^64-1 = 18446744073709551615 or
79 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020080 *
81 * The HTML version needs room for adding the 25 characters
82 * '<span class="rls"></span>' around digits at positions 3N+1 in order
83 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020084 */
Christopher Faulet99bca652017-11-14 16:47:26 +010085THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
86THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020087
Willy Tarreau588297f2014-06-16 15:16:40 +020088/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
89 * to quote strings larger than a max configuration line.
90 */
Christopher Faulet99bca652017-11-14 16:47:26 +010091THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
92THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020093
Willy Tarreau06e69b52021-03-02 14:01:35 +010094/* thread-local PRNG state. It's modified to start from a different sequence
95 * on all threads upon startup. It must not be used or anything beyond getting
96 * statistical values as it's 100% predictable.
97 */
98THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
99
Willy Tarreaubaaee002006-06-26 02:48:02 +0200100/*
William Lallemande7340ec2012-01-24 11:15:39 +0100101 * unsigned long long ASCII representation
102 *
103 * return the last char '\0' or NULL if no enough
104 * space in dst
105 */
106char *ulltoa(unsigned long long n, char *dst, size_t size)
107{
108 int i = 0;
109 char *res;
110
111 switch(n) {
112 case 1ULL ... 9ULL:
113 i = 0;
114 break;
115
116 case 10ULL ... 99ULL:
117 i = 1;
118 break;
119
120 case 100ULL ... 999ULL:
121 i = 2;
122 break;
123
124 case 1000ULL ... 9999ULL:
125 i = 3;
126 break;
127
128 case 10000ULL ... 99999ULL:
129 i = 4;
130 break;
131
132 case 100000ULL ... 999999ULL:
133 i = 5;
134 break;
135
136 case 1000000ULL ... 9999999ULL:
137 i = 6;
138 break;
139
140 case 10000000ULL ... 99999999ULL:
141 i = 7;
142 break;
143
144 case 100000000ULL ... 999999999ULL:
145 i = 8;
146 break;
147
148 case 1000000000ULL ... 9999999999ULL:
149 i = 9;
150 break;
151
152 case 10000000000ULL ... 99999999999ULL:
153 i = 10;
154 break;
155
156 case 100000000000ULL ... 999999999999ULL:
157 i = 11;
158 break;
159
160 case 1000000000000ULL ... 9999999999999ULL:
161 i = 12;
162 break;
163
164 case 10000000000000ULL ... 99999999999999ULL:
165 i = 13;
166 break;
167
168 case 100000000000000ULL ... 999999999999999ULL:
169 i = 14;
170 break;
171
172 case 1000000000000000ULL ... 9999999999999999ULL:
173 i = 15;
174 break;
175
176 case 10000000000000000ULL ... 99999999999999999ULL:
177 i = 16;
178 break;
179
180 case 100000000000000000ULL ... 999999999999999999ULL:
181 i = 17;
182 break;
183
184 case 1000000000000000000ULL ... 9999999999999999999ULL:
185 i = 18;
186 break;
187
188 case 10000000000000000000ULL ... ULLONG_MAX:
189 i = 19;
190 break;
191 }
192 if (i + 2 > size) // (i + 1) + '\0'
193 return NULL; // too long
194 res = dst + i + 1;
195 *res = '\0';
196 for (; i >= 0; i--) {
197 dst[i] = n % 10ULL + '0';
198 n /= 10ULL;
199 }
200 return res;
201}
202
203/*
204 * unsigned long ASCII representation
205 *
206 * return the last char '\0' or NULL if no enough
207 * space in dst
208 */
209char *ultoa_o(unsigned long n, char *dst, size_t size)
210{
211 int i = 0;
212 char *res;
213
214 switch (n) {
215 case 0U ... 9UL:
216 i = 0;
217 break;
218
219 case 10U ... 99UL:
220 i = 1;
221 break;
222
223 case 100U ... 999UL:
224 i = 2;
225 break;
226
227 case 1000U ... 9999UL:
228 i = 3;
229 break;
230
231 case 10000U ... 99999UL:
232 i = 4;
233 break;
234
235 case 100000U ... 999999UL:
236 i = 5;
237 break;
238
239 case 1000000U ... 9999999UL:
240 i = 6;
241 break;
242
243 case 10000000U ... 99999999UL:
244 i = 7;
245 break;
246
247 case 100000000U ... 999999999UL:
248 i = 8;
249 break;
250#if __WORDSIZE == 32
251
252 case 1000000000ULL ... ULONG_MAX:
253 i = 9;
254 break;
255
256#elif __WORDSIZE == 64
257
258 case 1000000000ULL ... 9999999999UL:
259 i = 9;
260 break;
261
262 case 10000000000ULL ... 99999999999UL:
263 i = 10;
264 break;
265
266 case 100000000000ULL ... 999999999999UL:
267 i = 11;
268 break;
269
270 case 1000000000000ULL ... 9999999999999UL:
271 i = 12;
272 break;
273
274 case 10000000000000ULL ... 99999999999999UL:
275 i = 13;
276 break;
277
278 case 100000000000000ULL ... 999999999999999UL:
279 i = 14;
280 break;
281
282 case 1000000000000000ULL ... 9999999999999999UL:
283 i = 15;
284 break;
285
286 case 10000000000000000ULL ... 99999999999999999UL:
287 i = 16;
288 break;
289
290 case 100000000000000000ULL ... 999999999999999999UL:
291 i = 17;
292 break;
293
294 case 1000000000000000000ULL ... 9999999999999999999UL:
295 i = 18;
296 break;
297
298 case 10000000000000000000ULL ... ULONG_MAX:
299 i = 19;
300 break;
301
302#endif
303 }
304 if (i + 2 > size) // (i + 1) + '\0'
305 return NULL; // too long
306 res = dst + i + 1;
307 *res = '\0';
308 for (; i >= 0; i--) {
309 dst[i] = n % 10U + '0';
310 n /= 10U;
311 }
312 return res;
313}
314
315/*
316 * signed long ASCII representation
317 *
318 * return the last char '\0' or NULL if no enough
319 * space in dst
320 */
321char *ltoa_o(long int n, char *dst, size_t size)
322{
323 char *pos = dst;
324
325 if (n < 0) {
326 if (size < 3)
327 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
328 *pos = '-';
329 pos++;
330 dst = ultoa_o(-n, pos, size - 1);
331 } else {
332 dst = ultoa_o(n, dst, size);
333 }
334 return dst;
335}
336
337/*
338 * signed long long ASCII representation
339 *
340 * return the last char '\0' or NULL if no enough
341 * space in dst
342 */
343char *lltoa(long long n, char *dst, size_t size)
344{
345 char *pos = dst;
346
347 if (n < 0) {
348 if (size < 3)
349 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
350 *pos = '-';
351 pos++;
352 dst = ulltoa(-n, pos, size - 1);
353 } else {
354 dst = ulltoa(n, dst, size);
355 }
356 return dst;
357}
358
359/*
360 * write a ascii representation of a unsigned into dst,
361 * return a pointer to the last character
362 * Pad the ascii representation with '0', using size.
363 */
364char *utoa_pad(unsigned int n, char *dst, size_t size)
365{
366 int i = 0;
367 char *ret;
368
369 switch(n) {
370 case 0U ... 9U:
371 i = 0;
372 break;
373
374 case 10U ... 99U:
375 i = 1;
376 break;
377
378 case 100U ... 999U:
379 i = 2;
380 break;
381
382 case 1000U ... 9999U:
383 i = 3;
384 break;
385
386 case 10000U ... 99999U:
387 i = 4;
388 break;
389
390 case 100000U ... 999999U:
391 i = 5;
392 break;
393
394 case 1000000U ... 9999999U:
395 i = 6;
396 break;
397
398 case 10000000U ... 99999999U:
399 i = 7;
400 break;
401
402 case 100000000U ... 999999999U:
403 i = 8;
404 break;
405
406 case 1000000000U ... 4294967295U:
407 i = 9;
408 break;
409 }
410 if (i + 2 > size) // (i + 1) + '\0'
411 return NULL; // too long
412 if (i < size)
413 i = size - 2; // padding - '\0'
414
415 ret = dst + i + 1;
416 *ret = '\0';
417 for (; i >= 0; i--) {
418 dst[i] = n % 10U + '0';
419 n /= 10U;
420 }
421 return ret;
422}
423
424/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200425 * copies at most <size-1> chars from <src> to <dst>. Last char is always
426 * set to 0, unless <size> is 0. The number of chars copied is returned
427 * (excluding the terminating zero).
428 * This code has been optimized for size and speed : on x86, it's 45 bytes
429 * long, uses only registers, and consumes only 4 cycles per char.
430 */
431int strlcpy2(char *dst, const char *src, int size)
432{
433 char *orig = dst;
434 if (size) {
435 while (--size && (*dst = *src)) {
436 src++; dst++;
437 }
438 *dst = 0;
439 }
440 return dst - orig;
441}
442
443/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200444 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200445 * the ascii representation for number 'n' in decimal.
446 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100447char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200448{
449 char *pos;
450
Willy Tarreau72d759c2007-10-25 12:14:10 +0200451 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200452 *pos-- = '\0';
453
454 do {
455 *pos-- = '0' + n % 10;
456 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200457 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200458 return pos + 1;
459}
460
Willy Tarreau91092e52007-10-25 16:58:42 +0200461/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200462 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200463 * the ascii representation for number 'n' in decimal.
464 */
465char *lltoa_r(long long int in, char *buffer, int size)
466{
467 char *pos;
468 int neg = 0;
469 unsigned long long int n;
470
471 pos = buffer + size - 1;
472 *pos-- = '\0';
473
474 if (in < 0) {
475 neg = 1;
476 n = -in;
477 }
478 else
479 n = in;
480
481 do {
482 *pos-- = '0' + n % 10;
483 n /= 10;
484 } while (n && pos >= buffer);
485 if (neg && pos > buffer)
486 *pos-- = '-';
487 return pos + 1;
488}
489
490/*
491 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200492 * the ascii representation for signed number 'n' in decimal.
493 */
494char *sltoa_r(long n, char *buffer, int size)
495{
496 char *pos;
497
498 if (n >= 0)
499 return ultoa_r(n, buffer, size);
500
501 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
502 *pos = '-';
503 return pos;
504}
505
506/*
507 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200508 * the ascii representation for number 'n' in decimal, formatted for
509 * HTML output with tags to create visual grouping by 3 digits. The
510 * output needs to support at least 171 characters.
511 */
512const char *ulltoh_r(unsigned long long n, char *buffer, int size)
513{
514 char *start;
515 int digit = 0;
516
517 start = buffer + size;
518 *--start = '\0';
519
520 do {
521 if (digit == 3 && start >= buffer + 7)
522 memcpy(start -= 7, "</span>", 7);
523
524 if (start >= buffer + 1) {
525 *--start = '0' + n % 10;
526 n /= 10;
527 }
528
529 if (digit == 3 && start >= buffer + 18)
530 memcpy(start -= 18, "<span class=\"rls\">", 18);
531
532 if (digit++ == 3)
533 digit = 1;
534 } while (n && start > buffer);
535 return start;
536}
537
538/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200539 * This function simply returns a locally allocated string containing the ascii
540 * representation for number 'n' in decimal, unless n is 0 in which case it
541 * returns the alternate string (or an empty string if the alternate string is
542 * NULL). It use is intended for limits reported in reports, where it's
543 * desirable not to display anything if there is no limit. Warning! it shares
544 * the same vector as ultoa_r().
545 */
546const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
547{
548 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
549}
550
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200551/* Trims the first "%f" float in a string to its minimum number of digits after
552 * the decimal point by trimming trailing zeroes, even dropping the decimal
553 * point if not needed. The string is in <buffer> of length <len>, and the
554 * number is expected to start at or after position <num_start> (the first
555 * point appearing there is considered). A NUL character is always placed at
556 * the end if some trimming occurs. The new buffer length is returned.
557 */
558size_t flt_trim(char *buffer, size_t num_start, size_t len)
559{
560 char *end = buffer + len;
561 char *p = buffer + num_start;
562 char *trim;
563
564 do {
565 if (p >= end)
566 return len;
567 trim = p++;
568 } while (*trim != '.');
569
570 /* For now <trim> is on the decimal point. Let's look for any other
571 * meaningful digit after it.
572 */
573 while (p < end) {
574 if (*p++ != '0')
575 trim = p;
576 }
577
578 if (trim < end)
579 *trim = 0;
580
581 return trim - buffer;
582}
583
Willy Tarreauae03d262021-05-08 07:35:00 +0200584/*
585 * This function simply returns a locally allocated string containing
586 * the ascii representation for number 'n' in decimal with useless trailing
587 * zeroes trimmed.
588 */
589char *ftoa_r(double n, char *buffer, int size)
590{
591 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
592 return buffer;
593}
594
Willy Tarreau588297f2014-06-16 15:16:40 +0200595/* returns a locally allocated string containing the quoted encoding of the
596 * input string. The output may be truncated to QSTR_SIZE chars, but it is
597 * guaranteed that the string will always be properly terminated. Quotes are
598 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
599 * always be at least 4 chars.
600 */
601const char *qstr(const char *str)
602{
603 char *ret = quoted_str[quoted_idx];
604 char *p, *end;
605
606 if (++quoted_idx >= NB_QSTR)
607 quoted_idx = 0;
608
609 p = ret;
610 end = ret + QSTR_SIZE;
611
612 *p++ = '"';
613
614 /* always keep 3 chars to support passing "" and the ending " */
615 while (*str && p < end - 3) {
616 if (*str == '"') {
617 *p++ = '"';
618 *p++ = '"';
619 }
620 else
621 *p++ = *str;
622 str++;
623 }
624 *p++ = '"';
625 return ret;
626}
627
Robert Tsai81ae1952007-12-05 10:47:29 +0100628/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200629 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
630 *
631 * It looks like this one would be a good candidate for inlining, but this is
632 * not interesting because it around 35 bytes long and often called multiple
633 * times within the same function.
634 */
635int ishex(char s)
636{
637 s -= '0';
638 if ((unsigned char)s <= 9)
639 return 1;
640 s -= 'A' - '0';
641 if ((unsigned char)s <= 5)
642 return 1;
643 s -= 'a' - 'A';
644 if ((unsigned char)s <= 5)
645 return 1;
646 return 0;
647}
648
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100649/* rounds <i> down to the closest value having max 2 digits */
650unsigned int round_2dig(unsigned int i)
651{
652 unsigned int mul = 1;
653
654 while (i >= 100) {
655 i /= 10;
656 mul *= 10;
657 }
658 return i * mul;
659}
660
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100661/*
662 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
663 * invalid character is found, a pointer to it is returned. If everything is
664 * fine, NULL is returned.
665 */
666const char *invalid_char(const char *name)
667{
668 if (!*name)
669 return name;
670
671 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100672 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100673 *name != '_' && *name != '-')
674 return name;
675 name++;
676 }
677 return NULL;
678}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200679
680/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200681 * Checks <name> for invalid characters. Valid chars are [_.-] and those
682 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200683 * If an invalid character is found, a pointer to it is returned.
684 * If everything is fine, NULL is returned.
685 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200686static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200687
688 if (!*name)
689 return name;
690
691 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100692 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200693 *name != '_' && *name != '-')
694 return name;
695
696 name++;
697 }
698
699 return NULL;
700}
701
702/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200703 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
704 * If an invalid character is found, a pointer to it is returned.
705 * If everything is fine, NULL is returned.
706 */
707const char *invalid_domainchar(const char *name) {
708 return __invalid_char(name, isalnum);
709}
710
711/*
712 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
713 * If an invalid character is found, a pointer to it is returned.
714 * If everything is fine, NULL is returned.
715 */
716const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200717 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200718}
719
720/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100721 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100722 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
723 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
724 * the function tries to guess the address family from the syntax. If the
725 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100726 * string is assumed to contain only an address, no port. The address can be a
727 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
728 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
729 * The return address will only have the address family and the address set,
730 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100731 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
732 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100733 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200734 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100735struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200736{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100737 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100738 /* max IPv6 length, including brackets and terminating NULL */
739 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100740 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100741
742 /* check IPv6 with square brackets */
743 if (str[0] == '[') {
744 size_t iplength = strlen(str);
745
746 if (iplength < 4) {
747 /* minimal size is 4 when using brackets "[::]" */
748 goto fail;
749 }
750 else if (iplength >= sizeof(tmpip)) {
751 /* IPv6 literal can not be larger than tmpip */
752 goto fail;
753 }
754 else {
755 if (str[iplength - 1] != ']') {
756 /* if address started with bracket, it should end with bracket */
757 goto fail;
758 }
759 else {
760 memcpy(tmpip, str + 1, iplength - 2);
761 tmpip[iplength - 2] = '\0';
762 str = tmpip;
763 }
764 }
765 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100766
Willy Tarreaufab5a432011-03-04 15:31:53 +0100767 /* Any IPv6 address */
768 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100769 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
770 sa->ss_family = AF_INET6;
771 else if (sa->ss_family != AF_INET6)
772 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100773 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100774 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100775 }
776
Willy Tarreau24709282013-03-10 21:32:12 +0100777 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100778 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100779 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
780 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100781 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100782 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100783 }
784
785 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100786 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
787 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100788 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100789 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100790 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100791 }
792
793 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100794 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
795 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100796 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100797 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100798 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100799 }
800
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100801 if (!resolve)
802 return NULL;
803
Emeric Brund30e9a12020-12-23 18:49:16 +0100804 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200805 return NULL;
806
David du Colombierd5f43282011-03-17 10:40:16 +0100807#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200808 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100809 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100810 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100811
812 memset(&result, 0, sizeof(result));
813 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100814 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100815 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200816 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100817 hints.ai_protocol = 0;
818
819 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100820 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
821 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100822 else if (sa->ss_family != result->ai_family) {
823 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100824 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100825 }
Willy Tarreau24709282013-03-10 21:32:12 +0100826
David du Colombierd5f43282011-03-17 10:40:16 +0100827 switch (result->ai_family) {
828 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100829 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100830 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100831 success = 1;
832 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100833 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100834 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100835 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100836 success = 1;
837 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100838 }
839 }
840
Sean Carey58ea0392013-02-15 23:39:18 +0100841 if (result)
842 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100843
844 if (success)
845 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100846 }
David du Colombierd5f43282011-03-17 10:40:16 +0100847#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200848 /* try to resolve an IPv4/IPv6 hostname */
849 he = gethostbyname(str);
850 if (he) {
851 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
852 sa->ss_family = he->h_addrtype;
853 else if (sa->ss_family != he->h_addrtype)
854 goto fail;
855
856 switch (sa->ss_family) {
857 case AF_INET:
858 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100859 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200860 return sa;
861 case AF_INET6:
862 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100863 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200864 return sa;
865 }
866 }
867
David du Colombierd5f43282011-03-17 10:40:16 +0100868 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100869 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100870 return NULL;
871}
872
873/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100874 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
875 * range or offset consisting in two integers that the caller will have to
876 * check to find the relevant input format. The following format are supported :
877 *
878 * String format | address | port | low | high
879 * addr | <addr> | 0 | 0 | 0
880 * addr: | <addr> | 0 | 0 | 0
881 * addr:port | <addr> | <port> | <port> | <port>
882 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
883 * addr:+port | <addr> | <port> | 0 | <port>
884 * addr:-port | <addr> |-<port> | <port> | 0
885 *
886 * The detection of a port range or increment by the caller is made by
887 * comparing <low> and <high>. If both are equal, then port 0 means no port
888 * was specified. The caller may pass NULL for <low> and <high> if it is not
889 * interested in retrieving port ranges.
890 *
891 * Note that <addr> above may also be :
892 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
893 * - "*" => family will be AF_INET and address will be INADDR_ANY
894 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
895 * - a host name => family and address will depend on host name resolving.
896 *
Willy Tarreau24709282013-03-10 21:32:12 +0100897 * A prefix may be passed in before the address above to force the family :
898 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
899 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
900 * - "unix@" => force address to be a path to a UNIX socket even if the
901 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200902 * - 'abns@' -> force address to belong to the abstract namespace (Linux
903 * only). These sockets are just like Unix sockets but without
904 * the need for an underlying file system. The address is a
905 * string. Technically it's like a Unix socket with a zero in
906 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100907 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100908 *
mildisff5d5102015-10-26 18:50:08 +0100909 * IPv6 addresses can be declared with or without square brackets. When using
910 * square brackets for IPv6 addresses, the port separator (colon) is optional.
911 * If not using square brackets, and in order to avoid any ambiguity with
912 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
913 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
914 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100915 *
916 * If <pfx> is non-null, it is used as a string prefix before any path-based
917 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100918 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200919 * if <fqdn> is non-null, it will be filled with :
920 * - a pointer to the FQDN of the server name to resolve if there's one, and
921 * that the caller will have to free(),
922 * - NULL if there was an explicit address that doesn't require resolution.
923 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200924 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
925 * still honored so it is possible for the caller to know whether a resolution
926 * failed by clearing this flag and checking if <fqdn> was filled, indicating
927 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200928 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100929 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200930 * the address when cast to sockaddr_in and the address family is
931 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200932 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200933 * The matching protocol will be set into <proto> if non-null.
934 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200935 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
936 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100937 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200938struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
939 struct protocol **proto, char **err,
940 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100941{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100942 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100943 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200944 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100945 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100946 char *port1, *port2;
947 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200948 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200949 int new_fd = -1;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200950 enum proto_type proto_type;
951 int ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100952
953 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200954 if (fqdn)
955 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200956
Willy Tarreaudad36a32013-03-11 01:20:04 +0100957 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100958 if (str2 == NULL) {
959 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100960 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100961 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200962
Willy Tarreau9f69f462015-09-08 16:01:25 +0200963 if (!*str2) {
964 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
965 goto out;
966 }
967
Willy Tarreau24709282013-03-10 21:32:12 +0100968 memset(&ss, 0, sizeof(ss));
969
Willy Tarreaue835bd82020-09-16 11:35:47 +0200970 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100971 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
Willy Tarreaue3b45182021-10-27 17:28:55 +0200972 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM))) {
973 proto_type = PROTO_TYPE_DGRAM;
974 ctrl_type = SOCK_DGRAM;
975 } else {
976 proto_type = PROTO_TYPE_STREAM;
977 ctrl_type = SOCK_STREAM;
978 }
Willy Tarreaue835bd82020-09-16 11:35:47 +0200979
980 if (strncmp(str2, "stream+", 7) == 0) {
981 str2 += 7;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200982 proto_type = PROTO_TYPE_STREAM;
983 ctrl_type = SOCK_STREAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200984 }
985 else if (strncmp(str2, "dgram+", 6) == 0) {
986 str2 += 6;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200987 proto_type = PROTO_TYPE_DGRAM;
988 ctrl_type = SOCK_DGRAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200989 }
990
Willy Tarreau24709282013-03-10 21:32:12 +0100991 if (strncmp(str2, "unix@", 5) == 0) {
992 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200993 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100994 ss.ss_family = AF_UNIX;
995 }
Emeric Brunce325c42021-04-02 17:05:09 +0200996 else if (strncmp(str2, "uxdg@", 5) == 0) {
997 str2 += 5;
998 abstract = 0;
999 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001000 proto_type = PROTO_TYPE_DGRAM;
1001 ctrl_type = SOCK_DGRAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001002 }
1003 else if (strncmp(str2, "uxst@", 5) == 0) {
1004 str2 += 5;
1005 abstract = 0;
1006 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001007 proto_type = PROTO_TYPE_STREAM;
1008 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001009 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001010 else if (strncmp(str2, "abns@", 5) == 0) {
1011 str2 += 5;
1012 abstract = 1;
1013 ss.ss_family = AF_UNIX;
1014 }
Emeric Brunce325c42021-04-02 17:05:09 +02001015 else if (strncmp(str2, "ip@", 3) == 0) {
1016 str2 += 3;
1017 ss.ss_family = AF_UNSPEC;
1018 }
Willy Tarreau24709282013-03-10 21:32:12 +01001019 else if (strncmp(str2, "ipv4@", 5) == 0) {
1020 str2 += 5;
1021 ss.ss_family = AF_INET;
1022 }
1023 else if (strncmp(str2, "ipv6@", 5) == 0) {
1024 str2 += 5;
1025 ss.ss_family = AF_INET6;
1026 }
Emeric Brunce325c42021-04-02 17:05:09 +02001027 else if (strncmp(str2, "tcp4@", 5) == 0) {
1028 str2 += 5;
1029 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001030 proto_type = PROTO_TYPE_STREAM;
1031 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001032 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001033 else if (strncmp(str2, "udp4@", 5) == 0) {
1034 str2 += 5;
1035 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001036 proto_type = PROTO_TYPE_DGRAM;
1037 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001038 }
Emeric Brunce325c42021-04-02 17:05:09 +02001039 else if (strncmp(str2, "tcp6@", 5) == 0) {
1040 str2 += 5;
1041 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001042 proto_type = PROTO_TYPE_STREAM;
1043 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001044 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001045 else if (strncmp(str2, "udp6@", 5) == 0) {
1046 str2 += 5;
1047 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001048 proto_type = PROTO_TYPE_DGRAM;
1049 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001050 }
Emeric Brunce325c42021-04-02 17:05:09 +02001051 else if (strncmp(str2, "tcp@", 4) == 0) {
1052 str2 += 4;
1053 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001054 proto_type = PROTO_TYPE_STREAM;
1055 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001056 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001057 else if (strncmp(str2, "udp@", 4) == 0) {
1058 str2 += 4;
1059 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001060 proto_type = PROTO_TYPE_DGRAM;
1061 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001062 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001063 else if (strncmp(str2, "quic4@", 6) == 0) {
1064 str2 += 6;
1065 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001066 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001067 ctrl_type = SOCK_STREAM;
1068 }
1069 else if (strncmp(str2, "quic6@", 6) == 0) {
1070 str2 += 6;
1071 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001072 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001073 ctrl_type = SOCK_STREAM;
1074 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001075 else if (strncmp(str2, "fd@", 3) == 0) {
1076 str2 += 3;
1077 ss.ss_family = AF_CUST_EXISTING_FD;
1078 }
1079 else if (strncmp(str2, "sockpair@", 9) == 0) {
1080 str2 += 9;
1081 ss.ss_family = AF_CUST_SOCKPAIR;
1082 }
Willy Tarreau24709282013-03-10 21:32:12 +01001083 else if (*str2 == '/') {
1084 ss.ss_family = AF_UNIX;
1085 }
1086 else
1087 ss.ss_family = AF_UNSPEC;
1088
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001089 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001090 struct sockaddr_storage ss2;
1091 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001092 char *endptr;
1093
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001094 new_fd = strtol(str2, &endptr, 10);
1095 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001096 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1097 goto out;
1098 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001099
Willy Tarreaua215be22020-09-16 10:14:16 +02001100 /* just verify that it's a socket */
1101 addr_len = sizeof(ss2);
1102 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1103 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1104 goto out;
1105 }
1106
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001107 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1108 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001109 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001110 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001111 char *endptr;
1112
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001113 new_fd = strtol(str2, &endptr, 10);
1114 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001115 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001116 goto out;
1117 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001118
Willy Tarreau6edc7222020-09-15 17:41:56 +02001119 if (opts & PA_O_SOCKET_FD) {
1120 socklen_t addr_len;
1121 int type;
1122
1123 addr_len = sizeof(ss);
1124 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1125 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1126 goto out;
1127 }
1128
1129 addr_len = sizeof(type);
1130 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue3b45182021-10-27 17:28:55 +02001131 (type == SOCK_STREAM) != (proto_type == PROTO_TYPE_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001132 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1133 goto out;
1134 }
1135
1136 porta = portl = porth = get_host_port(&ss);
1137 } else if (opts & PA_O_RAW_FD) {
1138 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1139 ((struct sockaddr_in *)&ss)->sin_port = 0;
1140 } else {
1141 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1142 goto out;
1143 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001144 }
1145 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001146 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001147 int prefix_path_len;
1148 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001149 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001150
1151 /* complete unix socket path name during startup or soft-restart is
1152 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1153 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001154 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001155 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001156 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001157
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001158 adr_len = strlen(str2);
1159 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001160 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1161 goto out;
1162 }
1163
Willy Tarreauccfccef2014-05-10 01:49:15 +02001164 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001165 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001166 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001167 memcpy(un->sun_path, pfx, prefix_path_len);
1168 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001169 }
Willy Tarreau24709282013-03-10 21:32:12 +01001170 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001171 char *end = str2 + strlen(str2);
1172 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001173
mildisff5d5102015-10-26 18:50:08 +01001174 /* search for : or ] whatever comes first */
1175 for (chr = end-1; chr > str2; chr--) {
1176 if (*chr == ']' || *chr == ':')
1177 break;
1178 }
1179
1180 if (*chr == ':') {
1181 /* Found a colon before a closing-bracket, must be a port separator.
1182 * This guarantee backward compatibility.
1183 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001184 if (!(opts & PA_O_PORT_OK)) {
1185 memprintf(err, "port specification not permitted here in '%s'", str);
1186 goto out;
1187 }
mildisff5d5102015-10-26 18:50:08 +01001188 *chr++ = '\0';
1189 port1 = chr;
1190 }
1191 else {
1192 /* Either no colon and no closing-bracket
1193 * or directly ending with a closing-bracket.
1194 * However, no port.
1195 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001196 if (opts & PA_O_PORT_MAND) {
1197 memprintf(err, "missing port specification in '%s'", str);
1198 goto out;
1199 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001200 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001201 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001202
Willy Tarreau90807112020-02-25 08:16:33 +01001203 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001204 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001205 if (port2) {
1206 if (!(opts & PA_O_PORT_RANGE)) {
1207 memprintf(err, "port range not permitted here in '%s'", str);
1208 goto out;
1209 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001210 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001211 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001212 else
1213 port2 = port1;
1214 portl = atoi(port1);
1215 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001216
1217 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1218 memprintf(err, "invalid port '%s'", port1);
1219 goto out;
1220 }
1221
1222 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1223 memprintf(err, "invalid port '%s'", port2);
1224 goto out;
1225 }
1226
1227 if (portl > porth) {
1228 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1229 goto out;
1230 }
1231
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001232 porta = portl;
1233 }
1234 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001235 if (!(opts & PA_O_PORT_OFS)) {
1236 memprintf(err, "port offset not permitted here in '%s'", str);
1237 goto out;
1238 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001239 portl = atoi(port1 + 1);
1240 porta = -portl;
1241 }
1242 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001243 if (!(opts & PA_O_PORT_OFS)) {
1244 memprintf(err, "port offset not permitted here in '%s'", str);
1245 goto out;
1246 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001247 porth = atoi(port1 + 1);
1248 porta = porth;
1249 }
1250 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001251 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001252 goto out;
1253 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001254 else if (opts & PA_O_PORT_MAND) {
1255 memprintf(err, "missing port specification in '%s'", str);
1256 goto out;
1257 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001258
1259 /* first try to parse the IP without resolving. If it fails, it
1260 * tells us we need to keep a copy of the FQDN to resolve later
1261 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001262 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001263 */
1264 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001265 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1266 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001267 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1268 goto out;
1269 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001270
Willy Tarreauceccdd72016-11-02 22:27:10 +01001271 if (fqdn) {
1272 if (str2 != back)
1273 memmove(back, str2, strlen(str2) + 1);
1274 *fqdn = back;
1275 back = NULL;
1276 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001277 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001278 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001279 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001280
Willy Tarreaue835bd82020-09-16 11:35:47 +02001281 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1282 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1283 goto out;
1284 }
1285 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1286 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1287 goto out;
1288 }
1289
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001290 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001291 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001292 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1293 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001294 * in which case the address is not known yet (this is only
1295 * for servers actually).
1296 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001297 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreaue3b45182021-10-27 17:28:55 +02001298 proto_type,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001299 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001300
Emeric Brun26754902021-04-07 14:26:44 +02001301 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001302 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1303 goto out;
1304 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001305
1306 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1307 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1308 goto out;
1309 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001310 }
1311
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001312 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001313 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001314 if (port)
1315 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001316 if (low)
1317 *low = portl;
1318 if (high)
1319 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001320 if (fd)
1321 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001322 if (proto)
1323 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001324 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001325 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001326}
1327
Thayne McCombs92149f92020-11-20 01:28:26 -07001328/* converts <addr> and <port> into a string representation of the address and port. This is sort
1329 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1330 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1331 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1332 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1333 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1334 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1335 *
1336 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1337 */
1338char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1339{
1340 char buffer[INET6_ADDRSTRLEN];
1341 char *out = NULL;
1342 const void *ptr;
1343 const char *path;
1344
1345 switch (addr->ss_family) {
1346 case AF_INET:
1347 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1348 break;
1349 case AF_INET6:
1350 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1351 break;
1352 case AF_UNIX:
1353 path = ((struct sockaddr_un *)addr)->sun_path;
1354 if (path[0] == '\0') {
1355 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1356 return memprintf(&out, "abns@%.*s", max_length, path+1);
1357 } else {
1358 return strdup(path);
1359 }
1360 case AF_CUST_SOCKPAIR:
1361 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1362 default:
1363 return NULL;
1364 }
1365 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1366 if (map_ports)
1367 return memprintf(&out, "%s:%+d", buffer, port);
1368 else
1369 return memprintf(&out, "%s:%d", buffer, port);
1370}
1371
1372
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001373/* converts <str> to a struct in_addr containing a network mask. It can be
1374 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001375 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001376 */
1377int str2mask(const char *str, struct in_addr *mask)
1378{
1379 if (strchr(str, '.') != NULL) { /* dotted notation */
1380 if (!inet_pton(AF_INET, str, mask))
1381 return 0;
1382 }
1383 else { /* mask length */
1384 char *err;
1385 unsigned long len = strtol(str, &err, 10);
1386
1387 if (!*str || (err && *err) || (unsigned)len > 32)
1388 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001389
1390 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001391 }
1392 return 1;
1393}
1394
Tim Duesterhus47185172018-01-25 16:24:49 +01001395/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001396 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001397 * if the conversion succeeds otherwise zero.
1398 */
1399int str2mask6(const char *str, struct in6_addr *mask)
1400{
1401 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1402 if (!inet_pton(AF_INET6, str, mask))
1403 return 0;
1404 }
1405 else { /* mask length */
1406 char *err;
1407 unsigned long len = strtol(str, &err, 10);
1408
1409 if (!*str || (err && *err) || (unsigned)len > 128)
1410 return 0;
1411
1412 len2mask6(len, mask);
1413 }
1414 return 1;
1415}
1416
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001417/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1418 * succeeds otherwise zero.
1419 */
1420int cidr2dotted(int cidr, struct in_addr *mask) {
1421
1422 if (cidr < 0 || cidr > 32)
1423 return 0;
1424
1425 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1426 return 1;
1427}
1428
Thierry Fournier70473a52016-02-17 17:12:14 +01001429/* Convert mask from bit length form to in_addr form.
1430 * This function never fails.
1431 */
1432void len2mask4(int len, struct in_addr *addr)
1433{
1434 if (len >= 32) {
1435 addr->s_addr = 0xffffffff;
1436 return;
1437 }
1438 if (len <= 0) {
1439 addr->s_addr = 0x00000000;
1440 return;
1441 }
1442 addr->s_addr = 0xffffffff << (32 - len);
1443 addr->s_addr = htonl(addr->s_addr);
1444}
1445
1446/* Convert mask from bit length form to in6_addr form.
1447 * This function never fails.
1448 */
1449void len2mask6(int len, struct in6_addr *addr)
1450{
1451 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1452 len -= 32;
1453 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1454 len -= 32;
1455 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1456 len -= 32;
1457 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1458}
1459
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001460/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001461 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001462 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001463 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001464 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1465 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001466int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001467{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001468 __label__ out_free, out_err;
1469 char *c, *s;
1470 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001471
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001472 s = strdup(str);
1473 if (!s)
1474 return 0;
1475
Willy Tarreaubaaee002006-06-26 02:48:02 +02001476 memset(mask, 0, sizeof(*mask));
1477 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001478
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001479 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001480 *c++ = '\0';
1481 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001482 if (!str2mask(c, mask))
1483 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001484 }
1485 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001486 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001487 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001488 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001489 struct hostent *he;
1490
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001491 if (!resolve)
1492 goto out_err;
1493
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001494 if ((he = gethostbyname(s)) == NULL) {
1495 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001496 }
1497 else
1498 *addr = *(struct in_addr *) *(he->h_addr_list);
1499 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001500
1501 ret_val = 1;
1502 out_free:
1503 free(s);
1504 return ret_val;
1505 out_err:
1506 ret_val = 0;
1507 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001508}
1509
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001510
1511/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001512 * converts <str> to two struct in6_addr* which must be pre-allocated.
1513 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001514 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001515 * Returns 1 if OK, 0 if error.
1516 */
1517int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1518{
1519 char *c, *s;
1520 int ret_val = 0;
1521 char *err;
1522 unsigned long len = 128;
1523
1524 s = strdup(str);
1525 if (!s)
1526 return 0;
1527
1528 memset(mask, 0, sizeof(*mask));
1529 memset(addr, 0, sizeof(*addr));
1530
1531 if ((c = strrchr(s, '/')) != NULL) {
1532 *c++ = '\0'; /* c points to the mask */
1533 if (!*c)
1534 goto out_free;
1535
1536 len = strtoul(c, &err, 10);
1537 if ((err && *err) || (unsigned)len > 128)
1538 goto out_free;
1539 }
1540 *mask = len; /* OK we have a valid mask in <len> */
1541
1542 if (!inet_pton(AF_INET6, s, addr))
1543 goto out_free;
1544
1545 ret_val = 1;
1546 out_free:
1547 free(s);
1548 return ret_val;
1549}
1550
1551
1552/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001553 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1554 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1555 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001556 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001557int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001558{
1559 int saw_digit, octets, ch;
1560 u_char tmp[4], *tp;
1561 const char *cp = addr;
1562
1563 saw_digit = 0;
1564 octets = 0;
1565 *(tp = tmp) = 0;
1566
1567 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001568 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001569 if (digit > 9 && ch != '.')
1570 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001571 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001572 if (digit <= 9) {
1573 u_int new = *tp * 10 + digit;
1574 if (new > 255)
1575 return 0;
1576 *tp = new;
1577 if (!saw_digit) {
1578 if (++octets > 4)
1579 return 0;
1580 saw_digit = 1;
1581 }
1582 } else if (ch == '.' && saw_digit) {
1583 if (octets == 4)
1584 return 0;
1585 *++tp = 0;
1586 saw_digit = 0;
1587 } else
1588 return 0;
1589 }
1590
1591 if (octets < 4)
1592 return 0;
1593
1594 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001595 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001596}
1597
1598/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001599 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001600 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001601 * the hostname. Actually only http and https are supported. <out> can be NULL.
1602 * This function returns the consumed length. It is useful if you parse complete
1603 * url like http://host:port/path, because the consumed length corresponds to
1604 * the first character of the path. If the conversion fails, it returns -1.
1605 *
1606 * This function tries to resolve the DNS name if haproxy is in starting mode.
1607 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001608 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001609int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001610{
1611 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001612 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001613 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001614 unsigned long long int http_code = 0;
1615 int default_port;
1616 struct hostent *he;
1617 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001618
1619 /* Firstly, try to find :// pattern */
1620 while (curr < url+ulen && url_code != 0x3a2f2f) {
1621 url_code = ((url_code & 0xffff) << 8);
1622 url_code += (unsigned char)*curr++;
1623 }
1624
1625 /* Secondly, if :// pattern is found, verify parsed stuff
1626 * before pattern is matching our http pattern.
1627 * If so parse ip address and port in uri.
1628 *
1629 * WARNING: Current code doesn't support dynamic async dns resolver.
1630 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001631 if (url_code != 0x3a2f2f)
1632 return -1;
1633
1634 /* Copy scheme, and utrn to lower case. */
1635 while (cp < curr - 3)
1636 http_code = (http_code << 8) + *cp++;
1637 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001638
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001639 /* HTTP or HTTPS url matching */
1640 if (http_code == 0x2020202068747470ULL) {
1641 default_port = 80;
1642 if (out)
1643 out->scheme = SCH_HTTP;
1644 }
1645 else if (http_code == 0x2020206874747073ULL) {
1646 default_port = 443;
1647 if (out)
1648 out->scheme = SCH_HTTPS;
1649 }
1650 else
1651 return -1;
1652
1653 /* If the next char is '[', the host address is IPv6. */
1654 if (*curr == '[') {
1655 curr++;
1656
1657 /* Check trash size */
1658 if (trash.size < ulen)
1659 return -1;
1660
1661 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001662 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001663 for (end = curr;
1664 end < url + ulen && *end != ']';
1665 end++, p++)
1666 *p = *end;
1667 if (*end != ']')
1668 return -1;
1669 *p = '\0';
1670
1671 /* Update out. */
1672 if (out) {
1673 out->host = curr;
1674 out->host_len = end - curr;
1675 }
1676
1677 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001678 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001679 return -1;
1680 end++;
1681
1682 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001683 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001684 end++;
1685 default_port = read_uint(&end, url + ulen);
1686 }
1687 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1688 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1689 return end - url;
1690 }
1691 else {
William Lallemand8a913742022-02-18 16:13:12 +01001692 /* we need to copy the string into the trash because url2ipv4
1693 * needs a \0 at the end of the string */
1694 if (trash.size < ulen)
1695 return -1;
1696
1697 memcpy(trash.area, curr, ulen - (curr - url));
1698 trash.area[ulen - (curr - url)] = '\0';
1699
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001700 /* We are looking for IP address. If you want to parse and
1701 * resolve hostname found in url, you can use str2sa_range(), but
1702 * be warned this can slow down global daemon performances
1703 * while handling lagging dns responses.
1704 */
William Lallemand8a913742022-02-18 16:13:12 +01001705 ret = url2ipv4(trash.area, &((struct sockaddr_in *)addr)->sin_addr);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001706 if (ret) {
1707 /* Update out. */
1708 if (out) {
1709 out->host = curr;
1710 out->host_len = ret;
1711 }
1712
William Lallemandb938b772022-03-24 21:59:03 +01001713 curr += ret;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001714
1715 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001716 if (curr < url + ulen && *curr == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001717 curr++;
1718 default_port = read_uint(&curr, url + ulen);
1719 }
1720 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1721
1722 /* Set family. */
1723 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1724 return curr - url;
1725 }
1726 else if (global.mode & MODE_STARTING) {
1727 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1728 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001729 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001730
1731 /* look for : or / or end */
1732 for (end = curr;
1733 end < url + ulen && *end != '/' && *end != ':';
1734 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001735 memcpy(trash.area, curr, end - curr);
1736 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001737
1738 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001739 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001740 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001741 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001742
1743 /* Update out. */
1744 if (out) {
1745 out->host = curr;
1746 out->host_len = end - curr;
1747 }
1748
1749 /* Decode port. */
William Lallemand3d7a9182022-03-25 17:37:51 +01001750 if (end < url + ulen && *end == ':') {
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001751 end++;
1752 default_port = read_uint(&end, url + ulen);
1753 }
1754
1755 /* Copy IP address, set port and family. */
1756 switch (he->h_addrtype) {
1757 case AF_INET:
1758 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1759 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1760 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1761 return end - url;
1762
1763 case AF_INET6:
1764 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1765 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1766 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1767 return end - url;
1768 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001769 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001770 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001771 return -1;
1772}
1773
Willy Tarreau631f01c2011-09-05 00:36:48 +02001774/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1775 * address family is returned so that it's easy for the caller to adapt to the
1776 * output format. Zero is returned if the address family is not supported. -1
1777 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1778 * supported.
1779 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001780int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001781{
1782
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001783 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001784
1785 if (size < 5)
1786 return 0;
1787 *str = '\0';
1788
1789 switch (addr->ss_family) {
1790 case AF_INET:
1791 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1792 break;
1793 case AF_INET6:
1794 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1795 break;
1796 case AF_UNIX:
1797 memcpy(str, "unix", 5);
1798 return addr->ss_family;
1799 default:
1800 return 0;
1801 }
1802
1803 if (inet_ntop(addr->ss_family, ptr, str, size))
1804 return addr->ss_family;
1805
1806 /* failed */
1807 return -1;
1808}
1809
Simon Horman75ab8bd2014-06-16 09:39:41 +09001810/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1811 * address family is returned so that it's easy for the caller to adapt to the
1812 * output format. Zero is returned if the address family is not supported. -1
1813 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1814 * supported.
1815 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001816int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001817{
1818
1819 uint16_t port;
1820
1821
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001822 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001823 return 0;
1824 *str = '\0';
1825
1826 switch (addr->ss_family) {
1827 case AF_INET:
1828 port = ((struct sockaddr_in *)addr)->sin_port;
1829 break;
1830 case AF_INET6:
1831 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1832 break;
1833 case AF_UNIX:
1834 memcpy(str, "unix", 5);
1835 return addr->ss_family;
1836 default:
1837 return 0;
1838 }
1839
1840 snprintf(str, size, "%u", ntohs(port));
1841 return addr->ss_family;
1842}
1843
Willy Tarreau16e01562016-08-09 16:46:18 +02001844/* check if the given address is local to the system or not. It will return
1845 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1846 * it is. We don't want to iterate over all interfaces for this (and it is not
1847 * portable). So instead we try to bind in UDP to this address on a free non
1848 * privileged port and to connect to the same address, port 0 (connect doesn't
1849 * care). If it succeeds, we own the address. Note that non-inet addresses are
1850 * considered local since they're most likely AF_UNIX.
1851 */
1852int addr_is_local(const struct netns_entry *ns,
1853 const struct sockaddr_storage *orig)
1854{
1855 struct sockaddr_storage addr;
1856 int result;
1857 int fd;
1858
1859 if (!is_inet_addr(orig))
1860 return 1;
1861
1862 memcpy(&addr, orig, sizeof(addr));
1863 set_host_port(&addr, 0);
1864
1865 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1866 if (fd < 0)
1867 return -1;
1868
1869 result = -1;
1870 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1871 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1872 result = 0; // fail, non-local address
1873 else
1874 result = 1; // success, local address
1875 }
1876 else {
1877 if (errno == EADDRNOTAVAIL)
1878 result = 0; // definitely not local :-)
1879 }
1880 close(fd);
1881
1882 return result;
1883}
1884
Willy Tarreaubaaee002006-06-26 02:48:02 +02001885/* will try to encode the string <string> replacing all characters tagged in
1886 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1887 * prefixed by <escape>, and will store the result between <start> (included)
1888 * and <stop> (excluded), and will always terminate the string with a '\0'
1889 * before <stop>. The position of the '\0' is returned if the conversion
1890 * completes. If bytes are missing between <start> and <stop>, then the
1891 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1892 * cannot even be stored so we return <start> without writing the 0.
1893 * The input string must also be zero-terminated.
1894 */
1895const char hextab[16] = "0123456789ABCDEF";
1896char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001897 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001898 const char *string)
1899{
1900 if (start < stop) {
1901 stop--; /* reserve one byte for the final '\0' */
1902 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001903 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001904 *start++ = *string;
1905 else {
1906 if (start + 3 >= stop)
1907 break;
1908 *start++ = escape;
1909 *start++ = hextab[(*string >> 4) & 15];
1910 *start++ = hextab[*string & 15];
1911 }
1912 string++;
1913 }
1914 *start = '\0';
1915 }
1916 return start;
1917}
1918
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001919/*
1920 * Same behavior as encode_string() above, except that it encodes chunk
1921 * <chunk> instead of a string.
1922 */
1923char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001924 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001925 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001926{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001927 char *str = chunk->area;
1928 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001929
1930 if (start < stop) {
1931 stop--; /* reserve one byte for the final '\0' */
1932 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001933 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001934 *start++ = *str;
1935 else {
1936 if (start + 3 >= stop)
1937 break;
1938 *start++ = escape;
1939 *start++ = hextab[(*str >> 4) & 15];
1940 *start++ = hextab[*str & 15];
1941 }
1942 str++;
1943 }
1944 *start = '\0';
1945 }
1946 return start;
1947}
1948
Dragan Dosen0edd1092016-02-12 13:23:02 +01001949/*
1950 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001951 * character. The input <string> must be zero-terminated. The result will
1952 * be stored between <start> (included) and <stop> (excluded). This
1953 * function will always try to terminate the resulting string with a '\0'
1954 * before <stop>, and will return its position if the conversion
1955 * completes.
1956 */
1957char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001958 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001959 const char *string)
1960{
1961 if (start < stop) {
1962 stop--; /* reserve one byte for the final '\0' */
1963 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001964 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001965 *start++ = *string;
1966 else {
1967 if (start + 2 >= stop)
1968 break;
1969 *start++ = escape;
1970 *start++ = *string;
1971 }
1972 string++;
1973 }
1974 *start = '\0';
1975 }
1976 return start;
1977}
1978
1979/*
1980 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001981 * character. <chunk> contains the input to be escaped. The result will be
1982 * stored between <start> (included) and <stop> (excluded). The function
1983 * will always try to terminate the resulting string with a '\0' before
1984 * <stop>, and will return its position if the conversion completes.
1985 */
1986char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001987 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001988 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001989{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001990 char *str = chunk->area;
1991 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001992
1993 if (start < stop) {
1994 stop--; /* reserve one byte for the final '\0' */
1995 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001996 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001997 *start++ = *str;
1998 else {
1999 if (start + 2 >= stop)
2000 break;
2001 *start++ = escape;
2002 *start++ = *str;
2003 }
2004 str++;
2005 }
2006 *start = '\0';
2007 }
2008 return start;
2009}
2010
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002011/* Check a string for using it in a CSV output format. If the string contains
2012 * one of the following four char <">, <,>, CR or LF, the string is
2013 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2014 * <str> is the input string to be escaped. The function assumes that
2015 * the input string is null-terminated.
2016 *
2017 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002018 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002019 * format.
2020 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002021 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002022 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002023 * If <quote> is 1, the converter puts the quotes only if any reserved character
2024 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002025 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002026 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002027 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002028 * The function returns the converted string on its output. If an error
2029 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002030 * for using the function directly as printf() argument.
2031 *
2032 * If the output buffer is too short to contain the input string, the result
2033 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002034 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002035 * This function appends the encoding to the existing output chunk, and it
2036 * guarantees that it starts immediately at the first available character of
2037 * the chunk. Please use csv_enc() instead if you want to replace the output
2038 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002039 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002040const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002041{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002042 char *end = output->area + output->size;
2043 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002044 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002045
Willy Tarreaub631c292016-01-08 10:04:08 +01002046 if (quote == 1) {
2047 /* automatic quoting: first verify if we'll have to quote the string */
2048 if (!strpbrk(str, "\n\r,\""))
2049 quote = 0;
2050 }
2051
2052 if (quote)
2053 *ptr++ = '"';
2054
Willy Tarreau898529b2016-01-06 18:07:04 +01002055 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2056 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002057 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002058 ptr++;
2059 if (ptr >= end - 2) {
2060 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002061 break;
2062 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002063 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002064 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002065 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002066 str++;
2067 }
2068
Willy Tarreaub631c292016-01-08 10:04:08 +01002069 if (quote)
2070 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002071
Willy Tarreau898529b2016-01-06 18:07:04 +01002072 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002073 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002074 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002075}
2076
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002077/* Decode an URL-encoded string in-place. The resulting string might
2078 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002079 * aborted, the string is truncated before the issue and a negative value is
2080 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002081 * If the 'in_form' argument is non-nul the string is assumed to be part of
2082 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2083 * turned to a space. If it's zero, this will only be done after a question
2084 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002085 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002086int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002087{
2088 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002089 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002090
2091 in = string;
2092 out = string;
2093 while (*in) {
2094 switch (*in) {
2095 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002096 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002097 break;
2098 case '%' :
2099 if (!ishex(in[1]) || !ishex(in[2]))
2100 goto end;
2101 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2102 in += 2;
2103 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002104 case '?':
2105 in_form = 1;
2106 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002107 default:
2108 *out++ = *in;
2109 break;
2110 }
2111 in++;
2112 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002113 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002114 end:
2115 *out = 0;
2116 return ret;
2117}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002118
Willy Tarreau6911fa42007-03-04 18:06:08 +01002119unsigned int str2ui(const char *s)
2120{
2121 return __str2ui(s);
2122}
2123
2124unsigned int str2uic(const char *s)
2125{
2126 return __str2uic(s);
2127}
2128
2129unsigned int strl2ui(const char *s, int len)
2130{
2131 return __strl2ui(s, len);
2132}
2133
2134unsigned int strl2uic(const char *s, int len)
2135{
2136 return __strl2uic(s, len);
2137}
2138
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002139unsigned int read_uint(const char **s, const char *end)
2140{
2141 return __read_uint(s, end);
2142}
2143
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002144/* This function reads an unsigned integer from the string pointed to by <s> and
2145 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2146 * function automatically stops at <end>. If the number overflows, the 2^64-1
2147 * value is returned.
2148 */
2149unsigned long long int read_uint64(const char **s, const char *end)
2150{
2151 const char *ptr = *s;
2152 unsigned long long int i = 0, tmp;
2153 unsigned int j;
2154
2155 while (ptr < end) {
2156
2157 /* read next char */
2158 j = *ptr - '0';
2159 if (j > 9)
2160 goto read_uint64_end;
2161
2162 /* add char to the number and check overflow. */
2163 tmp = i * 10;
2164 if (tmp / 10 != i) {
2165 i = ULLONG_MAX;
2166 goto read_uint64_eat;
2167 }
2168 if (ULLONG_MAX - tmp < j) {
2169 i = ULLONG_MAX;
2170 goto read_uint64_eat;
2171 }
2172 i = tmp + j;
2173 ptr++;
2174 }
2175read_uint64_eat:
2176 /* eat each numeric char */
2177 while (ptr < end) {
2178 if ((unsigned int)(*ptr - '0') > 9)
2179 break;
2180 ptr++;
2181 }
2182read_uint64_end:
2183 *s = ptr;
2184 return i;
2185}
2186
2187/* This function reads an integer from the string pointed to by <s> and returns
2188 * it. The <s> pointer is adjusted to point to the first unread char. The function
2189 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2190 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2191 * returned.
2192 */
2193long long int read_int64(const char **s, const char *end)
2194{
2195 unsigned long long int i = 0;
2196 int neg = 0;
2197
2198 /* Look for minus char. */
2199 if (**s == '-') {
2200 neg = 1;
2201 (*s)++;
2202 }
2203 else if (**s == '+')
2204 (*s)++;
2205
2206 /* convert as positive number. */
2207 i = read_uint64(s, end);
2208
2209 if (neg) {
2210 if (i > 0x8000000000000000ULL)
2211 return LLONG_MIN;
2212 return -i;
2213 }
2214 if (i > 0x7fffffffffffffffULL)
2215 return LLONG_MAX;
2216 return i;
2217}
2218
Willy Tarreau6911fa42007-03-04 18:06:08 +01002219/* This one is 7 times faster than strtol() on athlon with checks.
2220 * It returns the value of the number composed of all valid digits read,
2221 * and can process negative numbers too.
2222 */
2223int strl2ic(const char *s, int len)
2224{
2225 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002226 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002227
2228 if (len > 0) {
2229 if (*s != '-') {
2230 /* positive number */
2231 while (len-- > 0) {
2232 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002233 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002234 if (j > 9)
2235 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002236 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002237 }
2238 } else {
2239 /* negative number */
2240 s++;
2241 while (--len > 0) {
2242 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002243 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002244 if (j > 9)
2245 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002246 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002247 }
2248 }
2249 }
2250 return i;
2251}
2252
2253
2254/* This function reads exactly <len> chars from <s> and converts them to a
2255 * signed integer which it stores into <ret>. It accurately detects any error
2256 * (truncated string, invalid chars, overflows). It is meant to be used in
2257 * applications designed for hostile environments. It returns zero when the
2258 * number has successfully been converted, non-zero otherwise. When an error
2259 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2260 * faster than strtol().
2261 */
2262int strl2irc(const char *s, int len, int *ret)
2263{
2264 int i = 0;
2265 int j;
2266
2267 if (!len)
2268 return 1;
2269
2270 if (*s != '-') {
2271 /* positive number */
2272 while (len-- > 0) {
2273 j = (*s++) - '0';
2274 if (j > 9) return 1; /* invalid char */
2275 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2276 i = i * 10;
2277 if (i + j < i) return 1; /* check for addition overflow */
2278 i = i + j;
2279 }
2280 } else {
2281 /* negative number */
2282 s++;
2283 while (--len > 0) {
2284 j = (*s++) - '0';
2285 if (j > 9) return 1; /* invalid char */
2286 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2287 i = i * 10;
2288 if (i - j > i) return 1; /* check for subtract overflow */
2289 i = i - j;
2290 }
2291 }
2292 *ret = i;
2293 return 0;
2294}
2295
2296
2297/* This function reads exactly <len> chars from <s> and converts them to a
2298 * signed integer which it stores into <ret>. It accurately detects any error
2299 * (truncated string, invalid chars, overflows). It is meant to be used in
2300 * applications designed for hostile environments. It returns zero when the
2301 * number has successfully been converted, non-zero otherwise. When an error
2302 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002303 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002304 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002305
2306int strl2llrc(const char *s, int len, long long *ret)
2307{
2308 long long i = 0;
2309 int j;
2310
2311 if (!len)
2312 return 1;
2313
2314 if (*s != '-') {
2315 /* positive number */
2316 while (len-- > 0) {
2317 j = (*s++) - '0';
2318 if (j > 9) return 1; /* invalid char */
2319 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2320 i = i * 10LL;
2321 if (i + j < i) return 1; /* check for addition overflow */
2322 i = i + j;
2323 }
2324 } else {
2325 /* negative number */
2326 s++;
2327 while (--len > 0) {
2328 j = (*s++) - '0';
2329 if (j > 9) return 1; /* invalid char */
2330 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2331 i = i * 10LL;
2332 if (i - j > i) return 1; /* check for subtract overflow */
2333 i = i - j;
2334 }
2335 }
2336 *ret = i;
2337 return 0;
2338}
2339
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002340/* This function is used with pat_parse_dotted_ver(). It converts a string
2341 * composed by two number separated by a dot. Each part must contain in 16 bits
2342 * because internally they will be represented as a 32-bit quantity stored in
2343 * a 64-bit integer. It returns zero when the number has successfully been
2344 * converted, non-zero otherwise. When an error is returned, the <ret> value
2345 * is left untouched.
2346 *
2347 * "1.3" -> 0x0000000000010003
2348 * "65535.65535" -> 0x00000000ffffffff
2349 */
2350int strl2llrc_dotted(const char *text, int len, long long *ret)
2351{
2352 const char *end = &text[len];
2353 const char *p;
2354 long long major, minor;
2355
2356 /* Look for dot. */
2357 for (p = text; p < end; p++)
2358 if (*p == '.')
2359 break;
2360
2361 /* Convert major. */
2362 if (strl2llrc(text, p - text, &major) != 0)
2363 return 1;
2364
2365 /* Check major. */
2366 if (major >= 65536)
2367 return 1;
2368
2369 /* Convert minor. */
2370 minor = 0;
2371 if (p < end)
2372 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2373 return 1;
2374
2375 /* Check minor. */
2376 if (minor >= 65536)
2377 return 1;
2378
2379 /* Compose value. */
2380 *ret = (major << 16) | (minor & 0xffff);
2381 return 0;
2382}
2383
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002384/* This function parses a time value optionally followed by a unit suffix among
2385 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2386 * expected by the caller. The computation does its best to avoid overflows.
2387 * The value is returned in <ret> if everything is fine, and a NULL is returned
2388 * by the function. In case of error, a pointer to the error is returned and
2389 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002390 * Values resulting in values larger than or equal to 2^31 after conversion are
2391 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2392 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002393 */
2394const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2395{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002396 unsigned long long imult, idiv;
2397 unsigned long long omult, odiv;
2398 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002399 const char *str = text;
2400
2401 if (!isdigit((unsigned char)*text))
2402 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002403
2404 omult = odiv = 1;
2405
2406 switch (unit_flags & TIME_UNIT_MASK) {
2407 case TIME_UNIT_US: omult = 1000000; break;
2408 case TIME_UNIT_MS: omult = 1000; break;
2409 case TIME_UNIT_S: break;
2410 case TIME_UNIT_MIN: odiv = 60; break;
2411 case TIME_UNIT_HOUR: odiv = 3600; break;
2412 case TIME_UNIT_DAY: odiv = 86400; break;
2413 default: break;
2414 }
2415
2416 value = 0;
2417
2418 while (1) {
2419 unsigned int j;
2420
2421 j = *text - '0';
2422 if (j > 9)
2423 break;
2424 text++;
2425 value *= 10;
2426 value += j;
2427 }
2428
2429 imult = idiv = 1;
2430 switch (*text) {
2431 case '\0': /* no unit = default unit */
2432 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002433 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002434 case 's': /* second = unscaled unit */
2435 break;
2436 case 'u': /* microsecond : "us" */
2437 if (text[1] == 's') {
2438 idiv = 1000000;
2439 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002440 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002441 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002442 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002443 case 'm': /* millisecond : "ms" or minute: "m" */
2444 if (text[1] == 's') {
2445 idiv = 1000;
2446 text++;
2447 } else
2448 imult = 60;
2449 break;
2450 case 'h': /* hour : "h" */
2451 imult = 3600;
2452 break;
2453 case 'd': /* day : "d" */
2454 imult = 86400;
2455 break;
2456 default:
2457 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002458 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002459 if (*(++text) != '\0') {
2460 ha_warning("unexpected character '%c' after the timer value '%s', only "
2461 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2462 " This will be reported as an error in next versions.\n", *text, str);
2463 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002464
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002465 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002466 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2467 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2468 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2469 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2470
Willy Tarreau9faebe32019-06-07 19:00:37 +02002471 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2472 if (result >= 0x80000000)
2473 return PARSE_TIME_OVER;
2474 if (!result && value)
2475 return PARSE_TIME_UNDER;
2476 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002477 return NULL;
2478}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002479
Emeric Brun39132b22010-01-04 14:57:24 +01002480/* this function converts the string starting at <text> to an unsigned int
2481 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002482 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002483 */
2484const char *parse_size_err(const char *text, unsigned *ret) {
2485 unsigned value = 0;
2486
Christopher Faulet82635a02020-12-11 09:30:45 +01002487 if (!isdigit((unsigned char)*text))
2488 return text;
2489
Emeric Brun39132b22010-01-04 14:57:24 +01002490 while (1) {
2491 unsigned int j;
2492
2493 j = *text - '0';
2494 if (j > 9)
2495 break;
2496 if (value > ~0U / 10)
2497 return text;
2498 value *= 10;
2499 if (value > (value + j))
2500 return text;
2501 value += j;
2502 text++;
2503 }
2504
2505 switch (*text) {
2506 case '\0':
2507 break;
2508 case 'K':
2509 case 'k':
2510 if (value > ~0U >> 10)
2511 return text;
2512 value = value << 10;
2513 break;
2514 case 'M':
2515 case 'm':
2516 if (value > ~0U >> 20)
2517 return text;
2518 value = value << 20;
2519 break;
2520 case 'G':
2521 case 'g':
2522 if (value > ~0U >> 30)
2523 return text;
2524 value = value << 30;
2525 break;
2526 default:
2527 return text;
2528 }
2529
Godbach58048a22015-01-28 17:36:16 +08002530 if (*text != '\0' && *++text != '\0')
2531 return text;
2532
Emeric Brun39132b22010-01-04 14:57:24 +01002533 *ret = value;
2534 return NULL;
2535}
2536
Willy Tarreau126d4062013-12-03 17:50:47 +01002537/*
2538 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002539 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002540 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002541 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002542 */
2543int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2544{
2545 int len;
2546 const char *p = source;
2547 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002548 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002549
2550 len = strlen(source);
2551 if (len % 2) {
2552 memprintf(err, "an even number of hex digit is expected");
2553 return 0;
2554 }
2555
2556 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002557
Willy Tarreau126d4062013-12-03 17:50:47 +01002558 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002559 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002560 if (!*binstr) {
2561 memprintf(err, "out of memory while loading string pattern");
2562 return 0;
2563 }
2564 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002565 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002566 else {
2567 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002568 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002569 len, *binstrlen);
2570 return 0;
2571 }
2572 alloc = 0;
2573 }
2574 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002575
2576 i = j = 0;
2577 while (j < len) {
2578 if (!ishex(p[i++]))
2579 goto bad_input;
2580 if (!ishex(p[i++]))
2581 goto bad_input;
2582 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2583 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002584 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002585
2586bad_input:
2587 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002588 if (alloc)
2589 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002590 return 0;
2591}
2592
Willy Tarreau946ba592009-05-10 15:41:18 +02002593/* copies at most <n> characters from <src> and always terminates with '\0' */
2594char *my_strndup(const char *src, int n)
2595{
2596 int len = 0;
2597 char *ret;
2598
2599 while (len < n && src[len])
2600 len++;
2601
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002602 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002603 if (!ret)
2604 return ret;
2605 memcpy(ret, src, len);
2606 ret[len] = '\0';
2607 return ret;
2608}
2609
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002610/*
2611 * search needle in haystack
2612 * returns the pointer if found, returns NULL otherwise
2613 */
2614const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2615{
2616 const void *c = NULL;
2617 unsigned char f;
2618
2619 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2620 return NULL;
2621
2622 f = *(char *)needle;
2623 c = haystack;
2624 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2625 if ((haystacklen - (c - haystack)) < needlelen)
2626 return NULL;
2627
2628 if (memcmp(c, needle, needlelen) == 0)
2629 return c;
2630 ++c;
2631 }
2632 return NULL;
2633}
2634
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002635/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002636size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2637{
2638 size_t ret = 0;
2639
2640 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2641 str++;
2642 ret++;
2643 }
2644 return ret;
2645}
2646
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002647/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002648size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2649{
2650 size_t ret = 0;
2651
2652 while (ret < len) {
2653 if(memchr(reject, *((int *)str), rejectlen))
2654 return ret;
2655 str++;
2656 ret++;
2657 }
2658 return ret;
2659}
2660
Willy Tarreau482b00d2009-10-04 22:48:42 +02002661/* This function returns the first unused key greater than or equal to <key> in
2662 * ID tree <root>. Zero is returned if no place is found.
2663 */
2664unsigned int get_next_id(struct eb_root *root, unsigned int key)
2665{
2666 struct eb32_node *used;
2667
2668 do {
2669 used = eb32_lookup_ge(root, key);
2670 if (!used || used->key > key)
2671 return key; /* key is available */
2672 key++;
2673 } while (key);
2674 return key;
2675}
2676
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002677/* dump the full tree to <file> in DOT format for debugging purposes. Will
2678 * optionally highlight node <subj> if found, depending on operation <op> :
2679 * 0 : nothing
2680 * >0 : insertion, node/leaf are surrounded in red
2681 * <0 : removal, node/leaf are dashed with no background
2682 * Will optionally add "desc" as a label on the graph if set and non-null.
2683 */
2684void 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 +01002685{
2686 struct eb32sc_node *node;
2687 unsigned long scope = -1;
2688
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002689 fprintf(file, "digraph ebtree {\n");
2690
2691 if (desc && *desc) {
2692 fprintf(file,
2693 " fontname=\"fixed\";\n"
2694 " fontsize=8;\n"
2695 " label=\"%s\";\n", desc);
2696 }
2697
Willy Tarreaued3cda02017-11-15 15:04:05 +01002698 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002699 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2700 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002701 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2702 );
2703
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002704 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002705 (long)eb_root_to_node(root),
2706 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002707 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2708
2709 node = eb32sc_first(root, scope);
2710 while (node) {
2711 if (node->node.node_p) {
2712 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002713 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2714 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2715 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002716
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002717 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002718 (long)node,
2719 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002720 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002721
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002722 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002723 (long)node,
2724 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002725 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2726
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002727 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002728 (long)node,
2729 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002730 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2731 }
2732
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002733 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2734 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2735 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002736
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002737 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002738 (long)node,
2739 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002740 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002741 node = eb32sc_next(node, scope);
2742 }
2743 fprintf(file, "}\n");
2744}
2745
Willy Tarreau348238b2010-01-18 15:05:57 +01002746/* This function compares a sample word possibly followed by blanks to another
2747 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2748 * otherwise zero. This intends to be used when checking HTTP headers for some
2749 * values. Note that it validates a word followed only by blanks but does not
2750 * validate a word followed by blanks then other chars.
2751 */
2752int word_match(const char *sample, int slen, const char *word, int wlen)
2753{
2754 if (slen < wlen)
2755 return 0;
2756
2757 while (wlen) {
2758 char c = *sample ^ *word;
2759 if (c && c != ('A' ^ 'a'))
2760 return 0;
2761 sample++;
2762 word++;
2763 slen--;
2764 wlen--;
2765 }
2766
2767 while (slen) {
2768 if (*sample != ' ' && *sample != '\t')
2769 return 0;
2770 sample++;
2771 slen--;
2772 }
2773 return 1;
2774}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002775
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002776/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2777 * is particularly fast because it avoids expensive operations such as
2778 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002779 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002780 */
2781unsigned int inetaddr_host(const char *text)
2782{
2783 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2784 register unsigned int dig100, dig10, dig1;
2785 int s;
2786 const char *p, *d;
2787
2788 dig1 = dig10 = dig100 = ascii_zero;
2789 s = 24;
2790
2791 p = text;
2792 while (1) {
2793 if (((unsigned)(*p - '0')) <= 9) {
2794 p++;
2795 continue;
2796 }
2797
2798 /* here, we have a complete byte between <text> and <p> (exclusive) */
2799 if (p == text)
2800 goto end;
2801
2802 d = p - 1;
2803 dig1 |= (unsigned int)(*d << s);
2804 if (d == text)
2805 goto end;
2806
2807 d--;
2808 dig10 |= (unsigned int)(*d << s);
2809 if (d == text)
2810 goto end;
2811
2812 d--;
2813 dig100 |= (unsigned int)(*d << s);
2814 end:
2815 if (!s || *p != '.')
2816 break;
2817
2818 s -= 8;
2819 text = ++p;
2820 }
2821
2822 dig100 -= ascii_zero;
2823 dig10 -= ascii_zero;
2824 dig1 -= ascii_zero;
2825 return ((dig100 * 10) + dig10) * 10 + dig1;
2826}
2827
2828/*
2829 * Idem except the first unparsed character has to be passed in <stop>.
2830 */
2831unsigned int inetaddr_host_lim(const char *text, const char *stop)
2832{
2833 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2834 register unsigned int dig100, dig10, dig1;
2835 int s;
2836 const char *p, *d;
2837
2838 dig1 = dig10 = dig100 = ascii_zero;
2839 s = 24;
2840
2841 p = text;
2842 while (1) {
2843 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2844 p++;
2845 continue;
2846 }
2847
2848 /* here, we have a complete byte between <text> and <p> (exclusive) */
2849 if (p == text)
2850 goto end;
2851
2852 d = p - 1;
2853 dig1 |= (unsigned int)(*d << s);
2854 if (d == text)
2855 goto end;
2856
2857 d--;
2858 dig10 |= (unsigned int)(*d << s);
2859 if (d == text)
2860 goto end;
2861
2862 d--;
2863 dig100 |= (unsigned int)(*d << s);
2864 end:
2865 if (!s || p == stop || *p != '.')
2866 break;
2867
2868 s -= 8;
2869 text = ++p;
2870 }
2871
2872 dig100 -= ascii_zero;
2873 dig10 -= ascii_zero;
2874 dig1 -= ascii_zero;
2875 return ((dig100 * 10) + dig10) * 10 + dig1;
2876}
2877
2878/*
2879 * Idem except the pointer to first unparsed byte is returned into <ret> which
2880 * must not be NULL.
2881 */
Willy Tarreau74172752010-10-15 23:21:42 +02002882unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002883{
2884 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2885 register unsigned int dig100, dig10, dig1;
2886 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002887 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002888
2889 dig1 = dig10 = dig100 = ascii_zero;
2890 s = 24;
2891
2892 p = text;
2893 while (1) {
2894 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2895 p++;
2896 continue;
2897 }
2898
2899 /* here, we have a complete byte between <text> and <p> (exclusive) */
2900 if (p == text)
2901 goto end;
2902
2903 d = p - 1;
2904 dig1 |= (unsigned int)(*d << s);
2905 if (d == text)
2906 goto end;
2907
2908 d--;
2909 dig10 |= (unsigned int)(*d << s);
2910 if (d == text)
2911 goto end;
2912
2913 d--;
2914 dig100 |= (unsigned int)(*d << s);
2915 end:
2916 if (!s || p == stop || *p != '.')
2917 break;
2918
2919 s -= 8;
2920 text = ++p;
2921 }
2922
2923 *ret = p;
2924 dig100 -= ascii_zero;
2925 dig10 -= ascii_zero;
2926 dig1 -= ascii_zero;
2927 return ((dig100 * 10) + dig10) * 10 + dig1;
2928}
2929
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002930/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2931 * or the number of chars read in case of success. Maybe this could be replaced
2932 * by one of the functions above. Also, apparently this function does not support
2933 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002934 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002935 */
2936int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2937{
2938 const char *addr;
2939 int saw_digit, octets, ch;
2940 u_char tmp[4], *tp;
2941 const char *cp = buf;
2942
2943 saw_digit = 0;
2944 octets = 0;
2945 *(tp = tmp) = 0;
2946
2947 for (addr = buf; addr - buf < len; addr++) {
2948 unsigned char digit = (ch = *addr) - '0';
2949
2950 if (digit > 9 && ch != '.')
2951 break;
2952
2953 if (digit <= 9) {
2954 u_int new = *tp * 10 + digit;
2955
2956 if (new > 255)
2957 return 0;
2958
2959 *tp = new;
2960
2961 if (!saw_digit) {
2962 if (++octets > 4)
2963 return 0;
2964 saw_digit = 1;
2965 }
2966 } else if (ch == '.' && saw_digit) {
2967 if (octets == 4)
2968 return 0;
2969
2970 *++tp = 0;
2971 saw_digit = 0;
2972 } else
2973 return 0;
2974 }
2975
2976 if (octets < 4)
2977 return 0;
2978
2979 memcpy(&dst->s_addr, tmp, 4);
2980 return addr - cp;
2981}
2982
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002983/* This function converts the string in <buf> of the len <len> to
2984 * struct in6_addr <dst> which must be allocated by the caller.
2985 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002986 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002987 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002988int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2989{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002990 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002991 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002992
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002993 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002994 return 0;
2995
2996 memcpy(null_term_ip6, buf, len);
2997 null_term_ip6[len] = '\0';
2998
Willy Tarreau075415a2013-12-12 11:29:39 +01002999 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003000 return 0;
3001
Willy Tarreau075415a2013-12-12 11:29:39 +01003002 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01003003 return 1;
3004}
3005
Willy Tarreauacf95772010-06-14 19:09:21 +02003006/* To be used to quote config arg positions. Returns the short string at <ptr>
3007 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
3008 * if ptr is NULL or empty. The string is locally allocated.
3009 */
3010const char *quote_arg(const char *ptr)
3011{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003012 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003013 int i;
3014
3015 if (!ptr || !*ptr)
3016 return "end of line";
3017 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003018 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003019 val[i] = *ptr++;
3020 val[i++] = '\'';
3021 val[i] = '\0';
3022 return val;
3023}
3024
Willy Tarreau5b180202010-07-18 10:40:48 +02003025/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3026int get_std_op(const char *str)
3027{
3028 int ret = -1;
3029
3030 if (*str == 'e' && str[1] == 'q')
3031 ret = STD_OP_EQ;
3032 else if (*str == 'n' && str[1] == 'e')
3033 ret = STD_OP_NE;
3034 else if (*str == 'l') {
3035 if (str[1] == 'e') ret = STD_OP_LE;
3036 else if (str[1] == 't') ret = STD_OP_LT;
3037 }
3038 else if (*str == 'g') {
3039 if (str[1] == 'e') ret = STD_OP_GE;
3040 else if (str[1] == 't') ret = STD_OP_GT;
3041 }
3042
3043 if (ret == -1 || str[2] != '\0')
3044 return -1;
3045 return ret;
3046}
3047
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003048/* hash a 32-bit integer to another 32-bit integer */
3049unsigned int full_hash(unsigned int a)
3050{
3051 return __full_hash(a);
3052}
3053
Willy Tarreauf3241112019-02-26 09:56:22 +01003054/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3055 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3056 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3057 * a popcount variant and is described here :
3058 * https://graphics.stanford.edu/~seander/bithacks.html
3059 */
3060unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3061{
3062 unsigned long a, b, c, d;
3063 unsigned int s;
3064 unsigned int t;
3065
3066 a = m - ((m >> 1) & ~0UL/3);
3067 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3068 c = (b + (b >> 4)) & ~0UL/0x11;
3069 d = (c + (c >> 8)) & ~0UL/0x101;
3070
3071 r++; // make r be 1..64
3072
3073 t = 0;
3074 s = LONGBITS;
3075 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003076 unsigned long d2 = (d >> 16) >> 16;
3077 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003078 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3079 }
3080
3081 t = (d >> (s - 16)) & 0xff;
3082 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3083 t = (c >> (s - 8)) & 0xf;
3084 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3085 t = (b >> (s - 4)) & 0x7;
3086 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3087 t = (a >> (s - 2)) & 0x3;
3088 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3089 t = (m >> (s - 1)) & 0x1;
3090 s -= ((t - r) & 256) >> 8;
3091
3092 return s - 1;
3093}
3094
3095/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3096 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3097 * using mask_prep_rank_map() below.
3098 */
3099unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3100 unsigned long a, unsigned long b,
3101 unsigned long c, unsigned long d)
3102{
3103 unsigned int s;
3104 unsigned int t;
3105
3106 r++; // make r be 1..64
3107
3108 t = 0;
3109 s = LONGBITS;
3110 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003111 unsigned long d2 = (d >> 16) >> 16;
3112 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003113 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3114 }
3115
3116 t = (d >> (s - 16)) & 0xff;
3117 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3118 t = (c >> (s - 8)) & 0xf;
3119 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3120 t = (b >> (s - 4)) & 0x7;
3121 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3122 t = (a >> (s - 2)) & 0x3;
3123 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3124 t = (m >> (s - 1)) & 0x1;
3125 s -= ((t - r) & 256) >> 8;
3126
3127 return s - 1;
3128}
3129
3130/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3131 * above.
3132 */
3133void mask_prep_rank_map(unsigned long m,
3134 unsigned long *a, unsigned long *b,
3135 unsigned long *c, unsigned long *d)
3136{
3137 *a = m - ((m >> 1) & ~0UL/3);
3138 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3139 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3140 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3141}
3142
David du Colombier4f92d322011-03-24 11:09:31 +01003143/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003144 * otherwise zero. Note that <addr> may not necessarily be aligned
3145 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003146 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003147int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003148{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003149 struct in_addr addr_copy;
3150
3151 memcpy(&addr_copy, addr, sizeof(addr_copy));
3152 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003153}
3154
3155/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003156 * otherwise zero. Note that <addr> may not necessarily be aligned
3157 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003158 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003159int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003160{
3161 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003162 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003163
Willy Tarreaueec1d382016-07-13 11:59:39 +02003164 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003165 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003166 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003167 (((int *)net)[i] & ((int *)mask)[i]))
3168 return 0;
3169 return 1;
3170}
3171
3172/* RFC 4291 prefix */
3173const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3174 0x00, 0x00, 0x00, 0x00,
3175 0x00, 0x00, 0xFF, 0xFF };
3176
Joseph Herlant32b83272018-11-15 11:58:28 -08003177/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003178 * Input and output may overlap.
3179 */
David du Colombier4f92d322011-03-24 11:09:31 +01003180void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3181{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003182 struct in_addr tmp_addr;
3183
3184 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003185 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003186 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003187}
3188
Joseph Herlant32b83272018-11-15 11:58:28 -08003189/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003190 * Return true if conversion is possible and false otherwise.
3191 */
3192int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3193{
3194 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3195 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3196 sizeof(struct in_addr));
3197 return 1;
3198 }
3199
3200 return 0;
3201}
3202
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003203/* compare two struct sockaddr_storage and return:
3204 * 0 (true) if the addr is the same in both
3205 * 1 (false) if the addr is not the same in both
3206 * -1 (unable) if one of the addr is not AF_INET*
3207 */
3208int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3209{
3210 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3211 return -1;
3212
3213 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3214 return -1;
3215
3216 if (ss1->ss_family != ss2->ss_family)
3217 return 1;
3218
3219 switch (ss1->ss_family) {
3220 case AF_INET:
3221 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3222 &((struct sockaddr_in *)ss2)->sin_addr,
3223 sizeof(struct in_addr)) != 0;
3224 case AF_INET6:
3225 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3226 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3227 sizeof(struct in6_addr)) != 0;
3228 }
3229
3230 return 1;
3231}
3232
Christopher Faulet9553de72021-02-26 09:12:50 +01003233/* compare a struct sockaddr_storage to a struct net_addr and return :
3234 * 0 (true) if <addr> is matching <net>
3235 * 1 (false) if <addr> is not matching <net>
3236 * -1 (unable) if <addr> or <net> is not AF_INET*
3237 */
3238int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3239{
3240 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3241 return -1;
3242
3243 if ((net->family != AF_INET) && (net->family != AF_INET6))
3244 return -1;
3245
3246 if (addr->ss_family != net->family)
3247 return 1;
3248
3249 if (addr->ss_family == AF_INET &&
3250 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3251 return 0;
3252 else {
3253 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3254 const struct in6_addr *nip6 = &net->addr.v6.ip;
3255 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3256
3257 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3258 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3259 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3260 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3261 return 0;
3262 }
3263
3264 return 1;
3265}
3266
Baptiste Assmann08396c82016-01-31 00:27:17 +01003267/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003268 * The caller must allocate and clear <dest> before calling.
3269 * The source must be in either AF_INET or AF_INET6 family, or the destination
3270 * address will be undefined. If the destination address used to hold a port,
3271 * it is preserved, so that this function can be used to switch to another
3272 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003273 */
3274struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3275{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003276 int prev_port;
3277
3278 prev_port = get_net_port(dest);
3279 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003280 dest->ss_family = source->ss_family;
3281
3282 /* copy new addr and apply it */
3283 switch (source->ss_family) {
3284 case AF_INET:
3285 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003286 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003287 break;
3288 case AF_INET6:
3289 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 +01003290 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003291 break;
3292 }
3293
3294 return dest;
3295}
3296
William Lallemand421f5b52012-02-06 18:15:57 +01003297char *human_time(int t, short hz_div) {
3298 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3299 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003300 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003301 int cnt=2; // print two numbers
3302
3303 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003304 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003305 return rv;
3306 }
3307
3308 if (unlikely(hz_div > 1))
3309 t /= hz_div;
3310
3311 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003312 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003313 cnt--;
3314 }
3315
3316 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003317 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003318 cnt--;
3319 }
3320
3321 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003322 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003323 cnt--;
3324 }
3325
3326 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003327 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003328
3329 return rv;
3330}
3331
3332const char *monthname[12] = {
3333 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3334 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3335};
3336
3337/* date2str_log: write a date in the format :
3338 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3339 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3340 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3341 *
3342 * without using sprintf. return a pointer to the last char written (\0) or
3343 * NULL if there isn't enough space.
3344 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003345char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003346{
3347
3348 if (size < 25) /* the size is fixed: 24 chars + \0 */
3349 return NULL;
3350
3351 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003352 if (!dst)
3353 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003354 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003355
William Lallemand421f5b52012-02-06 18:15:57 +01003356 memcpy(dst, monthname[tm->tm_mon], 3); // month
3357 dst += 3;
3358 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003359
William Lallemand421f5b52012-02-06 18:15:57 +01003360 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003361 if (!dst)
3362 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003363 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003364
William Lallemand421f5b52012-02-06 18:15:57 +01003365 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003366 if (!dst)
3367 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003368 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003369
William Lallemand421f5b52012-02-06 18:15:57 +01003370 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003371 if (!dst)
3372 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003373 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003374
William Lallemand421f5b52012-02-06 18:15:57 +01003375 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003376 if (!dst)
3377 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003378 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003379
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003380 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003381 if (!dst)
3382 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003383 *dst = '\0';
3384
3385 return dst;
3386}
3387
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003388/* Base year used to compute leap years */
3389#define TM_YEAR_BASE 1900
3390
3391/* Return the difference in seconds between two times (leap seconds are ignored).
3392 * Retrieved from glibc 2.18 source code.
3393 */
3394static int my_tm_diff(const struct tm *a, const struct tm *b)
3395{
3396 /* Compute intervening leap days correctly even if year is negative.
3397 * Take care to avoid int overflow in leap day calculations,
3398 * but it's OK to assume that A and B are close to each other.
3399 */
3400 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3401 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3402 int a100 = a4 / 25 - (a4 % 25 < 0);
3403 int b100 = b4 / 25 - (b4 % 25 < 0);
3404 int a400 = a100 >> 2;
3405 int b400 = b100 >> 2;
3406 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3407 int years = a->tm_year - b->tm_year;
3408 int days = (365 * years + intervening_leap_days
3409 + (a->tm_yday - b->tm_yday));
3410 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3411 + (a->tm_min - b->tm_min))
3412 + (a->tm_sec - b->tm_sec));
3413}
3414
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003415/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003416 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003417 * The string returned has the same format as returned by strftime(... "%z", tm).
3418 * Offsets are kept in an internal cache for better performances.
3419 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003420const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003421{
3422 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003423 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003424
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003425 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003426 struct tm tm_gmt;
3427 int diff;
3428 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003429
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003430 /* Pretend DST not active if its status is unknown */
3431 if (isdst < 0)
3432 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003433
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003434 /* Fetch the offset and initialize it if needed */
3435 gmt_offset = gmt_offsets[isdst & 0x01];
3436 if (unlikely(!*gmt_offset)) {
3437 get_gmtime(t, &tm_gmt);
3438 diff = my_tm_diff(tm, &tm_gmt);
3439 if (diff < 0) {
3440 diff = -diff;
3441 *gmt_offset = '-';
3442 } else {
3443 *gmt_offset = '+';
3444 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003445 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003446 diff /= 60; /* Convert to minutes */
3447 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3448 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003449
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003450 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003451}
3452
William Lallemand421f5b52012-02-06 18:15:57 +01003453/* gmt2str_log: write a date in the format :
3454 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3455 * return a pointer to the last char written (\0) or
3456 * NULL if there isn't enough space.
3457 */
3458char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3459{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003460 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003461 return NULL;
3462
3463 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003464 if (!dst)
3465 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003466 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003467
William Lallemand421f5b52012-02-06 18:15:57 +01003468 memcpy(dst, monthname[tm->tm_mon], 3); // month
3469 dst += 3;
3470 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003471
William Lallemand421f5b52012-02-06 18:15:57 +01003472 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003473 if (!dst)
3474 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003475 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003476
William Lallemand421f5b52012-02-06 18:15:57 +01003477 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003478 if (!dst)
3479 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003480 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003481
William Lallemand421f5b52012-02-06 18:15:57 +01003482 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003483 if (!dst)
3484 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003485 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003486
William Lallemand421f5b52012-02-06 18:15:57 +01003487 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003488 if (!dst)
3489 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003490 *dst++ = ' ';
3491 *dst++ = '+';
3492 *dst++ = '0';
3493 *dst++ = '0';
3494 *dst++ = '0';
3495 *dst++ = '0';
3496 *dst = '\0';
3497
3498 return dst;
3499}
3500
Yuxans Yao4e25b012012-10-19 10:36:09 +08003501/* localdate2str_log: write a date in the format :
3502 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003503 * Both t and tm must represent the same time.
3504 * return a pointer to the last char written (\0) or
3505 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003506 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003507char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003508{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003509 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003510 if (size < 27) /* the size is fixed: 26 chars + \0 */
3511 return NULL;
3512
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003513 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003514
Yuxans Yao4e25b012012-10-19 10:36:09 +08003515 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003516 if (!dst)
3517 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003518 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003519
Yuxans Yao4e25b012012-10-19 10:36:09 +08003520 memcpy(dst, monthname[tm->tm_mon], 3); // month
3521 dst += 3;
3522 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003523
Yuxans Yao4e25b012012-10-19 10:36:09 +08003524 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003525 if (!dst)
3526 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003527 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003528
Yuxans Yao4e25b012012-10-19 10:36:09 +08003529 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003530 if (!dst)
3531 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003532 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003533
Yuxans Yao4e25b012012-10-19 10:36:09 +08003534 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003535 if (!dst)
3536 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003537 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003538
Yuxans Yao4e25b012012-10-19 10:36:09 +08003539 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003540 if (!dst)
3541 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003542 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003543
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003544 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003545 dst += 5;
3546 *dst = '\0';
3547
3548 return dst;
3549}
3550
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003551/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3552 * It is meant as a portable replacement for timegm() for use with valid inputs.
3553 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3554 */
3555time_t my_timegm(const struct tm *tm)
3556{
3557 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3558 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3559 * sum of the extra N days for elapsed months. The sum of all these N
3560 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3561 * in a 5-bit word. This means that with 60 bits we can represent a
3562 * matrix of all these values at once, which is fast and efficient to
3563 * access. The extra February day for leap years is not counted here.
3564 *
3565 * Jan : none = 0 (0)
3566 * Feb : Jan = 3 (3)
3567 * Mar : Jan..Feb = 3 (3 + 0)
3568 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3569 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3570 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3571 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3572 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3573 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3574 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3575 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3576 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3577 */
3578 uint64_t extra =
3579 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3580 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3581 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3582 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3583
3584 unsigned int y = tm->tm_year + 1900;
3585 unsigned int m = tm->tm_mon;
3586 unsigned long days = 0;
3587
3588 /* days since 1/1/1970 for full years */
3589 days += days_since_zero(y) - days_since_zero(1970);
3590
3591 /* days for full months in the current year */
3592 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3593
3594 /* count + 1 after March for leap years. A leap year is a year multiple
3595 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3596 * is leap, 1900 isn't, 1904 is.
3597 */
3598 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3599 days++;
3600
3601 days += tm->tm_mday - 1;
3602 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3603}
3604
Thierry Fournier93127942016-01-20 18:49:45 +01003605/* This function check a char. It returns true and updates
3606 * <date> and <len> pointer to the new position if the
3607 * character is found.
3608 */
3609static inline int parse_expect_char(const char **date, int *len, char c)
3610{
3611 if (*len < 1 || **date != c)
3612 return 0;
3613 (*len)--;
3614 (*date)++;
3615 return 1;
3616}
3617
3618/* This function expects a string <str> of len <l>. It return true and updates.
3619 * <date> and <len> if the string matches, otherwise, it returns false.
3620 */
3621static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3622{
3623 if (*len < l || strncmp(*date, str, l) != 0)
3624 return 0;
3625 (*len) -= l;
3626 (*date) += l;
3627 return 1;
3628}
3629
3630/* This macro converts 3 chars name in integer. */
3631#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3632
3633/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3634 * / %x54.75.65 ; "Tue", case-sensitive
3635 * / %x57.65.64 ; "Wed", case-sensitive
3636 * / %x54.68.75 ; "Thu", case-sensitive
3637 * / %x46.72.69 ; "Fri", case-sensitive
3638 * / %x53.61.74 ; "Sat", case-sensitive
3639 * / %x53.75.6E ; "Sun", case-sensitive
3640 *
3641 * This array must be alphabetically sorted
3642 */
3643static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3644{
3645 if (*len < 3)
3646 return 0;
3647 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3648 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3649 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3650 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3651 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3652 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3653 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3654 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3655 default: return 0;
3656 }
3657 *len -= 3;
3658 *date += 3;
3659 return 1;
3660}
3661
3662/* month = %x4A.61.6E ; "Jan", case-sensitive
3663 * / %x46.65.62 ; "Feb", case-sensitive
3664 * / %x4D.61.72 ; "Mar", case-sensitive
3665 * / %x41.70.72 ; "Apr", case-sensitive
3666 * / %x4D.61.79 ; "May", case-sensitive
3667 * / %x4A.75.6E ; "Jun", case-sensitive
3668 * / %x4A.75.6C ; "Jul", case-sensitive
3669 * / %x41.75.67 ; "Aug", case-sensitive
3670 * / %x53.65.70 ; "Sep", case-sensitive
3671 * / %x4F.63.74 ; "Oct", case-sensitive
3672 * / %x4E.6F.76 ; "Nov", case-sensitive
3673 * / %x44.65.63 ; "Dec", case-sensitive
3674 *
3675 * This array must be alphabetically sorted
3676 */
3677static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3678{
3679 if (*len < 3)
3680 return 0;
3681 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3682 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3683 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3684 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3685 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3686 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3687 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3688 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3689 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3690 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3691 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3692 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3693 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3694 default: return 0;
3695 }
3696 *len -= 3;
3697 *date += 3;
3698 return 1;
3699}
3700
3701/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3702 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3703 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3704 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3705 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3706 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3707 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3708 *
3709 * This array must be alphabetically sorted
3710 */
3711static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3712{
3713 if (*len < 6) /* Minimum length. */
3714 return 0;
3715 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3716 case STR2I3('M','o','n'):
3717 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3718 tm->tm_wday = 1;
3719 return 1;
3720 case STR2I3('T','u','e'):
3721 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3722 tm->tm_wday = 2;
3723 return 1;
3724 case STR2I3('W','e','d'):
3725 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3726 tm->tm_wday = 3;
3727 return 1;
3728 case STR2I3('T','h','u'):
3729 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3730 tm->tm_wday = 4;
3731 return 1;
3732 case STR2I3('F','r','i'):
3733 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3734 tm->tm_wday = 5;
3735 return 1;
3736 case STR2I3('S','a','t'):
3737 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3738 tm->tm_wday = 6;
3739 return 1;
3740 case STR2I3('S','u','n'):
3741 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3742 tm->tm_wday = 7;
3743 return 1;
3744 }
3745 return 0;
3746}
3747
3748/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3749static inline int parse_digit(const char **date, int *len, int *digit)
3750{
3751 if (*len < 1 || **date < '0' || **date > '9')
3752 return 0;
3753 *digit = (**date - '0');
3754 (*date)++;
3755 (*len)--;
3756 return 1;
3757}
3758
3759/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3760static inline int parse_2digit(const char **date, int *len, int *digit)
3761{
3762 int value;
3763
3764 RET0_UNLESS(parse_digit(date, len, &value));
3765 (*digit) = value * 10;
3766 RET0_UNLESS(parse_digit(date, len, &value));
3767 (*digit) += value;
3768
3769 return 1;
3770}
3771
3772/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3773static inline int parse_4digit(const char **date, int *len, int *digit)
3774{
3775 int value;
3776
3777 RET0_UNLESS(parse_digit(date, len, &value));
3778 (*digit) = value * 1000;
3779
3780 RET0_UNLESS(parse_digit(date, len, &value));
3781 (*digit) += value * 100;
3782
3783 RET0_UNLESS(parse_digit(date, len, &value));
3784 (*digit) += value * 10;
3785
3786 RET0_UNLESS(parse_digit(date, len, &value));
3787 (*digit) += value;
3788
3789 return 1;
3790}
3791
3792/* time-of-day = hour ":" minute ":" second
3793 * ; 00:00:00 - 23:59:60 (leap second)
3794 *
3795 * hour = 2DIGIT
3796 * minute = 2DIGIT
3797 * second = 2DIGIT
3798 */
3799static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3800{
3801 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3802 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3803 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3804 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3805 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3806 return 1;
3807}
3808
3809/* From RFC7231
3810 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3811 *
3812 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3813 * ; fixed length/zone/capitalization subset of the format
3814 * ; see Section 3.3 of [RFC5322]
3815 *
3816 *
3817 * date1 = day SP month SP year
3818 * ; e.g., 02 Jun 1982
3819 *
3820 * day = 2DIGIT
3821 * year = 4DIGIT
3822 *
3823 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3824 *
3825 * time-of-day = hour ":" minute ":" second
3826 * ; 00:00:00 - 23:59:60 (leap second)
3827 *
3828 * hour = 2DIGIT
3829 * minute = 2DIGIT
3830 * second = 2DIGIT
3831 *
3832 * DIGIT = decimal 0-9
3833 */
3834int parse_imf_date(const char *date, int len, struct tm *tm)
3835{
David Carlier327298c2016-11-20 10:42:38 +00003836 /* tm_gmtoff, if present, ought to be zero'ed */
3837 memset(tm, 0, sizeof(*tm));
3838
Thierry Fournier93127942016-01-20 18:49:45 +01003839 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3840 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3841 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3842 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3843 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3844 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3845 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3846 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3847 tm->tm_year -= 1900;
3848 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3849 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3850 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3851 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3852 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003853 return 1;
3854}
3855
3856/* From RFC7231
3857 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3858 *
3859 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3860 * date2 = day "-" month "-" 2DIGIT
3861 * ; e.g., 02-Jun-82
3862 *
3863 * day = 2DIGIT
3864 */
3865int parse_rfc850_date(const char *date, int len, struct tm *tm)
3866{
3867 int year;
3868
David Carlier327298c2016-11-20 10:42:38 +00003869 /* tm_gmtoff, if present, ought to be zero'ed */
3870 memset(tm, 0, sizeof(*tm));
3871
Thierry Fournier93127942016-01-20 18:49:45 +01003872 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3873 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3874 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3875 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3876 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3877 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3878 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3879
3880 /* year = 2DIGIT
3881 *
3882 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3883 * two-digit year, MUST interpret a timestamp that appears to be more
3884 * than 50 years in the future as representing the most recent year in
3885 * the past that had the same last two digits.
3886 */
3887 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3888
3889 /* expect SP */
3890 if (!parse_expect_char(&date, &len, ' ')) {
3891 /* Maybe we have the date with 4 digits. */
3892 RET0_UNLESS(parse_2digit(&date, &len, &year));
3893 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3894 /* expect SP */
3895 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3896 } else {
3897 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3898 * tm_year is the number of year since 1900, so for +1900, we
3899 * do nothing, and for +2000, we add 100.
3900 */
3901 if (tm->tm_year <= 60)
3902 tm->tm_year += 100;
3903 }
3904
3905 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3906 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3907 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3908 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003909
3910 return 1;
3911}
3912
3913/* From RFC7231
3914 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3915 *
3916 * asctime-date = day-name SP date3 SP time-of-day SP year
3917 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3918 * ; e.g., Jun 2
3919 *
3920 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3921 * whitespace in an HTTP-date beyond that specifically included as SP in
3922 * the grammar.
3923 */
3924int parse_asctime_date(const char *date, int len, struct tm *tm)
3925{
David Carlier327298c2016-11-20 10:42:38 +00003926 /* tm_gmtoff, if present, ought to be zero'ed */
3927 memset(tm, 0, sizeof(*tm));
3928
Thierry Fournier93127942016-01-20 18:49:45 +01003929 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3930 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3931 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3932 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3933
3934 /* expect SP and 1DIGIT or 2DIGIT */
3935 if (parse_expect_char(&date, &len, ' '))
3936 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3937 else
3938 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3939
3940 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3941 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3942 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3943 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3944 tm->tm_year -= 1900;
3945 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003946 return 1;
3947}
3948
3949/* From RFC7231
3950 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3951 *
3952 * HTTP-date = IMF-fixdate / obs-date
3953 * obs-date = rfc850-date / asctime-date
3954 *
3955 * parses an HTTP date in the RFC format and is accepted
3956 * alternatives. <date> is the strinf containing the date,
3957 * len is the len of the string. <tm> is filled with the
3958 * parsed time. We must considers this time as GMT.
3959 */
3960int parse_http_date(const char *date, int len, struct tm *tm)
3961{
3962 if (parse_imf_date(date, len, tm))
3963 return 1;
3964
3965 if (parse_rfc850_date(date, len, tm))
3966 return 1;
3967
3968 if (parse_asctime_date(date, len, tm))
3969 return 1;
3970
3971 return 0;
3972}
3973
Willy Tarreau4deeb102021-01-29 10:47:52 +01003974/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3975 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3976 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3977 * surrounded by <pfx> and <sfx> respectively if not NULL.
3978 */
3979int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3980{
3981 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3982 const char *unit;
3983
3984 if (!pfx)
3985 pfx = "";
3986 if (!sfx)
3987 sfx = "";
3988
3989 do {
3990 unit = " - "; if (val <= 0.0) break;
3991 unit = "ns"; if (val < 1000.0) break;
3992 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3993 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3994 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3995 unit = "m "; val /= 60.0; if (val < 60.0) break;
3996 unit = "h "; val /= 60.0; if (val < 24.0) break;
3997 unit = "d "; val /= 24.0; if (val < 365.0) break;
3998 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3999 unit = " inf "; val = 0.0; break;
4000 } while (0);
4001
4002 if (val <= 0.0)
4003 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
4004 else if (val < 10.0)
4005 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
4006 else if (val < 100.0)
4007 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
4008 else
4009 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4010}
4011
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004012/* Dynamically allocates a string of the proper length to hold the formatted
4013 * output. NULL is returned on error. The caller is responsible for freeing the
4014 * memory area using free(). The resulting string is returned in <out> if the
4015 * pointer is not NULL. A previous version of <out> might be used to build the
4016 * new string, and it will be freed before returning if it is not NULL, which
4017 * makes it possible to build complex strings from iterative calls without
4018 * having to care about freeing intermediate values, as in the example below :
4019 *
4020 * memprintf(&err, "invalid argument: '%s'", arg);
4021 * ...
4022 * memprintf(&err, "parser said : <%s>\n", *err);
4023 * ...
4024 * free(*err);
4025 *
4026 * This means that <err> must be initialized to NULL before first invocation.
4027 * The return value also holds the allocated string, which eases error checking
4028 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004029 * passed instead and it will be ignored. The returned message will then also
4030 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004031 *
4032 * It is also convenient to use it without any free except the last one :
4033 * err = NULL;
4034 * if (!fct1(err)) report(*err);
4035 * if (!fct2(err)) report(*err);
4036 * if (!fct3(err)) report(*err);
4037 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004038 *
4039 * memprintf relies on memvprintf. This last version can be called from any
4040 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004041 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004042char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004043{
4044 va_list args;
4045 char *ret = NULL;
4046 int allocated = 0;
4047 int needed = 0;
4048
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004049 if (!out)
4050 return NULL;
4051
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004052 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004053 char buf1;
4054
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004055 /* vsnprintf() will return the required length even when the
4056 * target buffer is NULL. We do this in a loop just in case
4057 * intermediate evaluations get wrong.
4058 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004059 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004060 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004061 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004062 if (needed < allocated) {
4063 /* Note: on Solaris 8, the first iteration always
4064 * returns -1 if allocated is zero, so we force a
4065 * retry.
4066 */
4067 if (!allocated)
4068 needed = 0;
4069 else
4070 break;
4071 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004072
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004073 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004074 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004075 } while (ret);
4076
4077 if (needed < 0) {
4078 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004079 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004080 }
4081
4082 if (out) {
4083 free(*out);
4084 *out = ret;
4085 }
4086
4087 return ret;
4088}
William Lallemand421f5b52012-02-06 18:15:57 +01004089
Christopher Faulet93a518f2017-10-24 11:25:33 +02004090char *memprintf(char **out, const char *format, ...)
4091{
4092 va_list args;
4093 char *ret = NULL;
4094
4095 va_start(args, format);
4096 ret = memvprintf(out, format, args);
4097 va_end(args);
4098
4099 return ret;
4100}
4101
Willy Tarreau21c705b2012-09-14 11:40:36 +02004102/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4103 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004104 * freed by the caller. It also supports being passed a NULL which results in the same
4105 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004106 * Example of use :
4107 * parse(cmd, &err); (callee: memprintf(&err, ...))
4108 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4109 * free(err);
4110 */
4111char *indent_msg(char **out, int level)
4112{
4113 char *ret, *in, *p;
4114 int needed = 0;
4115 int lf = 0;
4116 int lastlf = 0;
4117 int len;
4118
Willy Tarreau70eec382012-10-10 08:56:47 +02004119 if (!out || !*out)
4120 return NULL;
4121
Willy Tarreau21c705b2012-09-14 11:40:36 +02004122 in = *out - 1;
4123 while ((in = strchr(in + 1, '\n')) != NULL) {
4124 lastlf = in - *out;
4125 lf++;
4126 }
4127
4128 if (!lf) /* single line, no LF, return it as-is */
4129 return *out;
4130
4131 len = strlen(*out);
4132
4133 if (lf == 1 && lastlf == len - 1) {
4134 /* single line, LF at end, strip it and return as-is */
4135 (*out)[lastlf] = 0;
4136 return *out;
4137 }
4138
4139 /* OK now we have at least one LF, we need to process the whole string
4140 * as a multi-line string. What we'll do :
4141 * - prefix with an LF if there is none
4142 * - add <level> spaces before each line
4143 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4144 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4145 */
4146
4147 needed = 1 + level * (lf + 1) + len + 1;
4148 p = ret = malloc(needed);
4149 in = *out;
4150
4151 /* skip initial LFs */
4152 while (*in == '\n')
4153 in++;
4154
4155 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4156 while (*in) {
4157 *p++ = '\n';
4158 memset(p, ' ', level);
4159 p += level;
4160 do {
4161 *p++ = *in++;
4162 } while (*in && *in != '\n');
4163 if (*in)
4164 in++;
4165 }
4166 *p = 0;
4167
4168 free(*out);
4169 *out = ret;
4170
4171 return ret;
4172}
4173
Willy Tarreaua2c99112019-08-21 13:17:37 +02004174/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4175 * and end of lines replaced with <eol> if not 0. The first line to indent has
4176 * to be indicated in <first> (starts at zero), so that it is possible to skip
4177 * indenting the first line if it has to be appended after an existing message.
4178 * Empty strings are never indented, and NULL strings are considered empty both
4179 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4180 * character, non-zero otherwise.
4181 */
4182int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4183{
4184 int bol, lf;
4185 int pfxlen = pfx ? strlen(pfx) : 0;
4186
4187 if (!in)
4188 return 0;
4189
4190 bol = 1;
4191 lf = 0;
4192 while (*in) {
4193 if (bol && pfxlen) {
4194 if (first > 0)
4195 first--;
4196 else
4197 b_putblk(out, pfx, pfxlen);
4198 bol = 0;
4199 }
4200
4201 lf = (*in == '\n');
4202 bol |= lf;
4203 b_putchr(out, (lf && eol) ? eol : *in);
4204 in++;
4205 }
4206 return lf;
4207}
4208
Willy Tarreau9d22e562019-03-29 18:49:09 +01004209/* removes environment variable <name> from the environment as found in
4210 * environ. This is only provided as an alternative for systems without
4211 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004212 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004213 * <name> and to replace the matching pointers with the last pointer of
4214 * the array (since variables are not ordered).
4215 * It always returns 0 (success).
4216 */
4217int my_unsetenv(const char *name)
4218{
4219 extern char **environ;
4220 char **p = environ;
4221 int vars;
4222 int next;
4223 int len;
4224
4225 len = strlen(name);
4226 for (vars = 0; p[vars]; vars++)
4227 ;
4228 next = 0;
4229 while (next < vars) {
4230 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4231 next++;
4232 continue;
4233 }
4234 if (next < vars - 1)
4235 p[next] = p[vars - 1];
4236 p[--vars] = NULL;
4237 }
4238 return 0;
4239}
4240
Willy Tarreaudad36a32013-03-11 01:20:04 +01004241/* Convert occurrences of environment variables in the input string to their
4242 * corresponding value. A variable is identified as a series of alphanumeric
4243 * characters or underscores following a '$' sign. The <in> string must be
4244 * free()able. NULL returns NULL. The resulting string might be reallocated if
4245 * some expansion is made. Variable names may also be enclosed into braces if
4246 * needed (eg: to concatenate alphanum characters).
4247 */
4248char *env_expand(char *in)
4249{
4250 char *txt_beg;
4251 char *out;
4252 char *txt_end;
4253 char *var_beg;
4254 char *var_end;
4255 char *value;
4256 char *next;
4257 int out_len;
4258 int val_len;
4259
4260 if (!in)
4261 return in;
4262
4263 value = out = NULL;
4264 out_len = 0;
4265
4266 txt_beg = in;
4267 do {
4268 /* look for next '$' sign in <in> */
4269 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4270
4271 if (!*txt_end && !out) /* end and no expansion performed */
4272 return in;
4273
4274 val_len = 0;
4275 next = txt_end;
4276 if (*txt_end == '$') {
4277 char save;
4278
4279 var_beg = txt_end + 1;
4280 if (*var_beg == '{')
4281 var_beg++;
4282
4283 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004284 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004285 var_end++;
4286 }
4287
4288 next = var_end;
4289 if (*var_end == '}' && (var_beg > txt_end + 1))
4290 next++;
4291
4292 /* get value of the variable name at this location */
4293 save = *var_end;
4294 *var_end = '\0';
4295 value = getenv(var_beg);
4296 *var_end = save;
4297 val_len = value ? strlen(value) : 0;
4298 }
4299
Hubert Verstraete831962e2016-06-28 22:44:26 +02004300 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004301 if (txt_end > txt_beg) {
4302 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4303 out_len += txt_end - txt_beg;
4304 }
4305 if (val_len) {
4306 memcpy(out + out_len, value, val_len);
4307 out_len += val_len;
4308 }
4309 out[out_len] = 0;
4310 txt_beg = next;
4311 } while (*txt_beg);
4312
4313 /* here we know that <out> was allocated and that we don't need <in> anymore */
4314 free(in);
4315 return out;
4316}
4317
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004318
4319/* same as strstr() but case-insensitive and with limit length */
4320const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4321{
4322 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004323 unsigned int slen, plen;
4324 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004325
4326 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4327 return NULL;
4328
4329 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4330 return str1;
4331
4332 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4333 return NULL;
4334
4335 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 +02004336 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004337 start++;
4338 slen--;
4339 tmp1++;
4340
4341 if (tmp1 >= len_str1)
4342 return NULL;
4343
4344 /* if pattern longer than string */
4345 if (slen < plen)
4346 return NULL;
4347 }
4348
4349 sptr = start;
4350 pptr = (char *)str2;
4351
4352 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004353 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004354 sptr++;
4355 pptr++;
4356 tmp2++;
4357
4358 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4359 return start;
4360 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4361 return NULL;
4362 }
4363 }
4364 return NULL;
4365}
4366
Willy Tarreau3ff476e2022-03-30 10:02:56 +02004367/* Returns true if s1 < s2 < s3 otherwise zero. Both s1 and s3 may be NULL and
4368 * in this case only non-null strings are compared. This allows to pass initial
4369 * values in iterators and in sort functions.
4370 */
4371int strordered(const char *s1, const char *s2, const char *s3)
4372{
4373 return (!s1 || strcmp(s1, s2) < 0) && (!s3 || strcmp(s2, s3) < 0);
4374}
4375
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004376/* This function read the next valid utf8 char.
4377 * <s> is the byte srray to be decode, <len> is its length.
4378 * The function returns decoded char encoded like this:
4379 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4380 * are the length read. The decoded character is stored in <c>.
4381 */
4382unsigned char utf8_next(const char *s, int len, unsigned int *c)
4383{
4384 const unsigned char *p = (unsigned char *)s;
4385 int dec;
4386 unsigned char code = UTF8_CODE_OK;
4387
4388 if (len < 1)
4389 return UTF8_CODE_OK;
4390
4391 /* Check the type of UTF8 sequence
4392 *
4393 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4394 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4395 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4396 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4397 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4398 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4399 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4400 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4401 */
4402 switch (*p) {
4403 case 0x00 ... 0x7f:
4404 *c = *p;
4405 return UTF8_CODE_OK | 1;
4406
4407 case 0x80 ... 0xbf:
4408 *c = *p;
4409 return UTF8_CODE_BADSEQ | 1;
4410
4411 case 0xc0 ... 0xdf:
4412 if (len < 2) {
4413 *c = *p;
4414 return UTF8_CODE_BADSEQ | 1;
4415 }
4416 *c = *p & 0x1f;
4417 dec = 1;
4418 break;
4419
4420 case 0xe0 ... 0xef:
4421 if (len < 3) {
4422 *c = *p;
4423 return UTF8_CODE_BADSEQ | 1;
4424 }
4425 *c = *p & 0x0f;
4426 dec = 2;
4427 break;
4428
4429 case 0xf0 ... 0xf7:
4430 if (len < 4) {
4431 *c = *p;
4432 return UTF8_CODE_BADSEQ | 1;
4433 }
4434 *c = *p & 0x07;
4435 dec = 3;
4436 break;
4437
4438 case 0xf8 ... 0xfb:
4439 if (len < 5) {
4440 *c = *p;
4441 return UTF8_CODE_BADSEQ | 1;
4442 }
4443 *c = *p & 0x03;
4444 dec = 4;
4445 break;
4446
4447 case 0xfc ... 0xfd:
4448 if (len < 6) {
4449 *c = *p;
4450 return UTF8_CODE_BADSEQ | 1;
4451 }
4452 *c = *p & 0x01;
4453 dec = 5;
4454 break;
4455
4456 case 0xfe ... 0xff:
4457 default:
4458 *c = *p;
4459 return UTF8_CODE_BADSEQ | 1;
4460 }
4461
4462 p++;
4463
4464 while (dec > 0) {
4465
4466 /* need 0x10 for the 2 first bits */
4467 if ( ( *p & 0xc0 ) != 0x80 )
4468 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4469
4470 /* add data at char */
4471 *c = ( *c << 6 ) | ( *p & 0x3f );
4472
4473 dec--;
4474 p++;
4475 }
4476
4477 /* Check ovelong encoding.
4478 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4479 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4480 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4481 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004482 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004483 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4484 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4485 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4486 code |= UTF8_CODE_OVERLONG;
4487
4488 /* Check invalid UTF8 range. */
4489 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4490 (*c >= 0xfffe && *c <= 0xffff))
4491 code |= UTF8_CODE_INVRANGE;
4492
4493 return code | ((p-(unsigned char *)s)&0x0f);
4494}
4495
Maxime de Roucydc887852016-05-13 23:52:54 +02004496/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4497 * On failure : return 0 and <err> filled with an error message.
4498 * The caller is responsible for freeing the <err> and <str> copy
4499 * memory area using free()
4500 */
4501int list_append_word(struct list *li, const char *str, char **err)
4502{
4503 struct wordlist *wl;
4504
4505 wl = calloc(1, sizeof(*wl));
4506 if (!wl) {
4507 memprintf(err, "out of memory");
4508 goto fail_wl;
4509 }
4510
4511 wl->s = strdup(str);
4512 if (!wl->s) {
4513 memprintf(err, "out of memory");
4514 goto fail_wl_s;
4515 }
4516
Willy Tarreau2b718102021-04-21 07:32:39 +02004517 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004518
4519 return 1;
4520
4521fail_wl_s:
4522 free(wl->s);
4523fail_wl:
4524 free(wl);
4525 return 0;
4526}
4527
Willy Tarreau37101052019-05-20 16:48:20 +02004528/* indicates if a memory location may safely be read or not. The trick consists
4529 * in performing a harmless syscall using this location as an input and letting
4530 * the operating system report whether it's OK or not. For this we have the
4531 * stat() syscall, which will return EFAULT when the memory location supposed
4532 * to contain the file name is not readable. If it is readable it will then
4533 * either return 0 if the area contains an existing file name, or -1 with
4534 * another code. This must not be abused, and some audit systems might detect
4535 * this as abnormal activity. It's used only for unsafe dumps.
4536 */
4537int may_access(const void *ptr)
4538{
4539 struct stat buf;
4540
4541 if (stat(ptr, &buf) == 0)
4542 return 1;
4543 if (errno == EFAULT)
4544 return 0;
4545 return 1;
4546}
4547
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004548/* print a string of text buffer to <out>. The format is :
4549 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4550 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4551 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4552 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004553int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004554{
4555 unsigned char c;
Tim Duesterhus18795d42021-08-29 00:58:22 +02004556 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004557
Tim Duesterhus18795d42021-08-29 00:58:22 +02004558 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004559 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004560 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004561 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004562 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004563 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004564 }
4565 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004566 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004567 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004568 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004569 switch (c) {
4570 case ' ': c = ' '; break;
4571 case '\t': c = 't'; break;
4572 case '\n': c = 'n'; break;
4573 case '\r': c = 'r'; break;
4574 case '\e': c = 'e'; break;
4575 case '\\': c = '\\'; break;
4576 case '=': c = '='; break;
4577 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004578 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004579 }
4580 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004581 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004582 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004583 out->area[out->data++] = '\\';
4584 out->area[out->data++] = 'x';
4585 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
4591 return ptr;
4592}
4593
4594/* print a buffer in hexa.
4595 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4596 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004597int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004598{
4599 unsigned char c;
4600 int ptr = 0;
4601
4602 while (ptr < bsize) {
4603 c = buf[ptr];
4604
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004605 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004606 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004607 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4608 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004609
4610 ptr++;
4611 }
4612 return ptr;
4613}
4614
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004615/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4616 * prepending each line with prefix <pfx>. The output is *not* initialized.
4617 * The output will not wrap pas the buffer's end so it is more optimal if the
4618 * caller makes sure the buffer is aligned first. A trailing zero will always
4619 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004620 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4621 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004622 */
Willy Tarreau37101052019-05-20 16:48:20 +02004623void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004624{
4625 const unsigned char *d = buf;
4626 int i, j, start;
4627
4628 d = (const unsigned char *)(((unsigned long)buf) & -16);
4629 start = ((unsigned long)buf) & 15;
4630
4631 for (i = 0; i < start + len; i += 16) {
4632 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4633
Willy Tarreau37101052019-05-20 16:48:20 +02004634 // 0: unchecked, 1: checked safe, 2: danger
4635 unsafe = !!unsafe;
4636 if (unsafe && !may_access(d + i))
4637 unsafe = 2;
4638
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004639 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004640 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004641 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004642 else if (unsafe > 1)
4643 chunk_strcat(out, "** ");
4644 else
4645 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004646
4647 if (j == 7)
4648 chunk_strcat(out, "- ");
4649 }
4650 chunk_strcat(out, " ");
4651 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004652 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004653 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004654 else if (unsafe > 1)
4655 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004656 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004657 chunk_appendf(out, "%c", d[i + j]);
4658 else
4659 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004660 }
4661 chunk_strcat(out, "\n");
4662 }
4663}
4664
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004665/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4666 * enclosed in brackets after the address itself, formatted on 14 chars
4667 * including the "0x" prefix. This is meant to be used as a prefix for code
4668 * areas. For example:
4669 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4670 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4671 * is emitted. A NULL <pfx> will be considered empty.
4672 */
4673void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4674{
4675 int ok = 0;
4676 int i;
4677
4678 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4679
4680 for (i = 0; i < n; i++) {
4681 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4682 ok = may_access(addr + i);
4683 if (ok)
4684 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4685 else
4686 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4687 }
4688}
4689
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004690/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4691 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4692 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4693 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4694 * lines are respected within the limit of 70 output chars. Lines that are
4695 * continuation of a previous truncated line begin with "+" instead of " "
4696 * after the offset. The new pointer is returned.
4697 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004698int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004699 int *line, int ptr)
4700{
4701 int end;
4702 unsigned char c;
4703
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004704 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004705 if (end > out->size)
4706 return ptr;
4707
4708 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4709
4710 while (ptr < len && ptr < bsize) {
4711 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004712 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004713 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004714 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004715 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004716 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004717 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004718 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004719 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004720 switch (c) {
4721 case '\t': c = 't'; break;
4722 case '\n': c = 'n'; break;
4723 case '\r': c = 'r'; break;
4724 case '\e': c = 'e'; break;
4725 case '\\': c = '\\'; break;
4726 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004727 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004728 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004729 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004730 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004731 out->area[out->data++] = '\\';
4732 out->area[out->data++] = 'x';
4733 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4734 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004735 }
4736 if (buf[ptr++] == '\n') {
4737 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004738 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004739 *line = ptr;
4740 return ptr;
4741 }
4742 }
4743 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004744 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004745 return ptr;
4746}
4747
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004748/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004749 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4750 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004751 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004752void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4753 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004754{
Willy Tarreau73459792017-04-11 07:58:08 +02004755 unsigned int i;
4756 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004757
4758 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4759 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004760 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004761 for (j = 0; j < 8; j++) {
4762 if (b + j >= 0 && b + j < len)
4763 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4764 else
4765 fprintf(out, " ");
4766 }
4767
4768 if (b + j >= 0 && b + j < len)
4769 fputc('-', out);
4770 else
4771 fputc(' ', out);
4772
4773 for (j = 8; j < 16; j++) {
4774 if (b + j >= 0 && b + j < len)
4775 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4776 else
4777 fprintf(out, " ");
4778 }
4779
4780 fprintf(out, " ");
4781 for (j = 0; j < 16; j++) {
4782 if (b + j >= 0 && b + j < len) {
4783 if (isprint((unsigned char)buf[b + j]))
4784 fputc((unsigned char)buf[b + j], out);
4785 else
4786 fputc('.', out);
4787 }
4788 else
4789 fputc(' ', out);
4790 }
4791 fputc('\n', out);
4792 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004793}
4794
Willy Tarreaubb869862020-04-16 10:52:41 +02004795/* Tries to report the executable path name on platforms supporting this. If
4796 * not found or not possible, returns NULL.
4797 */
4798const char *get_exec_path()
4799{
4800 const char *ret = NULL;
4801
David Carlier43a56852022-03-04 15:50:48 +00004802#if defined(__linux__) && defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004803 long execfn = getauxval(AT_EXECFN);
4804
4805 if (execfn && execfn != ENOENT)
4806 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004807#elif defined(__FreeBSD__)
4808 Elf_Auxinfo *auxv;
4809 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4810 if (auxv->a_type == AT_EXECPATH) {
4811 ret = (const char *)auxv->a_un.a_ptr;
4812 break;
4813 }
4814 }
David Carlierbd2cced2021-08-17 08:44:25 +01004815#elif defined(__NetBSD__)
4816 AuxInfo *auxv;
4817 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4818 if (auxv->a_type == AT_SUN_EXECNAME) {
4819 ret = (const char *)auxv->a_v;
4820 break;
4821 }
4822 }
Willy Tarreaubb869862020-04-16 10:52:41 +02004823#endif
4824 return ret;
4825}
4826
Baruch Siache1651b22020-07-24 07:52:20 +03004827#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004828/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4829 * also returns the symbol size in <size>, otherwise returns 0 there.
4830 */
4831static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4832{
4833 int ret;
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004834#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreauf3d5c4b2022-01-28 09:42:29 +01004835 const ElfW(Sym) *sym __attribute__((may_alias));
Willy Tarreau9133e482020-03-04 10:19:36 +01004836
4837 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4838 if (ret)
4839 *size = sym ? sym->st_size : 0;
4840#else
David Carlierae5c42f2021-12-31 08:15:29 +00004841#if defined(__sun)
4842 ret = dladdr((void *)addr, dli);
4843#else
Willy Tarreau9133e482020-03-04 10:19:36 +01004844 ret = dladdr(addr, dli);
David Carlierae5c42f2021-12-31 08:15:29 +00004845#endif
Willy Tarreau9133e482020-03-04 10:19:36 +01004846 *size = 0;
4847#endif
4848 return ret;
4849}
Willy Tarreau64192392021-05-05 09:06:21 +02004850
4851/* Tries to retrieve the address of the first occurrence symbol <name>.
4852 * Note that NULL in return is not always an error as a symbol may have that
4853 * address in special situations.
4854 */
4855void *get_sym_curr_addr(const char *name)
4856{
4857 void *ptr = NULL;
4858
4859#ifdef RTLD_DEFAULT
4860 ptr = dlsym(RTLD_DEFAULT, name);
4861#endif
4862 return ptr;
4863}
4864
4865
4866/* Tries to retrieve the address of the next occurrence of symbol <name>
4867 * Note that NULL in return is not always an error as a symbol may have that
4868 * address in special situations.
4869 */
4870void *get_sym_next_addr(const char *name)
4871{
4872 void *ptr = NULL;
4873
4874#ifdef RTLD_NEXT
4875 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004876#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004877 return ptr;
4878}
4879
4880#else /* elf & linux & dl */
4881
4882/* no possible resolving on other platforms at the moment */
4883void *get_sym_curr_addr(const char *name)
4884{
4885 return NULL;
4886}
4887
4888void *get_sym_next_addr(const char *name)
4889{
4890 return NULL;
4891}
4892
4893#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004894
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004895/* Tries to append to buffer <buf> some indications about the symbol at address
4896 * <addr> using the following form:
4897 * lib:+0xoffset (unresolvable address from lib's base)
4898 * main+0xoffset (unresolvable address from main (+/-))
4899 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4900 * name (resolved exact exec address)
4901 * lib:name (resolved exact lib address)
4902 * name+0xoffset/0xsize (resolved address within exec symbol)
4903 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4904 *
4905 * The file name (lib or executable) is limited to what lies between the last
4906 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4907 * 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 +03004908 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004909 *
4910 * The symbol's base address is returned, or NULL when unresolved, in order to
4911 * allow the caller to match it against known ones.
4912 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004913const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004914{
4915 const struct {
4916 const void *func;
4917 const char *name;
4918 } fcts[] = {
4919 { .func = process_stream, .name = "process_stream" },
4920 { .func = task_run_applet, .name = "task_run_applet" },
Christopher Faulet4a7764a2022-04-01 16:58:52 +02004921 { .func = cs_conn_io_cb, .name = "cs_conn_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004922 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004923 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4924 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004925 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004926 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4927 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004928 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004929#ifdef USE_THREAD
4930 { .func = accept_queue_process, .name = "accept_queue_process" },
4931#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004932#ifdef USE_LUA
4933 { .func = hlua_process_task, .name = "hlua_process_task" },
4934#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004935#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004936 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4937 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4938#endif
4939 };
4940
Baruch Siache1651b22020-07-24 07:52:20 +03004941#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004942 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004943 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004944 const char *fname, *p;
4945#endif
4946 int i;
4947
4948 if (pfx)
4949 chunk_appendf(buf, "%s", pfx);
4950
4951 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4952 if (addr == fcts[i].func) {
4953 chunk_appendf(buf, "%s", fcts[i].name);
4954 return addr;
4955 }
4956 }
4957
Baruch Siache1651b22020-07-24 07:52:20 +03004958#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004959 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004960 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004961 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004962
4963 /* 1. prefix the library name if it's not the same object as the one
4964 * that contains the main function. The name is picked between last '/'
4965 * and first following '.'.
4966 */
4967 if (!dladdr(main, &dli_main))
4968 dli_main.dli_fbase = NULL;
4969
4970 if (dli_main.dli_fbase != dli.dli_fbase) {
4971 fname = dli.dli_fname;
4972 p = strrchr(fname, '/');
4973 if (p++)
4974 fname = p;
4975 p = strchr(fname, '.');
4976 if (!p)
4977 p = fname + strlen(fname);
4978
4979 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4980 }
4981
4982 /* 2. symbol name */
4983 if (dli.dli_sname) {
4984 /* known, dump it and return symbol's address (exact or relative) */
4985 chunk_appendf(buf, "%s", dli.dli_sname);
4986 if (addr != dli.dli_saddr) {
4987 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004988 if (size)
4989 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004990 }
4991 return dli.dli_saddr;
4992 }
4993 else if (dli_main.dli_fbase != dli.dli_fbase) {
4994 /* unresolved symbol from a known library, report relative offset */
4995 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4996 return NULL;
4997 }
Baruch Siache1651b22020-07-24 07:52:20 +03004998#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004999 unknown:
5000 /* unresolved symbol from the main file, report relative offset to main */
5001 if ((void*)addr < (void*)main)
5002 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
5003 else
5004 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
5005 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01005006}
5007
Willy Tarreau6ab7b212021-12-28 09:57:10 +01005008/* On systems where this is supported, let's provide a possibility to enumerate
5009 * the list of object files. The output is appended to a buffer initialized by
5010 * the caller, with one name per line. A trailing zero is always emitted if data
5011 * are written. Only real objects are dumped (executable and .so libs). The
5012 * function returns non-zero if it dumps anything. These functions do not make
5013 * use of the trash so that it is possible for the caller to call them with the
5014 * trash on input. The output format may be platform-specific but at least one
5015 * version must emit raw object file names when argument is zero.
5016 */
5017#if defined(HA_HAVE_DUMP_LIBS)
5018# if defined(HA_HAVE_DL_ITERATE_PHDR)
5019/* the private <data> we pass below is a dump context initialized like this */
5020struct dl_dump_ctx {
5021 struct buffer *buf;
5022 int with_addr;
5023};
5024
5025static int dl_dump_libs_cb(struct dl_phdr_info *info, size_t size, void *data)
5026{
5027 struct dl_dump_ctx *ctx = data;
5028 const char *fname;
5029 size_t p1, p2, beg, end;
5030 int idx;
5031
5032 if (!info || !info->dlpi_name)
5033 goto leave;
5034
5035 if (!*info->dlpi_name)
5036 fname = get_exec_path();
5037 else if (strchr(info->dlpi_name, '/'))
5038 fname = info->dlpi_name;
5039 else
5040 /* else it's a VDSO or similar and we're not interested */
5041 goto leave;
5042
5043 if (!ctx->with_addr)
5044 goto dump_name;
5045
5046 /* virtual addresses are relative to the load address and are per
5047 * pseudo-header, so we have to scan them all to find the furthest
5048 * one from the beginning. In this case we only dump entries if
5049 * they have at least one section.
5050 */
5051 beg = ~0; end = 0;
5052 for (idx = 0; idx < info->dlpi_phnum; idx++) {
5053 if (!info->dlpi_phdr[idx].p_memsz)
5054 continue;
5055 p1 = info->dlpi_phdr[idx].p_vaddr;
5056 if (p1 < beg)
5057 beg = p1;
5058 p2 = p1 + info->dlpi_phdr[idx].p_memsz - 1;
5059 if (p2 > end)
5060 end = p2;
5061 }
5062
5063 if (!idx)
5064 goto leave;
5065
5066 chunk_appendf(ctx->buf, "0x%012llx-0x%012llx (0x%07llx) ",
5067 (ullong)info->dlpi_addr + beg,
5068 (ullong)info->dlpi_addr + end,
5069 (ullong)(end - beg + 1));
5070 dump_name:
5071 chunk_appendf(ctx->buf, "%s\n", fname);
5072 leave:
5073 return 0;
5074}
5075
5076/* dumps lib names and optionally address ranges */
5077int dump_libs(struct buffer *output, int with_addr)
5078{
5079 struct dl_dump_ctx ctx = { .buf = output, .with_addr = with_addr };
5080 size_t old_data = output->data;
5081
5082 dl_iterate_phdr(dl_dump_libs_cb, &ctx);
5083 return output->data != old_data;
5084}
5085# else // no DL_ITERATE_PHDR
5086# error "No dump_libs() function for this platform"
5087# endif
5088#else // no HA_HAVE_DUMP_LIBS
5089
5090/* unsupported platform: do not dump anything */
5091int dump_libs(struct buffer *output, int with_addr)
5092{
5093 return 0;
5094}
5095
5096#endif // HA_HAVE_DUMP_LIBS
5097
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005098/*
5099 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005100 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005101 *
5102 * First, initializes the value with <sz> as address to 0 and initializes the
5103 * array with <nums> as address to NULL. Then allocates the array with <nums> as
5104 * address updating <sz> pointed value to the size of this array.
5105 *
5106 * Returns 1 if succeeded, 0 if not.
5107 */
5108int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
5109{
5110 unsigned int *n;
5111 const char *s, *end;
5112
5113 s = str;
5114 *sz = 0;
5115 end = str + strlen(str);
5116 *nums = n = NULL;
5117
5118 while (1) {
5119 unsigned int r;
5120
5121 if (s >= end)
5122 break;
5123
5124 r = read_uint(&s, end);
5125 /* Expected characters after having read an uint: '\0' or '.',
5126 * if '.', must not be terminal.
5127 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005128 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5129 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005130 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005131 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005132
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005133 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005134 if (!n)
5135 return 0;
5136
5137 n[(*sz)++] = r;
5138 }
5139 *nums = n;
5140
5141 return 1;
5142}
5143
Willy Tarreau4d589e72019-08-23 19:02:26 +02005144
5145/* returns the number of bytes needed to encode <v> as a varint. An inline
5146 * version exists for use with constants (__varint_bytes()).
5147 */
5148int varint_bytes(uint64_t v)
5149{
5150 int len = 1;
5151
5152 if (v >= 240) {
5153 v = (v - 240) >> 4;
5154 while (1) {
5155 len++;
5156 if (v < 128)
5157 break;
5158 v = (v - 128) >> 7;
5159 }
5160 }
5161 return len;
5162}
5163
Willy Tarreau52bf8392020-03-08 00:42:37 +01005164
5165/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005166static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005167
5168/* This is a thread-safe implementation of xoroshiro128** described below:
5169 * http://prng.di.unimi.it/
5170 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5171 * supports fast jumps and passes all common quality tests. It is thread-safe,
5172 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5173 * local lock on other ones.
5174 */
5175uint64_t ha_random64()
5176{
Willy Tarreau1544c142020-03-12 00:31:18 +01005177 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5178 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005179
5180#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5181 static HA_SPINLOCK_T rand_lock;
5182
5183 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5184#endif
5185
5186 old[0] = ha_random_state[0];
5187 old[1] = ha_random_state[1];
5188
5189#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5190 do {
5191#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005192 new[1] = old[0] ^ old[1];
5193 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5194 new[1] = rotl64(new[1], 37); // c
5195
5196#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5197 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5198#else
5199 ha_random_state[0] = new[0];
5200 ha_random_state[1] = new[1];
5201#if defined(USE_THREAD)
5202 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5203#endif
5204#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005205 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005206}
5207
5208/* seeds the random state using up to <len> bytes from <seed>, starting with
5209 * the first non-zero byte.
5210 */
5211void ha_random_seed(const unsigned char *seed, size_t len)
5212{
5213 size_t pos;
5214
5215 /* the seed must not be all zeroes, so we pre-fill it with alternating
5216 * bits and overwrite part of them with the block starting at the first
5217 * non-zero byte from the seed.
5218 */
5219 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5220
5221 for (pos = 0; pos < len; pos++)
5222 if (seed[pos] != 0)
5223 break;
5224
5225 if (pos == len)
5226 return;
5227
5228 seed += pos;
5229 len -= pos;
5230
5231 if (len > sizeof(ha_random_state))
5232 len = sizeof(ha_random_state);
5233
5234 memcpy(ha_random_state, seed, len);
5235}
5236
5237/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5238 * and is equivalent to calling ha_random64() as many times. It is used to
5239 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5240 * different generators (i.e. different processes after a fork). The <dist>
5241 * argument is the distance to jump to and is used in a loop so it rather not
5242 * be too large if the processing time is a concern.
5243 *
5244 * BEWARE: this function is NOT thread-safe and must not be called during
5245 * concurrent accesses to ha_random64().
5246 */
5247void ha_random_jump96(uint32_t dist)
5248{
5249 while (dist--) {
5250 uint64_t s0 = 0;
5251 uint64_t s1 = 0;
5252 int b;
5253
5254 for (b = 0; b < 64; b++) {
5255 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5256 s0 ^= ha_random_state[0];
5257 s1 ^= ha_random_state[1];
5258 }
5259 ha_random64();
5260 }
5261
5262 for (b = 0; b < 64; b++) {
5263 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5264 s0 ^= ha_random_state[0];
5265 s1 ^= ha_random_state[1];
5266 }
5267 ha_random64();
5268 }
5269 ha_random_state[0] = s0;
5270 ha_random_state[1] = s1;
5271 }
5272}
5273
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005274/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5275 * bytes large.
5276 */
5277void ha_generate_uuid(struct buffer *output)
5278{
5279 uint32_t rnd[4];
5280 uint64_t last;
5281
5282 last = ha_random64();
5283 rnd[0] = last;
5284 rnd[1] = last >> 32;
5285
5286 last = ha_random64();
5287 rnd[2] = last;
5288 rnd[3] = last >> 32;
5289
5290 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5291 rnd[0],
5292 rnd[1] & 0xFFFF,
5293 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5294 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5295 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5296}
5297
5298
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005299/* only used by parse_line() below. It supports writing in place provided that
5300 * <in> is updated to the next location before calling it. In that case, the
5301 * char at <in> may be overwritten.
5302 */
5303#define EMIT_CHAR(x) \
5304 do { \
5305 char __c = (char)(x); \
5306 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5307 err |= PARSE_ERR_OVERLAP; \
5308 if (outpos >= outmax) \
5309 err |= PARSE_ERR_TOOLARGE; \
5310 if (!err) \
5311 out[outpos] = __c; \
5312 outpos++; \
5313 } while (0)
5314
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005315/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005316 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5317 * extraneous ones are not emitted but <outlen> is updated so that the caller
5318 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5319 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005320 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5321 * it is guaranteed that at least one arg will point to the zero. It is safe
5322 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005323 *
5324 * <out> may overlap with <in> provided that it never goes further, in which
5325 * case the parser will accept to perform in-place parsing and unquoting/
5326 * unescaping but only if environment variables do not lead to expansion that
5327 * causes overlapping, otherwise the input string being destroyed, the error
5328 * will not be recoverable. Note that even during out-of-place <in> will
5329 * experience temporary modifications in-place for variable resolution and must
5330 * be writable, and will also receive zeroes to delimit words when using
5331 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5332 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5333 * starting point of the first invalid character sequence or unmatched
5334 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5335 * error reporting might be difficult since zeroes will have been inserted into
5336 * the string. One solution for the caller may consist in replacing all args
5337 * delimiters with spaces in this case.
5338 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005339uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, const char **errptr)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005340{
5341 char *quote = NULL;
5342 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005343 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005344 unsigned char hex1, hex2;
5345 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005346 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005347 size_t outpos = 0;
5348 int squote = 0;
5349 int dquote = 0;
5350 int arg = 0;
5351 uint32_t err = 0;
5352
5353 *nbargs = 0;
5354 *outlen = 0;
5355
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005356 /* argsmax may be -1 here, protecting args[] from any write */
5357 if (arg < argsmax)
5358 args[arg] = out;
5359
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005360 while (1) {
5361 if (*in >= '-' && *in != '\\') {
5362 /* speedup: directly send all regular chars starting
5363 * with '-', '.', '/', alnum etc...
5364 */
5365 EMIT_CHAR(*in++);
5366 continue;
5367 }
5368 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5369 /* end of line */
5370 break;
5371 }
5372 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5373 /* comment */
5374 break;
5375 }
5376 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5377 if (dquote) {
5378 dquote = 0;
5379 quote = NULL;
5380 }
5381 else {
5382 dquote = 1;
5383 quote = in;
5384 }
5385 in++;
5386 continue;
5387 }
5388 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5389 if (squote) {
5390 squote = 0;
5391 quote = NULL;
5392 }
5393 else {
5394 squote = 1;
5395 quote = in;
5396 }
5397 in++;
5398 continue;
5399 }
5400 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5401 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5402 * C equivalent value but only when they have a special meaning and within
5403 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5404 */
5405 char tosend = *in;
5406
5407 switch (in[1]) {
5408 case ' ':
5409 case '\\':
5410 tosend = in[1];
5411 in++;
5412 break;
5413
5414 case 't':
5415 tosend = '\t';
5416 in++;
5417 break;
5418
5419 case 'n':
5420 tosend = '\n';
5421 in++;
5422 break;
5423
5424 case 'r':
5425 tosend = '\r';
5426 in++;
5427 break;
5428
5429 case '#':
5430 /* escaping of "#" only if comments are supported */
5431 if (opts & PARSE_OPT_SHARP)
5432 in++;
5433 tosend = *in;
5434 break;
5435
5436 case '\'':
5437 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5438 if (opts & PARSE_OPT_SQUOTE && !squote)
5439 in++;
5440 tosend = *in;
5441 break;
5442
5443 case '"':
5444 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5445 if (opts & PARSE_OPT_DQUOTE && !squote)
5446 in++;
5447 tosend = *in;
5448 break;
5449
5450 case '$':
5451 /* escaping of '$' only inside double quotes and only if env supported */
5452 if (opts & PARSE_OPT_ENV && dquote)
5453 in++;
5454 tosend = *in;
5455 break;
5456
5457 case 'x':
5458 if (!ishex(in[2]) || !ishex(in[3])) {
5459 /* invalid or incomplete hex sequence */
5460 err |= PARSE_ERR_HEX;
5461 if (errptr)
5462 *errptr = in;
5463 goto leave;
5464 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005465 hex1 = toupper((unsigned char)in[2]) - '0';
5466 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005467 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5468 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5469 tosend = (hex1 << 4) + hex2;
5470 in += 3;
5471 break;
5472
5473 default:
5474 /* other combinations are not escape sequences */
5475 break;
5476 }
5477
5478 in++;
5479 EMIT_CHAR(tosend);
5480 }
5481 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5482 /* a non-escaped space is an argument separator */
5483 while (isspace((unsigned char)*in))
5484 in++;
5485 EMIT_CHAR(0);
5486 arg++;
5487 if (arg < argsmax)
5488 args[arg] = out + outpos;
5489 else
5490 err |= PARSE_ERR_TOOMANY;
5491 }
5492 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5493 /* environment variables are evaluated anywhere, or only
5494 * inside double quotes if they are supported.
5495 */
5496 char *var_name;
5497 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005498 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005499
5500 in++;
5501
5502 if (*in == '{')
5503 brace = in++;
5504
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005505 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005506 /* unacceptable character in variable name */
5507 err |= PARSE_ERR_VARNAME;
5508 if (errptr)
5509 *errptr = in;
5510 goto leave;
5511 }
5512
5513 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005514 if (*in == '.')
5515 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005516 while (isalnum((unsigned char)*in) || *in == '_')
5517 in++;
5518
5519 save_char = *in;
5520 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005521 if (unlikely(*var_name == '.')) {
5522 /* internal pseudo-variables */
5523 if (strcmp(var_name, ".LINE") == 0)
5524 value = ultoa(global.cfg_curr_line);
5525 else if (strcmp(var_name, ".FILE") == 0)
5526 value = global.cfg_curr_file;
5527 else if (strcmp(var_name, ".SECTION") == 0)
5528 value = global.cfg_curr_section;
5529 else {
5530 /* unsupported internal variable name */
5531 err |= PARSE_ERR_VARNAME;
5532 if (errptr)
5533 *errptr = var_name;
5534 goto leave;
5535 }
5536 } else {
5537 value = getenv(var_name);
5538 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005539 *in = save_char;
5540
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005541 /* support for '[*]' sequence to force word expansion,
5542 * only available inside braces */
5543 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5544 word_expand = in++;
5545
5546 if (*in++ != '*' || *in++ != ']') {
5547 err |= PARSE_ERR_WRONG_EXPAND;
5548 if (errptr)
5549 *errptr = word_expand;
5550 goto leave;
5551 }
5552 }
5553
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005554 if (brace) {
Willy Tarreauec347b12021-11-18 17:42:50 +01005555 if (*in == '-') {
5556 /* default value starts just after the '-' */
5557 if (!value)
5558 value = in + 1;
5559
5560 while (*in && *in != '}')
5561 in++;
5562 if (!*in)
5563 goto no_brace;
5564 *in = 0; // terminate the default value
5565 }
5566 else if (*in != '}') {
5567 no_brace:
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005568 /* unmatched brace */
5569 err |= PARSE_ERR_BRACE;
5570 if (errptr)
5571 *errptr = brace;
5572 goto leave;
5573 }
Willy Tarreauec347b12021-11-18 17:42:50 +01005574
5575 /* brace found, skip it */
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005576 in++;
5577 brace = NULL;
5578 }
5579
5580 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005581 while (*value) {
5582 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005583 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005584 EMIT_CHAR(0);
5585 ++arg;
5586 if (arg < argsmax)
5587 args[arg] = out + outpos;
5588 else
5589 err |= PARSE_ERR_TOOMANY;
5590
5591 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005592 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005593 ;
5594 } else {
5595 EMIT_CHAR(*value++);
5596 }
5597 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005598 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005599 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005600 }
5601 else {
5602 /* any other regular char */
5603 EMIT_CHAR(*in++);
5604 }
5605 }
5606
5607 /* end of output string */
5608 EMIT_CHAR(0);
5609 arg++;
5610
5611 if (quote) {
5612 /* unmatched quote */
5613 err |= PARSE_ERR_QUOTE;
5614 if (errptr)
5615 *errptr = quote;
5616 goto leave;
5617 }
5618 leave:
5619 *nbargs = arg;
5620 *outlen = outpos;
5621
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005622 /* empty all trailing args by making them point to the trailing zero,
5623 * at least the last one in any case.
5624 */
5625 if (arg > argsmax)
5626 arg = argsmax;
5627
5628 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005629 args[arg++] = out + outpos - 1;
5630
5631 return err;
5632}
5633#undef EMIT_CHAR
5634
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005635/* This is used to sanitize an input line that's about to be used for error reporting.
5636 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5637 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5638 * If non-printable chars are present in the output. It returns the new offset <pos>
5639 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5640 * be at least 6 to support two "..." otherwise the result is undefined. The line
5641 * itself must have at least 7 chars allocated for the same reason.
5642 */
5643size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5644{
5645 size_t shift = 0;
5646 char *out = line;
5647 char *in = line;
5648 char *end = line + width;
5649
5650 if (pos >= width) {
5651 /* if we have to shift, we'll be out of context, so let's
5652 * try to put <pos> at the center of width.
5653 */
5654 shift = pos - width / 2;
5655 in += shift + 3;
5656 end = out + width - 3;
5657 out[0] = out[1] = out[2] = '.';
5658 out += 3;
5659 }
5660
5661 while (out < end && *in) {
5662 if (isspace((unsigned char)*in))
5663 *out++ = ' ';
5664 else if (isprint((unsigned char)*in))
5665 *out++ = *in;
5666 else
5667 *out++ = '?';
5668 in++;
5669 }
5670
5671 if (end < line + width) {
5672 out[0] = out[1] = out[2] = '.';
5673 out += 3;
5674 }
5675
5676 *out++ = 0;
5677 return pos - shift;
5678}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005679
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005680/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005681 * transitions between characters. <fp> is a 1024-entries array indexed as
5682 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005683 * 1..26=letter, 27=digit, 28=other/begin/end.
5684 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005685 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005686void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005687{
5688 const char *p;
5689 int from, to;
5690 int c;
5691
Willy Tarreauba2c4452021-03-12 09:01:52 +01005692 from = 28; // begin
5693 for (p = word; *p; p++) {
5694 c = tolower(*p);
5695 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005696 case 'a'...'z': to = c - 'a' + 1; break;
5697 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5698 case '0'...'9': to = 27; break;
5699 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005700 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005701 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005702 fp[32 * from + to]++;
5703 from = to;
5704 }
5705 to = 28; // end
5706 fp[32 * from + to]++;
5707}
5708
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005709/* Initialize array <fp> with the fingerprint of word <word> by counting the
5710 * transitions between characters. <fp> is a 1024-entries array indexed as
5711 * 32*from+to. Positions for 'from' and 'to' are:
5712 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5713 */
5714void make_word_fingerprint(uint8_t *fp, const char *word)
5715{
5716 memset(fp, 0, 1024);
5717 update_word_fingerprint(fp, word);
5718}
5719
Willy Tarreauba2c4452021-03-12 09:01:52 +01005720/* Return the distance between two word fingerprints created by function
5721 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005722 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005723 */
5724int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5725{
5726 int i, k, dist = 0;
5727
5728 for (i = 0; i < 1024; i++) {
5729 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005730 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005731 }
5732 return dist;
5733}
5734
William Lallemand3aeb3f92021-08-21 23:59:56 +02005735/*
5736 * This function compares the loaded openssl version with a string <version>
5737 * This function use the same return code as compare_current_version:
5738 *
5739 * -1 : the version in argument is older than the current openssl version
5740 * 0 : the version in argument is the same as the current openssl version
5741 * 1 : the version in argument is newer than the current openssl version
5742 *
5743 * Or some errors:
5744 * -2 : openssl is not available on this process
5745 * -3 : the version in argument is not parsable
5746 */
5747int openssl_compare_current_version(const char *version)
5748{
5749#ifdef USE_OPENSSL
5750 int numversion;
5751
5752 numversion = openssl_version_parser(version);
5753 if (numversion == 0)
5754 return -3;
5755
5756 if (numversion < OPENSSL_VERSION_NUMBER)
5757 return -1;
5758 else if (numversion > OPENSSL_VERSION_NUMBER)
5759 return 1;
5760 else
5761 return 0;
5762#else
5763 return -2;
5764#endif
5765}
5766
Remi Tricot-Le Bretonb01179a2021-10-11 15:34:12 +02005767/*
5768 * This function compares the loaded openssl name with a string <name>
5769 * This function returns 0 if the OpenSSL name starts like the passed parameter,
5770 * 1 otherwise.
5771 */
5772int openssl_compare_current_name(const char *name)
5773{
5774#ifdef USE_OPENSSL
5775 int name_len = 0;
5776 const char *openssl_version = OpenSSL_version(OPENSSL_VERSION);
5777
5778 if (name) {
5779 name_len = strlen(name);
5780 if (strlen(name) <= strlen(openssl_version))
5781 return strncmp(openssl_version, name, name_len);
5782 }
5783#endif
5784 return 1;
5785}
5786
Willy Tarreau06e69b52021-03-02 14:01:35 +01005787static int init_tools_per_thread()
5788{
5789 /* Let's make each thread start from a different position */
5790 statistical_prng_state += tid * MAX_THREADS;
5791 if (!statistical_prng_state)
5792 statistical_prng_state++;
5793 return 1;
5794}
5795REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005796
Willy Tarreaubaaee002006-06-26 02:48:02 +02005797/*
5798 * Local variables:
5799 * c-indent-level: 8
5800 * c-basic-offset: 8
5801 * End:
5802 */