blob: 5d8483d4e31b8494e3b849219b3f0d6c69afd1b3 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
devnexen@gmail.comc4e52322021-08-17 12:55:49 +010019#if defined(__FreeBSD__)
20#include <elf.h>
21#include <dlfcn.h>
22extern void *__elf_aux_vector;
23#endif
24
David Carlierbd2cced2021-08-17 08:44:25 +010025#if defined(__NetBSD__)
26#include <sys/exec_elf.h>
27#include <dlfcn.h>
28#endif
29
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010030#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020031#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020033#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020034#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035#include <stdlib.h>
36#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010037#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020038#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010039#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020040#include <sys/stat.h>
41#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010042#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020043#include <netinet/in.h>
44#include <arpa/inet.h>
45
Willy Tarreau7b2108c2021-08-30 10:15:35 +020046#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreau30053062020-08-20 16:39:14 +020047#include <sys/auxv.h>
48#endif
49
Willy Tarreau48fbcae2020-06-03 18:09:46 +020050#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020051#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020052
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020053#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020054#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020055#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020056#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020057#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020058#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020059#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010060#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020061#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010062#include <haproxy/resolvers.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010063#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020064#include <haproxy/ssl_sock.h>
William Lallemand3aeb3f92021-08-21 23:59:56 +020065#include <haproxy/ssl_utils.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020066#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020067#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020068#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010069
Thierry Fournier93127942016-01-20 18:49:45 +010070/* This macro returns false if the test __x is false. Many
71 * of the following parsing function must be abort the processing
72 * if it returns 0, so this macro is useful for writing light code.
73 */
74#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
75
Willy Tarreau56adcf22012-12-23 18:00:29 +010076/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020077 * 2^64-1 = 18446744073709551615 or
78 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020079 *
80 * The HTML version needs room for adding the 25 characters
81 * '<span class="rls"></span>' around digits at positions 3N+1 in order
82 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020083 */
Christopher Faulet99bca652017-11-14 16:47:26 +010084THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
85THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020086
Willy Tarreau588297f2014-06-16 15:16:40 +020087/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
88 * to quote strings larger than a max configuration line.
89 */
Christopher Faulet99bca652017-11-14 16:47:26 +010090THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
91THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020092
Willy Tarreau06e69b52021-03-02 14:01:35 +010093/* thread-local PRNG state. It's modified to start from a different sequence
94 * on all threads upon startup. It must not be used or anything beyond getting
95 * statistical values as it's 100% predictable.
96 */
97THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
98
Willy Tarreaubaaee002006-06-26 02:48:02 +020099/*
William Lallemande7340ec2012-01-24 11:15:39 +0100100 * unsigned long long ASCII representation
101 *
102 * return the last char '\0' or NULL if no enough
103 * space in dst
104 */
105char *ulltoa(unsigned long long n, char *dst, size_t size)
106{
107 int i = 0;
108 char *res;
109
110 switch(n) {
111 case 1ULL ... 9ULL:
112 i = 0;
113 break;
114
115 case 10ULL ... 99ULL:
116 i = 1;
117 break;
118
119 case 100ULL ... 999ULL:
120 i = 2;
121 break;
122
123 case 1000ULL ... 9999ULL:
124 i = 3;
125 break;
126
127 case 10000ULL ... 99999ULL:
128 i = 4;
129 break;
130
131 case 100000ULL ... 999999ULL:
132 i = 5;
133 break;
134
135 case 1000000ULL ... 9999999ULL:
136 i = 6;
137 break;
138
139 case 10000000ULL ... 99999999ULL:
140 i = 7;
141 break;
142
143 case 100000000ULL ... 999999999ULL:
144 i = 8;
145 break;
146
147 case 1000000000ULL ... 9999999999ULL:
148 i = 9;
149 break;
150
151 case 10000000000ULL ... 99999999999ULL:
152 i = 10;
153 break;
154
155 case 100000000000ULL ... 999999999999ULL:
156 i = 11;
157 break;
158
159 case 1000000000000ULL ... 9999999999999ULL:
160 i = 12;
161 break;
162
163 case 10000000000000ULL ... 99999999999999ULL:
164 i = 13;
165 break;
166
167 case 100000000000000ULL ... 999999999999999ULL:
168 i = 14;
169 break;
170
171 case 1000000000000000ULL ... 9999999999999999ULL:
172 i = 15;
173 break;
174
175 case 10000000000000000ULL ... 99999999999999999ULL:
176 i = 16;
177 break;
178
179 case 100000000000000000ULL ... 999999999999999999ULL:
180 i = 17;
181 break;
182
183 case 1000000000000000000ULL ... 9999999999999999999ULL:
184 i = 18;
185 break;
186
187 case 10000000000000000000ULL ... ULLONG_MAX:
188 i = 19;
189 break;
190 }
191 if (i + 2 > size) // (i + 1) + '\0'
192 return NULL; // too long
193 res = dst + i + 1;
194 *res = '\0';
195 for (; i >= 0; i--) {
196 dst[i] = n % 10ULL + '0';
197 n /= 10ULL;
198 }
199 return res;
200}
201
202/*
203 * unsigned long ASCII representation
204 *
205 * return the last char '\0' or NULL if no enough
206 * space in dst
207 */
208char *ultoa_o(unsigned long n, char *dst, size_t size)
209{
210 int i = 0;
211 char *res;
212
213 switch (n) {
214 case 0U ... 9UL:
215 i = 0;
216 break;
217
218 case 10U ... 99UL:
219 i = 1;
220 break;
221
222 case 100U ... 999UL:
223 i = 2;
224 break;
225
226 case 1000U ... 9999UL:
227 i = 3;
228 break;
229
230 case 10000U ... 99999UL:
231 i = 4;
232 break;
233
234 case 100000U ... 999999UL:
235 i = 5;
236 break;
237
238 case 1000000U ... 9999999UL:
239 i = 6;
240 break;
241
242 case 10000000U ... 99999999UL:
243 i = 7;
244 break;
245
246 case 100000000U ... 999999999UL:
247 i = 8;
248 break;
249#if __WORDSIZE == 32
250
251 case 1000000000ULL ... ULONG_MAX:
252 i = 9;
253 break;
254
255#elif __WORDSIZE == 64
256
257 case 1000000000ULL ... 9999999999UL:
258 i = 9;
259 break;
260
261 case 10000000000ULL ... 99999999999UL:
262 i = 10;
263 break;
264
265 case 100000000000ULL ... 999999999999UL:
266 i = 11;
267 break;
268
269 case 1000000000000ULL ... 9999999999999UL:
270 i = 12;
271 break;
272
273 case 10000000000000ULL ... 99999999999999UL:
274 i = 13;
275 break;
276
277 case 100000000000000ULL ... 999999999999999UL:
278 i = 14;
279 break;
280
281 case 1000000000000000ULL ... 9999999999999999UL:
282 i = 15;
283 break;
284
285 case 10000000000000000ULL ... 99999999999999999UL:
286 i = 16;
287 break;
288
289 case 100000000000000000ULL ... 999999999999999999UL:
290 i = 17;
291 break;
292
293 case 1000000000000000000ULL ... 9999999999999999999UL:
294 i = 18;
295 break;
296
297 case 10000000000000000000ULL ... ULONG_MAX:
298 i = 19;
299 break;
300
301#endif
302 }
303 if (i + 2 > size) // (i + 1) + '\0'
304 return NULL; // too long
305 res = dst + i + 1;
306 *res = '\0';
307 for (; i >= 0; i--) {
308 dst[i] = n % 10U + '0';
309 n /= 10U;
310 }
311 return res;
312}
313
314/*
315 * signed long ASCII representation
316 *
317 * return the last char '\0' or NULL if no enough
318 * space in dst
319 */
320char *ltoa_o(long int n, char *dst, size_t size)
321{
322 char *pos = dst;
323
324 if (n < 0) {
325 if (size < 3)
326 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
327 *pos = '-';
328 pos++;
329 dst = ultoa_o(-n, pos, size - 1);
330 } else {
331 dst = ultoa_o(n, dst, size);
332 }
333 return dst;
334}
335
336/*
337 * signed long long ASCII representation
338 *
339 * return the last char '\0' or NULL if no enough
340 * space in dst
341 */
342char *lltoa(long long n, char *dst, size_t size)
343{
344 char *pos = dst;
345
346 if (n < 0) {
347 if (size < 3)
348 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
349 *pos = '-';
350 pos++;
351 dst = ulltoa(-n, pos, size - 1);
352 } else {
353 dst = ulltoa(n, dst, size);
354 }
355 return dst;
356}
357
358/*
359 * write a ascii representation of a unsigned into dst,
360 * return a pointer to the last character
361 * Pad the ascii representation with '0', using size.
362 */
363char *utoa_pad(unsigned int n, char *dst, size_t size)
364{
365 int i = 0;
366 char *ret;
367
368 switch(n) {
369 case 0U ... 9U:
370 i = 0;
371 break;
372
373 case 10U ... 99U:
374 i = 1;
375 break;
376
377 case 100U ... 999U:
378 i = 2;
379 break;
380
381 case 1000U ... 9999U:
382 i = 3;
383 break;
384
385 case 10000U ... 99999U:
386 i = 4;
387 break;
388
389 case 100000U ... 999999U:
390 i = 5;
391 break;
392
393 case 1000000U ... 9999999U:
394 i = 6;
395 break;
396
397 case 10000000U ... 99999999U:
398 i = 7;
399 break;
400
401 case 100000000U ... 999999999U:
402 i = 8;
403 break;
404
405 case 1000000000U ... 4294967295U:
406 i = 9;
407 break;
408 }
409 if (i + 2 > size) // (i + 1) + '\0'
410 return NULL; // too long
411 if (i < size)
412 i = size - 2; // padding - '\0'
413
414 ret = dst + i + 1;
415 *ret = '\0';
416 for (; i >= 0; i--) {
417 dst[i] = n % 10U + '0';
418 n /= 10U;
419 }
420 return ret;
421}
422
423/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200424 * copies at most <size-1> chars from <src> to <dst>. Last char is always
425 * set to 0, unless <size> is 0. The number of chars copied is returned
426 * (excluding the terminating zero).
427 * This code has been optimized for size and speed : on x86, it's 45 bytes
428 * long, uses only registers, and consumes only 4 cycles per char.
429 */
430int strlcpy2(char *dst, const char *src, int size)
431{
432 char *orig = dst;
433 if (size) {
434 while (--size && (*dst = *src)) {
435 src++; dst++;
436 }
437 *dst = 0;
438 }
439 return dst - orig;
440}
441
442/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200443 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200444 * the ascii representation for number 'n' in decimal.
445 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100446char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200447{
448 char *pos;
449
Willy Tarreau72d759c2007-10-25 12:14:10 +0200450 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200451 *pos-- = '\0';
452
453 do {
454 *pos-- = '0' + n % 10;
455 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200456 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200457 return pos + 1;
458}
459
Willy Tarreau91092e52007-10-25 16:58:42 +0200460/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200461 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200462 * the ascii representation for number 'n' in decimal.
463 */
464char *lltoa_r(long long int in, char *buffer, int size)
465{
466 char *pos;
467 int neg = 0;
468 unsigned long long int n;
469
470 pos = buffer + size - 1;
471 *pos-- = '\0';
472
473 if (in < 0) {
474 neg = 1;
475 n = -in;
476 }
477 else
478 n = in;
479
480 do {
481 *pos-- = '0' + n % 10;
482 n /= 10;
483 } while (n && pos >= buffer);
484 if (neg && pos > buffer)
485 *pos-- = '-';
486 return pos + 1;
487}
488
489/*
490 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200491 * the ascii representation for signed number 'n' in decimal.
492 */
493char *sltoa_r(long n, char *buffer, int size)
494{
495 char *pos;
496
497 if (n >= 0)
498 return ultoa_r(n, buffer, size);
499
500 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
501 *pos = '-';
502 return pos;
503}
504
505/*
506 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200507 * the ascii representation for number 'n' in decimal, formatted for
508 * HTML output with tags to create visual grouping by 3 digits. The
509 * output needs to support at least 171 characters.
510 */
511const char *ulltoh_r(unsigned long long n, char *buffer, int size)
512{
513 char *start;
514 int digit = 0;
515
516 start = buffer + size;
517 *--start = '\0';
518
519 do {
520 if (digit == 3 && start >= buffer + 7)
521 memcpy(start -= 7, "</span>", 7);
522
523 if (start >= buffer + 1) {
524 *--start = '0' + n % 10;
525 n /= 10;
526 }
527
528 if (digit == 3 && start >= buffer + 18)
529 memcpy(start -= 18, "<span class=\"rls\">", 18);
530
531 if (digit++ == 3)
532 digit = 1;
533 } while (n && start > buffer);
534 return start;
535}
536
537/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200538 * This function simply returns a locally allocated string containing the ascii
539 * representation for number 'n' in decimal, unless n is 0 in which case it
540 * returns the alternate string (or an empty string if the alternate string is
541 * NULL). It use is intended for limits reported in reports, where it's
542 * desirable not to display anything if there is no limit. Warning! it shares
543 * the same vector as ultoa_r().
544 */
545const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
546{
547 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
548}
549
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200550/* Trims the first "%f" float in a string to its minimum number of digits after
551 * the decimal point by trimming trailing zeroes, even dropping the decimal
552 * point if not needed. The string is in <buffer> of length <len>, and the
553 * number is expected to start at or after position <num_start> (the first
554 * point appearing there is considered). A NUL character is always placed at
555 * the end if some trimming occurs. The new buffer length is returned.
556 */
557size_t flt_trim(char *buffer, size_t num_start, size_t len)
558{
559 char *end = buffer + len;
560 char *p = buffer + num_start;
561 char *trim;
562
563 do {
564 if (p >= end)
565 return len;
566 trim = p++;
567 } while (*trim != '.');
568
569 /* For now <trim> is on the decimal point. Let's look for any other
570 * meaningful digit after it.
571 */
572 while (p < end) {
573 if (*p++ != '0')
574 trim = p;
575 }
576
577 if (trim < end)
578 *trim = 0;
579
580 return trim - buffer;
581}
582
Willy Tarreauae03d262021-05-08 07:35:00 +0200583/*
584 * This function simply returns a locally allocated string containing
585 * the ascii representation for number 'n' in decimal with useless trailing
586 * zeroes trimmed.
587 */
588char *ftoa_r(double n, char *buffer, int size)
589{
590 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
591 return buffer;
592}
593
Willy Tarreau588297f2014-06-16 15:16:40 +0200594/* returns a locally allocated string containing the quoted encoding of the
595 * input string. The output may be truncated to QSTR_SIZE chars, but it is
596 * guaranteed that the string will always be properly terminated. Quotes are
597 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
598 * always be at least 4 chars.
599 */
600const char *qstr(const char *str)
601{
602 char *ret = quoted_str[quoted_idx];
603 char *p, *end;
604
605 if (++quoted_idx >= NB_QSTR)
606 quoted_idx = 0;
607
608 p = ret;
609 end = ret + QSTR_SIZE;
610
611 *p++ = '"';
612
613 /* always keep 3 chars to support passing "" and the ending " */
614 while (*str && p < end - 3) {
615 if (*str == '"') {
616 *p++ = '"';
617 *p++ = '"';
618 }
619 else
620 *p++ = *str;
621 str++;
622 }
623 *p++ = '"';
624 return ret;
625}
626
Robert Tsai81ae1952007-12-05 10:47:29 +0100627/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200628 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
629 *
630 * It looks like this one would be a good candidate for inlining, but this is
631 * not interesting because it around 35 bytes long and often called multiple
632 * times within the same function.
633 */
634int ishex(char s)
635{
636 s -= '0';
637 if ((unsigned char)s <= 9)
638 return 1;
639 s -= 'A' - '0';
640 if ((unsigned char)s <= 5)
641 return 1;
642 s -= 'a' - 'A';
643 if ((unsigned char)s <= 5)
644 return 1;
645 return 0;
646}
647
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100648/* rounds <i> down to the closest value having max 2 digits */
649unsigned int round_2dig(unsigned int i)
650{
651 unsigned int mul = 1;
652
653 while (i >= 100) {
654 i /= 10;
655 mul *= 10;
656 }
657 return i * mul;
658}
659
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100660/*
661 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
662 * invalid character is found, a pointer to it is returned. If everything is
663 * fine, NULL is returned.
664 */
665const char *invalid_char(const char *name)
666{
667 if (!*name)
668 return name;
669
670 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100671 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100672 *name != '_' && *name != '-')
673 return name;
674 name++;
675 }
676 return NULL;
677}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200678
679/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200680 * Checks <name> for invalid characters. Valid chars are [_.-] and those
681 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200682 * If an invalid character is found, a pointer to it is returned.
683 * If everything is fine, NULL is returned.
684 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200685static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200686
687 if (!*name)
688 return name;
689
690 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100691 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200692 *name != '_' && *name != '-')
693 return name;
694
695 name++;
696 }
697
698 return NULL;
699}
700
701/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200702 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
703 * If an invalid character is found, a pointer to it is returned.
704 * If everything is fine, NULL is returned.
705 */
706const char *invalid_domainchar(const char *name) {
707 return __invalid_char(name, isalnum);
708}
709
710/*
711 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
712 * If an invalid character is found, a pointer to it is returned.
713 * If everything is fine, NULL is returned.
714 */
715const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200716 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200717}
718
719/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100720 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100721 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
722 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
723 * the function tries to guess the address family from the syntax. If the
724 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100725 * string is assumed to contain only an address, no port. The address can be a
726 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
727 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
728 * The return address will only have the address family and the address set,
729 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100730 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
731 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100732 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200733 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100734struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200735{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100736 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100737 /* max IPv6 length, including brackets and terminating NULL */
738 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100739 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100740
741 /* check IPv6 with square brackets */
742 if (str[0] == '[') {
743 size_t iplength = strlen(str);
744
745 if (iplength < 4) {
746 /* minimal size is 4 when using brackets "[::]" */
747 goto fail;
748 }
749 else if (iplength >= sizeof(tmpip)) {
750 /* IPv6 literal can not be larger than tmpip */
751 goto fail;
752 }
753 else {
754 if (str[iplength - 1] != ']') {
755 /* if address started with bracket, it should end with bracket */
756 goto fail;
757 }
758 else {
759 memcpy(tmpip, str + 1, iplength - 2);
760 tmpip[iplength - 2] = '\0';
761 str = tmpip;
762 }
763 }
764 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100765
Willy Tarreaufab5a432011-03-04 15:31:53 +0100766 /* Any IPv6 address */
767 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100768 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
769 sa->ss_family = AF_INET6;
770 else if (sa->ss_family != AF_INET6)
771 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100772 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100773 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100774 }
775
Willy Tarreau24709282013-03-10 21:32:12 +0100776 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100777 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100778 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
779 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100780 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100781 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100782 }
783
784 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100785 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
786 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100787 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100788 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100789 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100790 }
791
792 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100793 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
794 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100795 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100796 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100797 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100798 }
799
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100800 if (!resolve)
801 return NULL;
802
Emeric Brund30e9a12020-12-23 18:49:16 +0100803 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200804 return NULL;
805
David du Colombierd5f43282011-03-17 10:40:16 +0100806#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200807 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100808 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100809 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100810
811 memset(&result, 0, sizeof(result));
812 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100813 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100814 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200815 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100816 hints.ai_protocol = 0;
817
818 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100819 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
820 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100821 else if (sa->ss_family != result->ai_family) {
822 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100823 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100824 }
Willy Tarreau24709282013-03-10 21:32:12 +0100825
David du Colombierd5f43282011-03-17 10:40:16 +0100826 switch (result->ai_family) {
827 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100828 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100829 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100830 success = 1;
831 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100832 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100833 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100834 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100835 success = 1;
836 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100837 }
838 }
839
Sean Carey58ea0392013-02-15 23:39:18 +0100840 if (result)
841 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100842
843 if (success)
844 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100845 }
David du Colombierd5f43282011-03-17 10:40:16 +0100846#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200847 /* try to resolve an IPv4/IPv6 hostname */
848 he = gethostbyname(str);
849 if (he) {
850 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
851 sa->ss_family = he->h_addrtype;
852 else if (sa->ss_family != he->h_addrtype)
853 goto fail;
854
855 switch (sa->ss_family) {
856 case AF_INET:
857 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100858 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200859 return sa;
860 case AF_INET6:
861 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100862 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200863 return sa;
864 }
865 }
866
David du Colombierd5f43282011-03-17 10:40:16 +0100867 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100868 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100869 return NULL;
870}
871
872/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100873 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
874 * range or offset consisting in two integers that the caller will have to
875 * check to find the relevant input format. The following format are supported :
876 *
877 * String format | address | port | low | high
878 * addr | <addr> | 0 | 0 | 0
879 * addr: | <addr> | 0 | 0 | 0
880 * addr:port | <addr> | <port> | <port> | <port>
881 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
882 * addr:+port | <addr> | <port> | 0 | <port>
883 * addr:-port | <addr> |-<port> | <port> | 0
884 *
885 * The detection of a port range or increment by the caller is made by
886 * comparing <low> and <high>. If both are equal, then port 0 means no port
887 * was specified. The caller may pass NULL for <low> and <high> if it is not
888 * interested in retrieving port ranges.
889 *
890 * Note that <addr> above may also be :
891 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
892 * - "*" => family will be AF_INET and address will be INADDR_ANY
893 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
894 * - a host name => family and address will depend on host name resolving.
895 *
Willy Tarreau24709282013-03-10 21:32:12 +0100896 * A prefix may be passed in before the address above to force the family :
897 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
898 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
899 * - "unix@" => force address to be a path to a UNIX socket even if the
900 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200901 * - 'abns@' -> force address to belong to the abstract namespace (Linux
902 * only). These sockets are just like Unix sockets but without
903 * the need for an underlying file system. The address is a
904 * string. Technically it's like a Unix socket with a zero in
905 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100906 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100907 *
mildisff5d5102015-10-26 18:50:08 +0100908 * IPv6 addresses can be declared with or without square brackets. When using
909 * square brackets for IPv6 addresses, the port separator (colon) is optional.
910 * If not using square brackets, and in order to avoid any ambiguity with
911 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
912 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
913 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100914 *
915 * If <pfx> is non-null, it is used as a string prefix before any path-based
916 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100917 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200918 * if <fqdn> is non-null, it will be filled with :
919 * - a pointer to the FQDN of the server name to resolve if there's one, and
920 * that the caller will have to free(),
921 * - NULL if there was an explicit address that doesn't require resolution.
922 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200923 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
924 * still honored so it is possible for the caller to know whether a resolution
925 * failed by clearing this flag and checking if <fqdn> was filled, indicating
926 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200927 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100928 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200929 * the address when cast to sockaddr_in and the address family is
930 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200931 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200932 * The matching protocol will be set into <proto> if non-null.
933 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200934 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
935 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100936 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200937struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
938 struct protocol **proto, char **err,
939 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100940{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100941 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100942 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200943 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100944 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100945 char *port1, *port2;
946 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200947 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200948 int new_fd = -1;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200949 enum proto_type proto_type;
950 int ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100951
952 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200953 if (fqdn)
954 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200955
Willy Tarreaudad36a32013-03-11 01:20:04 +0100956 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100957 if (str2 == NULL) {
958 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100959 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100960 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200961
Willy Tarreau9f69f462015-09-08 16:01:25 +0200962 if (!*str2) {
963 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
964 goto out;
965 }
966
Willy Tarreau24709282013-03-10 21:32:12 +0100967 memset(&ss, 0, sizeof(ss));
968
Willy Tarreaue835bd82020-09-16 11:35:47 +0200969 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100970 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
Willy Tarreaue3b45182021-10-27 17:28:55 +0200971 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM))) {
972 proto_type = PROTO_TYPE_DGRAM;
973 ctrl_type = SOCK_DGRAM;
974 } else {
975 proto_type = PROTO_TYPE_STREAM;
976 ctrl_type = SOCK_STREAM;
977 }
Willy Tarreaue835bd82020-09-16 11:35:47 +0200978
979 if (strncmp(str2, "stream+", 7) == 0) {
980 str2 += 7;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200981 proto_type = PROTO_TYPE_STREAM;
982 ctrl_type = SOCK_STREAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200983 }
984 else if (strncmp(str2, "dgram+", 6) == 0) {
985 str2 += 6;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200986 proto_type = PROTO_TYPE_DGRAM;
987 ctrl_type = SOCK_DGRAM;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200988 }
989
Willy Tarreau24709282013-03-10 21:32:12 +0100990 if (strncmp(str2, "unix@", 5) == 0) {
991 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200992 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100993 ss.ss_family = AF_UNIX;
994 }
Emeric Brunce325c42021-04-02 17:05:09 +0200995 else if (strncmp(str2, "uxdg@", 5) == 0) {
996 str2 += 5;
997 abstract = 0;
998 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +0200999 proto_type = PROTO_TYPE_DGRAM;
1000 ctrl_type = SOCK_DGRAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001001 }
1002 else if (strncmp(str2, "uxst@", 5) == 0) {
1003 str2 += 5;
1004 abstract = 0;
1005 ss.ss_family = AF_UNIX;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001006 proto_type = PROTO_TYPE_STREAM;
1007 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001008 }
Willy Tarreauccfccef2014-05-10 01:49:15 +02001009 else if (strncmp(str2, "abns@", 5) == 0) {
1010 str2 += 5;
1011 abstract = 1;
1012 ss.ss_family = AF_UNIX;
1013 }
Emeric Brunce325c42021-04-02 17:05:09 +02001014 else if (strncmp(str2, "ip@", 3) == 0) {
1015 str2 += 3;
1016 ss.ss_family = AF_UNSPEC;
1017 }
Willy Tarreau24709282013-03-10 21:32:12 +01001018 else if (strncmp(str2, "ipv4@", 5) == 0) {
1019 str2 += 5;
1020 ss.ss_family = AF_INET;
1021 }
1022 else if (strncmp(str2, "ipv6@", 5) == 0) {
1023 str2 += 5;
1024 ss.ss_family = AF_INET6;
1025 }
Emeric Brunce325c42021-04-02 17:05:09 +02001026 else if (strncmp(str2, "tcp4@", 5) == 0) {
1027 str2 += 5;
1028 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001029 proto_type = PROTO_TYPE_STREAM;
1030 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001031 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001032 else if (strncmp(str2, "udp4@", 5) == 0) {
1033 str2 += 5;
1034 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001035 proto_type = PROTO_TYPE_DGRAM;
1036 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001037 }
Emeric Brunce325c42021-04-02 17:05:09 +02001038 else if (strncmp(str2, "tcp6@", 5) == 0) {
1039 str2 += 5;
1040 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001041 proto_type = PROTO_TYPE_STREAM;
1042 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001043 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001044 else if (strncmp(str2, "udp6@", 5) == 0) {
1045 str2 += 5;
1046 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001047 proto_type = PROTO_TYPE_DGRAM;
1048 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001049 }
Emeric Brunce325c42021-04-02 17:05:09 +02001050 else if (strncmp(str2, "tcp@", 4) == 0) {
1051 str2 += 4;
1052 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001053 proto_type = PROTO_TYPE_STREAM;
1054 ctrl_type = SOCK_STREAM;
Emeric Brunce325c42021-04-02 17:05:09 +02001055 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001056 else if (strncmp(str2, "udp@", 4) == 0) {
1057 str2 += 4;
1058 ss.ss_family = AF_UNSPEC;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001059 proto_type = PROTO_TYPE_DGRAM;
1060 ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001061 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001062 else if (strncmp(str2, "quic4@", 6) == 0) {
1063 str2 += 6;
1064 ss.ss_family = AF_INET;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001065 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001066 ctrl_type = SOCK_STREAM;
1067 }
1068 else if (strncmp(str2, "quic6@", 6) == 0) {
1069 str2 += 6;
1070 ss.ss_family = AF_INET6;
Willy Tarreaue3b45182021-10-27 17:28:55 +02001071 proto_type = PROTO_TYPE_DGRAM;
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001072 ctrl_type = SOCK_STREAM;
1073 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001074 else if (strncmp(str2, "fd@", 3) == 0) {
1075 str2 += 3;
1076 ss.ss_family = AF_CUST_EXISTING_FD;
1077 }
1078 else if (strncmp(str2, "sockpair@", 9) == 0) {
1079 str2 += 9;
1080 ss.ss_family = AF_CUST_SOCKPAIR;
1081 }
Willy Tarreau24709282013-03-10 21:32:12 +01001082 else if (*str2 == '/') {
1083 ss.ss_family = AF_UNIX;
1084 }
1085 else
1086 ss.ss_family = AF_UNSPEC;
1087
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001088 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001089 struct sockaddr_storage ss2;
1090 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001091 char *endptr;
1092
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001093 new_fd = strtol(str2, &endptr, 10);
1094 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001095 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1096 goto out;
1097 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001098
Willy Tarreaua215be22020-09-16 10:14:16 +02001099 /* just verify that it's a socket */
1100 addr_len = sizeof(ss2);
1101 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1102 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1103 goto out;
1104 }
1105
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001106 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1107 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001108 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001109 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001110 char *endptr;
1111
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001112 new_fd = strtol(str2, &endptr, 10);
1113 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001114 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001115 goto out;
1116 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001117
Willy Tarreau6edc7222020-09-15 17:41:56 +02001118 if (opts & PA_O_SOCKET_FD) {
1119 socklen_t addr_len;
1120 int type;
1121
1122 addr_len = sizeof(ss);
1123 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1124 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1125 goto out;
1126 }
1127
1128 addr_len = sizeof(type);
1129 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue3b45182021-10-27 17:28:55 +02001130 (type == SOCK_STREAM) != (proto_type == PROTO_TYPE_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001131 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1132 goto out;
1133 }
1134
1135 porta = portl = porth = get_host_port(&ss);
1136 } else if (opts & PA_O_RAW_FD) {
1137 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1138 ((struct sockaddr_in *)&ss)->sin_port = 0;
1139 } else {
1140 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1141 goto out;
1142 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001143 }
1144 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001145 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001146 int prefix_path_len;
1147 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001148 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001149
1150 /* complete unix socket path name during startup or soft-restart is
1151 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1152 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001153 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001154 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001155 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001156
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001157 adr_len = strlen(str2);
1158 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001159 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1160 goto out;
1161 }
1162
Willy Tarreauccfccef2014-05-10 01:49:15 +02001163 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001164 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001165 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001166 memcpy(un->sun_path, pfx, prefix_path_len);
1167 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001168 }
Willy Tarreau24709282013-03-10 21:32:12 +01001169 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001170 char *end = str2 + strlen(str2);
1171 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001172
mildisff5d5102015-10-26 18:50:08 +01001173 /* search for : or ] whatever comes first */
1174 for (chr = end-1; chr > str2; chr--) {
1175 if (*chr == ']' || *chr == ':')
1176 break;
1177 }
1178
1179 if (*chr == ':') {
1180 /* Found a colon before a closing-bracket, must be a port separator.
1181 * This guarantee backward compatibility.
1182 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001183 if (!(opts & PA_O_PORT_OK)) {
1184 memprintf(err, "port specification not permitted here in '%s'", str);
1185 goto out;
1186 }
mildisff5d5102015-10-26 18:50:08 +01001187 *chr++ = '\0';
1188 port1 = chr;
1189 }
1190 else {
1191 /* Either no colon and no closing-bracket
1192 * or directly ending with a closing-bracket.
1193 * However, no port.
1194 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001195 if (opts & PA_O_PORT_MAND) {
1196 memprintf(err, "missing port specification in '%s'", str);
1197 goto out;
1198 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001199 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001200 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001201
Willy Tarreau90807112020-02-25 08:16:33 +01001202 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001203 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001204 if (port2) {
1205 if (!(opts & PA_O_PORT_RANGE)) {
1206 memprintf(err, "port range not permitted here in '%s'", str);
1207 goto out;
1208 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001209 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001210 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001211 else
1212 port2 = port1;
1213 portl = atoi(port1);
1214 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001215
1216 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1217 memprintf(err, "invalid port '%s'", port1);
1218 goto out;
1219 }
1220
1221 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1222 memprintf(err, "invalid port '%s'", port2);
1223 goto out;
1224 }
1225
1226 if (portl > porth) {
1227 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1228 goto out;
1229 }
1230
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001231 porta = portl;
1232 }
1233 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001234 if (!(opts & PA_O_PORT_OFS)) {
1235 memprintf(err, "port offset not permitted here in '%s'", str);
1236 goto out;
1237 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001238 portl = atoi(port1 + 1);
1239 porta = -portl;
1240 }
1241 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001242 if (!(opts & PA_O_PORT_OFS)) {
1243 memprintf(err, "port offset not permitted here in '%s'", str);
1244 goto out;
1245 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001246 porth = atoi(port1 + 1);
1247 porta = porth;
1248 }
1249 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001250 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001251 goto out;
1252 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001253 else if (opts & PA_O_PORT_MAND) {
1254 memprintf(err, "missing port specification in '%s'", str);
1255 goto out;
1256 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001257
1258 /* first try to parse the IP without resolving. If it fails, it
1259 * tells us we need to keep a copy of the FQDN to resolve later
1260 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001261 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001262 */
1263 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001264 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1265 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001266 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1267 goto out;
1268 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001269
Willy Tarreauceccdd72016-11-02 22:27:10 +01001270 if (fqdn) {
1271 if (str2 != back)
1272 memmove(back, str2, strlen(str2) + 1);
1273 *fqdn = back;
1274 back = NULL;
1275 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001276 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001277 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001278 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001279
Willy Tarreaue835bd82020-09-16 11:35:47 +02001280 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1281 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1282 goto out;
1283 }
1284 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1285 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1286 goto out;
1287 }
1288
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001289 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001290 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001291 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1292 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001293 * in which case the address is not known yet (this is only
1294 * for servers actually).
1295 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001296 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreaue3b45182021-10-27 17:28:55 +02001297 proto_type,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001298 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001299
Emeric Brun26754902021-04-07 14:26:44 +02001300 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001301 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1302 goto out;
1303 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001304
1305 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1306 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1307 goto out;
1308 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001309 }
1310
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001311 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001312 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001313 if (port)
1314 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001315 if (low)
1316 *low = portl;
1317 if (high)
1318 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001319 if (fd)
1320 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001321 if (proto)
1322 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001323 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001324 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001325}
1326
Thayne McCombs92149f92020-11-20 01:28:26 -07001327/* converts <addr> and <port> into a string representation of the address and port. This is sort
1328 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1329 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1330 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1331 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1332 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1333 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1334 *
1335 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1336 */
1337char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1338{
1339 char buffer[INET6_ADDRSTRLEN];
1340 char *out = NULL;
1341 const void *ptr;
1342 const char *path;
1343
1344 switch (addr->ss_family) {
1345 case AF_INET:
1346 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1347 break;
1348 case AF_INET6:
1349 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1350 break;
1351 case AF_UNIX:
1352 path = ((struct sockaddr_un *)addr)->sun_path;
1353 if (path[0] == '\0') {
1354 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1355 return memprintf(&out, "abns@%.*s", max_length, path+1);
1356 } else {
1357 return strdup(path);
1358 }
1359 case AF_CUST_SOCKPAIR:
1360 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1361 default:
1362 return NULL;
1363 }
1364 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1365 if (map_ports)
1366 return memprintf(&out, "%s:%+d", buffer, port);
1367 else
1368 return memprintf(&out, "%s:%d", buffer, port);
1369}
1370
1371
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001372/* converts <str> to a struct in_addr containing a network mask. It can be
1373 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001374 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001375 */
1376int str2mask(const char *str, struct in_addr *mask)
1377{
1378 if (strchr(str, '.') != NULL) { /* dotted notation */
1379 if (!inet_pton(AF_INET, str, mask))
1380 return 0;
1381 }
1382 else { /* mask length */
1383 char *err;
1384 unsigned long len = strtol(str, &err, 10);
1385
1386 if (!*str || (err && *err) || (unsigned)len > 32)
1387 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001388
1389 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001390 }
1391 return 1;
1392}
1393
Tim Duesterhus47185172018-01-25 16:24:49 +01001394/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001395 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001396 * if the conversion succeeds otherwise zero.
1397 */
1398int str2mask6(const char *str, struct in6_addr *mask)
1399{
1400 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1401 if (!inet_pton(AF_INET6, str, mask))
1402 return 0;
1403 }
1404 else { /* mask length */
1405 char *err;
1406 unsigned long len = strtol(str, &err, 10);
1407
1408 if (!*str || (err && *err) || (unsigned)len > 128)
1409 return 0;
1410
1411 len2mask6(len, mask);
1412 }
1413 return 1;
1414}
1415
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001416/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1417 * succeeds otherwise zero.
1418 */
1419int cidr2dotted(int cidr, struct in_addr *mask) {
1420
1421 if (cidr < 0 || cidr > 32)
1422 return 0;
1423
1424 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1425 return 1;
1426}
1427
Thierry Fournier70473a52016-02-17 17:12:14 +01001428/* Convert mask from bit length form to in_addr form.
1429 * This function never fails.
1430 */
1431void len2mask4(int len, struct in_addr *addr)
1432{
1433 if (len >= 32) {
1434 addr->s_addr = 0xffffffff;
1435 return;
1436 }
1437 if (len <= 0) {
1438 addr->s_addr = 0x00000000;
1439 return;
1440 }
1441 addr->s_addr = 0xffffffff << (32 - len);
1442 addr->s_addr = htonl(addr->s_addr);
1443}
1444
1445/* Convert mask from bit length form to in6_addr form.
1446 * This function never fails.
1447 */
1448void len2mask6(int len, struct in6_addr *addr)
1449{
1450 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1451 len -= 32;
1452 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1453 len -= 32;
1454 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1455 len -= 32;
1456 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1457}
1458
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001459/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001460 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001461 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001462 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001463 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1464 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001465int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001466{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001467 __label__ out_free, out_err;
1468 char *c, *s;
1469 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001470
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001471 s = strdup(str);
1472 if (!s)
1473 return 0;
1474
Willy Tarreaubaaee002006-06-26 02:48:02 +02001475 memset(mask, 0, sizeof(*mask));
1476 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001477
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001478 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001479 *c++ = '\0';
1480 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001481 if (!str2mask(c, mask))
1482 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001483 }
1484 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001485 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001486 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001487 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001488 struct hostent *he;
1489
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001490 if (!resolve)
1491 goto out_err;
1492
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001493 if ((he = gethostbyname(s)) == NULL) {
1494 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001495 }
1496 else
1497 *addr = *(struct in_addr *) *(he->h_addr_list);
1498 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001499
1500 ret_val = 1;
1501 out_free:
1502 free(s);
1503 return ret_val;
1504 out_err:
1505 ret_val = 0;
1506 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001507}
1508
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001509
1510/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001511 * converts <str> to two struct in6_addr* which must be pre-allocated.
1512 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001513 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001514 * Returns 1 if OK, 0 if error.
1515 */
1516int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1517{
1518 char *c, *s;
1519 int ret_val = 0;
1520 char *err;
1521 unsigned long len = 128;
1522
1523 s = strdup(str);
1524 if (!s)
1525 return 0;
1526
1527 memset(mask, 0, sizeof(*mask));
1528 memset(addr, 0, sizeof(*addr));
1529
1530 if ((c = strrchr(s, '/')) != NULL) {
1531 *c++ = '\0'; /* c points to the mask */
1532 if (!*c)
1533 goto out_free;
1534
1535 len = strtoul(c, &err, 10);
1536 if ((err && *err) || (unsigned)len > 128)
1537 goto out_free;
1538 }
1539 *mask = len; /* OK we have a valid mask in <len> */
1540
1541 if (!inet_pton(AF_INET6, s, addr))
1542 goto out_free;
1543
1544 ret_val = 1;
1545 out_free:
1546 free(s);
1547 return ret_val;
1548}
1549
1550
1551/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001552 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1553 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1554 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001555 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001556int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001557{
1558 int saw_digit, octets, ch;
1559 u_char tmp[4], *tp;
1560 const char *cp = addr;
1561
1562 saw_digit = 0;
1563 octets = 0;
1564 *(tp = tmp) = 0;
1565
1566 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001567 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001568 if (digit > 9 && ch != '.')
1569 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001570 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001571 if (digit <= 9) {
1572 u_int new = *tp * 10 + digit;
1573 if (new > 255)
1574 return 0;
1575 *tp = new;
1576 if (!saw_digit) {
1577 if (++octets > 4)
1578 return 0;
1579 saw_digit = 1;
1580 }
1581 } else if (ch == '.' && saw_digit) {
1582 if (octets == 4)
1583 return 0;
1584 *++tp = 0;
1585 saw_digit = 0;
1586 } else
1587 return 0;
1588 }
1589
1590 if (octets < 4)
1591 return 0;
1592
1593 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001594 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001595}
1596
1597/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001598 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001599 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001600 * the hostname. Actually only http and https are supported. <out> can be NULL.
1601 * This function returns the consumed length. It is useful if you parse complete
1602 * url like http://host:port/path, because the consumed length corresponds to
1603 * the first character of the path. If the conversion fails, it returns -1.
1604 *
1605 * This function tries to resolve the DNS name if haproxy is in starting mode.
1606 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001607 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001608int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001609{
1610 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001611 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001612 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001613 unsigned long long int http_code = 0;
1614 int default_port;
1615 struct hostent *he;
1616 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001617
1618 /* Firstly, try to find :// pattern */
1619 while (curr < url+ulen && url_code != 0x3a2f2f) {
1620 url_code = ((url_code & 0xffff) << 8);
1621 url_code += (unsigned char)*curr++;
1622 }
1623
1624 /* Secondly, if :// pattern is found, verify parsed stuff
1625 * before pattern is matching our http pattern.
1626 * If so parse ip address and port in uri.
1627 *
1628 * WARNING: Current code doesn't support dynamic async dns resolver.
1629 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001630 if (url_code != 0x3a2f2f)
1631 return -1;
1632
1633 /* Copy scheme, and utrn to lower case. */
1634 while (cp < curr - 3)
1635 http_code = (http_code << 8) + *cp++;
1636 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001637
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001638 /* HTTP or HTTPS url matching */
1639 if (http_code == 0x2020202068747470ULL) {
1640 default_port = 80;
1641 if (out)
1642 out->scheme = SCH_HTTP;
1643 }
1644 else if (http_code == 0x2020206874747073ULL) {
1645 default_port = 443;
1646 if (out)
1647 out->scheme = SCH_HTTPS;
1648 }
1649 else
1650 return -1;
1651
1652 /* If the next char is '[', the host address is IPv6. */
1653 if (*curr == '[') {
1654 curr++;
1655
1656 /* Check trash size */
1657 if (trash.size < ulen)
1658 return -1;
1659
1660 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001661 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001662 for (end = curr;
1663 end < url + ulen && *end != ']';
1664 end++, p++)
1665 *p = *end;
1666 if (*end != ']')
1667 return -1;
1668 *p = '\0';
1669
1670 /* Update out. */
1671 if (out) {
1672 out->host = curr;
1673 out->host_len = end - curr;
1674 }
1675
1676 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001677 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001678 return -1;
1679 end++;
1680
1681 /* Decode port. */
1682 if (*end == ':') {
1683 end++;
1684 default_port = read_uint(&end, url + ulen);
1685 }
1686 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1687 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1688 return end - url;
1689 }
1690 else {
1691 /* We are looking for IP address. If you want to parse and
1692 * resolve hostname found in url, you can use str2sa_range(), but
1693 * be warned this can slow down global daemon performances
1694 * while handling lagging dns responses.
1695 */
1696 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1697 if (ret) {
1698 /* Update out. */
1699 if (out) {
1700 out->host = curr;
1701 out->host_len = ret;
1702 }
1703
1704 curr += ret;
1705
1706 /* Decode port. */
1707 if (*curr == ':') {
1708 curr++;
1709 default_port = read_uint(&curr, url + ulen);
1710 }
1711 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1712
1713 /* Set family. */
1714 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1715 return curr - url;
1716 }
1717 else if (global.mode & MODE_STARTING) {
1718 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1719 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001720 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001721
1722 /* look for : or / or end */
1723 for (end = curr;
1724 end < url + ulen && *end != '/' && *end != ':';
1725 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001726 memcpy(trash.area, curr, end - curr);
1727 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001728
1729 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001730 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001731 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001732 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001733
1734 /* Update out. */
1735 if (out) {
1736 out->host = curr;
1737 out->host_len = end - curr;
1738 }
1739
1740 /* Decode port. */
1741 if (*end == ':') {
1742 end++;
1743 default_port = read_uint(&end, url + ulen);
1744 }
1745
1746 /* Copy IP address, set port and family. */
1747 switch (he->h_addrtype) {
1748 case AF_INET:
1749 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1750 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1751 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1752 return end - url;
1753
1754 case AF_INET6:
1755 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1756 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1757 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1758 return end - url;
1759 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001760 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001761 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001762 return -1;
1763}
1764
Willy Tarreau631f01c2011-09-05 00:36:48 +02001765/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1766 * address family is returned so that it's easy for the caller to adapt to the
1767 * output format. Zero is returned if the address family is not supported. -1
1768 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1769 * supported.
1770 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001771int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001772{
1773
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001774 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001775
1776 if (size < 5)
1777 return 0;
1778 *str = '\0';
1779
1780 switch (addr->ss_family) {
1781 case AF_INET:
1782 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1783 break;
1784 case AF_INET6:
1785 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1786 break;
1787 case AF_UNIX:
1788 memcpy(str, "unix", 5);
1789 return addr->ss_family;
1790 default:
1791 return 0;
1792 }
1793
1794 if (inet_ntop(addr->ss_family, ptr, str, size))
1795 return addr->ss_family;
1796
1797 /* failed */
1798 return -1;
1799}
1800
Simon Horman75ab8bd2014-06-16 09:39:41 +09001801/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1802 * address family is returned so that it's easy for the caller to adapt to the
1803 * output format. Zero is returned if the address family is not supported. -1
1804 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1805 * supported.
1806 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001807int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001808{
1809
1810 uint16_t port;
1811
1812
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001813 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001814 return 0;
1815 *str = '\0';
1816
1817 switch (addr->ss_family) {
1818 case AF_INET:
1819 port = ((struct sockaddr_in *)addr)->sin_port;
1820 break;
1821 case AF_INET6:
1822 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1823 break;
1824 case AF_UNIX:
1825 memcpy(str, "unix", 5);
1826 return addr->ss_family;
1827 default:
1828 return 0;
1829 }
1830
1831 snprintf(str, size, "%u", ntohs(port));
1832 return addr->ss_family;
1833}
1834
Willy Tarreau16e01562016-08-09 16:46:18 +02001835/* check if the given address is local to the system or not. It will return
1836 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1837 * it is. We don't want to iterate over all interfaces for this (and it is not
1838 * portable). So instead we try to bind in UDP to this address on a free non
1839 * privileged port and to connect to the same address, port 0 (connect doesn't
1840 * care). If it succeeds, we own the address. Note that non-inet addresses are
1841 * considered local since they're most likely AF_UNIX.
1842 */
1843int addr_is_local(const struct netns_entry *ns,
1844 const struct sockaddr_storage *orig)
1845{
1846 struct sockaddr_storage addr;
1847 int result;
1848 int fd;
1849
1850 if (!is_inet_addr(orig))
1851 return 1;
1852
1853 memcpy(&addr, orig, sizeof(addr));
1854 set_host_port(&addr, 0);
1855
1856 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1857 if (fd < 0)
1858 return -1;
1859
1860 result = -1;
1861 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1862 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1863 result = 0; // fail, non-local address
1864 else
1865 result = 1; // success, local address
1866 }
1867 else {
1868 if (errno == EADDRNOTAVAIL)
1869 result = 0; // definitely not local :-)
1870 }
1871 close(fd);
1872
1873 return result;
1874}
1875
Willy Tarreaubaaee002006-06-26 02:48:02 +02001876/* will try to encode the string <string> replacing all characters tagged in
1877 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1878 * prefixed by <escape>, and will store the result between <start> (included)
1879 * and <stop> (excluded), and will always terminate the string with a '\0'
1880 * before <stop>. The position of the '\0' is returned if the conversion
1881 * completes. If bytes are missing between <start> and <stop>, then the
1882 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1883 * cannot even be stored so we return <start> without writing the 0.
1884 * The input string must also be zero-terminated.
1885 */
1886const char hextab[16] = "0123456789ABCDEF";
1887char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001888 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001889 const char *string)
1890{
1891 if (start < stop) {
1892 stop--; /* reserve one byte for the final '\0' */
1893 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001894 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001895 *start++ = *string;
1896 else {
1897 if (start + 3 >= stop)
1898 break;
1899 *start++ = escape;
1900 *start++ = hextab[(*string >> 4) & 15];
1901 *start++ = hextab[*string & 15];
1902 }
1903 string++;
1904 }
1905 *start = '\0';
1906 }
1907 return start;
1908}
1909
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001910/*
1911 * Same behavior as encode_string() above, except that it encodes chunk
1912 * <chunk> instead of a string.
1913 */
1914char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001915 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001916 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001917{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001918 char *str = chunk->area;
1919 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001920
1921 if (start < stop) {
1922 stop--; /* reserve one byte for the final '\0' */
1923 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001924 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001925 *start++ = *str;
1926 else {
1927 if (start + 3 >= stop)
1928 break;
1929 *start++ = escape;
1930 *start++ = hextab[(*str >> 4) & 15];
1931 *start++ = hextab[*str & 15];
1932 }
1933 str++;
1934 }
1935 *start = '\0';
1936 }
1937 return start;
1938}
1939
Dragan Dosen0edd1092016-02-12 13:23:02 +01001940/*
1941 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001942 * character. The input <string> must be zero-terminated. The result will
1943 * be stored between <start> (included) and <stop> (excluded). This
1944 * function will always try to terminate the resulting string with a '\0'
1945 * before <stop>, and will return its position if the conversion
1946 * completes.
1947 */
1948char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001949 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001950 const char *string)
1951{
1952 if (start < stop) {
1953 stop--; /* reserve one byte for the final '\0' */
1954 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001955 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001956 *start++ = *string;
1957 else {
1958 if (start + 2 >= stop)
1959 break;
1960 *start++ = escape;
1961 *start++ = *string;
1962 }
1963 string++;
1964 }
1965 *start = '\0';
1966 }
1967 return start;
1968}
1969
1970/*
1971 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001972 * character. <chunk> contains the input to be escaped. The result will be
1973 * stored between <start> (included) and <stop> (excluded). The function
1974 * will always try to terminate the resulting string with a '\0' before
1975 * <stop>, and will return its position if the conversion completes.
1976 */
1977char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001978 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001979 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001980{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001981 char *str = chunk->area;
1982 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001983
1984 if (start < stop) {
1985 stop--; /* reserve one byte for the final '\0' */
1986 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001987 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001988 *start++ = *str;
1989 else {
1990 if (start + 2 >= stop)
1991 break;
1992 *start++ = escape;
1993 *start++ = *str;
1994 }
1995 str++;
1996 }
1997 *start = '\0';
1998 }
1999 return start;
2000}
2001
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002002/* Check a string for using it in a CSV output format. If the string contains
2003 * one of the following four char <">, <,>, CR or LF, the string is
2004 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
2005 * <str> is the input string to be escaped. The function assumes that
2006 * the input string is null-terminated.
2007 *
2008 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01002009 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002010 * format.
2011 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002012 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002013 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002014 * If <quote> is 1, the converter puts the quotes only if any reserved character
2015 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002016 *
Willy Tarreau83061a82018-07-13 11:56:34 +02002017 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002018 *
Willy Tarreau898529b2016-01-06 18:07:04 +01002019 * The function returns the converted string on its output. If an error
2020 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002021 * for using the function directly as printf() argument.
2022 *
2023 * If the output buffer is too short to contain the input string, the result
2024 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01002025 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002026 * This function appends the encoding to the existing output chunk, and it
2027 * guarantees that it starts immediately at the first available character of
2028 * the chunk. Please use csv_enc() instead if you want to replace the output
2029 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002030 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002031const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002032{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002033 char *end = output->area + output->size;
2034 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002035 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002036
Willy Tarreaub631c292016-01-08 10:04:08 +01002037 if (quote == 1) {
2038 /* automatic quoting: first verify if we'll have to quote the string */
2039 if (!strpbrk(str, "\n\r,\""))
2040 quote = 0;
2041 }
2042
2043 if (quote)
2044 *ptr++ = '"';
2045
Willy Tarreau898529b2016-01-06 18:07:04 +01002046 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2047 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002048 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002049 ptr++;
2050 if (ptr >= end - 2) {
2051 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002052 break;
2053 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002054 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002055 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002056 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002057 str++;
2058 }
2059
Willy Tarreaub631c292016-01-08 10:04:08 +01002060 if (quote)
2061 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002062
Willy Tarreau898529b2016-01-06 18:07:04 +01002063 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002064 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002065 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002066}
2067
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002068/* Decode an URL-encoded string in-place. The resulting string might
2069 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002070 * aborted, the string is truncated before the issue and a negative value is
2071 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002072 * If the 'in_form' argument is non-nul the string is assumed to be part of
2073 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2074 * turned to a space. If it's zero, this will only be done after a question
2075 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002076 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002077int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002078{
2079 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002080 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002081
2082 in = string;
2083 out = string;
2084 while (*in) {
2085 switch (*in) {
2086 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002087 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002088 break;
2089 case '%' :
2090 if (!ishex(in[1]) || !ishex(in[2]))
2091 goto end;
2092 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2093 in += 2;
2094 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002095 case '?':
2096 in_form = 1;
2097 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002098 default:
2099 *out++ = *in;
2100 break;
2101 }
2102 in++;
2103 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002104 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002105 end:
2106 *out = 0;
2107 return ret;
2108}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002109
Willy Tarreau6911fa42007-03-04 18:06:08 +01002110unsigned int str2ui(const char *s)
2111{
2112 return __str2ui(s);
2113}
2114
2115unsigned int str2uic(const char *s)
2116{
2117 return __str2uic(s);
2118}
2119
2120unsigned int strl2ui(const char *s, int len)
2121{
2122 return __strl2ui(s, len);
2123}
2124
2125unsigned int strl2uic(const char *s, int len)
2126{
2127 return __strl2uic(s, len);
2128}
2129
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002130unsigned int read_uint(const char **s, const char *end)
2131{
2132 return __read_uint(s, end);
2133}
2134
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002135/* This function reads an unsigned integer from the string pointed to by <s> and
2136 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2137 * function automatically stops at <end>. If the number overflows, the 2^64-1
2138 * value is returned.
2139 */
2140unsigned long long int read_uint64(const char **s, const char *end)
2141{
2142 const char *ptr = *s;
2143 unsigned long long int i = 0, tmp;
2144 unsigned int j;
2145
2146 while (ptr < end) {
2147
2148 /* read next char */
2149 j = *ptr - '0';
2150 if (j > 9)
2151 goto read_uint64_end;
2152
2153 /* add char to the number and check overflow. */
2154 tmp = i * 10;
2155 if (tmp / 10 != i) {
2156 i = ULLONG_MAX;
2157 goto read_uint64_eat;
2158 }
2159 if (ULLONG_MAX - tmp < j) {
2160 i = ULLONG_MAX;
2161 goto read_uint64_eat;
2162 }
2163 i = tmp + j;
2164 ptr++;
2165 }
2166read_uint64_eat:
2167 /* eat each numeric char */
2168 while (ptr < end) {
2169 if ((unsigned int)(*ptr - '0') > 9)
2170 break;
2171 ptr++;
2172 }
2173read_uint64_end:
2174 *s = ptr;
2175 return i;
2176}
2177
2178/* This function reads an integer from the string pointed to by <s> and returns
2179 * it. The <s> pointer is adjusted to point to the first unread char. The function
2180 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2181 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2182 * returned.
2183 */
2184long long int read_int64(const char **s, const char *end)
2185{
2186 unsigned long long int i = 0;
2187 int neg = 0;
2188
2189 /* Look for minus char. */
2190 if (**s == '-') {
2191 neg = 1;
2192 (*s)++;
2193 }
2194 else if (**s == '+')
2195 (*s)++;
2196
2197 /* convert as positive number. */
2198 i = read_uint64(s, end);
2199
2200 if (neg) {
2201 if (i > 0x8000000000000000ULL)
2202 return LLONG_MIN;
2203 return -i;
2204 }
2205 if (i > 0x7fffffffffffffffULL)
2206 return LLONG_MAX;
2207 return i;
2208}
2209
Willy Tarreau6911fa42007-03-04 18:06:08 +01002210/* This one is 7 times faster than strtol() on athlon with checks.
2211 * It returns the value of the number composed of all valid digits read,
2212 * and can process negative numbers too.
2213 */
2214int strl2ic(const char *s, int len)
2215{
2216 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002217 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002218
2219 if (len > 0) {
2220 if (*s != '-') {
2221 /* positive number */
2222 while (len-- > 0) {
2223 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002224 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002225 if (j > 9)
2226 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002227 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002228 }
2229 } else {
2230 /* negative number */
2231 s++;
2232 while (--len > 0) {
2233 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002234 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002235 if (j > 9)
2236 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002237 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002238 }
2239 }
2240 }
2241 return i;
2242}
2243
2244
2245/* This function reads exactly <len> chars from <s> and converts them to a
2246 * signed integer which it stores into <ret>. It accurately detects any error
2247 * (truncated string, invalid chars, overflows). It is meant to be used in
2248 * applications designed for hostile environments. It returns zero when the
2249 * number has successfully been converted, non-zero otherwise. When an error
2250 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2251 * faster than strtol().
2252 */
2253int strl2irc(const char *s, int len, int *ret)
2254{
2255 int i = 0;
2256 int j;
2257
2258 if (!len)
2259 return 1;
2260
2261 if (*s != '-') {
2262 /* positive number */
2263 while (len-- > 0) {
2264 j = (*s++) - '0';
2265 if (j > 9) return 1; /* invalid char */
2266 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2267 i = i * 10;
2268 if (i + j < i) return 1; /* check for addition overflow */
2269 i = i + j;
2270 }
2271 } else {
2272 /* negative number */
2273 s++;
2274 while (--len > 0) {
2275 j = (*s++) - '0';
2276 if (j > 9) return 1; /* invalid char */
2277 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2278 i = i * 10;
2279 if (i - j > i) return 1; /* check for subtract overflow */
2280 i = i - j;
2281 }
2282 }
2283 *ret = i;
2284 return 0;
2285}
2286
2287
2288/* This function reads exactly <len> chars from <s> and converts them to a
2289 * signed integer which it stores into <ret>. It accurately detects any error
2290 * (truncated string, invalid chars, overflows). It is meant to be used in
2291 * applications designed for hostile environments. It returns zero when the
2292 * number has successfully been converted, non-zero otherwise. When an error
2293 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002294 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002295 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002296
2297int strl2llrc(const char *s, int len, long long *ret)
2298{
2299 long long i = 0;
2300 int j;
2301
2302 if (!len)
2303 return 1;
2304
2305 if (*s != '-') {
2306 /* positive number */
2307 while (len-- > 0) {
2308 j = (*s++) - '0';
2309 if (j > 9) return 1; /* invalid char */
2310 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2311 i = i * 10LL;
2312 if (i + j < i) return 1; /* check for addition overflow */
2313 i = i + j;
2314 }
2315 } else {
2316 /* negative number */
2317 s++;
2318 while (--len > 0) {
2319 j = (*s++) - '0';
2320 if (j > 9) return 1; /* invalid char */
2321 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2322 i = i * 10LL;
2323 if (i - j > i) return 1; /* check for subtract overflow */
2324 i = i - j;
2325 }
2326 }
2327 *ret = i;
2328 return 0;
2329}
2330
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002331/* This function is used with pat_parse_dotted_ver(). It converts a string
2332 * composed by two number separated by a dot. Each part must contain in 16 bits
2333 * because internally they will be represented as a 32-bit quantity stored in
2334 * a 64-bit integer. It returns zero when the number has successfully been
2335 * converted, non-zero otherwise. When an error is returned, the <ret> value
2336 * is left untouched.
2337 *
2338 * "1.3" -> 0x0000000000010003
2339 * "65535.65535" -> 0x00000000ffffffff
2340 */
2341int strl2llrc_dotted(const char *text, int len, long long *ret)
2342{
2343 const char *end = &text[len];
2344 const char *p;
2345 long long major, minor;
2346
2347 /* Look for dot. */
2348 for (p = text; p < end; p++)
2349 if (*p == '.')
2350 break;
2351
2352 /* Convert major. */
2353 if (strl2llrc(text, p - text, &major) != 0)
2354 return 1;
2355
2356 /* Check major. */
2357 if (major >= 65536)
2358 return 1;
2359
2360 /* Convert minor. */
2361 minor = 0;
2362 if (p < end)
2363 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2364 return 1;
2365
2366 /* Check minor. */
2367 if (minor >= 65536)
2368 return 1;
2369
2370 /* Compose value. */
2371 *ret = (major << 16) | (minor & 0xffff);
2372 return 0;
2373}
2374
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002375/* This function parses a time value optionally followed by a unit suffix among
2376 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2377 * expected by the caller. The computation does its best to avoid overflows.
2378 * The value is returned in <ret> if everything is fine, and a NULL is returned
2379 * by the function. In case of error, a pointer to the error is returned and
2380 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002381 * Values resulting in values larger than or equal to 2^31 after conversion are
2382 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2383 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002384 */
2385const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2386{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002387 unsigned long long imult, idiv;
2388 unsigned long long omult, odiv;
2389 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002390 const char *str = text;
2391
2392 if (!isdigit((unsigned char)*text))
2393 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002394
2395 omult = odiv = 1;
2396
2397 switch (unit_flags & TIME_UNIT_MASK) {
2398 case TIME_UNIT_US: omult = 1000000; break;
2399 case TIME_UNIT_MS: omult = 1000; break;
2400 case TIME_UNIT_S: break;
2401 case TIME_UNIT_MIN: odiv = 60; break;
2402 case TIME_UNIT_HOUR: odiv = 3600; break;
2403 case TIME_UNIT_DAY: odiv = 86400; break;
2404 default: break;
2405 }
2406
2407 value = 0;
2408
2409 while (1) {
2410 unsigned int j;
2411
2412 j = *text - '0';
2413 if (j > 9)
2414 break;
2415 text++;
2416 value *= 10;
2417 value += j;
2418 }
2419
2420 imult = idiv = 1;
2421 switch (*text) {
2422 case '\0': /* no unit = default unit */
2423 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002424 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002425 case 's': /* second = unscaled unit */
2426 break;
2427 case 'u': /* microsecond : "us" */
2428 if (text[1] == 's') {
2429 idiv = 1000000;
2430 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002431 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002432 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002433 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002434 case 'm': /* millisecond : "ms" or minute: "m" */
2435 if (text[1] == 's') {
2436 idiv = 1000;
2437 text++;
2438 } else
2439 imult = 60;
2440 break;
2441 case 'h': /* hour : "h" */
2442 imult = 3600;
2443 break;
2444 case 'd': /* day : "d" */
2445 imult = 86400;
2446 break;
2447 default:
2448 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002449 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002450 if (*(++text) != '\0') {
2451 ha_warning("unexpected character '%c' after the timer value '%s', only "
2452 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2453 " This will be reported as an error in next versions.\n", *text, str);
2454 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002455
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002456 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002457 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2458 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2459 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2460 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2461
Willy Tarreau9faebe32019-06-07 19:00:37 +02002462 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2463 if (result >= 0x80000000)
2464 return PARSE_TIME_OVER;
2465 if (!result && value)
2466 return PARSE_TIME_UNDER;
2467 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002468 return NULL;
2469}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002470
Emeric Brun39132b22010-01-04 14:57:24 +01002471/* this function converts the string starting at <text> to an unsigned int
2472 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002473 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002474 */
2475const char *parse_size_err(const char *text, unsigned *ret) {
2476 unsigned value = 0;
2477
Christopher Faulet82635a02020-12-11 09:30:45 +01002478 if (!isdigit((unsigned char)*text))
2479 return text;
2480
Emeric Brun39132b22010-01-04 14:57:24 +01002481 while (1) {
2482 unsigned int j;
2483
2484 j = *text - '0';
2485 if (j > 9)
2486 break;
2487 if (value > ~0U / 10)
2488 return text;
2489 value *= 10;
2490 if (value > (value + j))
2491 return text;
2492 value += j;
2493 text++;
2494 }
2495
2496 switch (*text) {
2497 case '\0':
2498 break;
2499 case 'K':
2500 case 'k':
2501 if (value > ~0U >> 10)
2502 return text;
2503 value = value << 10;
2504 break;
2505 case 'M':
2506 case 'm':
2507 if (value > ~0U >> 20)
2508 return text;
2509 value = value << 20;
2510 break;
2511 case 'G':
2512 case 'g':
2513 if (value > ~0U >> 30)
2514 return text;
2515 value = value << 30;
2516 break;
2517 default:
2518 return text;
2519 }
2520
Godbach58048a22015-01-28 17:36:16 +08002521 if (*text != '\0' && *++text != '\0')
2522 return text;
2523
Emeric Brun39132b22010-01-04 14:57:24 +01002524 *ret = value;
2525 return NULL;
2526}
2527
Willy Tarreau126d4062013-12-03 17:50:47 +01002528/*
2529 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002530 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002531 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002532 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002533 */
2534int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2535{
2536 int len;
2537 const char *p = source;
2538 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002539 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002540
2541 len = strlen(source);
2542 if (len % 2) {
2543 memprintf(err, "an even number of hex digit is expected");
2544 return 0;
2545 }
2546
2547 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002548
Willy Tarreau126d4062013-12-03 17:50:47 +01002549 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002550 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002551 if (!*binstr) {
2552 memprintf(err, "out of memory while loading string pattern");
2553 return 0;
2554 }
2555 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002556 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002557 else {
2558 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002559 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002560 len, *binstrlen);
2561 return 0;
2562 }
2563 alloc = 0;
2564 }
2565 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002566
2567 i = j = 0;
2568 while (j < len) {
2569 if (!ishex(p[i++]))
2570 goto bad_input;
2571 if (!ishex(p[i++]))
2572 goto bad_input;
2573 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2574 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002575 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002576
2577bad_input:
2578 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002579 if (alloc)
2580 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002581 return 0;
2582}
2583
Willy Tarreau946ba592009-05-10 15:41:18 +02002584/* copies at most <n> characters from <src> and always terminates with '\0' */
2585char *my_strndup(const char *src, int n)
2586{
2587 int len = 0;
2588 char *ret;
2589
2590 while (len < n && src[len])
2591 len++;
2592
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002593 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002594 if (!ret)
2595 return ret;
2596 memcpy(ret, src, len);
2597 ret[len] = '\0';
2598 return ret;
2599}
2600
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002601/*
2602 * search needle in haystack
2603 * returns the pointer if found, returns NULL otherwise
2604 */
2605const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2606{
2607 const void *c = NULL;
2608 unsigned char f;
2609
2610 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2611 return NULL;
2612
2613 f = *(char *)needle;
2614 c = haystack;
2615 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2616 if ((haystacklen - (c - haystack)) < needlelen)
2617 return NULL;
2618
2619 if (memcmp(c, needle, needlelen) == 0)
2620 return c;
2621 ++c;
2622 }
2623 return NULL;
2624}
2625
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002626/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002627size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2628{
2629 size_t ret = 0;
2630
2631 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2632 str++;
2633 ret++;
2634 }
2635 return ret;
2636}
2637
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002638/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002639size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2640{
2641 size_t ret = 0;
2642
2643 while (ret < len) {
2644 if(memchr(reject, *((int *)str), rejectlen))
2645 return ret;
2646 str++;
2647 ret++;
2648 }
2649 return ret;
2650}
2651
Willy Tarreau482b00d2009-10-04 22:48:42 +02002652/* This function returns the first unused key greater than or equal to <key> in
2653 * ID tree <root>. Zero is returned if no place is found.
2654 */
2655unsigned int get_next_id(struct eb_root *root, unsigned int key)
2656{
2657 struct eb32_node *used;
2658
2659 do {
2660 used = eb32_lookup_ge(root, key);
2661 if (!used || used->key > key)
2662 return key; /* key is available */
2663 key++;
2664 } while (key);
2665 return key;
2666}
2667
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002668/* dump the full tree to <file> in DOT format for debugging purposes. Will
2669 * optionally highlight node <subj> if found, depending on operation <op> :
2670 * 0 : nothing
2671 * >0 : insertion, node/leaf are surrounded in red
2672 * <0 : removal, node/leaf are dashed with no background
2673 * Will optionally add "desc" as a label on the graph if set and non-null.
2674 */
2675void 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 +01002676{
2677 struct eb32sc_node *node;
2678 unsigned long scope = -1;
2679
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002680 fprintf(file, "digraph ebtree {\n");
2681
2682 if (desc && *desc) {
2683 fprintf(file,
2684 " fontname=\"fixed\";\n"
2685 " fontsize=8;\n"
2686 " label=\"%s\";\n", desc);
2687 }
2688
Willy Tarreaued3cda02017-11-15 15:04:05 +01002689 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002690 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2691 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002692 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2693 );
2694
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002695 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002696 (long)eb_root_to_node(root),
2697 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002698 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2699
2700 node = eb32sc_first(root, scope);
2701 while (node) {
2702 if (node->node.node_p) {
2703 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002704 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2705 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2706 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002707
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002708 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002709 (long)node,
2710 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002711 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002712
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002713 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002714 (long)node,
2715 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002716 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2717
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002718 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002719 (long)node,
2720 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002721 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2722 }
2723
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002724 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2725 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2726 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002727
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002728 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002729 (long)node,
2730 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002731 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002732 node = eb32sc_next(node, scope);
2733 }
2734 fprintf(file, "}\n");
2735}
2736
Willy Tarreau348238b2010-01-18 15:05:57 +01002737/* This function compares a sample word possibly followed by blanks to another
2738 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2739 * otherwise zero. This intends to be used when checking HTTP headers for some
2740 * values. Note that it validates a word followed only by blanks but does not
2741 * validate a word followed by blanks then other chars.
2742 */
2743int word_match(const char *sample, int slen, const char *word, int wlen)
2744{
2745 if (slen < wlen)
2746 return 0;
2747
2748 while (wlen) {
2749 char c = *sample ^ *word;
2750 if (c && c != ('A' ^ 'a'))
2751 return 0;
2752 sample++;
2753 word++;
2754 slen--;
2755 wlen--;
2756 }
2757
2758 while (slen) {
2759 if (*sample != ' ' && *sample != '\t')
2760 return 0;
2761 sample++;
2762 slen--;
2763 }
2764 return 1;
2765}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002766
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002767/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2768 * is particularly fast because it avoids expensive operations such as
2769 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002770 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002771 */
2772unsigned int inetaddr_host(const char *text)
2773{
2774 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2775 register unsigned int dig100, dig10, dig1;
2776 int s;
2777 const char *p, *d;
2778
2779 dig1 = dig10 = dig100 = ascii_zero;
2780 s = 24;
2781
2782 p = text;
2783 while (1) {
2784 if (((unsigned)(*p - '0')) <= 9) {
2785 p++;
2786 continue;
2787 }
2788
2789 /* here, we have a complete byte between <text> and <p> (exclusive) */
2790 if (p == text)
2791 goto end;
2792
2793 d = p - 1;
2794 dig1 |= (unsigned int)(*d << s);
2795 if (d == text)
2796 goto end;
2797
2798 d--;
2799 dig10 |= (unsigned int)(*d << s);
2800 if (d == text)
2801 goto end;
2802
2803 d--;
2804 dig100 |= (unsigned int)(*d << s);
2805 end:
2806 if (!s || *p != '.')
2807 break;
2808
2809 s -= 8;
2810 text = ++p;
2811 }
2812
2813 dig100 -= ascii_zero;
2814 dig10 -= ascii_zero;
2815 dig1 -= ascii_zero;
2816 return ((dig100 * 10) + dig10) * 10 + dig1;
2817}
2818
2819/*
2820 * Idem except the first unparsed character has to be passed in <stop>.
2821 */
2822unsigned int inetaddr_host_lim(const char *text, const char *stop)
2823{
2824 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2825 register unsigned int dig100, dig10, dig1;
2826 int s;
2827 const char *p, *d;
2828
2829 dig1 = dig10 = dig100 = ascii_zero;
2830 s = 24;
2831
2832 p = text;
2833 while (1) {
2834 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2835 p++;
2836 continue;
2837 }
2838
2839 /* here, we have a complete byte between <text> and <p> (exclusive) */
2840 if (p == text)
2841 goto end;
2842
2843 d = p - 1;
2844 dig1 |= (unsigned int)(*d << s);
2845 if (d == text)
2846 goto end;
2847
2848 d--;
2849 dig10 |= (unsigned int)(*d << s);
2850 if (d == text)
2851 goto end;
2852
2853 d--;
2854 dig100 |= (unsigned int)(*d << s);
2855 end:
2856 if (!s || p == stop || *p != '.')
2857 break;
2858
2859 s -= 8;
2860 text = ++p;
2861 }
2862
2863 dig100 -= ascii_zero;
2864 dig10 -= ascii_zero;
2865 dig1 -= ascii_zero;
2866 return ((dig100 * 10) + dig10) * 10 + dig1;
2867}
2868
2869/*
2870 * Idem except the pointer to first unparsed byte is returned into <ret> which
2871 * must not be NULL.
2872 */
Willy Tarreau74172752010-10-15 23:21:42 +02002873unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002874{
2875 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2876 register unsigned int dig100, dig10, dig1;
2877 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002878 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002879
2880 dig1 = dig10 = dig100 = ascii_zero;
2881 s = 24;
2882
2883 p = text;
2884 while (1) {
2885 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2886 p++;
2887 continue;
2888 }
2889
2890 /* here, we have a complete byte between <text> and <p> (exclusive) */
2891 if (p == text)
2892 goto end;
2893
2894 d = p - 1;
2895 dig1 |= (unsigned int)(*d << s);
2896 if (d == text)
2897 goto end;
2898
2899 d--;
2900 dig10 |= (unsigned int)(*d << s);
2901 if (d == text)
2902 goto end;
2903
2904 d--;
2905 dig100 |= (unsigned int)(*d << s);
2906 end:
2907 if (!s || p == stop || *p != '.')
2908 break;
2909
2910 s -= 8;
2911 text = ++p;
2912 }
2913
2914 *ret = p;
2915 dig100 -= ascii_zero;
2916 dig10 -= ascii_zero;
2917 dig1 -= ascii_zero;
2918 return ((dig100 * 10) + dig10) * 10 + dig1;
2919}
2920
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002921/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2922 * or the number of chars read in case of success. Maybe this could be replaced
2923 * by one of the functions above. Also, apparently this function does not support
2924 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002925 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002926 */
2927int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2928{
2929 const char *addr;
2930 int saw_digit, octets, ch;
2931 u_char tmp[4], *tp;
2932 const char *cp = buf;
2933
2934 saw_digit = 0;
2935 octets = 0;
2936 *(tp = tmp) = 0;
2937
2938 for (addr = buf; addr - buf < len; addr++) {
2939 unsigned char digit = (ch = *addr) - '0';
2940
2941 if (digit > 9 && ch != '.')
2942 break;
2943
2944 if (digit <= 9) {
2945 u_int new = *tp * 10 + digit;
2946
2947 if (new > 255)
2948 return 0;
2949
2950 *tp = new;
2951
2952 if (!saw_digit) {
2953 if (++octets > 4)
2954 return 0;
2955 saw_digit = 1;
2956 }
2957 } else if (ch == '.' && saw_digit) {
2958 if (octets == 4)
2959 return 0;
2960
2961 *++tp = 0;
2962 saw_digit = 0;
2963 } else
2964 return 0;
2965 }
2966
2967 if (octets < 4)
2968 return 0;
2969
2970 memcpy(&dst->s_addr, tmp, 4);
2971 return addr - cp;
2972}
2973
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002974/* This function converts the string in <buf> of the len <len> to
2975 * struct in6_addr <dst> which must be allocated by the caller.
2976 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002977 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002978 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002979int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2980{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002981 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002982 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002983
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002984 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002985 return 0;
2986
2987 memcpy(null_term_ip6, buf, len);
2988 null_term_ip6[len] = '\0';
2989
Willy Tarreau075415a2013-12-12 11:29:39 +01002990 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002991 return 0;
2992
Willy Tarreau075415a2013-12-12 11:29:39 +01002993 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002994 return 1;
2995}
2996
Willy Tarreauacf95772010-06-14 19:09:21 +02002997/* To be used to quote config arg positions. Returns the short string at <ptr>
2998 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2999 * if ptr is NULL or empty. The string is locally allocated.
3000 */
3001const char *quote_arg(const char *ptr)
3002{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003003 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02003004 int i;
3005
3006 if (!ptr || !*ptr)
3007 return "end of line";
3008 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01003009 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02003010 val[i] = *ptr++;
3011 val[i++] = '\'';
3012 val[i] = '\0';
3013 return val;
3014}
3015
Willy Tarreau5b180202010-07-18 10:40:48 +02003016/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
3017int get_std_op(const char *str)
3018{
3019 int ret = -1;
3020
3021 if (*str == 'e' && str[1] == 'q')
3022 ret = STD_OP_EQ;
3023 else if (*str == 'n' && str[1] == 'e')
3024 ret = STD_OP_NE;
3025 else if (*str == 'l') {
3026 if (str[1] == 'e') ret = STD_OP_LE;
3027 else if (str[1] == 't') ret = STD_OP_LT;
3028 }
3029 else if (*str == 'g') {
3030 if (str[1] == 'e') ret = STD_OP_GE;
3031 else if (str[1] == 't') ret = STD_OP_GT;
3032 }
3033
3034 if (ret == -1 || str[2] != '\0')
3035 return -1;
3036 return ret;
3037}
3038
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003039/* hash a 32-bit integer to another 32-bit integer */
3040unsigned int full_hash(unsigned int a)
3041{
3042 return __full_hash(a);
3043}
3044
Willy Tarreauf3241112019-02-26 09:56:22 +01003045/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3046 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3047 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3048 * a popcount variant and is described here :
3049 * https://graphics.stanford.edu/~seander/bithacks.html
3050 */
3051unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3052{
3053 unsigned long a, b, c, d;
3054 unsigned int s;
3055 unsigned int t;
3056
3057 a = m - ((m >> 1) & ~0UL/3);
3058 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3059 c = (b + (b >> 4)) & ~0UL/0x11;
3060 d = (c + (c >> 8)) & ~0UL/0x101;
3061
3062 r++; // make r be 1..64
3063
3064 t = 0;
3065 s = LONGBITS;
3066 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003067 unsigned long d2 = (d >> 16) >> 16;
3068 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003069 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3070 }
3071
3072 t = (d >> (s - 16)) & 0xff;
3073 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3074 t = (c >> (s - 8)) & 0xf;
3075 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3076 t = (b >> (s - 4)) & 0x7;
3077 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3078 t = (a >> (s - 2)) & 0x3;
3079 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3080 t = (m >> (s - 1)) & 0x1;
3081 s -= ((t - r) & 256) >> 8;
3082
3083 return s - 1;
3084}
3085
3086/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3087 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3088 * using mask_prep_rank_map() below.
3089 */
3090unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3091 unsigned long a, unsigned long b,
3092 unsigned long c, unsigned long d)
3093{
3094 unsigned int s;
3095 unsigned int t;
3096
3097 r++; // make r be 1..64
3098
3099 t = 0;
3100 s = LONGBITS;
3101 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003102 unsigned long d2 = (d >> 16) >> 16;
3103 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003104 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3105 }
3106
3107 t = (d >> (s - 16)) & 0xff;
3108 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3109 t = (c >> (s - 8)) & 0xf;
3110 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3111 t = (b >> (s - 4)) & 0x7;
3112 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3113 t = (a >> (s - 2)) & 0x3;
3114 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3115 t = (m >> (s - 1)) & 0x1;
3116 s -= ((t - r) & 256) >> 8;
3117
3118 return s - 1;
3119}
3120
3121/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3122 * above.
3123 */
3124void mask_prep_rank_map(unsigned long m,
3125 unsigned long *a, unsigned long *b,
3126 unsigned long *c, unsigned long *d)
3127{
3128 *a = m - ((m >> 1) & ~0UL/3);
3129 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3130 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3131 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3132}
3133
David du Colombier4f92d322011-03-24 11:09:31 +01003134/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003135 * otherwise zero. Note that <addr> may not necessarily be aligned
3136 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003137 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003138int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003139{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003140 struct in_addr addr_copy;
3141
3142 memcpy(&addr_copy, addr, sizeof(addr_copy));
3143 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003144}
3145
3146/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003147 * otherwise zero. Note that <addr> may not necessarily be aligned
3148 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003149 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003150int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003151{
3152 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003153 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003154
Willy Tarreaueec1d382016-07-13 11:59:39 +02003155 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003156 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003157 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003158 (((int *)net)[i] & ((int *)mask)[i]))
3159 return 0;
3160 return 1;
3161}
3162
3163/* RFC 4291 prefix */
3164const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3165 0x00, 0x00, 0x00, 0x00,
3166 0x00, 0x00, 0xFF, 0xFF };
3167
Joseph Herlant32b83272018-11-15 11:58:28 -08003168/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003169 * Input and output may overlap.
3170 */
David du Colombier4f92d322011-03-24 11:09:31 +01003171void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3172{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003173 struct in_addr tmp_addr;
3174
3175 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003176 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003177 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003178}
3179
Joseph Herlant32b83272018-11-15 11:58:28 -08003180/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003181 * Return true if conversion is possible and false otherwise.
3182 */
3183int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3184{
3185 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3186 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3187 sizeof(struct in_addr));
3188 return 1;
3189 }
3190
3191 return 0;
3192}
3193
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003194/* compare two struct sockaddr_storage and return:
3195 * 0 (true) if the addr is the same in both
3196 * 1 (false) if the addr is not the same in both
3197 * -1 (unable) if one of the addr is not AF_INET*
3198 */
3199int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3200{
3201 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3202 return -1;
3203
3204 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3205 return -1;
3206
3207 if (ss1->ss_family != ss2->ss_family)
3208 return 1;
3209
3210 switch (ss1->ss_family) {
3211 case AF_INET:
3212 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3213 &((struct sockaddr_in *)ss2)->sin_addr,
3214 sizeof(struct in_addr)) != 0;
3215 case AF_INET6:
3216 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3217 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3218 sizeof(struct in6_addr)) != 0;
3219 }
3220
3221 return 1;
3222}
3223
Christopher Faulet9553de72021-02-26 09:12:50 +01003224/* compare a struct sockaddr_storage to a struct net_addr and return :
3225 * 0 (true) if <addr> is matching <net>
3226 * 1 (false) if <addr> is not matching <net>
3227 * -1 (unable) if <addr> or <net> is not AF_INET*
3228 */
3229int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3230{
3231 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3232 return -1;
3233
3234 if ((net->family != AF_INET) && (net->family != AF_INET6))
3235 return -1;
3236
3237 if (addr->ss_family != net->family)
3238 return 1;
3239
3240 if (addr->ss_family == AF_INET &&
3241 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3242 return 0;
3243 else {
3244 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3245 const struct in6_addr *nip6 = &net->addr.v6.ip;
3246 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3247
3248 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3249 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3250 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3251 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3252 return 0;
3253 }
3254
3255 return 1;
3256}
3257
Baptiste Assmann08396c82016-01-31 00:27:17 +01003258/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003259 * The caller must allocate and clear <dest> before calling.
3260 * The source must be in either AF_INET or AF_INET6 family, or the destination
3261 * address will be undefined. If the destination address used to hold a port,
3262 * it is preserved, so that this function can be used to switch to another
3263 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003264 */
3265struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3266{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003267 int prev_port;
3268
3269 prev_port = get_net_port(dest);
3270 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003271 dest->ss_family = source->ss_family;
3272
3273 /* copy new addr and apply it */
3274 switch (source->ss_family) {
3275 case AF_INET:
3276 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003277 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003278 break;
3279 case AF_INET6:
3280 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 +01003281 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003282 break;
3283 }
3284
3285 return dest;
3286}
3287
William Lallemand421f5b52012-02-06 18:15:57 +01003288char *human_time(int t, short hz_div) {
3289 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3290 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003291 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003292 int cnt=2; // print two numbers
3293
3294 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003295 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003296 return rv;
3297 }
3298
3299 if (unlikely(hz_div > 1))
3300 t /= hz_div;
3301
3302 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003303 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003304 cnt--;
3305 }
3306
3307 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003308 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003309 cnt--;
3310 }
3311
3312 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003313 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003314 cnt--;
3315 }
3316
3317 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003318 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003319
3320 return rv;
3321}
3322
3323const char *monthname[12] = {
3324 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3325 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3326};
3327
3328/* date2str_log: write a date in the format :
3329 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3330 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3331 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3332 *
3333 * without using sprintf. return a pointer to the last char written (\0) or
3334 * NULL if there isn't enough space.
3335 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003336char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003337{
3338
3339 if (size < 25) /* the size is fixed: 24 chars + \0 */
3340 return NULL;
3341
3342 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003343 if (!dst)
3344 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003345 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003346
William Lallemand421f5b52012-02-06 18:15:57 +01003347 memcpy(dst, monthname[tm->tm_mon], 3); // month
3348 dst += 3;
3349 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003350
William Lallemand421f5b52012-02-06 18:15:57 +01003351 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
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 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003357 if (!dst)
3358 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003359 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003360
William Lallemand421f5b52012-02-06 18:15:57 +01003361 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003362 if (!dst)
3363 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003364 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003365
William Lallemand421f5b52012-02-06 18:15:57 +01003366 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003367 if (!dst)
3368 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003369 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003370
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003371 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003372 if (!dst)
3373 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003374 *dst = '\0';
3375
3376 return dst;
3377}
3378
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003379/* Base year used to compute leap years */
3380#define TM_YEAR_BASE 1900
3381
3382/* Return the difference in seconds between two times (leap seconds are ignored).
3383 * Retrieved from glibc 2.18 source code.
3384 */
3385static int my_tm_diff(const struct tm *a, const struct tm *b)
3386{
3387 /* Compute intervening leap days correctly even if year is negative.
3388 * Take care to avoid int overflow in leap day calculations,
3389 * but it's OK to assume that A and B are close to each other.
3390 */
3391 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3392 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3393 int a100 = a4 / 25 - (a4 % 25 < 0);
3394 int b100 = b4 / 25 - (b4 % 25 < 0);
3395 int a400 = a100 >> 2;
3396 int b400 = b100 >> 2;
3397 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3398 int years = a->tm_year - b->tm_year;
3399 int days = (365 * years + intervening_leap_days
3400 + (a->tm_yday - b->tm_yday));
3401 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3402 + (a->tm_min - b->tm_min))
3403 + (a->tm_sec - b->tm_sec));
3404}
3405
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003406/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003407 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003408 * The string returned has the same format as returned by strftime(... "%z", tm).
3409 * Offsets are kept in an internal cache for better performances.
3410 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003411const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003412{
3413 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003414 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003415
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003416 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003417 struct tm tm_gmt;
3418 int diff;
3419 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003420
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003421 /* Pretend DST not active if its status is unknown */
3422 if (isdst < 0)
3423 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003424
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003425 /* Fetch the offset and initialize it if needed */
3426 gmt_offset = gmt_offsets[isdst & 0x01];
3427 if (unlikely(!*gmt_offset)) {
3428 get_gmtime(t, &tm_gmt);
3429 diff = my_tm_diff(tm, &tm_gmt);
3430 if (diff < 0) {
3431 diff = -diff;
3432 *gmt_offset = '-';
3433 } else {
3434 *gmt_offset = '+';
3435 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003436 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003437 diff /= 60; /* Convert to minutes */
3438 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3439 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003440
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003441 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003442}
3443
William Lallemand421f5b52012-02-06 18:15:57 +01003444/* gmt2str_log: write a date in the format :
3445 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3446 * return a pointer to the last char written (\0) or
3447 * NULL if there isn't enough space.
3448 */
3449char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3450{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003451 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003452 return NULL;
3453
3454 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003455 if (!dst)
3456 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003457 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003458
William Lallemand421f5b52012-02-06 18:15:57 +01003459 memcpy(dst, monthname[tm->tm_mon], 3); // month
3460 dst += 3;
3461 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003462
William Lallemand421f5b52012-02-06 18:15:57 +01003463 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
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 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003469 if (!dst)
3470 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003471 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003472
William Lallemand421f5b52012-02-06 18:15:57 +01003473 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003474 if (!dst)
3475 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003476 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003477
William Lallemand421f5b52012-02-06 18:15:57 +01003478 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003479 if (!dst)
3480 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003481 *dst++ = ' ';
3482 *dst++ = '+';
3483 *dst++ = '0';
3484 *dst++ = '0';
3485 *dst++ = '0';
3486 *dst++ = '0';
3487 *dst = '\0';
3488
3489 return dst;
3490}
3491
Yuxans Yao4e25b012012-10-19 10:36:09 +08003492/* localdate2str_log: write a date in the format :
3493 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003494 * Both t and tm must represent the same time.
3495 * return a pointer to the last char written (\0) or
3496 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003497 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003498char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003499{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003500 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003501 if (size < 27) /* the size is fixed: 26 chars + \0 */
3502 return NULL;
3503
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003504 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003505
Yuxans Yao4e25b012012-10-19 10:36:09 +08003506 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003507 if (!dst)
3508 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003509 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003510
Yuxans Yao4e25b012012-10-19 10:36:09 +08003511 memcpy(dst, monthname[tm->tm_mon], 3); // month
3512 dst += 3;
3513 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003514
Yuxans Yao4e25b012012-10-19 10:36:09 +08003515 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
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 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003521 if (!dst)
3522 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003523 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003524
Yuxans Yao4e25b012012-10-19 10:36:09 +08003525 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003526 if (!dst)
3527 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003528 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003529
Yuxans Yao4e25b012012-10-19 10:36:09 +08003530 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003531 if (!dst)
3532 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003533 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003534
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003535 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003536 dst += 5;
3537 *dst = '\0';
3538
3539 return dst;
3540}
3541
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003542/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3543 * It is meant as a portable replacement for timegm() for use with valid inputs.
3544 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3545 */
3546time_t my_timegm(const struct tm *tm)
3547{
3548 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3549 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3550 * sum of the extra N days for elapsed months. The sum of all these N
3551 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3552 * in a 5-bit word. This means that with 60 bits we can represent a
3553 * matrix of all these values at once, which is fast and efficient to
3554 * access. The extra February day for leap years is not counted here.
3555 *
3556 * Jan : none = 0 (0)
3557 * Feb : Jan = 3 (3)
3558 * Mar : Jan..Feb = 3 (3 + 0)
3559 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3560 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3561 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3562 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3563 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3564 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3565 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3566 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3567 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3568 */
3569 uint64_t extra =
3570 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3571 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3572 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3573 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3574
3575 unsigned int y = tm->tm_year + 1900;
3576 unsigned int m = tm->tm_mon;
3577 unsigned long days = 0;
3578
3579 /* days since 1/1/1970 for full years */
3580 days += days_since_zero(y) - days_since_zero(1970);
3581
3582 /* days for full months in the current year */
3583 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3584
3585 /* count + 1 after March for leap years. A leap year is a year multiple
3586 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3587 * is leap, 1900 isn't, 1904 is.
3588 */
3589 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3590 days++;
3591
3592 days += tm->tm_mday - 1;
3593 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3594}
3595
Thierry Fournier93127942016-01-20 18:49:45 +01003596/* This function check a char. It returns true and updates
3597 * <date> and <len> pointer to the new position if the
3598 * character is found.
3599 */
3600static inline int parse_expect_char(const char **date, int *len, char c)
3601{
3602 if (*len < 1 || **date != c)
3603 return 0;
3604 (*len)--;
3605 (*date)++;
3606 return 1;
3607}
3608
3609/* This function expects a string <str> of len <l>. It return true and updates.
3610 * <date> and <len> if the string matches, otherwise, it returns false.
3611 */
3612static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3613{
3614 if (*len < l || strncmp(*date, str, l) != 0)
3615 return 0;
3616 (*len) -= l;
3617 (*date) += l;
3618 return 1;
3619}
3620
3621/* This macro converts 3 chars name in integer. */
3622#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3623
3624/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3625 * / %x54.75.65 ; "Tue", case-sensitive
3626 * / %x57.65.64 ; "Wed", case-sensitive
3627 * / %x54.68.75 ; "Thu", case-sensitive
3628 * / %x46.72.69 ; "Fri", case-sensitive
3629 * / %x53.61.74 ; "Sat", case-sensitive
3630 * / %x53.75.6E ; "Sun", case-sensitive
3631 *
3632 * This array must be alphabetically sorted
3633 */
3634static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3635{
3636 if (*len < 3)
3637 return 0;
3638 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3639 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3640 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3641 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3642 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3643 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3644 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3645 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3646 default: return 0;
3647 }
3648 *len -= 3;
3649 *date += 3;
3650 return 1;
3651}
3652
3653/* month = %x4A.61.6E ; "Jan", case-sensitive
3654 * / %x46.65.62 ; "Feb", case-sensitive
3655 * / %x4D.61.72 ; "Mar", case-sensitive
3656 * / %x41.70.72 ; "Apr", case-sensitive
3657 * / %x4D.61.79 ; "May", case-sensitive
3658 * / %x4A.75.6E ; "Jun", case-sensitive
3659 * / %x4A.75.6C ; "Jul", case-sensitive
3660 * / %x41.75.67 ; "Aug", case-sensitive
3661 * / %x53.65.70 ; "Sep", case-sensitive
3662 * / %x4F.63.74 ; "Oct", case-sensitive
3663 * / %x4E.6F.76 ; "Nov", case-sensitive
3664 * / %x44.65.63 ; "Dec", case-sensitive
3665 *
3666 * This array must be alphabetically sorted
3667 */
3668static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3669{
3670 if (*len < 3)
3671 return 0;
3672 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3673 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3674 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3675 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3676 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3677 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3678 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3679 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3680 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3681 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3682 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3683 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3684 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3685 default: return 0;
3686 }
3687 *len -= 3;
3688 *date += 3;
3689 return 1;
3690}
3691
3692/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3693 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3694 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3695 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3696 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3697 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3698 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3699 *
3700 * This array must be alphabetically sorted
3701 */
3702static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3703{
3704 if (*len < 6) /* Minimum length. */
3705 return 0;
3706 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3707 case STR2I3('M','o','n'):
3708 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3709 tm->tm_wday = 1;
3710 return 1;
3711 case STR2I3('T','u','e'):
3712 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3713 tm->tm_wday = 2;
3714 return 1;
3715 case STR2I3('W','e','d'):
3716 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3717 tm->tm_wday = 3;
3718 return 1;
3719 case STR2I3('T','h','u'):
3720 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3721 tm->tm_wday = 4;
3722 return 1;
3723 case STR2I3('F','r','i'):
3724 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3725 tm->tm_wday = 5;
3726 return 1;
3727 case STR2I3('S','a','t'):
3728 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3729 tm->tm_wday = 6;
3730 return 1;
3731 case STR2I3('S','u','n'):
3732 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3733 tm->tm_wday = 7;
3734 return 1;
3735 }
3736 return 0;
3737}
3738
3739/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3740static inline int parse_digit(const char **date, int *len, int *digit)
3741{
3742 if (*len < 1 || **date < '0' || **date > '9')
3743 return 0;
3744 *digit = (**date - '0');
3745 (*date)++;
3746 (*len)--;
3747 return 1;
3748}
3749
3750/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3751static inline int parse_2digit(const char **date, int *len, int *digit)
3752{
3753 int value;
3754
3755 RET0_UNLESS(parse_digit(date, len, &value));
3756 (*digit) = value * 10;
3757 RET0_UNLESS(parse_digit(date, len, &value));
3758 (*digit) += value;
3759
3760 return 1;
3761}
3762
3763/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3764static inline int parse_4digit(const char **date, int *len, int *digit)
3765{
3766 int value;
3767
3768 RET0_UNLESS(parse_digit(date, len, &value));
3769 (*digit) = value * 1000;
3770
3771 RET0_UNLESS(parse_digit(date, len, &value));
3772 (*digit) += value * 100;
3773
3774 RET0_UNLESS(parse_digit(date, len, &value));
3775 (*digit) += value * 10;
3776
3777 RET0_UNLESS(parse_digit(date, len, &value));
3778 (*digit) += value;
3779
3780 return 1;
3781}
3782
3783/* time-of-day = hour ":" minute ":" second
3784 * ; 00:00:00 - 23:59:60 (leap second)
3785 *
3786 * hour = 2DIGIT
3787 * minute = 2DIGIT
3788 * second = 2DIGIT
3789 */
3790static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3791{
3792 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3793 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3794 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3795 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3796 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3797 return 1;
3798}
3799
3800/* From RFC7231
3801 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3802 *
3803 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3804 * ; fixed length/zone/capitalization subset of the format
3805 * ; see Section 3.3 of [RFC5322]
3806 *
3807 *
3808 * date1 = day SP month SP year
3809 * ; e.g., 02 Jun 1982
3810 *
3811 * day = 2DIGIT
3812 * year = 4DIGIT
3813 *
3814 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3815 *
3816 * time-of-day = hour ":" minute ":" second
3817 * ; 00:00:00 - 23:59:60 (leap second)
3818 *
3819 * hour = 2DIGIT
3820 * minute = 2DIGIT
3821 * second = 2DIGIT
3822 *
3823 * DIGIT = decimal 0-9
3824 */
3825int parse_imf_date(const char *date, int len, struct tm *tm)
3826{
David Carlier327298c2016-11-20 10:42:38 +00003827 /* tm_gmtoff, if present, ought to be zero'ed */
3828 memset(tm, 0, sizeof(*tm));
3829
Thierry Fournier93127942016-01-20 18:49:45 +01003830 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3831 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3832 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3833 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3834 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3835 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3836 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3837 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3838 tm->tm_year -= 1900;
3839 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3840 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3841 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3842 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3843 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003844 return 1;
3845}
3846
3847/* From RFC7231
3848 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3849 *
3850 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3851 * date2 = day "-" month "-" 2DIGIT
3852 * ; e.g., 02-Jun-82
3853 *
3854 * day = 2DIGIT
3855 */
3856int parse_rfc850_date(const char *date, int len, struct tm *tm)
3857{
3858 int year;
3859
David Carlier327298c2016-11-20 10:42:38 +00003860 /* tm_gmtoff, if present, ought to be zero'ed */
3861 memset(tm, 0, sizeof(*tm));
3862
Thierry Fournier93127942016-01-20 18:49:45 +01003863 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3864 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3865 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3866 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3867 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3868 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3869 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3870
3871 /* year = 2DIGIT
3872 *
3873 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3874 * two-digit year, MUST interpret a timestamp that appears to be more
3875 * than 50 years in the future as representing the most recent year in
3876 * the past that had the same last two digits.
3877 */
3878 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3879
3880 /* expect SP */
3881 if (!parse_expect_char(&date, &len, ' ')) {
3882 /* Maybe we have the date with 4 digits. */
3883 RET0_UNLESS(parse_2digit(&date, &len, &year));
3884 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3885 /* expect SP */
3886 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3887 } else {
3888 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3889 * tm_year is the number of year since 1900, so for +1900, we
3890 * do nothing, and for +2000, we add 100.
3891 */
3892 if (tm->tm_year <= 60)
3893 tm->tm_year += 100;
3894 }
3895
3896 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3897 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3898 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3899 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003900
3901 return 1;
3902}
3903
3904/* From RFC7231
3905 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3906 *
3907 * asctime-date = day-name SP date3 SP time-of-day SP year
3908 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3909 * ; e.g., Jun 2
3910 *
3911 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3912 * whitespace in an HTTP-date beyond that specifically included as SP in
3913 * the grammar.
3914 */
3915int parse_asctime_date(const char *date, int len, struct tm *tm)
3916{
David Carlier327298c2016-11-20 10:42:38 +00003917 /* tm_gmtoff, if present, ought to be zero'ed */
3918 memset(tm, 0, sizeof(*tm));
3919
Thierry Fournier93127942016-01-20 18:49:45 +01003920 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3921 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3922 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3923 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3924
3925 /* expect SP and 1DIGIT or 2DIGIT */
3926 if (parse_expect_char(&date, &len, ' '))
3927 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3928 else
3929 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3930
3931 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3932 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3933 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3934 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3935 tm->tm_year -= 1900;
3936 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003937 return 1;
3938}
3939
3940/* From RFC7231
3941 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3942 *
3943 * HTTP-date = IMF-fixdate / obs-date
3944 * obs-date = rfc850-date / asctime-date
3945 *
3946 * parses an HTTP date in the RFC format and is accepted
3947 * alternatives. <date> is the strinf containing the date,
3948 * len is the len of the string. <tm> is filled with the
3949 * parsed time. We must considers this time as GMT.
3950 */
3951int parse_http_date(const char *date, int len, struct tm *tm)
3952{
3953 if (parse_imf_date(date, len, tm))
3954 return 1;
3955
3956 if (parse_rfc850_date(date, len, tm))
3957 return 1;
3958
3959 if (parse_asctime_date(date, len, tm))
3960 return 1;
3961
3962 return 0;
3963}
3964
Willy Tarreau4deeb102021-01-29 10:47:52 +01003965/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3966 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3967 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3968 * surrounded by <pfx> and <sfx> respectively if not NULL.
3969 */
3970int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3971{
3972 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3973 const char *unit;
3974
3975 if (!pfx)
3976 pfx = "";
3977 if (!sfx)
3978 sfx = "";
3979
3980 do {
3981 unit = " - "; if (val <= 0.0) break;
3982 unit = "ns"; if (val < 1000.0) break;
3983 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3984 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3985 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3986 unit = "m "; val /= 60.0; if (val < 60.0) break;
3987 unit = "h "; val /= 60.0; if (val < 24.0) break;
3988 unit = "d "; val /= 24.0; if (val < 365.0) break;
3989 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3990 unit = " inf "; val = 0.0; break;
3991 } while (0);
3992
3993 if (val <= 0.0)
3994 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
3995 else if (val < 10.0)
3996 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
3997 else if (val < 100.0)
3998 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
3999 else
4000 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
4001}
4002
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004003/* Dynamically allocates a string of the proper length to hold the formatted
4004 * output. NULL is returned on error. The caller is responsible for freeing the
4005 * memory area using free(). The resulting string is returned in <out> if the
4006 * pointer is not NULL. A previous version of <out> might be used to build the
4007 * new string, and it will be freed before returning if it is not NULL, which
4008 * makes it possible to build complex strings from iterative calls without
4009 * having to care about freeing intermediate values, as in the example below :
4010 *
4011 * memprintf(&err, "invalid argument: '%s'", arg);
4012 * ...
4013 * memprintf(&err, "parser said : <%s>\n", *err);
4014 * ...
4015 * free(*err);
4016 *
4017 * This means that <err> must be initialized to NULL before first invocation.
4018 * The return value also holds the allocated string, which eases error checking
4019 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004020 * passed instead and it will be ignored. The returned message will then also
4021 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004022 *
4023 * It is also convenient to use it without any free except the last one :
4024 * err = NULL;
4025 * if (!fct1(err)) report(*err);
4026 * if (!fct2(err)) report(*err);
4027 * if (!fct3(err)) report(*err);
4028 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004029 *
4030 * memprintf relies on memvprintf. This last version can be called from any
4031 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004032 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004033char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004034{
4035 va_list args;
4036 char *ret = NULL;
4037 int allocated = 0;
4038 int needed = 0;
4039
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004040 if (!out)
4041 return NULL;
4042
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004043 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004044 char buf1;
4045
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004046 /* vsnprintf() will return the required length even when the
4047 * target buffer is NULL. We do this in a loop just in case
4048 * intermediate evaluations get wrong.
4049 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004050 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004051 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004052 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004053 if (needed < allocated) {
4054 /* Note: on Solaris 8, the first iteration always
4055 * returns -1 if allocated is zero, so we force a
4056 * retry.
4057 */
4058 if (!allocated)
4059 needed = 0;
4060 else
4061 break;
4062 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004063
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004064 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004065 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004066 } while (ret);
4067
4068 if (needed < 0) {
4069 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004070 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004071 }
4072
4073 if (out) {
4074 free(*out);
4075 *out = ret;
4076 }
4077
4078 return ret;
4079}
William Lallemand421f5b52012-02-06 18:15:57 +01004080
Christopher Faulet93a518f2017-10-24 11:25:33 +02004081char *memprintf(char **out, const char *format, ...)
4082{
4083 va_list args;
4084 char *ret = NULL;
4085
4086 va_start(args, format);
4087 ret = memvprintf(out, format, args);
4088 va_end(args);
4089
4090 return ret;
4091}
4092
Willy Tarreau21c705b2012-09-14 11:40:36 +02004093/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4094 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004095 * freed by the caller. It also supports being passed a NULL which results in the same
4096 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004097 * Example of use :
4098 * parse(cmd, &err); (callee: memprintf(&err, ...))
4099 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4100 * free(err);
4101 */
4102char *indent_msg(char **out, int level)
4103{
4104 char *ret, *in, *p;
4105 int needed = 0;
4106 int lf = 0;
4107 int lastlf = 0;
4108 int len;
4109
Willy Tarreau70eec382012-10-10 08:56:47 +02004110 if (!out || !*out)
4111 return NULL;
4112
Willy Tarreau21c705b2012-09-14 11:40:36 +02004113 in = *out - 1;
4114 while ((in = strchr(in + 1, '\n')) != NULL) {
4115 lastlf = in - *out;
4116 lf++;
4117 }
4118
4119 if (!lf) /* single line, no LF, return it as-is */
4120 return *out;
4121
4122 len = strlen(*out);
4123
4124 if (lf == 1 && lastlf == len - 1) {
4125 /* single line, LF at end, strip it and return as-is */
4126 (*out)[lastlf] = 0;
4127 return *out;
4128 }
4129
4130 /* OK now we have at least one LF, we need to process the whole string
4131 * as a multi-line string. What we'll do :
4132 * - prefix with an LF if there is none
4133 * - add <level> spaces before each line
4134 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4135 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4136 */
4137
4138 needed = 1 + level * (lf + 1) + len + 1;
4139 p = ret = malloc(needed);
4140 in = *out;
4141
4142 /* skip initial LFs */
4143 while (*in == '\n')
4144 in++;
4145
4146 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4147 while (*in) {
4148 *p++ = '\n';
4149 memset(p, ' ', level);
4150 p += level;
4151 do {
4152 *p++ = *in++;
4153 } while (*in && *in != '\n');
4154 if (*in)
4155 in++;
4156 }
4157 *p = 0;
4158
4159 free(*out);
4160 *out = ret;
4161
4162 return ret;
4163}
4164
Willy Tarreaua2c99112019-08-21 13:17:37 +02004165/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4166 * and end of lines replaced with <eol> if not 0. The first line to indent has
4167 * to be indicated in <first> (starts at zero), so that it is possible to skip
4168 * indenting the first line if it has to be appended after an existing message.
4169 * Empty strings are never indented, and NULL strings are considered empty both
4170 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4171 * character, non-zero otherwise.
4172 */
4173int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4174{
4175 int bol, lf;
4176 int pfxlen = pfx ? strlen(pfx) : 0;
4177
4178 if (!in)
4179 return 0;
4180
4181 bol = 1;
4182 lf = 0;
4183 while (*in) {
4184 if (bol && pfxlen) {
4185 if (first > 0)
4186 first--;
4187 else
4188 b_putblk(out, pfx, pfxlen);
4189 bol = 0;
4190 }
4191
4192 lf = (*in == '\n');
4193 bol |= lf;
4194 b_putchr(out, (lf && eol) ? eol : *in);
4195 in++;
4196 }
4197 return lf;
4198}
4199
Willy Tarreau9d22e562019-03-29 18:49:09 +01004200/* removes environment variable <name> from the environment as found in
4201 * environ. This is only provided as an alternative for systems without
4202 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004203 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004204 * <name> and to replace the matching pointers with the last pointer of
4205 * the array (since variables are not ordered).
4206 * It always returns 0 (success).
4207 */
4208int my_unsetenv(const char *name)
4209{
4210 extern char **environ;
4211 char **p = environ;
4212 int vars;
4213 int next;
4214 int len;
4215
4216 len = strlen(name);
4217 for (vars = 0; p[vars]; vars++)
4218 ;
4219 next = 0;
4220 while (next < vars) {
4221 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4222 next++;
4223 continue;
4224 }
4225 if (next < vars - 1)
4226 p[next] = p[vars - 1];
4227 p[--vars] = NULL;
4228 }
4229 return 0;
4230}
4231
Willy Tarreaudad36a32013-03-11 01:20:04 +01004232/* Convert occurrences of environment variables in the input string to their
4233 * corresponding value. A variable is identified as a series of alphanumeric
4234 * characters or underscores following a '$' sign. The <in> string must be
4235 * free()able. NULL returns NULL. The resulting string might be reallocated if
4236 * some expansion is made. Variable names may also be enclosed into braces if
4237 * needed (eg: to concatenate alphanum characters).
4238 */
4239char *env_expand(char *in)
4240{
4241 char *txt_beg;
4242 char *out;
4243 char *txt_end;
4244 char *var_beg;
4245 char *var_end;
4246 char *value;
4247 char *next;
4248 int out_len;
4249 int val_len;
4250
4251 if (!in)
4252 return in;
4253
4254 value = out = NULL;
4255 out_len = 0;
4256
4257 txt_beg = in;
4258 do {
4259 /* look for next '$' sign in <in> */
4260 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4261
4262 if (!*txt_end && !out) /* end and no expansion performed */
4263 return in;
4264
4265 val_len = 0;
4266 next = txt_end;
4267 if (*txt_end == '$') {
4268 char save;
4269
4270 var_beg = txt_end + 1;
4271 if (*var_beg == '{')
4272 var_beg++;
4273
4274 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004275 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004276 var_end++;
4277 }
4278
4279 next = var_end;
4280 if (*var_end == '}' && (var_beg > txt_end + 1))
4281 next++;
4282
4283 /* get value of the variable name at this location */
4284 save = *var_end;
4285 *var_end = '\0';
4286 value = getenv(var_beg);
4287 *var_end = save;
4288 val_len = value ? strlen(value) : 0;
4289 }
4290
Hubert Verstraete831962e2016-06-28 22:44:26 +02004291 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004292 if (txt_end > txt_beg) {
4293 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4294 out_len += txt_end - txt_beg;
4295 }
4296 if (val_len) {
4297 memcpy(out + out_len, value, val_len);
4298 out_len += val_len;
4299 }
4300 out[out_len] = 0;
4301 txt_beg = next;
4302 } while (*txt_beg);
4303
4304 /* here we know that <out> was allocated and that we don't need <in> anymore */
4305 free(in);
4306 return out;
4307}
4308
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004309
4310/* same as strstr() but case-insensitive and with limit length */
4311const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4312{
4313 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004314 unsigned int slen, plen;
4315 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004316
4317 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4318 return NULL;
4319
4320 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4321 return str1;
4322
4323 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4324 return NULL;
4325
4326 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 +02004327 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004328 start++;
4329 slen--;
4330 tmp1++;
4331
4332 if (tmp1 >= len_str1)
4333 return NULL;
4334
4335 /* if pattern longer than string */
4336 if (slen < plen)
4337 return NULL;
4338 }
4339
4340 sptr = start;
4341 pptr = (char *)str2;
4342
4343 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004344 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004345 sptr++;
4346 pptr++;
4347 tmp2++;
4348
4349 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4350 return start;
4351 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4352 return NULL;
4353 }
4354 }
4355 return NULL;
4356}
4357
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004358/* This function read the next valid utf8 char.
4359 * <s> is the byte srray to be decode, <len> is its length.
4360 * The function returns decoded char encoded like this:
4361 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4362 * are the length read. The decoded character is stored in <c>.
4363 */
4364unsigned char utf8_next(const char *s, int len, unsigned int *c)
4365{
4366 const unsigned char *p = (unsigned char *)s;
4367 int dec;
4368 unsigned char code = UTF8_CODE_OK;
4369
4370 if (len < 1)
4371 return UTF8_CODE_OK;
4372
4373 /* Check the type of UTF8 sequence
4374 *
4375 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4376 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4377 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4378 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4379 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4380 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4381 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4382 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4383 */
4384 switch (*p) {
4385 case 0x00 ... 0x7f:
4386 *c = *p;
4387 return UTF8_CODE_OK | 1;
4388
4389 case 0x80 ... 0xbf:
4390 *c = *p;
4391 return UTF8_CODE_BADSEQ | 1;
4392
4393 case 0xc0 ... 0xdf:
4394 if (len < 2) {
4395 *c = *p;
4396 return UTF8_CODE_BADSEQ | 1;
4397 }
4398 *c = *p & 0x1f;
4399 dec = 1;
4400 break;
4401
4402 case 0xe0 ... 0xef:
4403 if (len < 3) {
4404 *c = *p;
4405 return UTF8_CODE_BADSEQ | 1;
4406 }
4407 *c = *p & 0x0f;
4408 dec = 2;
4409 break;
4410
4411 case 0xf0 ... 0xf7:
4412 if (len < 4) {
4413 *c = *p;
4414 return UTF8_CODE_BADSEQ | 1;
4415 }
4416 *c = *p & 0x07;
4417 dec = 3;
4418 break;
4419
4420 case 0xf8 ... 0xfb:
4421 if (len < 5) {
4422 *c = *p;
4423 return UTF8_CODE_BADSEQ | 1;
4424 }
4425 *c = *p & 0x03;
4426 dec = 4;
4427 break;
4428
4429 case 0xfc ... 0xfd:
4430 if (len < 6) {
4431 *c = *p;
4432 return UTF8_CODE_BADSEQ | 1;
4433 }
4434 *c = *p & 0x01;
4435 dec = 5;
4436 break;
4437
4438 case 0xfe ... 0xff:
4439 default:
4440 *c = *p;
4441 return UTF8_CODE_BADSEQ | 1;
4442 }
4443
4444 p++;
4445
4446 while (dec > 0) {
4447
4448 /* need 0x10 for the 2 first bits */
4449 if ( ( *p & 0xc0 ) != 0x80 )
4450 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4451
4452 /* add data at char */
4453 *c = ( *c << 6 ) | ( *p & 0x3f );
4454
4455 dec--;
4456 p++;
4457 }
4458
4459 /* Check ovelong encoding.
4460 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4461 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4462 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4463 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004464 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004465 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4466 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4467 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4468 code |= UTF8_CODE_OVERLONG;
4469
4470 /* Check invalid UTF8 range. */
4471 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4472 (*c >= 0xfffe && *c <= 0xffff))
4473 code |= UTF8_CODE_INVRANGE;
4474
4475 return code | ((p-(unsigned char *)s)&0x0f);
4476}
4477
Maxime de Roucydc887852016-05-13 23:52:54 +02004478/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4479 * On failure : return 0 and <err> filled with an error message.
4480 * The caller is responsible for freeing the <err> and <str> copy
4481 * memory area using free()
4482 */
4483int list_append_word(struct list *li, const char *str, char **err)
4484{
4485 struct wordlist *wl;
4486
4487 wl = calloc(1, sizeof(*wl));
4488 if (!wl) {
4489 memprintf(err, "out of memory");
4490 goto fail_wl;
4491 }
4492
4493 wl->s = strdup(str);
4494 if (!wl->s) {
4495 memprintf(err, "out of memory");
4496 goto fail_wl_s;
4497 }
4498
Willy Tarreau2b718102021-04-21 07:32:39 +02004499 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004500
4501 return 1;
4502
4503fail_wl_s:
4504 free(wl->s);
4505fail_wl:
4506 free(wl);
4507 return 0;
4508}
4509
Willy Tarreau37101052019-05-20 16:48:20 +02004510/* indicates if a memory location may safely be read or not. The trick consists
4511 * in performing a harmless syscall using this location as an input and letting
4512 * the operating system report whether it's OK or not. For this we have the
4513 * stat() syscall, which will return EFAULT when the memory location supposed
4514 * to contain the file name is not readable. If it is readable it will then
4515 * either return 0 if the area contains an existing file name, or -1 with
4516 * another code. This must not be abused, and some audit systems might detect
4517 * this as abnormal activity. It's used only for unsafe dumps.
4518 */
4519int may_access(const void *ptr)
4520{
4521 struct stat buf;
4522
4523 if (stat(ptr, &buf) == 0)
4524 return 1;
4525 if (errno == EFAULT)
4526 return 0;
4527 return 1;
4528}
4529
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004530/* print a string of text buffer to <out>. The format is :
4531 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4532 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4533 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4534 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004535int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004536{
4537 unsigned char c;
Tim Duesterhus18795d42021-08-29 00:58:22 +02004538 size_t ptr = 0;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004539
Tim Duesterhus18795d42021-08-29 00:58:22 +02004540 while (ptr < bsize && buf[ptr]) {
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004541 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004542 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004543 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004544 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004545 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004546 }
4547 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004548 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004549 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004550 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004551 switch (c) {
4552 case ' ': c = ' '; break;
4553 case '\t': c = 't'; break;
4554 case '\n': c = 'n'; break;
4555 case '\r': c = 'r'; break;
4556 case '\e': c = 'e'; break;
4557 case '\\': c = '\\'; break;
4558 case '=': c = '='; break;
4559 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004560 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004561 }
4562 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004563 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004564 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004565 out->area[out->data++] = '\\';
4566 out->area[out->data++] = 'x';
4567 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4568 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004569 }
4570 ptr++;
4571 }
4572
4573 return ptr;
4574}
4575
4576/* print a buffer in hexa.
4577 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4578 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004579int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004580{
4581 unsigned char c;
4582 int ptr = 0;
4583
4584 while (ptr < bsize) {
4585 c = buf[ptr];
4586
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004587 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004588 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004589 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4590 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004591
4592 ptr++;
4593 }
4594 return ptr;
4595}
4596
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004597/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4598 * prepending each line with prefix <pfx>. The output is *not* initialized.
4599 * The output will not wrap pas the buffer's end so it is more optimal if the
4600 * caller makes sure the buffer is aligned first. A trailing zero will always
4601 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004602 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4603 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004604 */
Willy Tarreau37101052019-05-20 16:48:20 +02004605void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004606{
4607 const unsigned char *d = buf;
4608 int i, j, start;
4609
4610 d = (const unsigned char *)(((unsigned long)buf) & -16);
4611 start = ((unsigned long)buf) & 15;
4612
4613 for (i = 0; i < start + len; i += 16) {
4614 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4615
Willy Tarreau37101052019-05-20 16:48:20 +02004616 // 0: unchecked, 1: checked safe, 2: danger
4617 unsafe = !!unsafe;
4618 if (unsafe && !may_access(d + i))
4619 unsafe = 2;
4620
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004621 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004622 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004623 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004624 else if (unsafe > 1)
4625 chunk_strcat(out, "** ");
4626 else
4627 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004628
4629 if (j == 7)
4630 chunk_strcat(out, "- ");
4631 }
4632 chunk_strcat(out, " ");
4633 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004634 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004635 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004636 else if (unsafe > 1)
4637 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004638 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004639 chunk_appendf(out, "%c", d[i + j]);
4640 else
4641 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004642 }
4643 chunk_strcat(out, "\n");
4644 }
4645}
4646
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004647/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4648 * enclosed in brackets after the address itself, formatted on 14 chars
4649 * including the "0x" prefix. This is meant to be used as a prefix for code
4650 * areas. For example:
4651 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4652 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4653 * is emitted. A NULL <pfx> will be considered empty.
4654 */
4655void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4656{
4657 int ok = 0;
4658 int i;
4659
4660 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4661
4662 for (i = 0; i < n; i++) {
4663 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4664 ok = may_access(addr + i);
4665 if (ok)
4666 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4667 else
4668 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4669 }
4670}
4671
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004672/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4673 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4674 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4675 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4676 * lines are respected within the limit of 70 output chars. Lines that are
4677 * continuation of a previous truncated line begin with "+" instead of " "
4678 * after the offset. The new pointer is returned.
4679 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004680int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004681 int *line, int ptr)
4682{
4683 int end;
4684 unsigned char c;
4685
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004686 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004687 if (end > out->size)
4688 return ptr;
4689
4690 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4691
4692 while (ptr < len && ptr < bsize) {
4693 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004694 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004695 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004696 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004697 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004698 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004699 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004700 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004701 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004702 switch (c) {
4703 case '\t': c = 't'; break;
4704 case '\n': c = 'n'; break;
4705 case '\r': c = 'r'; break;
4706 case '\e': c = 'e'; break;
4707 case '\\': c = '\\'; break;
4708 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004709 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004710 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004711 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004712 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004713 out->area[out->data++] = '\\';
4714 out->area[out->data++] = 'x';
4715 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4716 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004717 }
4718 if (buf[ptr++] == '\n') {
4719 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004720 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004721 *line = ptr;
4722 return ptr;
4723 }
4724 }
4725 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004726 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004727 return ptr;
4728}
4729
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004730/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004731 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4732 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004733 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004734void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4735 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004736{
Willy Tarreau73459792017-04-11 07:58:08 +02004737 unsigned int i;
4738 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004739
4740 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4741 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004742 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004743 for (j = 0; j < 8; j++) {
4744 if (b + j >= 0 && b + j < len)
4745 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4746 else
4747 fprintf(out, " ");
4748 }
4749
4750 if (b + j >= 0 && b + j < len)
4751 fputc('-', out);
4752 else
4753 fputc(' ', out);
4754
4755 for (j = 8; j < 16; j++) {
4756 if (b + j >= 0 && b + j < len)
4757 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4758 else
4759 fprintf(out, " ");
4760 }
4761
4762 fprintf(out, " ");
4763 for (j = 0; j < 16; j++) {
4764 if (b + j >= 0 && b + j < len) {
4765 if (isprint((unsigned char)buf[b + j]))
4766 fputc((unsigned char)buf[b + j], out);
4767 else
4768 fputc('.', out);
4769 }
4770 else
4771 fputc(' ', out);
4772 }
4773 fputc('\n', out);
4774 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004775}
4776
Willy Tarreaubb869862020-04-16 10:52:41 +02004777/* Tries to report the executable path name on platforms supporting this. If
4778 * not found or not possible, returns NULL.
4779 */
4780const char *get_exec_path()
4781{
4782 const char *ret = NULL;
4783
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004784#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
Willy Tarreaubb869862020-04-16 10:52:41 +02004785 long execfn = getauxval(AT_EXECFN);
4786
4787 if (execfn && execfn != ENOENT)
4788 ret = (const char *)execfn;
devnexen@gmail.comc4e52322021-08-17 12:55:49 +01004789#elif defined(__FreeBSD__)
4790 Elf_Auxinfo *auxv;
4791 for (auxv = __elf_aux_vector; auxv->a_type != AT_NULL; ++auxv) {
4792 if (auxv->a_type == AT_EXECPATH) {
4793 ret = (const char *)auxv->a_un.a_ptr;
4794 break;
4795 }
4796 }
David Carlierbd2cced2021-08-17 08:44:25 +01004797#elif defined(__NetBSD__)
4798 AuxInfo *auxv;
4799 for (auxv = _dlauxinfo(); auxv->a_type != AT_NULL; ++auxv) {
4800 if (auxv->a_type == AT_SUN_EXECNAME) {
4801 ret = (const char *)auxv->a_v;
4802 break;
4803 }
4804 }
Willy Tarreaubb869862020-04-16 10:52:41 +02004805#endif
4806 return ret;
4807}
4808
Baruch Siache1651b22020-07-24 07:52:20 +03004809#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004810/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4811 * also returns the symbol size in <size>, otherwise returns 0 there.
4812 */
4813static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4814{
4815 int ret;
Willy Tarreau7b2108c2021-08-30 10:15:35 +02004816#if defined(__GLIBC__) && (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004817 const ElfW(Sym) *sym;
4818
4819 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4820 if (ret)
4821 *size = sym ? sym->st_size : 0;
4822#else
4823 ret = dladdr(addr, dli);
4824 *size = 0;
4825#endif
4826 return ret;
4827}
Willy Tarreau64192392021-05-05 09:06:21 +02004828
4829/* Tries to retrieve the address of the first occurrence symbol <name>.
4830 * Note that NULL in return is not always an error as a symbol may have that
4831 * address in special situations.
4832 */
4833void *get_sym_curr_addr(const char *name)
4834{
4835 void *ptr = NULL;
4836
4837#ifdef RTLD_DEFAULT
4838 ptr = dlsym(RTLD_DEFAULT, name);
4839#endif
4840 return ptr;
4841}
4842
4843
4844/* Tries to retrieve the address of the next occurrence of symbol <name>
4845 * Note that NULL in return is not always an error as a symbol may have that
4846 * address in special situations.
4847 */
4848void *get_sym_next_addr(const char *name)
4849{
4850 void *ptr = NULL;
4851
4852#ifdef RTLD_NEXT
4853 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004854#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004855 return ptr;
4856}
4857
4858#else /* elf & linux & dl */
4859
4860/* no possible resolving on other platforms at the moment */
4861void *get_sym_curr_addr(const char *name)
4862{
4863 return NULL;
4864}
4865
4866void *get_sym_next_addr(const char *name)
4867{
4868 return NULL;
4869}
4870
4871#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004872
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004873/* Tries to append to buffer <buf> some indications about the symbol at address
4874 * <addr> using the following form:
4875 * lib:+0xoffset (unresolvable address from lib's base)
4876 * main+0xoffset (unresolvable address from main (+/-))
4877 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4878 * name (resolved exact exec address)
4879 * lib:name (resolved exact lib address)
4880 * name+0xoffset/0xsize (resolved address within exec symbol)
4881 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4882 *
4883 * The file name (lib or executable) is limited to what lies between the last
4884 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4885 * the output if not null. The file is not dumped when it's the same as the one
Baruch Siache1651b22020-07-24 07:52:20 +03004886 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004887 *
4888 * The symbol's base address is returned, or NULL when unresolved, in order to
4889 * allow the caller to match it against known ones.
4890 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004891const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004892{
4893 const struct {
4894 const void *func;
4895 const char *name;
4896 } fcts[] = {
4897 { .func = process_stream, .name = "process_stream" },
4898 { .func = task_run_applet, .name = "task_run_applet" },
4899 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004900 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004901 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4902 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004903 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004904 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4905 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004906 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004907#ifdef USE_THREAD
4908 { .func = accept_queue_process, .name = "accept_queue_process" },
4909#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004910#ifdef USE_LUA
4911 { .func = hlua_process_task, .name = "hlua_process_task" },
4912#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004913#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004914 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4915 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4916#endif
4917 };
4918
Baruch Siache1651b22020-07-24 07:52:20 +03004919#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004920 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004921 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004922 const char *fname, *p;
4923#endif
4924 int i;
4925
4926 if (pfx)
4927 chunk_appendf(buf, "%s", pfx);
4928
4929 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4930 if (addr == fcts[i].func) {
4931 chunk_appendf(buf, "%s", fcts[i].name);
4932 return addr;
4933 }
4934 }
4935
Baruch Siache1651b22020-07-24 07:52:20 +03004936#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004937 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004938 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004939 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004940
4941 /* 1. prefix the library name if it's not the same object as the one
4942 * that contains the main function. The name is picked between last '/'
4943 * and first following '.'.
4944 */
4945 if (!dladdr(main, &dli_main))
4946 dli_main.dli_fbase = NULL;
4947
4948 if (dli_main.dli_fbase != dli.dli_fbase) {
4949 fname = dli.dli_fname;
4950 p = strrchr(fname, '/');
4951 if (p++)
4952 fname = p;
4953 p = strchr(fname, '.');
4954 if (!p)
4955 p = fname + strlen(fname);
4956
4957 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4958 }
4959
4960 /* 2. symbol name */
4961 if (dli.dli_sname) {
4962 /* known, dump it and return symbol's address (exact or relative) */
4963 chunk_appendf(buf, "%s", dli.dli_sname);
4964 if (addr != dli.dli_saddr) {
4965 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004966 if (size)
4967 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004968 }
4969 return dli.dli_saddr;
4970 }
4971 else if (dli_main.dli_fbase != dli.dli_fbase) {
4972 /* unresolved symbol from a known library, report relative offset */
4973 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4974 return NULL;
4975 }
Baruch Siache1651b22020-07-24 07:52:20 +03004976#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004977 unknown:
4978 /* unresolved symbol from the main file, report relative offset to main */
4979 if ((void*)addr < (void*)main)
4980 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4981 else
4982 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4983 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004984}
4985
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004986/*
4987 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004988 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004989 *
4990 * First, initializes the value with <sz> as address to 0 and initializes the
4991 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4992 * address updating <sz> pointed value to the size of this array.
4993 *
4994 * Returns 1 if succeeded, 0 if not.
4995 */
4996int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4997{
4998 unsigned int *n;
4999 const char *s, *end;
5000
5001 s = str;
5002 *sz = 0;
5003 end = str + strlen(str);
5004 *nums = n = NULL;
5005
5006 while (1) {
5007 unsigned int r;
5008
5009 if (s >= end)
5010 break;
5011
5012 r = read_uint(&s, end);
5013 /* Expected characters after having read an uint: '\0' or '.',
5014 * if '.', must not be terminal.
5015 */
Christopher Faulet4b524122021-02-11 10:42:41 +01005016 if (*s != '\0'&& (*s++ != '.' || s == end)) {
5017 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005018 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01005019 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005020
Frédéric Lécaille12a71842019-02-26 18:19:48 +01005021 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01005022 if (!n)
5023 return 0;
5024
5025 n[(*sz)++] = r;
5026 }
5027 *nums = n;
5028
5029 return 1;
5030}
5031
Willy Tarreau4d589e72019-08-23 19:02:26 +02005032
5033/* returns the number of bytes needed to encode <v> as a varint. An inline
5034 * version exists for use with constants (__varint_bytes()).
5035 */
5036int varint_bytes(uint64_t v)
5037{
5038 int len = 1;
5039
5040 if (v >= 240) {
5041 v = (v - 240) >> 4;
5042 while (1) {
5043 len++;
5044 if (v < 128)
5045 break;
5046 v = (v - 128) >> 7;
5047 }
5048 }
5049 return len;
5050}
5051
Willy Tarreau52bf8392020-03-08 00:42:37 +01005052
5053/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005054static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005055
5056/* This is a thread-safe implementation of xoroshiro128** described below:
5057 * http://prng.di.unimi.it/
5058 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5059 * supports fast jumps and passes all common quality tests. It is thread-safe,
5060 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5061 * local lock on other ones.
5062 */
5063uint64_t ha_random64()
5064{
Willy Tarreau1544c142020-03-12 00:31:18 +01005065 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5066 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005067
5068#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5069 static HA_SPINLOCK_T rand_lock;
5070
5071 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5072#endif
5073
5074 old[0] = ha_random_state[0];
5075 old[1] = ha_random_state[1];
5076
5077#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5078 do {
5079#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005080 new[1] = old[0] ^ old[1];
5081 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5082 new[1] = rotl64(new[1], 37); // c
5083
5084#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5085 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5086#else
5087 ha_random_state[0] = new[0];
5088 ha_random_state[1] = new[1];
5089#if defined(USE_THREAD)
5090 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5091#endif
5092#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005093 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005094}
5095
5096/* seeds the random state using up to <len> bytes from <seed>, starting with
5097 * the first non-zero byte.
5098 */
5099void ha_random_seed(const unsigned char *seed, size_t len)
5100{
5101 size_t pos;
5102
5103 /* the seed must not be all zeroes, so we pre-fill it with alternating
5104 * bits and overwrite part of them with the block starting at the first
5105 * non-zero byte from the seed.
5106 */
5107 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5108
5109 for (pos = 0; pos < len; pos++)
5110 if (seed[pos] != 0)
5111 break;
5112
5113 if (pos == len)
5114 return;
5115
5116 seed += pos;
5117 len -= pos;
5118
5119 if (len > sizeof(ha_random_state))
5120 len = sizeof(ha_random_state);
5121
5122 memcpy(ha_random_state, seed, len);
5123}
5124
5125/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5126 * and is equivalent to calling ha_random64() as many times. It is used to
5127 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5128 * different generators (i.e. different processes after a fork). The <dist>
5129 * argument is the distance to jump to and is used in a loop so it rather not
5130 * be too large if the processing time is a concern.
5131 *
5132 * BEWARE: this function is NOT thread-safe and must not be called during
5133 * concurrent accesses to ha_random64().
5134 */
5135void ha_random_jump96(uint32_t dist)
5136{
5137 while (dist--) {
5138 uint64_t s0 = 0;
5139 uint64_t s1 = 0;
5140 int b;
5141
5142 for (b = 0; b < 64; b++) {
5143 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5144 s0 ^= ha_random_state[0];
5145 s1 ^= ha_random_state[1];
5146 }
5147 ha_random64();
5148 }
5149
5150 for (b = 0; b < 64; b++) {
5151 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5152 s0 ^= ha_random_state[0];
5153 s1 ^= ha_random_state[1];
5154 }
5155 ha_random64();
5156 }
5157 ha_random_state[0] = s0;
5158 ha_random_state[1] = s1;
5159 }
5160}
5161
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005162/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5163 * bytes large.
5164 */
5165void ha_generate_uuid(struct buffer *output)
5166{
5167 uint32_t rnd[4];
5168 uint64_t last;
5169
5170 last = ha_random64();
5171 rnd[0] = last;
5172 rnd[1] = last >> 32;
5173
5174 last = ha_random64();
5175 rnd[2] = last;
5176 rnd[3] = last >> 32;
5177
5178 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5179 rnd[0],
5180 rnd[1] & 0xFFFF,
5181 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5182 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5183 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5184}
5185
5186
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005187/* only used by parse_line() below. It supports writing in place provided that
5188 * <in> is updated to the next location before calling it. In that case, the
5189 * char at <in> may be overwritten.
5190 */
5191#define EMIT_CHAR(x) \
5192 do { \
5193 char __c = (char)(x); \
5194 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5195 err |= PARSE_ERR_OVERLAP; \
5196 if (outpos >= outmax) \
5197 err |= PARSE_ERR_TOOLARGE; \
5198 if (!err) \
5199 out[outpos] = __c; \
5200 outpos++; \
5201 } while (0)
5202
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005203/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005204 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5205 * extraneous ones are not emitted but <outlen> is updated so that the caller
5206 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5207 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005208 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5209 * it is guaranteed that at least one arg will point to the zero. It is safe
5210 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005211 *
5212 * <out> may overlap with <in> provided that it never goes further, in which
5213 * case the parser will accept to perform in-place parsing and unquoting/
5214 * unescaping but only if environment variables do not lead to expansion that
5215 * causes overlapping, otherwise the input string being destroyed, the error
5216 * will not be recoverable. Note that even during out-of-place <in> will
5217 * experience temporary modifications in-place for variable resolution and must
5218 * be writable, and will also receive zeroes to delimit words when using
5219 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5220 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5221 * starting point of the first invalid character sequence or unmatched
5222 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5223 * error reporting might be difficult since zeroes will have been inserted into
5224 * the string. One solution for the caller may consist in replacing all args
5225 * delimiters with spaces in this case.
5226 */
Maximilian Mader29c6cd72021-06-06 00:50:21 +02005227uint32_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 +02005228{
5229 char *quote = NULL;
5230 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005231 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005232 unsigned char hex1, hex2;
5233 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005234 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005235 size_t outpos = 0;
5236 int squote = 0;
5237 int dquote = 0;
5238 int arg = 0;
5239 uint32_t err = 0;
5240
5241 *nbargs = 0;
5242 *outlen = 0;
5243
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005244 /* argsmax may be -1 here, protecting args[] from any write */
5245 if (arg < argsmax)
5246 args[arg] = out;
5247
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005248 while (1) {
5249 if (*in >= '-' && *in != '\\') {
5250 /* speedup: directly send all regular chars starting
5251 * with '-', '.', '/', alnum etc...
5252 */
5253 EMIT_CHAR(*in++);
5254 continue;
5255 }
5256 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5257 /* end of line */
5258 break;
5259 }
5260 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5261 /* comment */
5262 break;
5263 }
5264 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5265 if (dquote) {
5266 dquote = 0;
5267 quote = NULL;
5268 }
5269 else {
5270 dquote = 1;
5271 quote = in;
5272 }
5273 in++;
5274 continue;
5275 }
5276 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5277 if (squote) {
5278 squote = 0;
5279 quote = NULL;
5280 }
5281 else {
5282 squote = 1;
5283 quote = in;
5284 }
5285 in++;
5286 continue;
5287 }
5288 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5289 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5290 * C equivalent value but only when they have a special meaning and within
5291 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5292 */
5293 char tosend = *in;
5294
5295 switch (in[1]) {
5296 case ' ':
5297 case '\\':
5298 tosend = in[1];
5299 in++;
5300 break;
5301
5302 case 't':
5303 tosend = '\t';
5304 in++;
5305 break;
5306
5307 case 'n':
5308 tosend = '\n';
5309 in++;
5310 break;
5311
5312 case 'r':
5313 tosend = '\r';
5314 in++;
5315 break;
5316
5317 case '#':
5318 /* escaping of "#" only if comments are supported */
5319 if (opts & PARSE_OPT_SHARP)
5320 in++;
5321 tosend = *in;
5322 break;
5323
5324 case '\'':
5325 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5326 if (opts & PARSE_OPT_SQUOTE && !squote)
5327 in++;
5328 tosend = *in;
5329 break;
5330
5331 case '"':
5332 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5333 if (opts & PARSE_OPT_DQUOTE && !squote)
5334 in++;
5335 tosend = *in;
5336 break;
5337
5338 case '$':
5339 /* escaping of '$' only inside double quotes and only if env supported */
5340 if (opts & PARSE_OPT_ENV && dquote)
5341 in++;
5342 tosend = *in;
5343 break;
5344
5345 case 'x':
5346 if (!ishex(in[2]) || !ishex(in[3])) {
5347 /* invalid or incomplete hex sequence */
5348 err |= PARSE_ERR_HEX;
5349 if (errptr)
5350 *errptr = in;
5351 goto leave;
5352 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005353 hex1 = toupper((unsigned char)in[2]) - '0';
5354 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005355 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5356 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5357 tosend = (hex1 << 4) + hex2;
5358 in += 3;
5359 break;
5360
5361 default:
5362 /* other combinations are not escape sequences */
5363 break;
5364 }
5365
5366 in++;
5367 EMIT_CHAR(tosend);
5368 }
5369 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5370 /* a non-escaped space is an argument separator */
5371 while (isspace((unsigned char)*in))
5372 in++;
5373 EMIT_CHAR(0);
5374 arg++;
5375 if (arg < argsmax)
5376 args[arg] = out + outpos;
5377 else
5378 err |= PARSE_ERR_TOOMANY;
5379 }
5380 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5381 /* environment variables are evaluated anywhere, or only
5382 * inside double quotes if they are supported.
5383 */
5384 char *var_name;
5385 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005386 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005387
5388 in++;
5389
5390 if (*in == '{')
5391 brace = in++;
5392
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005393 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005394 /* unacceptable character in variable name */
5395 err |= PARSE_ERR_VARNAME;
5396 if (errptr)
5397 *errptr = in;
5398 goto leave;
5399 }
5400
5401 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005402 if (*in == '.')
5403 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005404 while (isalnum((unsigned char)*in) || *in == '_')
5405 in++;
5406
5407 save_char = *in;
5408 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005409 if (unlikely(*var_name == '.')) {
5410 /* internal pseudo-variables */
5411 if (strcmp(var_name, ".LINE") == 0)
5412 value = ultoa(global.cfg_curr_line);
5413 else if (strcmp(var_name, ".FILE") == 0)
5414 value = global.cfg_curr_file;
5415 else if (strcmp(var_name, ".SECTION") == 0)
5416 value = global.cfg_curr_section;
5417 else {
5418 /* unsupported internal variable name */
5419 err |= PARSE_ERR_VARNAME;
5420 if (errptr)
5421 *errptr = var_name;
5422 goto leave;
5423 }
5424 } else {
5425 value = getenv(var_name);
5426 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005427 *in = save_char;
5428
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005429 /* support for '[*]' sequence to force word expansion,
5430 * only available inside braces */
5431 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5432 word_expand = in++;
5433
5434 if (*in++ != '*' || *in++ != ']') {
5435 err |= PARSE_ERR_WRONG_EXPAND;
5436 if (errptr)
5437 *errptr = word_expand;
5438 goto leave;
5439 }
5440 }
5441
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005442 if (brace) {
Willy Tarreauec347b12021-11-18 17:42:50 +01005443 if (*in == '-') {
5444 /* default value starts just after the '-' */
5445 if (!value)
5446 value = in + 1;
5447
5448 while (*in && *in != '}')
5449 in++;
5450 if (!*in)
5451 goto no_brace;
5452 *in = 0; // terminate the default value
5453 }
5454 else if (*in != '}') {
5455 no_brace:
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005456 /* unmatched brace */
5457 err |= PARSE_ERR_BRACE;
5458 if (errptr)
5459 *errptr = brace;
5460 goto leave;
5461 }
Willy Tarreauec347b12021-11-18 17:42:50 +01005462
5463 /* brace found, skip it */
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005464 in++;
5465 brace = NULL;
5466 }
5467
5468 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005469 while (*value) {
5470 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005471 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005472 EMIT_CHAR(0);
5473 ++arg;
5474 if (arg < argsmax)
5475 args[arg] = out + outpos;
5476 else
5477 err |= PARSE_ERR_TOOMANY;
5478
5479 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005480 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005481 ;
5482 } else {
5483 EMIT_CHAR(*value++);
5484 }
5485 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005486 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005487 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005488 }
5489 else {
5490 /* any other regular char */
5491 EMIT_CHAR(*in++);
5492 }
5493 }
5494
5495 /* end of output string */
5496 EMIT_CHAR(0);
5497 arg++;
5498
5499 if (quote) {
5500 /* unmatched quote */
5501 err |= PARSE_ERR_QUOTE;
5502 if (errptr)
5503 *errptr = quote;
5504 goto leave;
5505 }
5506 leave:
5507 *nbargs = arg;
5508 *outlen = outpos;
5509
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005510 /* empty all trailing args by making them point to the trailing zero,
5511 * at least the last one in any case.
5512 */
5513 if (arg > argsmax)
5514 arg = argsmax;
5515
5516 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005517 args[arg++] = out + outpos - 1;
5518
5519 return err;
5520}
5521#undef EMIT_CHAR
5522
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005523/* This is used to sanitize an input line that's about to be used for error reporting.
5524 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5525 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5526 * If non-printable chars are present in the output. It returns the new offset <pos>
5527 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5528 * be at least 6 to support two "..." otherwise the result is undefined. The line
5529 * itself must have at least 7 chars allocated for the same reason.
5530 */
5531size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5532{
5533 size_t shift = 0;
5534 char *out = line;
5535 char *in = line;
5536 char *end = line + width;
5537
5538 if (pos >= width) {
5539 /* if we have to shift, we'll be out of context, so let's
5540 * try to put <pos> at the center of width.
5541 */
5542 shift = pos - width / 2;
5543 in += shift + 3;
5544 end = out + width - 3;
5545 out[0] = out[1] = out[2] = '.';
5546 out += 3;
5547 }
5548
5549 while (out < end && *in) {
5550 if (isspace((unsigned char)*in))
5551 *out++ = ' ';
5552 else if (isprint((unsigned char)*in))
5553 *out++ = *in;
5554 else
5555 *out++ = '?';
5556 in++;
5557 }
5558
5559 if (end < line + width) {
5560 out[0] = out[1] = out[2] = '.';
5561 out += 3;
5562 }
5563
5564 *out++ = 0;
5565 return pos - shift;
5566}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005567
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005568/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005569 * transitions between characters. <fp> is a 1024-entries array indexed as
5570 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005571 * 1..26=letter, 27=digit, 28=other/begin/end.
5572 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005573 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005574void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005575{
5576 const char *p;
5577 int from, to;
5578 int c;
5579
Willy Tarreauba2c4452021-03-12 09:01:52 +01005580 from = 28; // begin
5581 for (p = word; *p; p++) {
5582 c = tolower(*p);
5583 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005584 case 'a'...'z': to = c - 'a' + 1; break;
5585 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5586 case '0'...'9': to = 27; break;
5587 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005588 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005589 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005590 fp[32 * from + to]++;
5591 from = to;
5592 }
5593 to = 28; // end
5594 fp[32 * from + to]++;
5595}
5596
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005597/* Initialize array <fp> with the fingerprint of word <word> by counting the
5598 * transitions between characters. <fp> is a 1024-entries array indexed as
5599 * 32*from+to. Positions for 'from' and 'to' are:
5600 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5601 */
5602void make_word_fingerprint(uint8_t *fp, const char *word)
5603{
5604 memset(fp, 0, 1024);
5605 update_word_fingerprint(fp, word);
5606}
5607
Willy Tarreauba2c4452021-03-12 09:01:52 +01005608/* Return the distance between two word fingerprints created by function
5609 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005610 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005611 */
5612int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5613{
5614 int i, k, dist = 0;
5615
5616 for (i = 0; i < 1024; i++) {
5617 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005618 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005619 }
5620 return dist;
5621}
5622
William Lallemand3aeb3f92021-08-21 23:59:56 +02005623/*
5624 * This function compares the loaded openssl version with a string <version>
5625 * This function use the same return code as compare_current_version:
5626 *
5627 * -1 : the version in argument is older than the current openssl version
5628 * 0 : the version in argument is the same as the current openssl version
5629 * 1 : the version in argument is newer than the current openssl version
5630 *
5631 * Or some errors:
5632 * -2 : openssl is not available on this process
5633 * -3 : the version in argument is not parsable
5634 */
5635int openssl_compare_current_version(const char *version)
5636{
5637#ifdef USE_OPENSSL
5638 int numversion;
5639
5640 numversion = openssl_version_parser(version);
5641 if (numversion == 0)
5642 return -3;
5643
5644 if (numversion < OPENSSL_VERSION_NUMBER)
5645 return -1;
5646 else if (numversion > OPENSSL_VERSION_NUMBER)
5647 return 1;
5648 else
5649 return 0;
5650#else
5651 return -2;
5652#endif
5653}
5654
Remi Tricot-Le Bretonb01179a2021-10-11 15:34:12 +02005655/*
5656 * This function compares the loaded openssl name with a string <name>
5657 * This function returns 0 if the OpenSSL name starts like the passed parameter,
5658 * 1 otherwise.
5659 */
5660int openssl_compare_current_name(const char *name)
5661{
5662#ifdef USE_OPENSSL
5663 int name_len = 0;
5664 const char *openssl_version = OpenSSL_version(OPENSSL_VERSION);
5665
5666 if (name) {
5667 name_len = strlen(name);
5668 if (strlen(name) <= strlen(openssl_version))
5669 return strncmp(openssl_version, name, name_len);
5670 }
5671#endif
5672 return 1;
5673}
5674
Willy Tarreau06e69b52021-03-02 14:01:35 +01005675static int init_tools_per_thread()
5676{
5677 /* Let's make each thread start from a different position */
5678 statistical_prng_state += tid * MAX_THREADS;
5679 if (!statistical_prng_state)
5680 statistical_prng_state++;
5681 return 1;
5682}
5683REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005684
Willy Tarreaubaaee002006-06-26 02:48:02 +02005685/*
5686 * Local variables:
5687 * c-indent-level: 8
5688 * c-basic-offset: 8
5689 * End:
5690 */