blob: e94fed7e7283b5da7a175069f9181b272290ea5c [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
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010019#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020020#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020022#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020023#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <stdlib.h>
25#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010026#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020027#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010028#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020029#include <sys/stat.h>
30#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010031#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netinet/in.h>
33#include <arpa/inet.h>
34
Willy Tarreau30053062020-08-20 16:39:14 +020035#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
36#include <sys/auxv.h>
37#endif
38
Willy Tarreau48fbcae2020-06-03 18:09:46 +020039#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020040#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020041
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020042#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020043#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020044#include <haproxy/dgram.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020045#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020046#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020047#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020048#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010049#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020050#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010051#include <haproxy/resolvers.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010052#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020053#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020054#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020055#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020056#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010057
Thierry Fournier93127942016-01-20 18:49:45 +010058/* This macro returns false if the test __x is false. Many
59 * of the following parsing function must be abort the processing
60 * if it returns 0, so this macro is useful for writing light code.
61 */
62#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
63
Willy Tarreau56adcf22012-12-23 18:00:29 +010064/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020065 * 2^64-1 = 18446744073709551615 or
66 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020067 *
68 * The HTML version needs room for adding the 25 characters
69 * '<span class="rls"></span>' around digits at positions 3N+1 in order
70 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020071 */
Christopher Faulet99bca652017-11-14 16:47:26 +010072THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
73THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020074
Willy Tarreau588297f2014-06-16 15:16:40 +020075/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
76 * to quote strings larger than a max configuration line.
77 */
Christopher Faulet99bca652017-11-14 16:47:26 +010078THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
79THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020080
Willy Tarreau06e69b52021-03-02 14:01:35 +010081/* thread-local PRNG state. It's modified to start from a different sequence
82 * on all threads upon startup. It must not be used or anything beyond getting
83 * statistical values as it's 100% predictable.
84 */
85THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
86
Willy Tarreaubaaee002006-06-26 02:48:02 +020087/*
William Lallemande7340ec2012-01-24 11:15:39 +010088 * unsigned long long ASCII representation
89 *
90 * return the last char '\0' or NULL if no enough
91 * space in dst
92 */
93char *ulltoa(unsigned long long n, char *dst, size_t size)
94{
95 int i = 0;
96 char *res;
97
98 switch(n) {
99 case 1ULL ... 9ULL:
100 i = 0;
101 break;
102
103 case 10ULL ... 99ULL:
104 i = 1;
105 break;
106
107 case 100ULL ... 999ULL:
108 i = 2;
109 break;
110
111 case 1000ULL ... 9999ULL:
112 i = 3;
113 break;
114
115 case 10000ULL ... 99999ULL:
116 i = 4;
117 break;
118
119 case 100000ULL ... 999999ULL:
120 i = 5;
121 break;
122
123 case 1000000ULL ... 9999999ULL:
124 i = 6;
125 break;
126
127 case 10000000ULL ... 99999999ULL:
128 i = 7;
129 break;
130
131 case 100000000ULL ... 999999999ULL:
132 i = 8;
133 break;
134
135 case 1000000000ULL ... 9999999999ULL:
136 i = 9;
137 break;
138
139 case 10000000000ULL ... 99999999999ULL:
140 i = 10;
141 break;
142
143 case 100000000000ULL ... 999999999999ULL:
144 i = 11;
145 break;
146
147 case 1000000000000ULL ... 9999999999999ULL:
148 i = 12;
149 break;
150
151 case 10000000000000ULL ... 99999999999999ULL:
152 i = 13;
153 break;
154
155 case 100000000000000ULL ... 999999999999999ULL:
156 i = 14;
157 break;
158
159 case 1000000000000000ULL ... 9999999999999999ULL:
160 i = 15;
161 break;
162
163 case 10000000000000000ULL ... 99999999999999999ULL:
164 i = 16;
165 break;
166
167 case 100000000000000000ULL ... 999999999999999999ULL:
168 i = 17;
169 break;
170
171 case 1000000000000000000ULL ... 9999999999999999999ULL:
172 i = 18;
173 break;
174
175 case 10000000000000000000ULL ... ULLONG_MAX:
176 i = 19;
177 break;
178 }
179 if (i + 2 > size) // (i + 1) + '\0'
180 return NULL; // too long
181 res = dst + i + 1;
182 *res = '\0';
183 for (; i >= 0; i--) {
184 dst[i] = n % 10ULL + '0';
185 n /= 10ULL;
186 }
187 return res;
188}
189
190/*
191 * unsigned long ASCII representation
192 *
193 * return the last char '\0' or NULL if no enough
194 * space in dst
195 */
196char *ultoa_o(unsigned long n, char *dst, size_t size)
197{
198 int i = 0;
199 char *res;
200
201 switch (n) {
202 case 0U ... 9UL:
203 i = 0;
204 break;
205
206 case 10U ... 99UL:
207 i = 1;
208 break;
209
210 case 100U ... 999UL:
211 i = 2;
212 break;
213
214 case 1000U ... 9999UL:
215 i = 3;
216 break;
217
218 case 10000U ... 99999UL:
219 i = 4;
220 break;
221
222 case 100000U ... 999999UL:
223 i = 5;
224 break;
225
226 case 1000000U ... 9999999UL:
227 i = 6;
228 break;
229
230 case 10000000U ... 99999999UL:
231 i = 7;
232 break;
233
234 case 100000000U ... 999999999UL:
235 i = 8;
236 break;
237#if __WORDSIZE == 32
238
239 case 1000000000ULL ... ULONG_MAX:
240 i = 9;
241 break;
242
243#elif __WORDSIZE == 64
244
245 case 1000000000ULL ... 9999999999UL:
246 i = 9;
247 break;
248
249 case 10000000000ULL ... 99999999999UL:
250 i = 10;
251 break;
252
253 case 100000000000ULL ... 999999999999UL:
254 i = 11;
255 break;
256
257 case 1000000000000ULL ... 9999999999999UL:
258 i = 12;
259 break;
260
261 case 10000000000000ULL ... 99999999999999UL:
262 i = 13;
263 break;
264
265 case 100000000000000ULL ... 999999999999999UL:
266 i = 14;
267 break;
268
269 case 1000000000000000ULL ... 9999999999999999UL:
270 i = 15;
271 break;
272
273 case 10000000000000000ULL ... 99999999999999999UL:
274 i = 16;
275 break;
276
277 case 100000000000000000ULL ... 999999999999999999UL:
278 i = 17;
279 break;
280
281 case 1000000000000000000ULL ... 9999999999999999999UL:
282 i = 18;
283 break;
284
285 case 10000000000000000000ULL ... ULONG_MAX:
286 i = 19;
287 break;
288
289#endif
290 }
291 if (i + 2 > size) // (i + 1) + '\0'
292 return NULL; // too long
293 res = dst + i + 1;
294 *res = '\0';
295 for (; i >= 0; i--) {
296 dst[i] = n % 10U + '0';
297 n /= 10U;
298 }
299 return res;
300}
301
302/*
303 * signed long ASCII representation
304 *
305 * return the last char '\0' or NULL if no enough
306 * space in dst
307 */
308char *ltoa_o(long int n, char *dst, size_t size)
309{
310 char *pos = dst;
311
312 if (n < 0) {
313 if (size < 3)
314 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
315 *pos = '-';
316 pos++;
317 dst = ultoa_o(-n, pos, size - 1);
318 } else {
319 dst = ultoa_o(n, dst, size);
320 }
321 return dst;
322}
323
324/*
325 * signed long long ASCII representation
326 *
327 * return the last char '\0' or NULL if no enough
328 * space in dst
329 */
330char *lltoa(long long n, char *dst, size_t size)
331{
332 char *pos = dst;
333
334 if (n < 0) {
335 if (size < 3)
336 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
337 *pos = '-';
338 pos++;
339 dst = ulltoa(-n, pos, size - 1);
340 } else {
341 dst = ulltoa(n, dst, size);
342 }
343 return dst;
344}
345
346/*
347 * write a ascii representation of a unsigned into dst,
348 * return a pointer to the last character
349 * Pad the ascii representation with '0', using size.
350 */
351char *utoa_pad(unsigned int n, char *dst, size_t size)
352{
353 int i = 0;
354 char *ret;
355
356 switch(n) {
357 case 0U ... 9U:
358 i = 0;
359 break;
360
361 case 10U ... 99U:
362 i = 1;
363 break;
364
365 case 100U ... 999U:
366 i = 2;
367 break;
368
369 case 1000U ... 9999U:
370 i = 3;
371 break;
372
373 case 10000U ... 99999U:
374 i = 4;
375 break;
376
377 case 100000U ... 999999U:
378 i = 5;
379 break;
380
381 case 1000000U ... 9999999U:
382 i = 6;
383 break;
384
385 case 10000000U ... 99999999U:
386 i = 7;
387 break;
388
389 case 100000000U ... 999999999U:
390 i = 8;
391 break;
392
393 case 1000000000U ... 4294967295U:
394 i = 9;
395 break;
396 }
397 if (i + 2 > size) // (i + 1) + '\0'
398 return NULL; // too long
399 if (i < size)
400 i = size - 2; // padding - '\0'
401
402 ret = dst + i + 1;
403 *ret = '\0';
404 for (; i >= 0; i--) {
405 dst[i] = n % 10U + '0';
406 n /= 10U;
407 }
408 return ret;
409}
410
411/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200412 * copies at most <size-1> chars from <src> to <dst>. Last char is always
413 * set to 0, unless <size> is 0. The number of chars copied is returned
414 * (excluding the terminating zero).
415 * This code has been optimized for size and speed : on x86, it's 45 bytes
416 * long, uses only registers, and consumes only 4 cycles per char.
417 */
418int strlcpy2(char *dst, const char *src, int size)
419{
420 char *orig = dst;
421 if (size) {
422 while (--size && (*dst = *src)) {
423 src++; dst++;
424 }
425 *dst = 0;
426 }
427 return dst - orig;
428}
429
430/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200431 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200432 * the ascii representation for number 'n' in decimal.
433 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100434char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200435{
436 char *pos;
437
Willy Tarreau72d759c2007-10-25 12:14:10 +0200438 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200439 *pos-- = '\0';
440
441 do {
442 *pos-- = '0' + n % 10;
443 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200444 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200445 return pos + 1;
446}
447
Willy Tarreau91092e52007-10-25 16:58:42 +0200448/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200449 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200450 * the ascii representation for number 'n' in decimal.
451 */
452char *lltoa_r(long long int in, char *buffer, int size)
453{
454 char *pos;
455 int neg = 0;
456 unsigned long long int n;
457
458 pos = buffer + size - 1;
459 *pos-- = '\0';
460
461 if (in < 0) {
462 neg = 1;
463 n = -in;
464 }
465 else
466 n = in;
467
468 do {
469 *pos-- = '0' + n % 10;
470 n /= 10;
471 } while (n && pos >= buffer);
472 if (neg && pos > buffer)
473 *pos-- = '-';
474 return pos + 1;
475}
476
477/*
478 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200479 * the ascii representation for signed number 'n' in decimal.
480 */
481char *sltoa_r(long n, char *buffer, int size)
482{
483 char *pos;
484
485 if (n >= 0)
486 return ultoa_r(n, buffer, size);
487
488 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
489 *pos = '-';
490 return pos;
491}
492
493/*
494 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200495 * the ascii representation for number 'n' in decimal, formatted for
496 * HTML output with tags to create visual grouping by 3 digits. The
497 * output needs to support at least 171 characters.
498 */
499const char *ulltoh_r(unsigned long long n, char *buffer, int size)
500{
501 char *start;
502 int digit = 0;
503
504 start = buffer + size;
505 *--start = '\0';
506
507 do {
508 if (digit == 3 && start >= buffer + 7)
509 memcpy(start -= 7, "</span>", 7);
510
511 if (start >= buffer + 1) {
512 *--start = '0' + n % 10;
513 n /= 10;
514 }
515
516 if (digit == 3 && start >= buffer + 18)
517 memcpy(start -= 18, "<span class=\"rls\">", 18);
518
519 if (digit++ == 3)
520 digit = 1;
521 } while (n && start > buffer);
522 return start;
523}
524
525/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200526 * This function simply returns a locally allocated string containing the ascii
527 * representation for number 'n' in decimal, unless n is 0 in which case it
528 * returns the alternate string (or an empty string if the alternate string is
529 * NULL). It use is intended for limits reported in reports, where it's
530 * desirable not to display anything if there is no limit. Warning! it shares
531 * the same vector as ultoa_r().
532 */
533const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
534{
535 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
536}
537
Willy Tarreau56d1d8d2021-05-08 10:28:53 +0200538/* Trims the first "%f" float in a string to its minimum number of digits after
539 * the decimal point by trimming trailing zeroes, even dropping the decimal
540 * point if not needed. The string is in <buffer> of length <len>, and the
541 * number is expected to start at or after position <num_start> (the first
542 * point appearing there is considered). A NUL character is always placed at
543 * the end if some trimming occurs. The new buffer length is returned.
544 */
545size_t flt_trim(char *buffer, size_t num_start, size_t len)
546{
547 char *end = buffer + len;
548 char *p = buffer + num_start;
549 char *trim;
550
551 do {
552 if (p >= end)
553 return len;
554 trim = p++;
555 } while (*trim != '.');
556
557 /* For now <trim> is on the decimal point. Let's look for any other
558 * meaningful digit after it.
559 */
560 while (p < end) {
561 if (*p++ != '0')
562 trim = p;
563 }
564
565 if (trim < end)
566 *trim = 0;
567
568 return trim - buffer;
569}
570
Willy Tarreau588297f2014-06-16 15:16:40 +0200571/* returns a locally allocated string containing the quoted encoding of the
572 * input string. The output may be truncated to QSTR_SIZE chars, but it is
573 * guaranteed that the string will always be properly terminated. Quotes are
574 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
575 * always be at least 4 chars.
576 */
577const char *qstr(const char *str)
578{
579 char *ret = quoted_str[quoted_idx];
580 char *p, *end;
581
582 if (++quoted_idx >= NB_QSTR)
583 quoted_idx = 0;
584
585 p = ret;
586 end = ret + QSTR_SIZE;
587
588 *p++ = '"';
589
590 /* always keep 3 chars to support passing "" and the ending " */
591 while (*str && p < end - 3) {
592 if (*str == '"') {
593 *p++ = '"';
594 *p++ = '"';
595 }
596 else
597 *p++ = *str;
598 str++;
599 }
600 *p++ = '"';
601 return ret;
602}
603
Robert Tsai81ae1952007-12-05 10:47:29 +0100604/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200605 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
606 *
607 * It looks like this one would be a good candidate for inlining, but this is
608 * not interesting because it around 35 bytes long and often called multiple
609 * times within the same function.
610 */
611int ishex(char s)
612{
613 s -= '0';
614 if ((unsigned char)s <= 9)
615 return 1;
616 s -= 'A' - '0';
617 if ((unsigned char)s <= 5)
618 return 1;
619 s -= 'a' - 'A';
620 if ((unsigned char)s <= 5)
621 return 1;
622 return 0;
623}
624
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100625/* rounds <i> down to the closest value having max 2 digits */
626unsigned int round_2dig(unsigned int i)
627{
628 unsigned int mul = 1;
629
630 while (i >= 100) {
631 i /= 10;
632 mul *= 10;
633 }
634 return i * mul;
635}
636
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100637/*
638 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
639 * invalid character is found, a pointer to it is returned. If everything is
640 * fine, NULL is returned.
641 */
642const char *invalid_char(const char *name)
643{
644 if (!*name)
645 return name;
646
647 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100648 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100649 *name != '_' && *name != '-')
650 return name;
651 name++;
652 }
653 return NULL;
654}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200655
656/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200657 * Checks <name> for invalid characters. Valid chars are [_.-] and those
658 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200659 * If an invalid character is found, a pointer to it is returned.
660 * If everything is fine, NULL is returned.
661 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200662static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200663
664 if (!*name)
665 return name;
666
667 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100668 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200669 *name != '_' && *name != '-')
670 return name;
671
672 name++;
673 }
674
675 return NULL;
676}
677
678/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200679 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
680 * If an invalid character is found, a pointer to it is returned.
681 * If everything is fine, NULL is returned.
682 */
683const char *invalid_domainchar(const char *name) {
684 return __invalid_char(name, isalnum);
685}
686
687/*
688 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
689 * If an invalid character is found, a pointer to it is returned.
690 * If everything is fine, NULL is returned.
691 */
692const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200693 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200694}
695
696/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100697 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100698 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
699 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
700 * the function tries to guess the address family from the syntax. If the
701 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100702 * string is assumed to contain only an address, no port. The address can be a
703 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
704 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
705 * The return address will only have the address family and the address set,
706 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100707 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
708 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100709 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200710 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100711struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200712{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100713 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100714 /* max IPv6 length, including brackets and terminating NULL */
715 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100716 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100717
718 /* check IPv6 with square brackets */
719 if (str[0] == '[') {
720 size_t iplength = strlen(str);
721
722 if (iplength < 4) {
723 /* minimal size is 4 when using brackets "[::]" */
724 goto fail;
725 }
726 else if (iplength >= sizeof(tmpip)) {
727 /* IPv6 literal can not be larger than tmpip */
728 goto fail;
729 }
730 else {
731 if (str[iplength - 1] != ']') {
732 /* if address started with bracket, it should end with bracket */
733 goto fail;
734 }
735 else {
736 memcpy(tmpip, str + 1, iplength - 2);
737 tmpip[iplength - 2] = '\0';
738 str = tmpip;
739 }
740 }
741 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100742
Willy Tarreaufab5a432011-03-04 15:31:53 +0100743 /* Any IPv6 address */
744 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100745 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
746 sa->ss_family = AF_INET6;
747 else if (sa->ss_family != AF_INET6)
748 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100749 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100750 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100751 }
752
Willy Tarreau24709282013-03-10 21:32:12 +0100753 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100754 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100755 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
756 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100757 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100758 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100759 }
760
761 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100762 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
763 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100764 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100765 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100766 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100767 }
768
769 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100770 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
771 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100772 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100773 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100774 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100775 }
776
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100777 if (!resolve)
778 return NULL;
779
Emeric Brund30e9a12020-12-23 18:49:16 +0100780 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200781 return NULL;
782
David du Colombierd5f43282011-03-17 10:40:16 +0100783#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200784 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100785 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100786 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100787
788 memset(&result, 0, sizeof(result));
789 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100790 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100791 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200792 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100793 hints.ai_protocol = 0;
794
795 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100796 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
797 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100798 else if (sa->ss_family != result->ai_family) {
799 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100800 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100801 }
Willy Tarreau24709282013-03-10 21:32:12 +0100802
David du Colombierd5f43282011-03-17 10:40:16 +0100803 switch (result->ai_family) {
804 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100805 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100806 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100807 success = 1;
808 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100809 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100810 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100811 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100812 success = 1;
813 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100814 }
815 }
816
Sean Carey58ea0392013-02-15 23:39:18 +0100817 if (result)
818 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100819
820 if (success)
821 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100822 }
David du Colombierd5f43282011-03-17 10:40:16 +0100823#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200824 /* try to resolve an IPv4/IPv6 hostname */
825 he = gethostbyname(str);
826 if (he) {
827 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
828 sa->ss_family = he->h_addrtype;
829 else if (sa->ss_family != he->h_addrtype)
830 goto fail;
831
832 switch (sa->ss_family) {
833 case AF_INET:
834 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100835 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200836 return sa;
837 case AF_INET6:
838 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100839 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200840 return sa;
841 }
842 }
843
David du Colombierd5f43282011-03-17 10:40:16 +0100844 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100845 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100846 return NULL;
847}
848
849/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100850 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
851 * range or offset consisting in two integers that the caller will have to
852 * check to find the relevant input format. The following format are supported :
853 *
854 * String format | address | port | low | high
855 * addr | <addr> | 0 | 0 | 0
856 * addr: | <addr> | 0 | 0 | 0
857 * addr:port | <addr> | <port> | <port> | <port>
858 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
859 * addr:+port | <addr> | <port> | 0 | <port>
860 * addr:-port | <addr> |-<port> | <port> | 0
861 *
862 * The detection of a port range or increment by the caller is made by
863 * comparing <low> and <high>. If both are equal, then port 0 means no port
864 * was specified. The caller may pass NULL for <low> and <high> if it is not
865 * interested in retrieving port ranges.
866 *
867 * Note that <addr> above may also be :
868 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
869 * - "*" => family will be AF_INET and address will be INADDR_ANY
870 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
871 * - a host name => family and address will depend on host name resolving.
872 *
Willy Tarreau24709282013-03-10 21:32:12 +0100873 * A prefix may be passed in before the address above to force the family :
874 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
875 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
876 * - "unix@" => force address to be a path to a UNIX socket even if the
877 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200878 * - 'abns@' -> force address to belong to the abstract namespace (Linux
879 * only). These sockets are just like Unix sockets but without
880 * the need for an underlying file system. The address is a
881 * string. Technically it's like a Unix socket with a zero in
882 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100883 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100884 *
mildisff5d5102015-10-26 18:50:08 +0100885 * IPv6 addresses can be declared with or without square brackets. When using
886 * square brackets for IPv6 addresses, the port separator (colon) is optional.
887 * If not using square brackets, and in order to avoid any ambiguity with
888 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
889 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
890 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100891 *
892 * If <pfx> is non-null, it is used as a string prefix before any path-based
893 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100894 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200895 * if <fqdn> is non-null, it will be filled with :
896 * - a pointer to the FQDN of the server name to resolve if there's one, and
897 * that the caller will have to free(),
898 * - NULL if there was an explicit address that doesn't require resolution.
899 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200900 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
901 * still honored so it is possible for the caller to know whether a resolution
902 * failed by clearing this flag and checking if <fqdn> was filled, indicating
903 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200904 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100905 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200906 * the address when cast to sockaddr_in and the address family is
907 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200908 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200909 * The matching protocol will be set into <proto> if non-null.
910 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200911 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
912 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100913 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200914struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
915 struct protocol **proto, char **err,
916 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100917{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100918 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100919 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200920 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100921 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100922 char *port1, *port2;
923 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200924 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200925 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200926 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100927
928 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200929 if (fqdn)
930 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200931
Willy Tarreaudad36a32013-03-11 01:20:04 +0100932 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100933 if (str2 == NULL) {
934 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100935 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100936 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200937
Willy Tarreau9f69f462015-09-08 16:01:25 +0200938 if (!*str2) {
939 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
940 goto out;
941 }
942
Willy Tarreau24709282013-03-10 21:32:12 +0100943 memset(&ss, 0, sizeof(ss));
944
Willy Tarreaue835bd82020-09-16 11:35:47 +0200945 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100946 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
947 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM)))
Willy Tarreaue835bd82020-09-16 11:35:47 +0200948 sock_type = ctrl_type = SOCK_DGRAM;
949 else
950 sock_type = ctrl_type = SOCK_STREAM;
951
952 if (strncmp(str2, "stream+", 7) == 0) {
953 str2 += 7;
954 sock_type = ctrl_type = SOCK_STREAM;
955 }
956 else if (strncmp(str2, "dgram+", 6) == 0) {
957 str2 += 6;
958 sock_type = ctrl_type = SOCK_DGRAM;
959 }
960
Willy Tarreau24709282013-03-10 21:32:12 +0100961 if (strncmp(str2, "unix@", 5) == 0) {
962 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200963 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100964 ss.ss_family = AF_UNIX;
965 }
Emeric Brunce325c42021-04-02 17:05:09 +0200966 else if (strncmp(str2, "uxdg@", 5) == 0) {
967 str2 += 5;
968 abstract = 0;
969 ss.ss_family = AF_UNIX;
970 sock_type = ctrl_type = SOCK_DGRAM;
971 }
972 else if (strncmp(str2, "uxst@", 5) == 0) {
973 str2 += 5;
974 abstract = 0;
975 ss.ss_family = AF_UNIX;
976 sock_type = ctrl_type = SOCK_STREAM;
977 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200978 else if (strncmp(str2, "abns@", 5) == 0) {
979 str2 += 5;
980 abstract = 1;
981 ss.ss_family = AF_UNIX;
982 }
Emeric Brunce325c42021-04-02 17:05:09 +0200983 else if (strncmp(str2, "ip@", 3) == 0) {
984 str2 += 3;
985 ss.ss_family = AF_UNSPEC;
986 }
Willy Tarreau24709282013-03-10 21:32:12 +0100987 else if (strncmp(str2, "ipv4@", 5) == 0) {
988 str2 += 5;
989 ss.ss_family = AF_INET;
990 }
991 else if (strncmp(str2, "ipv6@", 5) == 0) {
992 str2 += 5;
993 ss.ss_family = AF_INET6;
994 }
Emeric Brunce325c42021-04-02 17:05:09 +0200995 else if (strncmp(str2, "tcp4@", 5) == 0) {
996 str2 += 5;
997 ss.ss_family = AF_INET;
998 sock_type = ctrl_type = SOCK_STREAM;
999 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001000 else if (strncmp(str2, "udp4@", 5) == 0) {
1001 str2 += 5;
1002 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001003 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001004 }
Emeric Brunce325c42021-04-02 17:05:09 +02001005 else if (strncmp(str2, "tcp6@", 5) == 0) {
1006 str2 += 5;
1007 ss.ss_family = AF_INET6;
1008 sock_type = ctrl_type = SOCK_STREAM;
1009 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001010 else if (strncmp(str2, "udp6@", 5) == 0) {
1011 str2 += 5;
1012 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001013 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001014 }
Emeric Brunce325c42021-04-02 17:05:09 +02001015 else if (strncmp(str2, "tcp@", 4) == 0) {
1016 str2 += 4;
1017 ss.ss_family = AF_UNSPEC;
1018 sock_type = ctrl_type = SOCK_STREAM;
1019 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001020 else if (strncmp(str2, "udp@", 4) == 0) {
1021 str2 += 4;
1022 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001023 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001024 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001025 else if (strncmp(str2, "quic4@", 6) == 0) {
1026 str2 += 6;
1027 ss.ss_family = AF_INET;
1028 sock_type = SOCK_DGRAM;
1029 ctrl_type = SOCK_STREAM;
1030 }
1031 else if (strncmp(str2, "quic6@", 6) == 0) {
1032 str2 += 6;
1033 ss.ss_family = AF_INET6;
1034 sock_type = SOCK_DGRAM;
1035 ctrl_type = SOCK_STREAM;
1036 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001037 else if (strncmp(str2, "fd@", 3) == 0) {
1038 str2 += 3;
1039 ss.ss_family = AF_CUST_EXISTING_FD;
1040 }
1041 else if (strncmp(str2, "sockpair@", 9) == 0) {
1042 str2 += 9;
1043 ss.ss_family = AF_CUST_SOCKPAIR;
1044 }
Willy Tarreau24709282013-03-10 21:32:12 +01001045 else if (*str2 == '/') {
1046 ss.ss_family = AF_UNIX;
1047 }
1048 else
1049 ss.ss_family = AF_UNSPEC;
1050
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001051 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001052 struct sockaddr_storage ss2;
1053 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001054 char *endptr;
1055
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001056 new_fd = strtol(str2, &endptr, 10);
1057 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001058 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1059 goto out;
1060 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001061
Willy Tarreaua215be22020-09-16 10:14:16 +02001062 /* just verify that it's a socket */
1063 addr_len = sizeof(ss2);
1064 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1065 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1066 goto out;
1067 }
1068
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001069 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1070 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001071 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001072 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001073 char *endptr;
1074
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001075 new_fd = strtol(str2, &endptr, 10);
1076 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001077 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001078 goto out;
1079 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001080
Willy Tarreau6edc7222020-09-15 17:41:56 +02001081 if (opts & PA_O_SOCKET_FD) {
1082 socklen_t addr_len;
1083 int type;
1084
1085 addr_len = sizeof(ss);
1086 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1087 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1088 goto out;
1089 }
1090
1091 addr_len = sizeof(type);
1092 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001093 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001094 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1095 goto out;
1096 }
1097
1098 porta = portl = porth = get_host_port(&ss);
1099 } else if (opts & PA_O_RAW_FD) {
1100 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1101 ((struct sockaddr_in *)&ss)->sin_port = 0;
1102 } else {
1103 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1104 goto out;
1105 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001106 }
1107 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001108 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001109 int prefix_path_len;
1110 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001111 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001112
1113 /* complete unix socket path name during startup or soft-restart is
1114 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1115 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001116 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001117 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001118 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001119
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001120 adr_len = strlen(str2);
1121 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001122 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1123 goto out;
1124 }
1125
Willy Tarreauccfccef2014-05-10 01:49:15 +02001126 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001127 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001128 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001129 memcpy(un->sun_path, pfx, prefix_path_len);
1130 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001131 }
Willy Tarreau24709282013-03-10 21:32:12 +01001132 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001133 char *end = str2 + strlen(str2);
1134 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001135
mildisff5d5102015-10-26 18:50:08 +01001136 /* search for : or ] whatever comes first */
1137 for (chr = end-1; chr > str2; chr--) {
1138 if (*chr == ']' || *chr == ':')
1139 break;
1140 }
1141
1142 if (*chr == ':') {
1143 /* Found a colon before a closing-bracket, must be a port separator.
1144 * This guarantee backward compatibility.
1145 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001146 if (!(opts & PA_O_PORT_OK)) {
1147 memprintf(err, "port specification not permitted here in '%s'", str);
1148 goto out;
1149 }
mildisff5d5102015-10-26 18:50:08 +01001150 *chr++ = '\0';
1151 port1 = chr;
1152 }
1153 else {
1154 /* Either no colon and no closing-bracket
1155 * or directly ending with a closing-bracket.
1156 * However, no port.
1157 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001158 if (opts & PA_O_PORT_MAND) {
1159 memprintf(err, "missing port specification in '%s'", str);
1160 goto out;
1161 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001162 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001163 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001164
Willy Tarreau90807112020-02-25 08:16:33 +01001165 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001166 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001167 if (port2) {
1168 if (!(opts & PA_O_PORT_RANGE)) {
1169 memprintf(err, "port range not permitted here in '%s'", str);
1170 goto out;
1171 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001172 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001173 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001174 else
1175 port2 = port1;
1176 portl = atoi(port1);
1177 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001178
1179 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1180 memprintf(err, "invalid port '%s'", port1);
1181 goto out;
1182 }
1183
1184 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1185 memprintf(err, "invalid port '%s'", port2);
1186 goto out;
1187 }
1188
1189 if (portl > porth) {
1190 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1191 goto out;
1192 }
1193
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001194 porta = portl;
1195 }
1196 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001197 if (!(opts & PA_O_PORT_OFS)) {
1198 memprintf(err, "port offset not permitted here in '%s'", str);
1199 goto out;
1200 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001201 portl = atoi(port1 + 1);
1202 porta = -portl;
1203 }
1204 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001205 if (!(opts & PA_O_PORT_OFS)) {
1206 memprintf(err, "port offset not permitted here in '%s'", str);
1207 goto out;
1208 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001209 porth = atoi(port1 + 1);
1210 porta = porth;
1211 }
1212 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001213 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001214 goto out;
1215 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001216 else if (opts & PA_O_PORT_MAND) {
1217 memprintf(err, "missing port specification in '%s'", str);
1218 goto out;
1219 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001220
1221 /* first try to parse the IP without resolving. If it fails, it
1222 * tells us we need to keep a copy of the FQDN to resolve later
1223 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001224 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001225 */
1226 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001227 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1228 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001229 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1230 goto out;
1231 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001232
Willy Tarreauceccdd72016-11-02 22:27:10 +01001233 if (fqdn) {
1234 if (str2 != back)
1235 memmove(back, str2, strlen(str2) + 1);
1236 *fqdn = back;
1237 back = NULL;
1238 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001239 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001240 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001241 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001242
Willy Tarreaue835bd82020-09-16 11:35:47 +02001243 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1244 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1245 goto out;
1246 }
1247 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1248 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1249 goto out;
1250 }
1251
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001252 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001253 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001254 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1255 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001256 * in which case the address is not known yet (this is only
1257 * for servers actually).
1258 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001259 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001260 sock_type == SOCK_DGRAM,
1261 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001262
Emeric Brun26754902021-04-07 14:26:44 +02001263 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001264 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1265 goto out;
1266 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001267
1268 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1269 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1270 goto out;
1271 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001272 }
1273
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001274 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001275 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001276 if (port)
1277 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001278 if (low)
1279 *low = portl;
1280 if (high)
1281 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001282 if (fd)
1283 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001284 if (proto)
1285 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001286 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001287 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001288}
1289
Thayne McCombs92149f92020-11-20 01:28:26 -07001290/* converts <addr> and <port> into a string representation of the address and port. This is sort
1291 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1292 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1293 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1294 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1295 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1296 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1297 *
1298 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1299 */
1300char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1301{
1302 char buffer[INET6_ADDRSTRLEN];
1303 char *out = NULL;
1304 const void *ptr;
1305 const char *path;
1306
1307 switch (addr->ss_family) {
1308 case AF_INET:
1309 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1310 break;
1311 case AF_INET6:
1312 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1313 break;
1314 case AF_UNIX:
1315 path = ((struct sockaddr_un *)addr)->sun_path;
1316 if (path[0] == '\0') {
1317 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1318 return memprintf(&out, "abns@%.*s", max_length, path+1);
1319 } else {
1320 return strdup(path);
1321 }
1322 case AF_CUST_SOCKPAIR:
1323 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1324 default:
1325 return NULL;
1326 }
1327 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1328 if (map_ports)
1329 return memprintf(&out, "%s:%+d", buffer, port);
1330 else
1331 return memprintf(&out, "%s:%d", buffer, port);
1332}
1333
1334
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001335/* converts <str> to a struct in_addr containing a network mask. It can be
1336 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001337 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001338 */
1339int str2mask(const char *str, struct in_addr *mask)
1340{
1341 if (strchr(str, '.') != NULL) { /* dotted notation */
1342 if (!inet_pton(AF_INET, str, mask))
1343 return 0;
1344 }
1345 else { /* mask length */
1346 char *err;
1347 unsigned long len = strtol(str, &err, 10);
1348
1349 if (!*str || (err && *err) || (unsigned)len > 32)
1350 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001351
1352 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001353 }
1354 return 1;
1355}
1356
Tim Duesterhus47185172018-01-25 16:24:49 +01001357/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001358 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001359 * if the conversion succeeds otherwise zero.
1360 */
1361int str2mask6(const char *str, struct in6_addr *mask)
1362{
1363 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1364 if (!inet_pton(AF_INET6, str, mask))
1365 return 0;
1366 }
1367 else { /* mask length */
1368 char *err;
1369 unsigned long len = strtol(str, &err, 10);
1370
1371 if (!*str || (err && *err) || (unsigned)len > 128)
1372 return 0;
1373
1374 len2mask6(len, mask);
1375 }
1376 return 1;
1377}
1378
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001379/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1380 * succeeds otherwise zero.
1381 */
1382int cidr2dotted(int cidr, struct in_addr *mask) {
1383
1384 if (cidr < 0 || cidr > 32)
1385 return 0;
1386
1387 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1388 return 1;
1389}
1390
Thierry Fournier70473a52016-02-17 17:12:14 +01001391/* Convert mask from bit length form to in_addr form.
1392 * This function never fails.
1393 */
1394void len2mask4(int len, struct in_addr *addr)
1395{
1396 if (len >= 32) {
1397 addr->s_addr = 0xffffffff;
1398 return;
1399 }
1400 if (len <= 0) {
1401 addr->s_addr = 0x00000000;
1402 return;
1403 }
1404 addr->s_addr = 0xffffffff << (32 - len);
1405 addr->s_addr = htonl(addr->s_addr);
1406}
1407
1408/* Convert mask from bit length form to in6_addr form.
1409 * This function never fails.
1410 */
1411void len2mask6(int len, struct in6_addr *addr)
1412{
1413 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1414 len -= 32;
1415 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1416 len -= 32;
1417 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1418 len -= 32;
1419 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1420}
1421
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001422/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001423 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001424 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001425 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001426 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1427 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001428int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001429{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001430 __label__ out_free, out_err;
1431 char *c, *s;
1432 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001433
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001434 s = strdup(str);
1435 if (!s)
1436 return 0;
1437
Willy Tarreaubaaee002006-06-26 02:48:02 +02001438 memset(mask, 0, sizeof(*mask));
1439 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001440
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001441 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001442 *c++ = '\0';
1443 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001444 if (!str2mask(c, mask))
1445 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001446 }
1447 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001448 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001449 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001450 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001451 struct hostent *he;
1452
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001453 if (!resolve)
1454 goto out_err;
1455
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001456 if ((he = gethostbyname(s)) == NULL) {
1457 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001458 }
1459 else
1460 *addr = *(struct in_addr *) *(he->h_addr_list);
1461 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001462
1463 ret_val = 1;
1464 out_free:
1465 free(s);
1466 return ret_val;
1467 out_err:
1468 ret_val = 0;
1469 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001470}
1471
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001472
1473/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001474 * converts <str> to two struct in6_addr* which must be pre-allocated.
1475 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001476 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001477 * Returns 1 if OK, 0 if error.
1478 */
1479int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1480{
1481 char *c, *s;
1482 int ret_val = 0;
1483 char *err;
1484 unsigned long len = 128;
1485
1486 s = strdup(str);
1487 if (!s)
1488 return 0;
1489
1490 memset(mask, 0, sizeof(*mask));
1491 memset(addr, 0, sizeof(*addr));
1492
1493 if ((c = strrchr(s, '/')) != NULL) {
1494 *c++ = '\0'; /* c points to the mask */
1495 if (!*c)
1496 goto out_free;
1497
1498 len = strtoul(c, &err, 10);
1499 if ((err && *err) || (unsigned)len > 128)
1500 goto out_free;
1501 }
1502 *mask = len; /* OK we have a valid mask in <len> */
1503
1504 if (!inet_pton(AF_INET6, s, addr))
1505 goto out_free;
1506
1507 ret_val = 1;
1508 out_free:
1509 free(s);
1510 return ret_val;
1511}
1512
1513
1514/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001515 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1516 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1517 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001518 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001519int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001520{
1521 int saw_digit, octets, ch;
1522 u_char tmp[4], *tp;
1523 const char *cp = addr;
1524
1525 saw_digit = 0;
1526 octets = 0;
1527 *(tp = tmp) = 0;
1528
1529 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001530 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001531 if (digit > 9 && ch != '.')
1532 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001533 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001534 if (digit <= 9) {
1535 u_int new = *tp * 10 + digit;
1536 if (new > 255)
1537 return 0;
1538 *tp = new;
1539 if (!saw_digit) {
1540 if (++octets > 4)
1541 return 0;
1542 saw_digit = 1;
1543 }
1544 } else if (ch == '.' && saw_digit) {
1545 if (octets == 4)
1546 return 0;
1547 *++tp = 0;
1548 saw_digit = 0;
1549 } else
1550 return 0;
1551 }
1552
1553 if (octets < 4)
1554 return 0;
1555
1556 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001557 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001558}
1559
1560/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001561 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001562 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001563 * the hostname. Actually only http and https are supported. <out> can be NULL.
1564 * This function returns the consumed length. It is useful if you parse complete
1565 * url like http://host:port/path, because the consumed length corresponds to
1566 * the first character of the path. If the conversion fails, it returns -1.
1567 *
1568 * This function tries to resolve the DNS name if haproxy is in starting mode.
1569 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001570 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001571int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001572{
1573 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001574 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001575 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001576 unsigned long long int http_code = 0;
1577 int default_port;
1578 struct hostent *he;
1579 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001580
1581 /* Firstly, try to find :// pattern */
1582 while (curr < url+ulen && url_code != 0x3a2f2f) {
1583 url_code = ((url_code & 0xffff) << 8);
1584 url_code += (unsigned char)*curr++;
1585 }
1586
1587 /* Secondly, if :// pattern is found, verify parsed stuff
1588 * before pattern is matching our http pattern.
1589 * If so parse ip address and port in uri.
1590 *
1591 * WARNING: Current code doesn't support dynamic async dns resolver.
1592 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001593 if (url_code != 0x3a2f2f)
1594 return -1;
1595
1596 /* Copy scheme, and utrn to lower case. */
1597 while (cp < curr - 3)
1598 http_code = (http_code << 8) + *cp++;
1599 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001600
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001601 /* HTTP or HTTPS url matching */
1602 if (http_code == 0x2020202068747470ULL) {
1603 default_port = 80;
1604 if (out)
1605 out->scheme = SCH_HTTP;
1606 }
1607 else if (http_code == 0x2020206874747073ULL) {
1608 default_port = 443;
1609 if (out)
1610 out->scheme = SCH_HTTPS;
1611 }
1612 else
1613 return -1;
1614
1615 /* If the next char is '[', the host address is IPv6. */
1616 if (*curr == '[') {
1617 curr++;
1618
1619 /* Check trash size */
1620 if (trash.size < ulen)
1621 return -1;
1622
1623 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001624 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001625 for (end = curr;
1626 end < url + ulen && *end != ']';
1627 end++, p++)
1628 *p = *end;
1629 if (*end != ']')
1630 return -1;
1631 *p = '\0';
1632
1633 /* Update out. */
1634 if (out) {
1635 out->host = curr;
1636 out->host_len = end - curr;
1637 }
1638
1639 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001640 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001641 return -1;
1642 end++;
1643
1644 /* Decode port. */
1645 if (*end == ':') {
1646 end++;
1647 default_port = read_uint(&end, url + ulen);
1648 }
1649 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1650 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1651 return end - url;
1652 }
1653 else {
1654 /* We are looking for IP address. If you want to parse and
1655 * resolve hostname found in url, you can use str2sa_range(), but
1656 * be warned this can slow down global daemon performances
1657 * while handling lagging dns responses.
1658 */
1659 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1660 if (ret) {
1661 /* Update out. */
1662 if (out) {
1663 out->host = curr;
1664 out->host_len = ret;
1665 }
1666
1667 curr += ret;
1668
1669 /* Decode port. */
1670 if (*curr == ':') {
1671 curr++;
1672 default_port = read_uint(&curr, url + ulen);
1673 }
1674 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1675
1676 /* Set family. */
1677 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1678 return curr - url;
1679 }
1680 else if (global.mode & MODE_STARTING) {
1681 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1682 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001683 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001684
1685 /* look for : or / or end */
1686 for (end = curr;
1687 end < url + ulen && *end != '/' && *end != ':';
1688 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001689 memcpy(trash.area, curr, end - curr);
1690 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001691
1692 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001693 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001694 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001695 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001696
1697 /* Update out. */
1698 if (out) {
1699 out->host = curr;
1700 out->host_len = end - curr;
1701 }
1702
1703 /* Decode port. */
1704 if (*end == ':') {
1705 end++;
1706 default_port = read_uint(&end, url + ulen);
1707 }
1708
1709 /* Copy IP address, set port and family. */
1710 switch (he->h_addrtype) {
1711 case AF_INET:
1712 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1713 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1714 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1715 return end - url;
1716
1717 case AF_INET6:
1718 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1719 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1720 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1721 return end - url;
1722 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001723 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001724 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001725 return -1;
1726}
1727
Willy Tarreau631f01c2011-09-05 00:36:48 +02001728/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1729 * address family is returned so that it's easy for the caller to adapt to the
1730 * output format. Zero is returned if the address family is not supported. -1
1731 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1732 * supported.
1733 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001734int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001735{
1736
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001737 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001738
1739 if (size < 5)
1740 return 0;
1741 *str = '\0';
1742
1743 switch (addr->ss_family) {
1744 case AF_INET:
1745 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1746 break;
1747 case AF_INET6:
1748 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1749 break;
1750 case AF_UNIX:
1751 memcpy(str, "unix", 5);
1752 return addr->ss_family;
1753 default:
1754 return 0;
1755 }
1756
1757 if (inet_ntop(addr->ss_family, ptr, str, size))
1758 return addr->ss_family;
1759
1760 /* failed */
1761 return -1;
1762}
1763
Simon Horman75ab8bd2014-06-16 09:39:41 +09001764/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1765 * address family is returned so that it's easy for the caller to adapt to the
1766 * output format. Zero is returned if the address family is not supported. -1
1767 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1768 * supported.
1769 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001770int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001771{
1772
1773 uint16_t port;
1774
1775
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001776 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001777 return 0;
1778 *str = '\0';
1779
1780 switch (addr->ss_family) {
1781 case AF_INET:
1782 port = ((struct sockaddr_in *)addr)->sin_port;
1783 break;
1784 case AF_INET6:
1785 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1786 break;
1787 case AF_UNIX:
1788 memcpy(str, "unix", 5);
1789 return addr->ss_family;
1790 default:
1791 return 0;
1792 }
1793
1794 snprintf(str, size, "%u", ntohs(port));
1795 return addr->ss_family;
1796}
1797
Willy Tarreau16e01562016-08-09 16:46:18 +02001798/* check if the given address is local to the system or not. It will return
1799 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1800 * it is. We don't want to iterate over all interfaces for this (and it is not
1801 * portable). So instead we try to bind in UDP to this address on a free non
1802 * privileged port and to connect to the same address, port 0 (connect doesn't
1803 * care). If it succeeds, we own the address. Note that non-inet addresses are
1804 * considered local since they're most likely AF_UNIX.
1805 */
1806int addr_is_local(const struct netns_entry *ns,
1807 const struct sockaddr_storage *orig)
1808{
1809 struct sockaddr_storage addr;
1810 int result;
1811 int fd;
1812
1813 if (!is_inet_addr(orig))
1814 return 1;
1815
1816 memcpy(&addr, orig, sizeof(addr));
1817 set_host_port(&addr, 0);
1818
1819 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1820 if (fd < 0)
1821 return -1;
1822
1823 result = -1;
1824 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1825 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1826 result = 0; // fail, non-local address
1827 else
1828 result = 1; // success, local address
1829 }
1830 else {
1831 if (errno == EADDRNOTAVAIL)
1832 result = 0; // definitely not local :-)
1833 }
1834 close(fd);
1835
1836 return result;
1837}
1838
Willy Tarreaubaaee002006-06-26 02:48:02 +02001839/* will try to encode the string <string> replacing all characters tagged in
1840 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1841 * prefixed by <escape>, and will store the result between <start> (included)
1842 * and <stop> (excluded), and will always terminate the string with a '\0'
1843 * before <stop>. The position of the '\0' is returned if the conversion
1844 * completes. If bytes are missing between <start> and <stop>, then the
1845 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1846 * cannot even be stored so we return <start> without writing the 0.
1847 * The input string must also be zero-terminated.
1848 */
1849const char hextab[16] = "0123456789ABCDEF";
1850char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001851 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001852 const char *string)
1853{
1854 if (start < stop) {
1855 stop--; /* reserve one byte for the final '\0' */
1856 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001857 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001858 *start++ = *string;
1859 else {
1860 if (start + 3 >= stop)
1861 break;
1862 *start++ = escape;
1863 *start++ = hextab[(*string >> 4) & 15];
1864 *start++ = hextab[*string & 15];
1865 }
1866 string++;
1867 }
1868 *start = '\0';
1869 }
1870 return start;
1871}
1872
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001873/*
1874 * Same behavior as encode_string() above, except that it encodes chunk
1875 * <chunk> instead of a string.
1876 */
1877char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001878 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001879 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001880{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001881 char *str = chunk->area;
1882 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001883
1884 if (start < stop) {
1885 stop--; /* reserve one byte for the final '\0' */
1886 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001887 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001888 *start++ = *str;
1889 else {
1890 if (start + 3 >= stop)
1891 break;
1892 *start++ = escape;
1893 *start++ = hextab[(*str >> 4) & 15];
1894 *start++ = hextab[*str & 15];
1895 }
1896 str++;
1897 }
1898 *start = '\0';
1899 }
1900 return start;
1901}
1902
Dragan Dosen0edd1092016-02-12 13:23:02 +01001903/*
1904 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001905 * character. The input <string> must be zero-terminated. The result will
1906 * be stored between <start> (included) and <stop> (excluded). This
1907 * function will always try to terminate the resulting string with a '\0'
1908 * before <stop>, and will return its position if the conversion
1909 * completes.
1910 */
1911char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001912 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001913 const char *string)
1914{
1915 if (start < stop) {
1916 stop--; /* reserve one byte for the final '\0' */
1917 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001918 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001919 *start++ = *string;
1920 else {
1921 if (start + 2 >= stop)
1922 break;
1923 *start++ = escape;
1924 *start++ = *string;
1925 }
1926 string++;
1927 }
1928 *start = '\0';
1929 }
1930 return start;
1931}
1932
1933/*
1934 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001935 * character. <chunk> contains the input to be escaped. The result will be
1936 * stored between <start> (included) and <stop> (excluded). The function
1937 * will always try to terminate the resulting string with a '\0' before
1938 * <stop>, and will return its position if the conversion completes.
1939 */
1940char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001941 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001942 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001943{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001944 char *str = chunk->area;
1945 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001946
1947 if (start < stop) {
1948 stop--; /* reserve one byte for the final '\0' */
1949 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001950 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001951 *start++ = *str;
1952 else {
1953 if (start + 2 >= stop)
1954 break;
1955 *start++ = escape;
1956 *start++ = *str;
1957 }
1958 str++;
1959 }
1960 *start = '\0';
1961 }
1962 return start;
1963}
1964
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001965/* Check a string for using it in a CSV output format. If the string contains
1966 * one of the following four char <">, <,>, CR or LF, the string is
1967 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1968 * <str> is the input string to be escaped. The function assumes that
1969 * the input string is null-terminated.
1970 *
1971 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001972 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001973 * format.
1974 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001975 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001976 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001977 * If <quote> is 1, the converter puts the quotes only if any reserved character
1978 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001979 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001980 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001981 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001982 * The function returns the converted string on its output. If an error
1983 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001984 * for using the function directly as printf() argument.
1985 *
1986 * If the output buffer is too short to contain the input string, the result
1987 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001988 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001989 * This function appends the encoding to the existing output chunk, and it
1990 * guarantees that it starts immediately at the first available character of
1991 * the chunk. Please use csv_enc() instead if you want to replace the output
1992 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001993 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001994const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001995{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001996 char *end = output->area + output->size;
1997 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001998 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001999
Willy Tarreaub631c292016-01-08 10:04:08 +01002000 if (quote == 1) {
2001 /* automatic quoting: first verify if we'll have to quote the string */
2002 if (!strpbrk(str, "\n\r,\""))
2003 quote = 0;
2004 }
2005
2006 if (quote)
2007 *ptr++ = '"';
2008
Willy Tarreau898529b2016-01-06 18:07:04 +01002009 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2010 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002011 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002012 ptr++;
2013 if (ptr >= end - 2) {
2014 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002015 break;
2016 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002017 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002018 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002019 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002020 str++;
2021 }
2022
Willy Tarreaub631c292016-01-08 10:04:08 +01002023 if (quote)
2024 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002025
Willy Tarreau898529b2016-01-06 18:07:04 +01002026 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002027 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002028 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002029}
2030
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002031/* Decode an URL-encoded string in-place. The resulting string might
2032 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002033 * aborted, the string is truncated before the issue and a negative value is
2034 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002035 * If the 'in_form' argument is non-nul the string is assumed to be part of
2036 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2037 * turned to a space. If it's zero, this will only be done after a question
2038 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002039 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002040int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002041{
2042 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002043 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002044
2045 in = string;
2046 out = string;
2047 while (*in) {
2048 switch (*in) {
2049 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002050 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002051 break;
2052 case '%' :
2053 if (!ishex(in[1]) || !ishex(in[2]))
2054 goto end;
2055 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2056 in += 2;
2057 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002058 case '?':
2059 in_form = 1;
2060 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002061 default:
2062 *out++ = *in;
2063 break;
2064 }
2065 in++;
2066 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002067 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002068 end:
2069 *out = 0;
2070 return ret;
2071}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002072
Willy Tarreau6911fa42007-03-04 18:06:08 +01002073unsigned int str2ui(const char *s)
2074{
2075 return __str2ui(s);
2076}
2077
2078unsigned int str2uic(const char *s)
2079{
2080 return __str2uic(s);
2081}
2082
2083unsigned int strl2ui(const char *s, int len)
2084{
2085 return __strl2ui(s, len);
2086}
2087
2088unsigned int strl2uic(const char *s, int len)
2089{
2090 return __strl2uic(s, len);
2091}
2092
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002093unsigned int read_uint(const char **s, const char *end)
2094{
2095 return __read_uint(s, end);
2096}
2097
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002098/* This function reads an unsigned integer from the string pointed to by <s> and
2099 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2100 * function automatically stops at <end>. If the number overflows, the 2^64-1
2101 * value is returned.
2102 */
2103unsigned long long int read_uint64(const char **s, const char *end)
2104{
2105 const char *ptr = *s;
2106 unsigned long long int i = 0, tmp;
2107 unsigned int j;
2108
2109 while (ptr < end) {
2110
2111 /* read next char */
2112 j = *ptr - '0';
2113 if (j > 9)
2114 goto read_uint64_end;
2115
2116 /* add char to the number and check overflow. */
2117 tmp = i * 10;
2118 if (tmp / 10 != i) {
2119 i = ULLONG_MAX;
2120 goto read_uint64_eat;
2121 }
2122 if (ULLONG_MAX - tmp < j) {
2123 i = ULLONG_MAX;
2124 goto read_uint64_eat;
2125 }
2126 i = tmp + j;
2127 ptr++;
2128 }
2129read_uint64_eat:
2130 /* eat each numeric char */
2131 while (ptr < end) {
2132 if ((unsigned int)(*ptr - '0') > 9)
2133 break;
2134 ptr++;
2135 }
2136read_uint64_end:
2137 *s = ptr;
2138 return i;
2139}
2140
2141/* This function reads an integer from the string pointed to by <s> and returns
2142 * it. The <s> pointer is adjusted to point to the first unread char. The function
2143 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2144 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2145 * returned.
2146 */
2147long long int read_int64(const char **s, const char *end)
2148{
2149 unsigned long long int i = 0;
2150 int neg = 0;
2151
2152 /* Look for minus char. */
2153 if (**s == '-') {
2154 neg = 1;
2155 (*s)++;
2156 }
2157 else if (**s == '+')
2158 (*s)++;
2159
2160 /* convert as positive number. */
2161 i = read_uint64(s, end);
2162
2163 if (neg) {
2164 if (i > 0x8000000000000000ULL)
2165 return LLONG_MIN;
2166 return -i;
2167 }
2168 if (i > 0x7fffffffffffffffULL)
2169 return LLONG_MAX;
2170 return i;
2171}
2172
Willy Tarreau6911fa42007-03-04 18:06:08 +01002173/* This one is 7 times faster than strtol() on athlon with checks.
2174 * It returns the value of the number composed of all valid digits read,
2175 * and can process negative numbers too.
2176 */
2177int strl2ic(const char *s, int len)
2178{
2179 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002180 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002181
2182 if (len > 0) {
2183 if (*s != '-') {
2184 /* positive number */
2185 while (len-- > 0) {
2186 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002187 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002188 if (j > 9)
2189 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002190 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002191 }
2192 } else {
2193 /* negative number */
2194 s++;
2195 while (--len > 0) {
2196 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002197 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002198 if (j > 9)
2199 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002200 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002201 }
2202 }
2203 }
2204 return i;
2205}
2206
2207
2208/* This function reads exactly <len> chars from <s> and converts them to a
2209 * signed integer which it stores into <ret>. It accurately detects any error
2210 * (truncated string, invalid chars, overflows). It is meant to be used in
2211 * applications designed for hostile environments. It returns zero when the
2212 * number has successfully been converted, non-zero otherwise. When an error
2213 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2214 * faster than strtol().
2215 */
2216int strl2irc(const char *s, int len, int *ret)
2217{
2218 int i = 0;
2219 int j;
2220
2221 if (!len)
2222 return 1;
2223
2224 if (*s != '-') {
2225 /* positive number */
2226 while (len-- > 0) {
2227 j = (*s++) - '0';
2228 if (j > 9) return 1; /* invalid char */
2229 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2230 i = i * 10;
2231 if (i + j < i) return 1; /* check for addition overflow */
2232 i = i + j;
2233 }
2234 } else {
2235 /* negative number */
2236 s++;
2237 while (--len > 0) {
2238 j = (*s++) - '0';
2239 if (j > 9) return 1; /* invalid char */
2240 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2241 i = i * 10;
2242 if (i - j > i) return 1; /* check for subtract overflow */
2243 i = i - j;
2244 }
2245 }
2246 *ret = i;
2247 return 0;
2248}
2249
2250
2251/* This function reads exactly <len> chars from <s> and converts them to a
2252 * signed integer which it stores into <ret>. It accurately detects any error
2253 * (truncated string, invalid chars, overflows). It is meant to be used in
2254 * applications designed for hostile environments. It returns zero when the
2255 * number has successfully been converted, non-zero otherwise. When an error
2256 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002257 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002258 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002259
2260int strl2llrc(const char *s, int len, long long *ret)
2261{
2262 long long i = 0;
2263 int j;
2264
2265 if (!len)
2266 return 1;
2267
2268 if (*s != '-') {
2269 /* positive number */
2270 while (len-- > 0) {
2271 j = (*s++) - '0';
2272 if (j > 9) return 1; /* invalid char */
2273 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2274 i = i * 10LL;
2275 if (i + j < i) return 1; /* check for addition overflow */
2276 i = i + j;
2277 }
2278 } else {
2279 /* negative number */
2280 s++;
2281 while (--len > 0) {
2282 j = (*s++) - '0';
2283 if (j > 9) return 1; /* invalid char */
2284 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2285 i = i * 10LL;
2286 if (i - j > i) return 1; /* check for subtract overflow */
2287 i = i - j;
2288 }
2289 }
2290 *ret = i;
2291 return 0;
2292}
2293
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002294/* This function is used with pat_parse_dotted_ver(). It converts a string
2295 * composed by two number separated by a dot. Each part must contain in 16 bits
2296 * because internally they will be represented as a 32-bit quantity stored in
2297 * a 64-bit integer. It returns zero when the number has successfully been
2298 * converted, non-zero otherwise. When an error is returned, the <ret> value
2299 * is left untouched.
2300 *
2301 * "1.3" -> 0x0000000000010003
2302 * "65535.65535" -> 0x00000000ffffffff
2303 */
2304int strl2llrc_dotted(const char *text, int len, long long *ret)
2305{
2306 const char *end = &text[len];
2307 const char *p;
2308 long long major, minor;
2309
2310 /* Look for dot. */
2311 for (p = text; p < end; p++)
2312 if (*p == '.')
2313 break;
2314
2315 /* Convert major. */
2316 if (strl2llrc(text, p - text, &major) != 0)
2317 return 1;
2318
2319 /* Check major. */
2320 if (major >= 65536)
2321 return 1;
2322
2323 /* Convert minor. */
2324 minor = 0;
2325 if (p < end)
2326 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2327 return 1;
2328
2329 /* Check minor. */
2330 if (minor >= 65536)
2331 return 1;
2332
2333 /* Compose value. */
2334 *ret = (major << 16) | (minor & 0xffff);
2335 return 0;
2336}
2337
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002338/* This function parses a time value optionally followed by a unit suffix among
2339 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2340 * expected by the caller. The computation does its best to avoid overflows.
2341 * The value is returned in <ret> if everything is fine, and a NULL is returned
2342 * by the function. In case of error, a pointer to the error is returned and
2343 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002344 * Values resulting in values larger than or equal to 2^31 after conversion are
2345 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2346 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002347 */
2348const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2349{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002350 unsigned long long imult, idiv;
2351 unsigned long long omult, odiv;
2352 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002353 const char *str = text;
2354
2355 if (!isdigit((unsigned char)*text))
2356 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002357
2358 omult = odiv = 1;
2359
2360 switch (unit_flags & TIME_UNIT_MASK) {
2361 case TIME_UNIT_US: omult = 1000000; break;
2362 case TIME_UNIT_MS: omult = 1000; break;
2363 case TIME_UNIT_S: break;
2364 case TIME_UNIT_MIN: odiv = 60; break;
2365 case TIME_UNIT_HOUR: odiv = 3600; break;
2366 case TIME_UNIT_DAY: odiv = 86400; break;
2367 default: break;
2368 }
2369
2370 value = 0;
2371
2372 while (1) {
2373 unsigned int j;
2374
2375 j = *text - '0';
2376 if (j > 9)
2377 break;
2378 text++;
2379 value *= 10;
2380 value += j;
2381 }
2382
2383 imult = idiv = 1;
2384 switch (*text) {
2385 case '\0': /* no unit = default unit */
2386 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002387 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002388 case 's': /* second = unscaled unit */
2389 break;
2390 case 'u': /* microsecond : "us" */
2391 if (text[1] == 's') {
2392 idiv = 1000000;
2393 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002394 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002395 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002396 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002397 case 'm': /* millisecond : "ms" or minute: "m" */
2398 if (text[1] == 's') {
2399 idiv = 1000;
2400 text++;
2401 } else
2402 imult = 60;
2403 break;
2404 case 'h': /* hour : "h" */
2405 imult = 3600;
2406 break;
2407 case 'd': /* day : "d" */
2408 imult = 86400;
2409 break;
2410 default:
2411 return text;
2412 break;
2413 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002414 if (*(++text) != '\0') {
2415 ha_warning("unexpected character '%c' after the timer value '%s', only "
2416 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2417 " This will be reported as an error in next versions.\n", *text, str);
2418 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002419
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002420 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002421 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2422 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2423 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2424 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2425
Willy Tarreau9faebe32019-06-07 19:00:37 +02002426 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2427 if (result >= 0x80000000)
2428 return PARSE_TIME_OVER;
2429 if (!result && value)
2430 return PARSE_TIME_UNDER;
2431 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002432 return NULL;
2433}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002434
Emeric Brun39132b22010-01-04 14:57:24 +01002435/* this function converts the string starting at <text> to an unsigned int
2436 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002437 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002438 */
2439const char *parse_size_err(const char *text, unsigned *ret) {
2440 unsigned value = 0;
2441
Christopher Faulet82635a02020-12-11 09:30:45 +01002442 if (!isdigit((unsigned char)*text))
2443 return text;
2444
Emeric Brun39132b22010-01-04 14:57:24 +01002445 while (1) {
2446 unsigned int j;
2447
2448 j = *text - '0';
2449 if (j > 9)
2450 break;
2451 if (value > ~0U / 10)
2452 return text;
2453 value *= 10;
2454 if (value > (value + j))
2455 return text;
2456 value += j;
2457 text++;
2458 }
2459
2460 switch (*text) {
2461 case '\0':
2462 break;
2463 case 'K':
2464 case 'k':
2465 if (value > ~0U >> 10)
2466 return text;
2467 value = value << 10;
2468 break;
2469 case 'M':
2470 case 'm':
2471 if (value > ~0U >> 20)
2472 return text;
2473 value = value << 20;
2474 break;
2475 case 'G':
2476 case 'g':
2477 if (value > ~0U >> 30)
2478 return text;
2479 value = value << 30;
2480 break;
2481 default:
2482 return text;
2483 }
2484
Godbach58048a22015-01-28 17:36:16 +08002485 if (*text != '\0' && *++text != '\0')
2486 return text;
2487
Emeric Brun39132b22010-01-04 14:57:24 +01002488 *ret = value;
2489 return NULL;
2490}
2491
Willy Tarreau126d4062013-12-03 17:50:47 +01002492/*
2493 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002494 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002495 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002496 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002497 */
2498int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2499{
2500 int len;
2501 const char *p = source;
2502 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002503 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002504
2505 len = strlen(source);
2506 if (len % 2) {
2507 memprintf(err, "an even number of hex digit is expected");
2508 return 0;
2509 }
2510
2511 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002512
Willy Tarreau126d4062013-12-03 17:50:47 +01002513 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002514 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002515 if (!*binstr) {
2516 memprintf(err, "out of memory while loading string pattern");
2517 return 0;
2518 }
2519 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002520 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002521 else {
2522 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002523 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002524 len, *binstrlen);
2525 return 0;
2526 }
2527 alloc = 0;
2528 }
2529 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002530
2531 i = j = 0;
2532 while (j < len) {
2533 if (!ishex(p[i++]))
2534 goto bad_input;
2535 if (!ishex(p[i++]))
2536 goto bad_input;
2537 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2538 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002539 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002540
2541bad_input:
2542 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002543 if (alloc)
2544 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002545 return 0;
2546}
2547
Willy Tarreau946ba592009-05-10 15:41:18 +02002548/* copies at most <n> characters from <src> and always terminates with '\0' */
2549char *my_strndup(const char *src, int n)
2550{
2551 int len = 0;
2552 char *ret;
2553
2554 while (len < n && src[len])
2555 len++;
2556
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002557 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002558 if (!ret)
2559 return ret;
2560 memcpy(ret, src, len);
2561 ret[len] = '\0';
2562 return ret;
2563}
2564
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002565/*
2566 * search needle in haystack
2567 * returns the pointer if found, returns NULL otherwise
2568 */
2569const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2570{
2571 const void *c = NULL;
2572 unsigned char f;
2573
2574 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2575 return NULL;
2576
2577 f = *(char *)needle;
2578 c = haystack;
2579 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2580 if ((haystacklen - (c - haystack)) < needlelen)
2581 return NULL;
2582
2583 if (memcmp(c, needle, needlelen) == 0)
2584 return c;
2585 ++c;
2586 }
2587 return NULL;
2588}
2589
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002590/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002591size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2592{
2593 size_t ret = 0;
2594
2595 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2596 str++;
2597 ret++;
2598 }
2599 return ret;
2600}
2601
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002602/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002603size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2604{
2605 size_t ret = 0;
2606
2607 while (ret < len) {
2608 if(memchr(reject, *((int *)str), rejectlen))
2609 return ret;
2610 str++;
2611 ret++;
2612 }
2613 return ret;
2614}
2615
Willy Tarreau482b00d2009-10-04 22:48:42 +02002616/* This function returns the first unused key greater than or equal to <key> in
2617 * ID tree <root>. Zero is returned if no place is found.
2618 */
2619unsigned int get_next_id(struct eb_root *root, unsigned int key)
2620{
2621 struct eb32_node *used;
2622
2623 do {
2624 used = eb32_lookup_ge(root, key);
2625 if (!used || used->key > key)
2626 return key; /* key is available */
2627 key++;
2628 } while (key);
2629 return key;
2630}
2631
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002632/* dump the full tree to <file> in DOT format for debugging purposes. Will
2633 * optionally highlight node <subj> if found, depending on operation <op> :
2634 * 0 : nothing
2635 * >0 : insertion, node/leaf are surrounded in red
2636 * <0 : removal, node/leaf are dashed with no background
2637 * Will optionally add "desc" as a label on the graph if set and non-null.
2638 */
2639void 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 +01002640{
2641 struct eb32sc_node *node;
2642 unsigned long scope = -1;
2643
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002644 fprintf(file, "digraph ebtree {\n");
2645
2646 if (desc && *desc) {
2647 fprintf(file,
2648 " fontname=\"fixed\";\n"
2649 " fontsize=8;\n"
2650 " label=\"%s\";\n", desc);
2651 }
2652
Willy Tarreaued3cda02017-11-15 15:04:05 +01002653 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002654 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2655 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002656 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2657 );
2658
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002659 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002660 (long)eb_root_to_node(root),
2661 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002662 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2663
2664 node = eb32sc_first(root, scope);
2665 while (node) {
2666 if (node->node.node_p) {
2667 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002668 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2669 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2670 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002671
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002672 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002673 (long)node,
2674 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002675 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002676
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002677 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002678 (long)node,
2679 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002680 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2681
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002682 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002683 (long)node,
2684 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002685 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2686 }
2687
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002688 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2689 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2690 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002691
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002692 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002693 (long)node,
2694 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002695 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002696 node = eb32sc_next(node, scope);
2697 }
2698 fprintf(file, "}\n");
2699}
2700
Willy Tarreau348238b2010-01-18 15:05:57 +01002701/* This function compares a sample word possibly followed by blanks to another
2702 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2703 * otherwise zero. This intends to be used when checking HTTP headers for some
2704 * values. Note that it validates a word followed only by blanks but does not
2705 * validate a word followed by blanks then other chars.
2706 */
2707int word_match(const char *sample, int slen, const char *word, int wlen)
2708{
2709 if (slen < wlen)
2710 return 0;
2711
2712 while (wlen) {
2713 char c = *sample ^ *word;
2714 if (c && c != ('A' ^ 'a'))
2715 return 0;
2716 sample++;
2717 word++;
2718 slen--;
2719 wlen--;
2720 }
2721
2722 while (slen) {
2723 if (*sample != ' ' && *sample != '\t')
2724 return 0;
2725 sample++;
2726 slen--;
2727 }
2728 return 1;
2729}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002730
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002731/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2732 * is particularly fast because it avoids expensive operations such as
2733 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002734 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002735 */
2736unsigned int inetaddr_host(const char *text)
2737{
2738 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2739 register unsigned int dig100, dig10, dig1;
2740 int s;
2741 const char *p, *d;
2742
2743 dig1 = dig10 = dig100 = ascii_zero;
2744 s = 24;
2745
2746 p = text;
2747 while (1) {
2748 if (((unsigned)(*p - '0')) <= 9) {
2749 p++;
2750 continue;
2751 }
2752
2753 /* here, we have a complete byte between <text> and <p> (exclusive) */
2754 if (p == text)
2755 goto end;
2756
2757 d = p - 1;
2758 dig1 |= (unsigned int)(*d << s);
2759 if (d == text)
2760 goto end;
2761
2762 d--;
2763 dig10 |= (unsigned int)(*d << s);
2764 if (d == text)
2765 goto end;
2766
2767 d--;
2768 dig100 |= (unsigned int)(*d << s);
2769 end:
2770 if (!s || *p != '.')
2771 break;
2772
2773 s -= 8;
2774 text = ++p;
2775 }
2776
2777 dig100 -= ascii_zero;
2778 dig10 -= ascii_zero;
2779 dig1 -= ascii_zero;
2780 return ((dig100 * 10) + dig10) * 10 + dig1;
2781}
2782
2783/*
2784 * Idem except the first unparsed character has to be passed in <stop>.
2785 */
2786unsigned int inetaddr_host_lim(const char *text, const char *stop)
2787{
2788 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2789 register unsigned int dig100, dig10, dig1;
2790 int s;
2791 const char *p, *d;
2792
2793 dig1 = dig10 = dig100 = ascii_zero;
2794 s = 24;
2795
2796 p = text;
2797 while (1) {
2798 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2799 p++;
2800 continue;
2801 }
2802
2803 /* here, we have a complete byte between <text> and <p> (exclusive) */
2804 if (p == text)
2805 goto end;
2806
2807 d = p - 1;
2808 dig1 |= (unsigned int)(*d << s);
2809 if (d == text)
2810 goto end;
2811
2812 d--;
2813 dig10 |= (unsigned int)(*d << s);
2814 if (d == text)
2815 goto end;
2816
2817 d--;
2818 dig100 |= (unsigned int)(*d << s);
2819 end:
2820 if (!s || p == stop || *p != '.')
2821 break;
2822
2823 s -= 8;
2824 text = ++p;
2825 }
2826
2827 dig100 -= ascii_zero;
2828 dig10 -= ascii_zero;
2829 dig1 -= ascii_zero;
2830 return ((dig100 * 10) + dig10) * 10 + dig1;
2831}
2832
2833/*
2834 * Idem except the pointer to first unparsed byte is returned into <ret> which
2835 * must not be NULL.
2836 */
Willy Tarreau74172752010-10-15 23:21:42 +02002837unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002838{
2839 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2840 register unsigned int dig100, dig10, dig1;
2841 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002842 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002843
2844 dig1 = dig10 = dig100 = ascii_zero;
2845 s = 24;
2846
2847 p = text;
2848 while (1) {
2849 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2850 p++;
2851 continue;
2852 }
2853
2854 /* here, we have a complete byte between <text> and <p> (exclusive) */
2855 if (p == text)
2856 goto end;
2857
2858 d = p - 1;
2859 dig1 |= (unsigned int)(*d << s);
2860 if (d == text)
2861 goto end;
2862
2863 d--;
2864 dig10 |= (unsigned int)(*d << s);
2865 if (d == text)
2866 goto end;
2867
2868 d--;
2869 dig100 |= (unsigned int)(*d << s);
2870 end:
2871 if (!s || p == stop || *p != '.')
2872 break;
2873
2874 s -= 8;
2875 text = ++p;
2876 }
2877
2878 *ret = p;
2879 dig100 -= ascii_zero;
2880 dig10 -= ascii_zero;
2881 dig1 -= ascii_zero;
2882 return ((dig100 * 10) + dig10) * 10 + dig1;
2883}
2884
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002885/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2886 * or the number of chars read in case of success. Maybe this could be replaced
2887 * by one of the functions above. Also, apparently this function does not support
2888 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002889 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002890 */
2891int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2892{
2893 const char *addr;
2894 int saw_digit, octets, ch;
2895 u_char tmp[4], *tp;
2896 const char *cp = buf;
2897
2898 saw_digit = 0;
2899 octets = 0;
2900 *(tp = tmp) = 0;
2901
2902 for (addr = buf; addr - buf < len; addr++) {
2903 unsigned char digit = (ch = *addr) - '0';
2904
2905 if (digit > 9 && ch != '.')
2906 break;
2907
2908 if (digit <= 9) {
2909 u_int new = *tp * 10 + digit;
2910
2911 if (new > 255)
2912 return 0;
2913
2914 *tp = new;
2915
2916 if (!saw_digit) {
2917 if (++octets > 4)
2918 return 0;
2919 saw_digit = 1;
2920 }
2921 } else if (ch == '.' && saw_digit) {
2922 if (octets == 4)
2923 return 0;
2924
2925 *++tp = 0;
2926 saw_digit = 0;
2927 } else
2928 return 0;
2929 }
2930
2931 if (octets < 4)
2932 return 0;
2933
2934 memcpy(&dst->s_addr, tmp, 4);
2935 return addr - cp;
2936}
2937
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002938/* This function converts the string in <buf> of the len <len> to
2939 * struct in6_addr <dst> which must be allocated by the caller.
2940 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002941 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002942 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002943int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2944{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002945 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002946 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002947
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002948 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002949 return 0;
2950
2951 memcpy(null_term_ip6, buf, len);
2952 null_term_ip6[len] = '\0';
2953
Willy Tarreau075415a2013-12-12 11:29:39 +01002954 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002955 return 0;
2956
Willy Tarreau075415a2013-12-12 11:29:39 +01002957 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002958 return 1;
2959}
2960
Willy Tarreauacf95772010-06-14 19:09:21 +02002961/* To be used to quote config arg positions. Returns the short string at <ptr>
2962 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2963 * if ptr is NULL or empty. The string is locally allocated.
2964 */
2965const char *quote_arg(const char *ptr)
2966{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002967 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002968 int i;
2969
2970 if (!ptr || !*ptr)
2971 return "end of line";
2972 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002973 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002974 val[i] = *ptr++;
2975 val[i++] = '\'';
2976 val[i] = '\0';
2977 return val;
2978}
2979
Willy Tarreau5b180202010-07-18 10:40:48 +02002980/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2981int get_std_op(const char *str)
2982{
2983 int ret = -1;
2984
2985 if (*str == 'e' && str[1] == 'q')
2986 ret = STD_OP_EQ;
2987 else if (*str == 'n' && str[1] == 'e')
2988 ret = STD_OP_NE;
2989 else if (*str == 'l') {
2990 if (str[1] == 'e') ret = STD_OP_LE;
2991 else if (str[1] == 't') ret = STD_OP_LT;
2992 }
2993 else if (*str == 'g') {
2994 if (str[1] == 'e') ret = STD_OP_GE;
2995 else if (str[1] == 't') ret = STD_OP_GT;
2996 }
2997
2998 if (ret == -1 || str[2] != '\0')
2999 return -1;
3000 return ret;
3001}
3002
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003003/* hash a 32-bit integer to another 32-bit integer */
3004unsigned int full_hash(unsigned int a)
3005{
3006 return __full_hash(a);
3007}
3008
Willy Tarreauf3241112019-02-26 09:56:22 +01003009/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3010 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3011 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3012 * a popcount variant and is described here :
3013 * https://graphics.stanford.edu/~seander/bithacks.html
3014 */
3015unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3016{
3017 unsigned long a, b, c, d;
3018 unsigned int s;
3019 unsigned int t;
3020
3021 a = m - ((m >> 1) & ~0UL/3);
3022 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3023 c = (b + (b >> 4)) & ~0UL/0x11;
3024 d = (c + (c >> 8)) & ~0UL/0x101;
3025
3026 r++; // make r be 1..64
3027
3028 t = 0;
3029 s = LONGBITS;
3030 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003031 unsigned long d2 = (d >> 16) >> 16;
3032 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003033 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3034 }
3035
3036 t = (d >> (s - 16)) & 0xff;
3037 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3038 t = (c >> (s - 8)) & 0xf;
3039 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3040 t = (b >> (s - 4)) & 0x7;
3041 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3042 t = (a >> (s - 2)) & 0x3;
3043 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3044 t = (m >> (s - 1)) & 0x1;
3045 s -= ((t - r) & 256) >> 8;
3046
3047 return s - 1;
3048}
3049
3050/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3051 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3052 * using mask_prep_rank_map() below.
3053 */
3054unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3055 unsigned long a, unsigned long b,
3056 unsigned long c, unsigned long d)
3057{
3058 unsigned int s;
3059 unsigned int t;
3060
3061 r++; // make r be 1..64
3062
3063 t = 0;
3064 s = LONGBITS;
3065 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003066 unsigned long d2 = (d >> 16) >> 16;
3067 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003068 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3069 }
3070
3071 t = (d >> (s - 16)) & 0xff;
3072 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3073 t = (c >> (s - 8)) & 0xf;
3074 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3075 t = (b >> (s - 4)) & 0x7;
3076 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3077 t = (a >> (s - 2)) & 0x3;
3078 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3079 t = (m >> (s - 1)) & 0x1;
3080 s -= ((t - r) & 256) >> 8;
3081
3082 return s - 1;
3083}
3084
3085/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3086 * above.
3087 */
3088void mask_prep_rank_map(unsigned long m,
3089 unsigned long *a, unsigned long *b,
3090 unsigned long *c, unsigned long *d)
3091{
3092 *a = m - ((m >> 1) & ~0UL/3);
3093 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3094 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3095 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3096}
3097
David du Colombier4f92d322011-03-24 11:09:31 +01003098/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003099 * otherwise zero. Note that <addr> may not necessarily be aligned
3100 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003101 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003102int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003103{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003104 struct in_addr addr_copy;
3105
3106 memcpy(&addr_copy, addr, sizeof(addr_copy));
3107 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003108}
3109
3110/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003111 * otherwise zero. Note that <addr> may not necessarily be aligned
3112 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003113 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003114int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003115{
3116 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003117 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003118
Willy Tarreaueec1d382016-07-13 11:59:39 +02003119 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003120 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003121 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003122 (((int *)net)[i] & ((int *)mask)[i]))
3123 return 0;
3124 return 1;
3125}
3126
3127/* RFC 4291 prefix */
3128const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3129 0x00, 0x00, 0x00, 0x00,
3130 0x00, 0x00, 0xFF, 0xFF };
3131
Joseph Herlant32b83272018-11-15 11:58:28 -08003132/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003133 * Input and output may overlap.
3134 */
David du Colombier4f92d322011-03-24 11:09:31 +01003135void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3136{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003137 struct in_addr tmp_addr;
3138
3139 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003140 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003141 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003142}
3143
Joseph Herlant32b83272018-11-15 11:58:28 -08003144/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003145 * Return true if conversion is possible and false otherwise.
3146 */
3147int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3148{
3149 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3150 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3151 sizeof(struct in_addr));
3152 return 1;
3153 }
3154
3155 return 0;
3156}
3157
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003158/* compare two struct sockaddr_storage and return:
3159 * 0 (true) if the addr is the same in both
3160 * 1 (false) if the addr is not the same in both
3161 * -1 (unable) if one of the addr is not AF_INET*
3162 */
3163int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3164{
3165 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3166 return -1;
3167
3168 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3169 return -1;
3170
3171 if (ss1->ss_family != ss2->ss_family)
3172 return 1;
3173
3174 switch (ss1->ss_family) {
3175 case AF_INET:
3176 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3177 &((struct sockaddr_in *)ss2)->sin_addr,
3178 sizeof(struct in_addr)) != 0;
3179 case AF_INET6:
3180 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3181 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3182 sizeof(struct in6_addr)) != 0;
3183 }
3184
3185 return 1;
3186}
3187
Christopher Faulet9553de72021-02-26 09:12:50 +01003188/* compare a struct sockaddr_storage to a struct net_addr and return :
3189 * 0 (true) if <addr> is matching <net>
3190 * 1 (false) if <addr> is not matching <net>
3191 * -1 (unable) if <addr> or <net> is not AF_INET*
3192 */
3193int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3194{
3195 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3196 return -1;
3197
3198 if ((net->family != AF_INET) && (net->family != AF_INET6))
3199 return -1;
3200
3201 if (addr->ss_family != net->family)
3202 return 1;
3203
3204 if (addr->ss_family == AF_INET &&
3205 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3206 return 0;
3207 else {
3208 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3209 const struct in6_addr *nip6 = &net->addr.v6.ip;
3210 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3211
3212 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3213 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3214 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3215 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3216 return 0;
3217 }
3218
3219 return 1;
3220}
3221
Baptiste Assmann08396c82016-01-31 00:27:17 +01003222/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003223 * The caller must allocate and clear <dest> before calling.
3224 * The source must be in either AF_INET or AF_INET6 family, or the destination
3225 * address will be undefined. If the destination address used to hold a port,
3226 * it is preserved, so that this function can be used to switch to another
3227 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003228 */
3229struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3230{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003231 int prev_port;
3232
3233 prev_port = get_net_port(dest);
3234 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003235 dest->ss_family = source->ss_family;
3236
3237 /* copy new addr and apply it */
3238 switch (source->ss_family) {
3239 case AF_INET:
3240 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003241 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003242 break;
3243 case AF_INET6:
3244 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 +01003245 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003246 break;
3247 }
3248
3249 return dest;
3250}
3251
William Lallemand421f5b52012-02-06 18:15:57 +01003252char *human_time(int t, short hz_div) {
3253 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3254 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003255 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003256 int cnt=2; // print two numbers
3257
3258 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003259 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003260 return rv;
3261 }
3262
3263 if (unlikely(hz_div > 1))
3264 t /= hz_div;
3265
3266 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003267 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003268 cnt--;
3269 }
3270
3271 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003272 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003273 cnt--;
3274 }
3275
3276 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003277 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003278 cnt--;
3279 }
3280
3281 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003282 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003283
3284 return rv;
3285}
3286
3287const char *monthname[12] = {
3288 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3289 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3290};
3291
3292/* date2str_log: write a date in the format :
3293 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3294 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3295 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3296 *
3297 * without using sprintf. return a pointer to the last char written (\0) or
3298 * NULL if there isn't enough space.
3299 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003300char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003301{
3302
3303 if (size < 25) /* the size is fixed: 24 chars + \0 */
3304 return NULL;
3305
3306 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003307 if (!dst)
3308 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003309 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003310
William Lallemand421f5b52012-02-06 18:15:57 +01003311 memcpy(dst, monthname[tm->tm_mon], 3); // month
3312 dst += 3;
3313 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003314
William Lallemand421f5b52012-02-06 18:15:57 +01003315 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003316 if (!dst)
3317 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003318 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003319
William Lallemand421f5b52012-02-06 18:15:57 +01003320 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003321 if (!dst)
3322 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003323 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003324
William Lallemand421f5b52012-02-06 18:15:57 +01003325 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003326 if (!dst)
3327 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003328 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003329
William Lallemand421f5b52012-02-06 18:15:57 +01003330 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003331 if (!dst)
3332 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003333 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003334
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003335 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003336 if (!dst)
3337 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003338 *dst = '\0';
3339
3340 return dst;
3341}
3342
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003343/* Base year used to compute leap years */
3344#define TM_YEAR_BASE 1900
3345
3346/* Return the difference in seconds between two times (leap seconds are ignored).
3347 * Retrieved from glibc 2.18 source code.
3348 */
3349static int my_tm_diff(const struct tm *a, const struct tm *b)
3350{
3351 /* Compute intervening leap days correctly even if year is negative.
3352 * Take care to avoid int overflow in leap day calculations,
3353 * but it's OK to assume that A and B are close to each other.
3354 */
3355 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3356 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3357 int a100 = a4 / 25 - (a4 % 25 < 0);
3358 int b100 = b4 / 25 - (b4 % 25 < 0);
3359 int a400 = a100 >> 2;
3360 int b400 = b100 >> 2;
3361 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3362 int years = a->tm_year - b->tm_year;
3363 int days = (365 * years + intervening_leap_days
3364 + (a->tm_yday - b->tm_yday));
3365 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3366 + (a->tm_min - b->tm_min))
3367 + (a->tm_sec - b->tm_sec));
3368}
3369
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003370/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003371 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003372 * The string returned has the same format as returned by strftime(... "%z", tm).
3373 * Offsets are kept in an internal cache for better performances.
3374 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003375const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003376{
3377 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003378 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003379
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003380 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003381 struct tm tm_gmt;
3382 int diff;
3383 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003384
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003385 /* Pretend DST not active if its status is unknown */
3386 if (isdst < 0)
3387 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003388
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003389 /* Fetch the offset and initialize it if needed */
3390 gmt_offset = gmt_offsets[isdst & 0x01];
3391 if (unlikely(!*gmt_offset)) {
3392 get_gmtime(t, &tm_gmt);
3393 diff = my_tm_diff(tm, &tm_gmt);
3394 if (diff < 0) {
3395 diff = -diff;
3396 *gmt_offset = '-';
3397 } else {
3398 *gmt_offset = '+';
3399 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003400 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003401 diff /= 60; /* Convert to minutes */
3402 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3403 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003404
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003405 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003406}
3407
William Lallemand421f5b52012-02-06 18:15:57 +01003408/* gmt2str_log: write a date in the format :
3409 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3410 * return a pointer to the last char written (\0) or
3411 * NULL if there isn't enough space.
3412 */
3413char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3414{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003415 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003416 return NULL;
3417
3418 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003419 if (!dst)
3420 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003421 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003422
William Lallemand421f5b52012-02-06 18:15:57 +01003423 memcpy(dst, monthname[tm->tm_mon], 3); // month
3424 dst += 3;
3425 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003426
William Lallemand421f5b52012-02-06 18:15:57 +01003427 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003428 if (!dst)
3429 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003430 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003431
William Lallemand421f5b52012-02-06 18:15:57 +01003432 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003433 if (!dst)
3434 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003435 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003436
William Lallemand421f5b52012-02-06 18:15:57 +01003437 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003438 if (!dst)
3439 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003440 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003441
William Lallemand421f5b52012-02-06 18:15:57 +01003442 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003443 if (!dst)
3444 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003445 *dst++ = ' ';
3446 *dst++ = '+';
3447 *dst++ = '0';
3448 *dst++ = '0';
3449 *dst++ = '0';
3450 *dst++ = '0';
3451 *dst = '\0';
3452
3453 return dst;
3454}
3455
Yuxans Yao4e25b012012-10-19 10:36:09 +08003456/* localdate2str_log: write a date in the format :
3457 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003458 * Both t and tm must represent the same time.
3459 * return a pointer to the last char written (\0) or
3460 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003461 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003462char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003463{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003464 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003465 if (size < 27) /* the size is fixed: 26 chars + \0 */
3466 return NULL;
3467
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003468 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003469
Yuxans Yao4e25b012012-10-19 10:36:09 +08003470 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003471 if (!dst)
3472 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003473 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003474
Yuxans Yao4e25b012012-10-19 10:36:09 +08003475 memcpy(dst, monthname[tm->tm_mon], 3); // month
3476 dst += 3;
3477 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003478
Yuxans Yao4e25b012012-10-19 10:36:09 +08003479 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003480 if (!dst)
3481 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003482 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003483
Yuxans Yao4e25b012012-10-19 10:36:09 +08003484 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003485 if (!dst)
3486 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003487 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003488
Yuxans Yao4e25b012012-10-19 10:36:09 +08003489 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003490 if (!dst)
3491 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003492 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003493
Yuxans Yao4e25b012012-10-19 10:36:09 +08003494 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003495 if (!dst)
3496 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003497 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003498
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003499 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003500 dst += 5;
3501 *dst = '\0';
3502
3503 return dst;
3504}
3505
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003506/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3507 * It is meant as a portable replacement for timegm() for use with valid inputs.
3508 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3509 */
3510time_t my_timegm(const struct tm *tm)
3511{
3512 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3513 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3514 * sum of the extra N days for elapsed months. The sum of all these N
3515 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3516 * in a 5-bit word. This means that with 60 bits we can represent a
3517 * matrix of all these values at once, which is fast and efficient to
3518 * access. The extra February day for leap years is not counted here.
3519 *
3520 * Jan : none = 0 (0)
3521 * Feb : Jan = 3 (3)
3522 * Mar : Jan..Feb = 3 (3 + 0)
3523 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3524 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3525 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3526 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3527 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3528 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3529 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3530 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3531 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3532 */
3533 uint64_t extra =
3534 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3535 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3536 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3537 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3538
3539 unsigned int y = tm->tm_year + 1900;
3540 unsigned int m = tm->tm_mon;
3541 unsigned long days = 0;
3542
3543 /* days since 1/1/1970 for full years */
3544 days += days_since_zero(y) - days_since_zero(1970);
3545
3546 /* days for full months in the current year */
3547 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3548
3549 /* count + 1 after March for leap years. A leap year is a year multiple
3550 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3551 * is leap, 1900 isn't, 1904 is.
3552 */
3553 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3554 days++;
3555
3556 days += tm->tm_mday - 1;
3557 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3558}
3559
Thierry Fournier93127942016-01-20 18:49:45 +01003560/* This function check a char. It returns true and updates
3561 * <date> and <len> pointer to the new position if the
3562 * character is found.
3563 */
3564static inline int parse_expect_char(const char **date, int *len, char c)
3565{
3566 if (*len < 1 || **date != c)
3567 return 0;
3568 (*len)--;
3569 (*date)++;
3570 return 1;
3571}
3572
3573/* This function expects a string <str> of len <l>. It return true and updates.
3574 * <date> and <len> if the string matches, otherwise, it returns false.
3575 */
3576static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3577{
3578 if (*len < l || strncmp(*date, str, l) != 0)
3579 return 0;
3580 (*len) -= l;
3581 (*date) += l;
3582 return 1;
3583}
3584
3585/* This macro converts 3 chars name in integer. */
3586#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3587
3588/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3589 * / %x54.75.65 ; "Tue", case-sensitive
3590 * / %x57.65.64 ; "Wed", case-sensitive
3591 * / %x54.68.75 ; "Thu", case-sensitive
3592 * / %x46.72.69 ; "Fri", case-sensitive
3593 * / %x53.61.74 ; "Sat", case-sensitive
3594 * / %x53.75.6E ; "Sun", case-sensitive
3595 *
3596 * This array must be alphabetically sorted
3597 */
3598static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3599{
3600 if (*len < 3)
3601 return 0;
3602 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3603 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3604 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3605 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3606 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3607 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3608 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3609 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3610 default: return 0;
3611 }
3612 *len -= 3;
3613 *date += 3;
3614 return 1;
3615}
3616
3617/* month = %x4A.61.6E ; "Jan", case-sensitive
3618 * / %x46.65.62 ; "Feb", case-sensitive
3619 * / %x4D.61.72 ; "Mar", case-sensitive
3620 * / %x41.70.72 ; "Apr", case-sensitive
3621 * / %x4D.61.79 ; "May", case-sensitive
3622 * / %x4A.75.6E ; "Jun", case-sensitive
3623 * / %x4A.75.6C ; "Jul", case-sensitive
3624 * / %x41.75.67 ; "Aug", case-sensitive
3625 * / %x53.65.70 ; "Sep", case-sensitive
3626 * / %x4F.63.74 ; "Oct", case-sensitive
3627 * / %x4E.6F.76 ; "Nov", case-sensitive
3628 * / %x44.65.63 ; "Dec", case-sensitive
3629 *
3630 * This array must be alphabetically sorted
3631 */
3632static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3633{
3634 if (*len < 3)
3635 return 0;
3636 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3637 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3638 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3639 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3640 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3641 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3642 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3643 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3644 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3645 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3646 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3647 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3648 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3649 default: return 0;
3650 }
3651 *len -= 3;
3652 *date += 3;
3653 return 1;
3654}
3655
3656/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3657 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3658 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3659 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3660 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3661 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3662 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3663 *
3664 * This array must be alphabetically sorted
3665 */
3666static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3667{
3668 if (*len < 6) /* Minimum length. */
3669 return 0;
3670 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3671 case STR2I3('M','o','n'):
3672 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3673 tm->tm_wday = 1;
3674 return 1;
3675 case STR2I3('T','u','e'):
3676 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3677 tm->tm_wday = 2;
3678 return 1;
3679 case STR2I3('W','e','d'):
3680 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3681 tm->tm_wday = 3;
3682 return 1;
3683 case STR2I3('T','h','u'):
3684 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3685 tm->tm_wday = 4;
3686 return 1;
3687 case STR2I3('F','r','i'):
3688 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3689 tm->tm_wday = 5;
3690 return 1;
3691 case STR2I3('S','a','t'):
3692 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3693 tm->tm_wday = 6;
3694 return 1;
3695 case STR2I3('S','u','n'):
3696 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3697 tm->tm_wday = 7;
3698 return 1;
3699 }
3700 return 0;
3701}
3702
3703/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3704static inline int parse_digit(const char **date, int *len, int *digit)
3705{
3706 if (*len < 1 || **date < '0' || **date > '9')
3707 return 0;
3708 *digit = (**date - '0');
3709 (*date)++;
3710 (*len)--;
3711 return 1;
3712}
3713
3714/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3715static inline int parse_2digit(const char **date, int *len, int *digit)
3716{
3717 int value;
3718
3719 RET0_UNLESS(parse_digit(date, len, &value));
3720 (*digit) = value * 10;
3721 RET0_UNLESS(parse_digit(date, len, &value));
3722 (*digit) += value;
3723
3724 return 1;
3725}
3726
3727/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3728static inline int parse_4digit(const char **date, int *len, int *digit)
3729{
3730 int value;
3731
3732 RET0_UNLESS(parse_digit(date, len, &value));
3733 (*digit) = value * 1000;
3734
3735 RET0_UNLESS(parse_digit(date, len, &value));
3736 (*digit) += value * 100;
3737
3738 RET0_UNLESS(parse_digit(date, len, &value));
3739 (*digit) += value * 10;
3740
3741 RET0_UNLESS(parse_digit(date, len, &value));
3742 (*digit) += value;
3743
3744 return 1;
3745}
3746
3747/* time-of-day = hour ":" minute ":" second
3748 * ; 00:00:00 - 23:59:60 (leap second)
3749 *
3750 * hour = 2DIGIT
3751 * minute = 2DIGIT
3752 * second = 2DIGIT
3753 */
3754static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3755{
3756 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3757 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3758 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3759 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3760 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3761 return 1;
3762}
3763
3764/* From RFC7231
3765 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3766 *
3767 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3768 * ; fixed length/zone/capitalization subset of the format
3769 * ; see Section 3.3 of [RFC5322]
3770 *
3771 *
3772 * date1 = day SP month SP year
3773 * ; e.g., 02 Jun 1982
3774 *
3775 * day = 2DIGIT
3776 * year = 4DIGIT
3777 *
3778 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3779 *
3780 * time-of-day = hour ":" minute ":" second
3781 * ; 00:00:00 - 23:59:60 (leap second)
3782 *
3783 * hour = 2DIGIT
3784 * minute = 2DIGIT
3785 * second = 2DIGIT
3786 *
3787 * DIGIT = decimal 0-9
3788 */
3789int parse_imf_date(const char *date, int len, struct tm *tm)
3790{
David Carlier327298c2016-11-20 10:42:38 +00003791 /* tm_gmtoff, if present, ought to be zero'ed */
3792 memset(tm, 0, sizeof(*tm));
3793
Thierry Fournier93127942016-01-20 18:49:45 +01003794 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3795 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3796 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3797 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3798 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3799 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3800 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3801 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3802 tm->tm_year -= 1900;
3803 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3804 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3805 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3806 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3807 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003808 return 1;
3809}
3810
3811/* From RFC7231
3812 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3813 *
3814 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3815 * date2 = day "-" month "-" 2DIGIT
3816 * ; e.g., 02-Jun-82
3817 *
3818 * day = 2DIGIT
3819 */
3820int parse_rfc850_date(const char *date, int len, struct tm *tm)
3821{
3822 int year;
3823
David Carlier327298c2016-11-20 10:42:38 +00003824 /* tm_gmtoff, if present, ought to be zero'ed */
3825 memset(tm, 0, sizeof(*tm));
3826
Thierry Fournier93127942016-01-20 18:49:45 +01003827 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3828 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3829 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3830 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3831 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3832 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3833 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3834
3835 /* year = 2DIGIT
3836 *
3837 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3838 * two-digit year, MUST interpret a timestamp that appears to be more
3839 * than 50 years in the future as representing the most recent year in
3840 * the past that had the same last two digits.
3841 */
3842 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3843
3844 /* expect SP */
3845 if (!parse_expect_char(&date, &len, ' ')) {
3846 /* Maybe we have the date with 4 digits. */
3847 RET0_UNLESS(parse_2digit(&date, &len, &year));
3848 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3849 /* expect SP */
3850 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3851 } else {
3852 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3853 * tm_year is the number of year since 1900, so for +1900, we
3854 * do nothing, and for +2000, we add 100.
3855 */
3856 if (tm->tm_year <= 60)
3857 tm->tm_year += 100;
3858 }
3859
3860 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3861 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3862 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3863 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003864
3865 return 1;
3866}
3867
3868/* From RFC7231
3869 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3870 *
3871 * asctime-date = day-name SP date3 SP time-of-day SP year
3872 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3873 * ; e.g., Jun 2
3874 *
3875 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3876 * whitespace in an HTTP-date beyond that specifically included as SP in
3877 * the grammar.
3878 */
3879int parse_asctime_date(const char *date, int len, struct tm *tm)
3880{
David Carlier327298c2016-11-20 10:42:38 +00003881 /* tm_gmtoff, if present, ought to be zero'ed */
3882 memset(tm, 0, sizeof(*tm));
3883
Thierry Fournier93127942016-01-20 18:49:45 +01003884 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3885 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3886 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3887 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3888
3889 /* expect SP and 1DIGIT or 2DIGIT */
3890 if (parse_expect_char(&date, &len, ' '))
3891 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3892 else
3893 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3894
3895 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
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_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3899 tm->tm_year -= 1900;
3900 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003901 return 1;
3902}
3903
3904/* From RFC7231
3905 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3906 *
3907 * HTTP-date = IMF-fixdate / obs-date
3908 * obs-date = rfc850-date / asctime-date
3909 *
3910 * parses an HTTP date in the RFC format and is accepted
3911 * alternatives. <date> is the strinf containing the date,
3912 * len is the len of the string. <tm> is filled with the
3913 * parsed time. We must considers this time as GMT.
3914 */
3915int parse_http_date(const char *date, int len, struct tm *tm)
3916{
3917 if (parse_imf_date(date, len, tm))
3918 return 1;
3919
3920 if (parse_rfc850_date(date, len, tm))
3921 return 1;
3922
3923 if (parse_asctime_date(date, len, tm))
3924 return 1;
3925
3926 return 0;
3927}
3928
Willy Tarreau4deeb102021-01-29 10:47:52 +01003929/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3930 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3931 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3932 * surrounded by <pfx> and <sfx> respectively if not NULL.
3933 */
3934int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3935{
3936 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3937 const char *unit;
3938
3939 if (!pfx)
3940 pfx = "";
3941 if (!sfx)
3942 sfx = "";
3943
3944 do {
3945 unit = " - "; if (val <= 0.0) break;
3946 unit = "ns"; if (val < 1000.0) break;
3947 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3948 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3949 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3950 unit = "m "; val /= 60.0; if (val < 60.0) break;
3951 unit = "h "; val /= 60.0; if (val < 24.0) break;
3952 unit = "d "; val /= 24.0; if (val < 365.0) break;
3953 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3954 unit = " inf "; val = 0.0; break;
3955 } while (0);
3956
3957 if (val <= 0.0)
3958 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
3959 else if (val < 10.0)
3960 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
3961 else if (val < 100.0)
3962 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
3963 else
3964 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
3965}
3966
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003967/* Dynamically allocates a string of the proper length to hold the formatted
3968 * output. NULL is returned on error. The caller is responsible for freeing the
3969 * memory area using free(). The resulting string is returned in <out> if the
3970 * pointer is not NULL. A previous version of <out> might be used to build the
3971 * new string, and it will be freed before returning if it is not NULL, which
3972 * makes it possible to build complex strings from iterative calls without
3973 * having to care about freeing intermediate values, as in the example below :
3974 *
3975 * memprintf(&err, "invalid argument: '%s'", arg);
3976 * ...
3977 * memprintf(&err, "parser said : <%s>\n", *err);
3978 * ...
3979 * free(*err);
3980 *
3981 * This means that <err> must be initialized to NULL before first invocation.
3982 * The return value also holds the allocated string, which eases error checking
3983 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003984 * passed instead and it will be ignored. The returned message will then also
3985 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003986 *
3987 * It is also convenient to use it without any free except the last one :
3988 * err = NULL;
3989 * if (!fct1(err)) report(*err);
3990 * if (!fct2(err)) report(*err);
3991 * if (!fct3(err)) report(*err);
3992 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003993 *
3994 * memprintf relies on memvprintf. This last version can be called from any
3995 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003996 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003997char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003998{
3999 va_list args;
4000 char *ret = NULL;
4001 int allocated = 0;
4002 int needed = 0;
4003
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004004 if (!out)
4005 return NULL;
4006
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004007 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004008 char buf1;
4009
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004010 /* vsnprintf() will return the required length even when the
4011 * target buffer is NULL. We do this in a loop just in case
4012 * intermediate evaluations get wrong.
4013 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004014 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004015 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004016 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004017 if (needed < allocated) {
4018 /* Note: on Solaris 8, the first iteration always
4019 * returns -1 if allocated is zero, so we force a
4020 * retry.
4021 */
4022 if (!allocated)
4023 needed = 0;
4024 else
4025 break;
4026 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004027
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004028 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004029 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004030 } while (ret);
4031
4032 if (needed < 0) {
4033 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004034 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004035 }
4036
4037 if (out) {
4038 free(*out);
4039 *out = ret;
4040 }
4041
4042 return ret;
4043}
William Lallemand421f5b52012-02-06 18:15:57 +01004044
Christopher Faulet93a518f2017-10-24 11:25:33 +02004045char *memprintf(char **out, const char *format, ...)
4046{
4047 va_list args;
4048 char *ret = NULL;
4049
4050 va_start(args, format);
4051 ret = memvprintf(out, format, args);
4052 va_end(args);
4053
4054 return ret;
4055}
4056
Willy Tarreau21c705b2012-09-14 11:40:36 +02004057/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4058 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004059 * freed by the caller. It also supports being passed a NULL which results in the same
4060 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004061 * Example of use :
4062 * parse(cmd, &err); (callee: memprintf(&err, ...))
4063 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4064 * free(err);
4065 */
4066char *indent_msg(char **out, int level)
4067{
4068 char *ret, *in, *p;
4069 int needed = 0;
4070 int lf = 0;
4071 int lastlf = 0;
4072 int len;
4073
Willy Tarreau70eec382012-10-10 08:56:47 +02004074 if (!out || !*out)
4075 return NULL;
4076
Willy Tarreau21c705b2012-09-14 11:40:36 +02004077 in = *out - 1;
4078 while ((in = strchr(in + 1, '\n')) != NULL) {
4079 lastlf = in - *out;
4080 lf++;
4081 }
4082
4083 if (!lf) /* single line, no LF, return it as-is */
4084 return *out;
4085
4086 len = strlen(*out);
4087
4088 if (lf == 1 && lastlf == len - 1) {
4089 /* single line, LF at end, strip it and return as-is */
4090 (*out)[lastlf] = 0;
4091 return *out;
4092 }
4093
4094 /* OK now we have at least one LF, we need to process the whole string
4095 * as a multi-line string. What we'll do :
4096 * - prefix with an LF if there is none
4097 * - add <level> spaces before each line
4098 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4099 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4100 */
4101
4102 needed = 1 + level * (lf + 1) + len + 1;
4103 p = ret = malloc(needed);
4104 in = *out;
4105
4106 /* skip initial LFs */
4107 while (*in == '\n')
4108 in++;
4109
4110 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4111 while (*in) {
4112 *p++ = '\n';
4113 memset(p, ' ', level);
4114 p += level;
4115 do {
4116 *p++ = *in++;
4117 } while (*in && *in != '\n');
4118 if (*in)
4119 in++;
4120 }
4121 *p = 0;
4122
4123 free(*out);
4124 *out = ret;
4125
4126 return ret;
4127}
4128
Willy Tarreaua2c99112019-08-21 13:17:37 +02004129/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4130 * and end of lines replaced with <eol> if not 0. The first line to indent has
4131 * to be indicated in <first> (starts at zero), so that it is possible to skip
4132 * indenting the first line if it has to be appended after an existing message.
4133 * Empty strings are never indented, and NULL strings are considered empty both
4134 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4135 * character, non-zero otherwise.
4136 */
4137int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4138{
4139 int bol, lf;
4140 int pfxlen = pfx ? strlen(pfx) : 0;
4141
4142 if (!in)
4143 return 0;
4144
4145 bol = 1;
4146 lf = 0;
4147 while (*in) {
4148 if (bol && pfxlen) {
4149 if (first > 0)
4150 first--;
4151 else
4152 b_putblk(out, pfx, pfxlen);
4153 bol = 0;
4154 }
4155
4156 lf = (*in == '\n');
4157 bol |= lf;
4158 b_putchr(out, (lf && eol) ? eol : *in);
4159 in++;
4160 }
4161 return lf;
4162}
4163
Willy Tarreau9d22e562019-03-29 18:49:09 +01004164/* removes environment variable <name> from the environment as found in
4165 * environ. This is only provided as an alternative for systems without
4166 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004167 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004168 * <name> and to replace the matching pointers with the last pointer of
4169 * the array (since variables are not ordered).
4170 * It always returns 0 (success).
4171 */
4172int my_unsetenv(const char *name)
4173{
4174 extern char **environ;
4175 char **p = environ;
4176 int vars;
4177 int next;
4178 int len;
4179
4180 len = strlen(name);
4181 for (vars = 0; p[vars]; vars++)
4182 ;
4183 next = 0;
4184 while (next < vars) {
4185 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4186 next++;
4187 continue;
4188 }
4189 if (next < vars - 1)
4190 p[next] = p[vars - 1];
4191 p[--vars] = NULL;
4192 }
4193 return 0;
4194}
4195
Willy Tarreaudad36a32013-03-11 01:20:04 +01004196/* Convert occurrences of environment variables in the input string to their
4197 * corresponding value. A variable is identified as a series of alphanumeric
4198 * characters or underscores following a '$' sign. The <in> string must be
4199 * free()able. NULL returns NULL. The resulting string might be reallocated if
4200 * some expansion is made. Variable names may also be enclosed into braces if
4201 * needed (eg: to concatenate alphanum characters).
4202 */
4203char *env_expand(char *in)
4204{
4205 char *txt_beg;
4206 char *out;
4207 char *txt_end;
4208 char *var_beg;
4209 char *var_end;
4210 char *value;
4211 char *next;
4212 int out_len;
4213 int val_len;
4214
4215 if (!in)
4216 return in;
4217
4218 value = out = NULL;
4219 out_len = 0;
4220
4221 txt_beg = in;
4222 do {
4223 /* look for next '$' sign in <in> */
4224 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4225
4226 if (!*txt_end && !out) /* end and no expansion performed */
4227 return in;
4228
4229 val_len = 0;
4230 next = txt_end;
4231 if (*txt_end == '$') {
4232 char save;
4233
4234 var_beg = txt_end + 1;
4235 if (*var_beg == '{')
4236 var_beg++;
4237
4238 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004239 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004240 var_end++;
4241 }
4242
4243 next = var_end;
4244 if (*var_end == '}' && (var_beg > txt_end + 1))
4245 next++;
4246
4247 /* get value of the variable name at this location */
4248 save = *var_end;
4249 *var_end = '\0';
4250 value = getenv(var_beg);
4251 *var_end = save;
4252 val_len = value ? strlen(value) : 0;
4253 }
4254
Hubert Verstraete831962e2016-06-28 22:44:26 +02004255 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004256 if (txt_end > txt_beg) {
4257 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4258 out_len += txt_end - txt_beg;
4259 }
4260 if (val_len) {
4261 memcpy(out + out_len, value, val_len);
4262 out_len += val_len;
4263 }
4264 out[out_len] = 0;
4265 txt_beg = next;
4266 } while (*txt_beg);
4267
4268 /* here we know that <out> was allocated and that we don't need <in> anymore */
4269 free(in);
4270 return out;
4271}
4272
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004273
4274/* same as strstr() but case-insensitive and with limit length */
4275const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4276{
4277 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004278 unsigned int slen, plen;
4279 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004280
4281 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4282 return NULL;
4283
4284 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4285 return str1;
4286
4287 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4288 return NULL;
4289
4290 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 +02004291 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004292 start++;
4293 slen--;
4294 tmp1++;
4295
4296 if (tmp1 >= len_str1)
4297 return NULL;
4298
4299 /* if pattern longer than string */
4300 if (slen < plen)
4301 return NULL;
4302 }
4303
4304 sptr = start;
4305 pptr = (char *)str2;
4306
4307 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004308 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004309 sptr++;
4310 pptr++;
4311 tmp2++;
4312
4313 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4314 return start;
4315 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4316 return NULL;
4317 }
4318 }
4319 return NULL;
4320}
4321
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004322/* This function read the next valid utf8 char.
4323 * <s> is the byte srray to be decode, <len> is its length.
4324 * The function returns decoded char encoded like this:
4325 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4326 * are the length read. The decoded character is stored in <c>.
4327 */
4328unsigned char utf8_next(const char *s, int len, unsigned int *c)
4329{
4330 const unsigned char *p = (unsigned char *)s;
4331 int dec;
4332 unsigned char code = UTF8_CODE_OK;
4333
4334 if (len < 1)
4335 return UTF8_CODE_OK;
4336
4337 /* Check the type of UTF8 sequence
4338 *
4339 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4340 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4341 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4342 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4343 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4344 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4345 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4346 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4347 */
4348 switch (*p) {
4349 case 0x00 ... 0x7f:
4350 *c = *p;
4351 return UTF8_CODE_OK | 1;
4352
4353 case 0x80 ... 0xbf:
4354 *c = *p;
4355 return UTF8_CODE_BADSEQ | 1;
4356
4357 case 0xc0 ... 0xdf:
4358 if (len < 2) {
4359 *c = *p;
4360 return UTF8_CODE_BADSEQ | 1;
4361 }
4362 *c = *p & 0x1f;
4363 dec = 1;
4364 break;
4365
4366 case 0xe0 ... 0xef:
4367 if (len < 3) {
4368 *c = *p;
4369 return UTF8_CODE_BADSEQ | 1;
4370 }
4371 *c = *p & 0x0f;
4372 dec = 2;
4373 break;
4374
4375 case 0xf0 ... 0xf7:
4376 if (len < 4) {
4377 *c = *p;
4378 return UTF8_CODE_BADSEQ | 1;
4379 }
4380 *c = *p & 0x07;
4381 dec = 3;
4382 break;
4383
4384 case 0xf8 ... 0xfb:
4385 if (len < 5) {
4386 *c = *p;
4387 return UTF8_CODE_BADSEQ | 1;
4388 }
4389 *c = *p & 0x03;
4390 dec = 4;
4391 break;
4392
4393 case 0xfc ... 0xfd:
4394 if (len < 6) {
4395 *c = *p;
4396 return UTF8_CODE_BADSEQ | 1;
4397 }
4398 *c = *p & 0x01;
4399 dec = 5;
4400 break;
4401
4402 case 0xfe ... 0xff:
4403 default:
4404 *c = *p;
4405 return UTF8_CODE_BADSEQ | 1;
4406 }
4407
4408 p++;
4409
4410 while (dec > 0) {
4411
4412 /* need 0x10 for the 2 first bits */
4413 if ( ( *p & 0xc0 ) != 0x80 )
4414 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4415
4416 /* add data at char */
4417 *c = ( *c << 6 ) | ( *p & 0x3f );
4418
4419 dec--;
4420 p++;
4421 }
4422
4423 /* Check ovelong encoding.
4424 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4425 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4426 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4427 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004428 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004429 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4430 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4431 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4432 code |= UTF8_CODE_OVERLONG;
4433
4434 /* Check invalid UTF8 range. */
4435 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4436 (*c >= 0xfffe && *c <= 0xffff))
4437 code |= UTF8_CODE_INVRANGE;
4438
4439 return code | ((p-(unsigned char *)s)&0x0f);
4440}
4441
Maxime de Roucydc887852016-05-13 23:52:54 +02004442/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4443 * On failure : return 0 and <err> filled with an error message.
4444 * The caller is responsible for freeing the <err> and <str> copy
4445 * memory area using free()
4446 */
4447int list_append_word(struct list *li, const char *str, char **err)
4448{
4449 struct wordlist *wl;
4450
4451 wl = calloc(1, sizeof(*wl));
4452 if (!wl) {
4453 memprintf(err, "out of memory");
4454 goto fail_wl;
4455 }
4456
4457 wl->s = strdup(str);
4458 if (!wl->s) {
4459 memprintf(err, "out of memory");
4460 goto fail_wl_s;
4461 }
4462
Willy Tarreau2b718102021-04-21 07:32:39 +02004463 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004464
4465 return 1;
4466
4467fail_wl_s:
4468 free(wl->s);
4469fail_wl:
4470 free(wl);
4471 return 0;
4472}
4473
Willy Tarreau37101052019-05-20 16:48:20 +02004474/* indicates if a memory location may safely be read or not. The trick consists
4475 * in performing a harmless syscall using this location as an input and letting
4476 * the operating system report whether it's OK or not. For this we have the
4477 * stat() syscall, which will return EFAULT when the memory location supposed
4478 * to contain the file name is not readable. If it is readable it will then
4479 * either return 0 if the area contains an existing file name, or -1 with
4480 * another code. This must not be abused, and some audit systems might detect
4481 * this as abnormal activity. It's used only for unsafe dumps.
4482 */
4483int may_access(const void *ptr)
4484{
4485 struct stat buf;
4486
4487 if (stat(ptr, &buf) == 0)
4488 return 1;
4489 if (errno == EFAULT)
4490 return 0;
4491 return 1;
4492}
4493
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004494/* print a string of text buffer to <out>. The format is :
4495 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4496 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4497 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4498 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004499int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004500{
4501 unsigned char c;
4502 int ptr = 0;
4503
4504 while (buf[ptr] && ptr < bsize) {
4505 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004506 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004507 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004508 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004509 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004510 }
4511 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004512 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004513 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004514 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004515 switch (c) {
4516 case ' ': c = ' '; break;
4517 case '\t': c = 't'; break;
4518 case '\n': c = 'n'; break;
4519 case '\r': c = 'r'; break;
4520 case '\e': c = 'e'; break;
4521 case '\\': c = '\\'; break;
4522 case '=': c = '='; break;
4523 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004524 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004525 }
4526 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004527 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004528 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004529 out->area[out->data++] = '\\';
4530 out->area[out->data++] = 'x';
4531 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4532 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004533 }
4534 ptr++;
4535 }
4536
4537 return ptr;
4538}
4539
4540/* print a buffer in hexa.
4541 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4542 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004543int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004544{
4545 unsigned char c;
4546 int ptr = 0;
4547
4548 while (ptr < bsize) {
4549 c = buf[ptr];
4550
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004551 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004552 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004553 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4554 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004555
4556 ptr++;
4557 }
4558 return ptr;
4559}
4560
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004561/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4562 * prepending each line with prefix <pfx>. The output is *not* initialized.
4563 * The output will not wrap pas the buffer's end so it is more optimal if the
4564 * caller makes sure the buffer is aligned first. A trailing zero will always
4565 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004566 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4567 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004568 */
Willy Tarreau37101052019-05-20 16:48:20 +02004569void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004570{
4571 const unsigned char *d = buf;
4572 int i, j, start;
4573
4574 d = (const unsigned char *)(((unsigned long)buf) & -16);
4575 start = ((unsigned long)buf) & 15;
4576
4577 for (i = 0; i < start + len; i += 16) {
4578 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4579
Willy Tarreau37101052019-05-20 16:48:20 +02004580 // 0: unchecked, 1: checked safe, 2: danger
4581 unsafe = !!unsafe;
4582 if (unsafe && !may_access(d + i))
4583 unsafe = 2;
4584
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004585 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004586 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004587 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004588 else if (unsafe > 1)
4589 chunk_strcat(out, "** ");
4590 else
4591 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004592
4593 if (j == 7)
4594 chunk_strcat(out, "- ");
4595 }
4596 chunk_strcat(out, " ");
4597 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004598 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004599 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004600 else if (unsafe > 1)
4601 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004602 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004603 chunk_appendf(out, "%c", d[i + j]);
4604 else
4605 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004606 }
4607 chunk_strcat(out, "\n");
4608 }
4609}
4610
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004611/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4612 * enclosed in brackets after the address itself, formatted on 14 chars
4613 * including the "0x" prefix. This is meant to be used as a prefix for code
4614 * areas. For example:
4615 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4616 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4617 * is emitted. A NULL <pfx> will be considered empty.
4618 */
4619void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4620{
4621 int ok = 0;
4622 int i;
4623
4624 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4625
4626 for (i = 0; i < n; i++) {
4627 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4628 ok = may_access(addr + i);
4629 if (ok)
4630 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4631 else
4632 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4633 }
4634}
4635
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004636/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4637 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4638 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4639 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4640 * lines are respected within the limit of 70 output chars. Lines that are
4641 * continuation of a previous truncated line begin with "+" instead of " "
4642 * after the offset. The new pointer is returned.
4643 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004644int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004645 int *line, int ptr)
4646{
4647 int end;
4648 unsigned char c;
4649
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004650 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004651 if (end > out->size)
4652 return ptr;
4653
4654 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4655
4656 while (ptr < len && ptr < bsize) {
4657 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004658 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004659 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004660 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004661 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004662 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004663 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004664 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004665 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004666 switch (c) {
4667 case '\t': c = 't'; break;
4668 case '\n': c = 'n'; break;
4669 case '\r': c = 'r'; break;
4670 case '\e': c = 'e'; break;
4671 case '\\': c = '\\'; break;
4672 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004673 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004674 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004675 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004676 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004677 out->area[out->data++] = '\\';
4678 out->area[out->data++] = 'x';
4679 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4680 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004681 }
4682 if (buf[ptr++] == '\n') {
4683 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004684 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004685 *line = ptr;
4686 return ptr;
4687 }
4688 }
4689 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004690 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004691 return ptr;
4692}
4693
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004694/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004695 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4696 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004697 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004698void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4699 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004700{
Willy Tarreau73459792017-04-11 07:58:08 +02004701 unsigned int i;
4702 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004703
4704 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4705 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004706 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004707 for (j = 0; j < 8; j++) {
4708 if (b + j >= 0 && b + j < len)
4709 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4710 else
4711 fprintf(out, " ");
4712 }
4713
4714 if (b + j >= 0 && b + j < len)
4715 fputc('-', out);
4716 else
4717 fputc(' ', out);
4718
4719 for (j = 8; j < 16; j++) {
4720 if (b + j >= 0 && b + j < len)
4721 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4722 else
4723 fprintf(out, " ");
4724 }
4725
4726 fprintf(out, " ");
4727 for (j = 0; j < 16; j++) {
4728 if (b + j >= 0 && b + j < len) {
4729 if (isprint((unsigned char)buf[b + j]))
4730 fputc((unsigned char)buf[b + j], out);
4731 else
4732 fputc('.', out);
4733 }
4734 else
4735 fputc(' ', out);
4736 }
4737 fputc('\n', out);
4738 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004739}
4740
Willy Tarreaubb869862020-04-16 10:52:41 +02004741/* Tries to report the executable path name on platforms supporting this. If
4742 * not found or not possible, returns NULL.
4743 */
4744const char *get_exec_path()
4745{
4746 const char *ret = NULL;
4747
4748#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4749 long execfn = getauxval(AT_EXECFN);
4750
4751 if (execfn && execfn != ENOENT)
4752 ret = (const char *)execfn;
4753#endif
4754 return ret;
4755}
4756
Baruch Siache1651b22020-07-24 07:52:20 +03004757#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004758/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4759 * also returns the symbol size in <size>, otherwise returns 0 there.
4760 */
4761static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4762{
4763 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004764#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004765 const ElfW(Sym) *sym;
4766
4767 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4768 if (ret)
4769 *size = sym ? sym->st_size : 0;
4770#else
4771 ret = dladdr(addr, dli);
4772 *size = 0;
4773#endif
4774 return ret;
4775}
Willy Tarreau64192392021-05-05 09:06:21 +02004776
4777/* Tries to retrieve the address of the first occurrence symbol <name>.
4778 * Note that NULL in return is not always an error as a symbol may have that
4779 * address in special situations.
4780 */
4781void *get_sym_curr_addr(const char *name)
4782{
4783 void *ptr = NULL;
4784
4785#ifdef RTLD_DEFAULT
4786 ptr = dlsym(RTLD_DEFAULT, name);
4787#endif
4788 return ptr;
4789}
4790
4791
4792/* Tries to retrieve the address of the next occurrence of symbol <name>
4793 * Note that NULL in return is not always an error as a symbol may have that
4794 * address in special situations.
4795 */
4796void *get_sym_next_addr(const char *name)
4797{
4798 void *ptr = NULL;
4799
4800#ifdef RTLD_NEXT
4801 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004802#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004803 return ptr;
4804}
4805
4806#else /* elf & linux & dl */
4807
4808/* no possible resolving on other platforms at the moment */
4809void *get_sym_curr_addr(const char *name)
4810{
4811 return NULL;
4812}
4813
4814void *get_sym_next_addr(const char *name)
4815{
4816 return NULL;
4817}
4818
4819#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004820
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004821/* Tries to append to buffer <buf> some indications about the symbol at address
4822 * <addr> using the following form:
4823 * lib:+0xoffset (unresolvable address from lib's base)
4824 * main+0xoffset (unresolvable address from main (+/-))
4825 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4826 * name (resolved exact exec address)
4827 * lib:name (resolved exact lib address)
4828 * name+0xoffset/0xsize (resolved address within exec symbol)
4829 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4830 *
4831 * The file name (lib or executable) is limited to what lies between the last
4832 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4833 * 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 +03004834 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004835 *
4836 * The symbol's base address is returned, or NULL when unresolved, in order to
4837 * allow the caller to match it against known ones.
4838 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004839const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004840{
4841 const struct {
4842 const void *func;
4843 const char *name;
4844 } fcts[] = {
4845 { .func = process_stream, .name = "process_stream" },
4846 { .func = task_run_applet, .name = "task_run_applet" },
4847 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004848 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004849 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4850 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004851 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004852 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4853 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004854 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004855#ifdef USE_THREAD
4856 { .func = accept_queue_process, .name = "accept_queue_process" },
4857#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004858#ifdef USE_LUA
4859 { .func = hlua_process_task, .name = "hlua_process_task" },
4860#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004861#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004862 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4863 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4864#endif
4865 };
4866
Baruch Siache1651b22020-07-24 07:52:20 +03004867#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004868 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004869 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004870 const char *fname, *p;
4871#endif
4872 int i;
4873
4874 if (pfx)
4875 chunk_appendf(buf, "%s", pfx);
4876
4877 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4878 if (addr == fcts[i].func) {
4879 chunk_appendf(buf, "%s", fcts[i].name);
4880 return addr;
4881 }
4882 }
4883
Baruch Siache1651b22020-07-24 07:52:20 +03004884#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004885 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004886 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004887 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004888
4889 /* 1. prefix the library name if it's not the same object as the one
4890 * that contains the main function. The name is picked between last '/'
4891 * and first following '.'.
4892 */
4893 if (!dladdr(main, &dli_main))
4894 dli_main.dli_fbase = NULL;
4895
4896 if (dli_main.dli_fbase != dli.dli_fbase) {
4897 fname = dli.dli_fname;
4898 p = strrchr(fname, '/');
4899 if (p++)
4900 fname = p;
4901 p = strchr(fname, '.');
4902 if (!p)
4903 p = fname + strlen(fname);
4904
4905 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4906 }
4907
4908 /* 2. symbol name */
4909 if (dli.dli_sname) {
4910 /* known, dump it and return symbol's address (exact or relative) */
4911 chunk_appendf(buf, "%s", dli.dli_sname);
4912 if (addr != dli.dli_saddr) {
4913 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004914 if (size)
4915 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004916 }
4917 return dli.dli_saddr;
4918 }
4919 else if (dli_main.dli_fbase != dli.dli_fbase) {
4920 /* unresolved symbol from a known library, report relative offset */
4921 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4922 return NULL;
4923 }
Baruch Siache1651b22020-07-24 07:52:20 +03004924#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004925 unknown:
4926 /* unresolved symbol from the main file, report relative offset to main */
4927 if ((void*)addr < (void*)main)
4928 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4929 else
4930 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4931 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004932}
4933
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004934/*
4935 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004936 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004937 *
4938 * First, initializes the value with <sz> as address to 0 and initializes the
4939 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4940 * address updating <sz> pointed value to the size of this array.
4941 *
4942 * Returns 1 if succeeded, 0 if not.
4943 */
4944int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4945{
4946 unsigned int *n;
4947 const char *s, *end;
4948
4949 s = str;
4950 *sz = 0;
4951 end = str + strlen(str);
4952 *nums = n = NULL;
4953
4954 while (1) {
4955 unsigned int r;
4956
4957 if (s >= end)
4958 break;
4959
4960 r = read_uint(&s, end);
4961 /* Expected characters after having read an uint: '\0' or '.',
4962 * if '.', must not be terminal.
4963 */
Christopher Faulet4b524122021-02-11 10:42:41 +01004964 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4965 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004966 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01004967 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004968
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004969 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004970 if (!n)
4971 return 0;
4972
4973 n[(*sz)++] = r;
4974 }
4975 *nums = n;
4976
4977 return 1;
4978}
4979
Willy Tarreau4d589e72019-08-23 19:02:26 +02004980
4981/* returns the number of bytes needed to encode <v> as a varint. An inline
4982 * version exists for use with constants (__varint_bytes()).
4983 */
4984int varint_bytes(uint64_t v)
4985{
4986 int len = 1;
4987
4988 if (v >= 240) {
4989 v = (v - 240) >> 4;
4990 while (1) {
4991 len++;
4992 if (v < 128)
4993 break;
4994 v = (v - 128) >> 7;
4995 }
4996 }
4997 return len;
4998}
4999
Willy Tarreau52bf8392020-03-08 00:42:37 +01005000
5001/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005002static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005003
5004/* This is a thread-safe implementation of xoroshiro128** described below:
5005 * http://prng.di.unimi.it/
5006 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5007 * supports fast jumps and passes all common quality tests. It is thread-safe,
5008 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5009 * local lock on other ones.
5010 */
5011uint64_t ha_random64()
5012{
5013 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01005014 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5015 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005016
5017#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5018 static HA_SPINLOCK_T rand_lock;
5019
5020 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5021#endif
5022
5023 old[0] = ha_random_state[0];
5024 old[1] = ha_random_state[1];
5025
5026#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5027 do {
5028#endif
5029 result = rotl64(old[0] * 5, 7) * 9;
5030 new[1] = old[0] ^ old[1];
5031 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5032 new[1] = rotl64(new[1], 37); // c
5033
5034#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5035 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5036#else
5037 ha_random_state[0] = new[0];
5038 ha_random_state[1] = new[1];
5039#if defined(USE_THREAD)
5040 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5041#endif
5042#endif
5043 return result;
5044}
5045
5046/* seeds the random state using up to <len> bytes from <seed>, starting with
5047 * the first non-zero byte.
5048 */
5049void ha_random_seed(const unsigned char *seed, size_t len)
5050{
5051 size_t pos;
5052
5053 /* the seed must not be all zeroes, so we pre-fill it with alternating
5054 * bits and overwrite part of them with the block starting at the first
5055 * non-zero byte from the seed.
5056 */
5057 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5058
5059 for (pos = 0; pos < len; pos++)
5060 if (seed[pos] != 0)
5061 break;
5062
5063 if (pos == len)
5064 return;
5065
5066 seed += pos;
5067 len -= pos;
5068
5069 if (len > sizeof(ha_random_state))
5070 len = sizeof(ha_random_state);
5071
5072 memcpy(ha_random_state, seed, len);
5073}
5074
5075/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5076 * and is equivalent to calling ha_random64() as many times. It is used to
5077 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5078 * different generators (i.e. different processes after a fork). The <dist>
5079 * argument is the distance to jump to and is used in a loop so it rather not
5080 * be too large if the processing time is a concern.
5081 *
5082 * BEWARE: this function is NOT thread-safe and must not be called during
5083 * concurrent accesses to ha_random64().
5084 */
5085void ha_random_jump96(uint32_t dist)
5086{
5087 while (dist--) {
5088 uint64_t s0 = 0;
5089 uint64_t s1 = 0;
5090 int b;
5091
5092 for (b = 0; b < 64; b++) {
5093 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5094 s0 ^= ha_random_state[0];
5095 s1 ^= ha_random_state[1];
5096 }
5097 ha_random64();
5098 }
5099
5100 for (b = 0; b < 64; b++) {
5101 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5102 s0 ^= ha_random_state[0];
5103 s1 ^= ha_random_state[1];
5104 }
5105 ha_random64();
5106 }
5107 ha_random_state[0] = s0;
5108 ha_random_state[1] = s1;
5109 }
5110}
5111
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005112/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5113 * bytes large.
5114 */
5115void ha_generate_uuid(struct buffer *output)
5116{
5117 uint32_t rnd[4];
5118 uint64_t last;
5119
5120 last = ha_random64();
5121 rnd[0] = last;
5122 rnd[1] = last >> 32;
5123
5124 last = ha_random64();
5125 rnd[2] = last;
5126 rnd[3] = last >> 32;
5127
5128 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5129 rnd[0],
5130 rnd[1] & 0xFFFF,
5131 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5132 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5133 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5134}
5135
5136
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005137/* only used by parse_line() below. It supports writing in place provided that
5138 * <in> is updated to the next location before calling it. In that case, the
5139 * char at <in> may be overwritten.
5140 */
5141#define EMIT_CHAR(x) \
5142 do { \
5143 char __c = (char)(x); \
5144 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5145 err |= PARSE_ERR_OVERLAP; \
5146 if (outpos >= outmax) \
5147 err |= PARSE_ERR_TOOLARGE; \
5148 if (!err) \
5149 out[outpos] = __c; \
5150 outpos++; \
5151 } while (0)
5152
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005153/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005154 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5155 * extraneous ones are not emitted but <outlen> is updated so that the caller
5156 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5157 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005158 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5159 * it is guaranteed that at least one arg will point to the zero. It is safe
5160 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005161 *
5162 * <out> may overlap with <in> provided that it never goes further, in which
5163 * case the parser will accept to perform in-place parsing and unquoting/
5164 * unescaping but only if environment variables do not lead to expansion that
5165 * causes overlapping, otherwise the input string being destroyed, the error
5166 * will not be recoverable. Note that even during out-of-place <in> will
5167 * experience temporary modifications in-place for variable resolution and must
5168 * be writable, and will also receive zeroes to delimit words when using
5169 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5170 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5171 * starting point of the first invalid character sequence or unmatched
5172 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5173 * error reporting might be difficult since zeroes will have been inserted into
5174 * the string. One solution for the caller may consist in replacing all args
5175 * delimiters with spaces in this case.
5176 */
5177uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
5178{
5179 char *quote = NULL;
5180 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005181 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005182 unsigned char hex1, hex2;
5183 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005184 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005185 size_t outpos = 0;
5186 int squote = 0;
5187 int dquote = 0;
5188 int arg = 0;
5189 uint32_t err = 0;
5190
5191 *nbargs = 0;
5192 *outlen = 0;
5193
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005194 /* argsmax may be -1 here, protecting args[] from any write */
5195 if (arg < argsmax)
5196 args[arg] = out;
5197
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005198 while (1) {
5199 if (*in >= '-' && *in != '\\') {
5200 /* speedup: directly send all regular chars starting
5201 * with '-', '.', '/', alnum etc...
5202 */
5203 EMIT_CHAR(*in++);
5204 continue;
5205 }
5206 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5207 /* end of line */
5208 break;
5209 }
5210 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5211 /* comment */
5212 break;
5213 }
5214 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5215 if (dquote) {
5216 dquote = 0;
5217 quote = NULL;
5218 }
5219 else {
5220 dquote = 1;
5221 quote = in;
5222 }
5223 in++;
5224 continue;
5225 }
5226 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5227 if (squote) {
5228 squote = 0;
5229 quote = NULL;
5230 }
5231 else {
5232 squote = 1;
5233 quote = in;
5234 }
5235 in++;
5236 continue;
5237 }
5238 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5239 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5240 * C equivalent value but only when they have a special meaning and within
5241 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5242 */
5243 char tosend = *in;
5244
5245 switch (in[1]) {
5246 case ' ':
5247 case '\\':
5248 tosend = in[1];
5249 in++;
5250 break;
5251
5252 case 't':
5253 tosend = '\t';
5254 in++;
5255 break;
5256
5257 case 'n':
5258 tosend = '\n';
5259 in++;
5260 break;
5261
5262 case 'r':
5263 tosend = '\r';
5264 in++;
5265 break;
5266
5267 case '#':
5268 /* escaping of "#" only if comments are supported */
5269 if (opts & PARSE_OPT_SHARP)
5270 in++;
5271 tosend = *in;
5272 break;
5273
5274 case '\'':
5275 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5276 if (opts & PARSE_OPT_SQUOTE && !squote)
5277 in++;
5278 tosend = *in;
5279 break;
5280
5281 case '"':
5282 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5283 if (opts & PARSE_OPT_DQUOTE && !squote)
5284 in++;
5285 tosend = *in;
5286 break;
5287
5288 case '$':
5289 /* escaping of '$' only inside double quotes and only if env supported */
5290 if (opts & PARSE_OPT_ENV && dquote)
5291 in++;
5292 tosend = *in;
5293 break;
5294
5295 case 'x':
5296 if (!ishex(in[2]) || !ishex(in[3])) {
5297 /* invalid or incomplete hex sequence */
5298 err |= PARSE_ERR_HEX;
5299 if (errptr)
5300 *errptr = in;
5301 goto leave;
5302 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005303 hex1 = toupper((unsigned char)in[2]) - '0';
5304 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005305 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5306 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5307 tosend = (hex1 << 4) + hex2;
5308 in += 3;
5309 break;
5310
5311 default:
5312 /* other combinations are not escape sequences */
5313 break;
5314 }
5315
5316 in++;
5317 EMIT_CHAR(tosend);
5318 }
5319 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5320 /* a non-escaped space is an argument separator */
5321 while (isspace((unsigned char)*in))
5322 in++;
5323 EMIT_CHAR(0);
5324 arg++;
5325 if (arg < argsmax)
5326 args[arg] = out + outpos;
5327 else
5328 err |= PARSE_ERR_TOOMANY;
5329 }
5330 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5331 /* environment variables are evaluated anywhere, or only
5332 * inside double quotes if they are supported.
5333 */
5334 char *var_name;
5335 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005336 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005337
5338 in++;
5339
5340 if (*in == '{')
5341 brace = in++;
5342
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005343 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005344 /* unacceptable character in variable name */
5345 err |= PARSE_ERR_VARNAME;
5346 if (errptr)
5347 *errptr = in;
5348 goto leave;
5349 }
5350
5351 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005352 if (*in == '.')
5353 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005354 while (isalnum((unsigned char)*in) || *in == '_')
5355 in++;
5356
5357 save_char = *in;
5358 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005359 if (unlikely(*var_name == '.')) {
5360 /* internal pseudo-variables */
5361 if (strcmp(var_name, ".LINE") == 0)
5362 value = ultoa(global.cfg_curr_line);
5363 else if (strcmp(var_name, ".FILE") == 0)
5364 value = global.cfg_curr_file;
5365 else if (strcmp(var_name, ".SECTION") == 0)
5366 value = global.cfg_curr_section;
5367 else {
5368 /* unsupported internal variable name */
5369 err |= PARSE_ERR_VARNAME;
5370 if (errptr)
5371 *errptr = var_name;
5372 goto leave;
5373 }
5374 } else {
5375 value = getenv(var_name);
5376 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005377 *in = save_char;
5378
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005379 /* support for '[*]' sequence to force word expansion,
5380 * only available inside braces */
5381 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5382 word_expand = in++;
5383
5384 if (*in++ != '*' || *in++ != ']') {
5385 err |= PARSE_ERR_WRONG_EXPAND;
5386 if (errptr)
5387 *errptr = word_expand;
5388 goto leave;
5389 }
5390 }
5391
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005392 if (brace) {
5393 if (*in != '}') {
5394 /* unmatched brace */
5395 err |= PARSE_ERR_BRACE;
5396 if (errptr)
5397 *errptr = brace;
5398 goto leave;
5399 }
5400 in++;
5401 brace = NULL;
5402 }
5403
5404 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005405 while (*value) {
5406 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005407 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005408 EMIT_CHAR(0);
5409 ++arg;
5410 if (arg < argsmax)
5411 args[arg] = out + outpos;
5412 else
5413 err |= PARSE_ERR_TOOMANY;
5414
5415 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005416 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005417 ;
5418 } else {
5419 EMIT_CHAR(*value++);
5420 }
5421 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005422 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005423 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005424 }
5425 else {
5426 /* any other regular char */
5427 EMIT_CHAR(*in++);
5428 }
5429 }
5430
5431 /* end of output string */
5432 EMIT_CHAR(0);
5433 arg++;
5434
5435 if (quote) {
5436 /* unmatched quote */
5437 err |= PARSE_ERR_QUOTE;
5438 if (errptr)
5439 *errptr = quote;
5440 goto leave;
5441 }
5442 leave:
5443 *nbargs = arg;
5444 *outlen = outpos;
5445
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005446 /* empty all trailing args by making them point to the trailing zero,
5447 * at least the last one in any case.
5448 */
5449 if (arg > argsmax)
5450 arg = argsmax;
5451
5452 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005453 args[arg++] = out + outpos - 1;
5454
5455 return err;
5456}
5457#undef EMIT_CHAR
5458
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005459/* This is used to sanitize an input line that's about to be used for error reporting.
5460 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5461 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5462 * If non-printable chars are present in the output. It returns the new offset <pos>
5463 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5464 * be at least 6 to support two "..." otherwise the result is undefined. The line
5465 * itself must have at least 7 chars allocated for the same reason.
5466 */
5467size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5468{
5469 size_t shift = 0;
5470 char *out = line;
5471 char *in = line;
5472 char *end = line + width;
5473
5474 if (pos >= width) {
5475 /* if we have to shift, we'll be out of context, so let's
5476 * try to put <pos> at the center of width.
5477 */
5478 shift = pos - width / 2;
5479 in += shift + 3;
5480 end = out + width - 3;
5481 out[0] = out[1] = out[2] = '.';
5482 out += 3;
5483 }
5484
5485 while (out < end && *in) {
5486 if (isspace((unsigned char)*in))
5487 *out++ = ' ';
5488 else if (isprint((unsigned char)*in))
5489 *out++ = *in;
5490 else
5491 *out++ = '?';
5492 in++;
5493 }
5494
5495 if (end < line + width) {
5496 out[0] = out[1] = out[2] = '.';
5497 out += 3;
5498 }
5499
5500 *out++ = 0;
5501 return pos - shift;
5502}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005503
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005504/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005505 * transitions between characters. <fp> is a 1024-entries array indexed as
5506 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005507 * 1..26=letter, 27=digit, 28=other/begin/end.
5508 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005509 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005510void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005511{
5512 const char *p;
5513 int from, to;
5514 int c;
5515
Willy Tarreauba2c4452021-03-12 09:01:52 +01005516 from = 28; // begin
5517 for (p = word; *p; p++) {
5518 c = tolower(*p);
5519 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005520 case 'a'...'z': to = c - 'a' + 1; break;
5521 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5522 case '0'...'9': to = 27; break;
5523 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005524 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005525 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005526 fp[32 * from + to]++;
5527 from = to;
5528 }
5529 to = 28; // end
5530 fp[32 * from + to]++;
5531}
5532
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005533/* Initialize array <fp> with the fingerprint of word <word> by counting the
5534 * transitions between characters. <fp> is a 1024-entries array indexed as
5535 * 32*from+to. Positions for 'from' and 'to' are:
5536 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5537 */
5538void make_word_fingerprint(uint8_t *fp, const char *word)
5539{
5540 memset(fp, 0, 1024);
5541 update_word_fingerprint(fp, word);
5542}
5543
Willy Tarreauba2c4452021-03-12 09:01:52 +01005544/* Return the distance between two word fingerprints created by function
5545 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005546 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005547 */
5548int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5549{
5550 int i, k, dist = 0;
5551
5552 for (i = 0; i < 1024; i++) {
5553 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005554 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005555 }
5556 return dist;
5557}
5558
Willy Tarreau06e69b52021-03-02 14:01:35 +01005559static int init_tools_per_thread()
5560{
5561 /* Let's make each thread start from a different position */
5562 statistical_prng_state += tid * MAX_THREADS;
5563 if (!statistical_prng_state)
5564 statistical_prng_state++;
5565 return 1;
5566}
5567REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005568
Willy Tarreaubaaee002006-06-26 02:48:02 +02005569/*
5570 * Local variables:
5571 * c-indent-level: 8
5572 * c-basic-offset: 8
5573 * End:
5574 */