blob: 718bb49b8fa10c4b8b2bb33755b0d4894b25043d [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 Tarreauae03d262021-05-08 07:35:00 +0200571/*
572 * This function simply returns a locally allocated string containing
573 * the ascii representation for number 'n' in decimal with useless trailing
574 * zeroes trimmed.
575 */
576char *ftoa_r(double n, char *buffer, int size)
577{
578 flt_trim(buffer, 0, snprintf(buffer, size, "%f", n));
579 return buffer;
580}
581
Willy Tarreau588297f2014-06-16 15:16:40 +0200582/* returns a locally allocated string containing the quoted encoding of the
583 * input string. The output may be truncated to QSTR_SIZE chars, but it is
584 * guaranteed that the string will always be properly terminated. Quotes are
585 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
586 * always be at least 4 chars.
587 */
588const char *qstr(const char *str)
589{
590 char *ret = quoted_str[quoted_idx];
591 char *p, *end;
592
593 if (++quoted_idx >= NB_QSTR)
594 quoted_idx = 0;
595
596 p = ret;
597 end = ret + QSTR_SIZE;
598
599 *p++ = '"';
600
601 /* always keep 3 chars to support passing "" and the ending " */
602 while (*str && p < end - 3) {
603 if (*str == '"') {
604 *p++ = '"';
605 *p++ = '"';
606 }
607 else
608 *p++ = *str;
609 str++;
610 }
611 *p++ = '"';
612 return ret;
613}
614
Robert Tsai81ae1952007-12-05 10:47:29 +0100615/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200616 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
617 *
618 * It looks like this one would be a good candidate for inlining, but this is
619 * not interesting because it around 35 bytes long and often called multiple
620 * times within the same function.
621 */
622int ishex(char s)
623{
624 s -= '0';
625 if ((unsigned char)s <= 9)
626 return 1;
627 s -= 'A' - '0';
628 if ((unsigned char)s <= 5)
629 return 1;
630 s -= 'a' - 'A';
631 if ((unsigned char)s <= 5)
632 return 1;
633 return 0;
634}
635
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100636/* rounds <i> down to the closest value having max 2 digits */
637unsigned int round_2dig(unsigned int i)
638{
639 unsigned int mul = 1;
640
641 while (i >= 100) {
642 i /= 10;
643 mul *= 10;
644 }
645 return i * mul;
646}
647
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100648/*
649 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
650 * invalid character is found, a pointer to it is returned. If everything is
651 * fine, NULL is returned.
652 */
653const char *invalid_char(const char *name)
654{
655 if (!*name)
656 return name;
657
658 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100659 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100660 *name != '_' && *name != '-')
661 return name;
662 name++;
663 }
664 return NULL;
665}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200666
667/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200668 * Checks <name> for invalid characters. Valid chars are [_.-] and those
669 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200670 * If an invalid character is found, a pointer to it is returned.
671 * If everything is fine, NULL is returned.
672 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200673static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200674
675 if (!*name)
676 return name;
677
678 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100679 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200680 *name != '_' && *name != '-')
681 return name;
682
683 name++;
684 }
685
686 return NULL;
687}
688
689/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200690 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
691 * If an invalid character is found, a pointer to it is returned.
692 * If everything is fine, NULL is returned.
693 */
694const char *invalid_domainchar(const char *name) {
695 return __invalid_char(name, isalnum);
696}
697
698/*
699 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
700 * If an invalid character is found, a pointer to it is returned.
701 * If everything is fine, NULL is returned.
702 */
703const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200704 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200705}
706
707/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100708 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100709 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
710 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
711 * the function tries to guess the address family from the syntax. If the
712 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100713 * string is assumed to contain only an address, no port. The address can be a
714 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
715 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
716 * The return address will only have the address family and the address set,
717 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100718 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
719 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100720 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200721 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100722struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200723{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100724 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100725 /* max IPv6 length, including brackets and terminating NULL */
726 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100727 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100728
729 /* check IPv6 with square brackets */
730 if (str[0] == '[') {
731 size_t iplength = strlen(str);
732
733 if (iplength < 4) {
734 /* minimal size is 4 when using brackets "[::]" */
735 goto fail;
736 }
737 else if (iplength >= sizeof(tmpip)) {
738 /* IPv6 literal can not be larger than tmpip */
739 goto fail;
740 }
741 else {
742 if (str[iplength - 1] != ']') {
743 /* if address started with bracket, it should end with bracket */
744 goto fail;
745 }
746 else {
747 memcpy(tmpip, str + 1, iplength - 2);
748 tmpip[iplength - 2] = '\0';
749 str = tmpip;
750 }
751 }
752 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100753
Willy Tarreaufab5a432011-03-04 15:31:53 +0100754 /* Any IPv6 address */
755 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100756 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
757 sa->ss_family = AF_INET6;
758 else if (sa->ss_family != AF_INET6)
759 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100760 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100761 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100762 }
763
Willy Tarreau24709282013-03-10 21:32:12 +0100764 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100765 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100766 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
767 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100768 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100769 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100770 }
771
772 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100773 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
774 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100775 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100776 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100777 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100778 }
779
780 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100781 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
782 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100783 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100784 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100785 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100786 }
787
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100788 if (!resolve)
789 return NULL;
790
Emeric Brund30e9a12020-12-23 18:49:16 +0100791 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200792 return NULL;
793
David du Colombierd5f43282011-03-17 10:40:16 +0100794#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200795 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100796 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100797 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100798
799 memset(&result, 0, sizeof(result));
800 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100801 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100802 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200803 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100804 hints.ai_protocol = 0;
805
806 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100807 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
808 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100809 else if (sa->ss_family != result->ai_family) {
810 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100811 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100812 }
Willy Tarreau24709282013-03-10 21:32:12 +0100813
David du Colombierd5f43282011-03-17 10:40:16 +0100814 switch (result->ai_family) {
815 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100816 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100817 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100818 success = 1;
819 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100820 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100821 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100822 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100823 success = 1;
824 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100825 }
826 }
827
Sean Carey58ea0392013-02-15 23:39:18 +0100828 if (result)
829 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100830
831 if (success)
832 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100833 }
David du Colombierd5f43282011-03-17 10:40:16 +0100834#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200835 /* try to resolve an IPv4/IPv6 hostname */
836 he = gethostbyname(str);
837 if (he) {
838 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
839 sa->ss_family = he->h_addrtype;
840 else if (sa->ss_family != he->h_addrtype)
841 goto fail;
842
843 switch (sa->ss_family) {
844 case AF_INET:
845 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100846 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200847 return sa;
848 case AF_INET6:
849 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100850 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200851 return sa;
852 }
853 }
854
David du Colombierd5f43282011-03-17 10:40:16 +0100855 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100856 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100857 return NULL;
858}
859
860/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100861 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
862 * range or offset consisting in two integers that the caller will have to
863 * check to find the relevant input format. The following format are supported :
864 *
865 * String format | address | port | low | high
866 * addr | <addr> | 0 | 0 | 0
867 * addr: | <addr> | 0 | 0 | 0
868 * addr:port | <addr> | <port> | <port> | <port>
869 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
870 * addr:+port | <addr> | <port> | 0 | <port>
871 * addr:-port | <addr> |-<port> | <port> | 0
872 *
873 * The detection of a port range or increment by the caller is made by
874 * comparing <low> and <high>. If both are equal, then port 0 means no port
875 * was specified. The caller may pass NULL for <low> and <high> if it is not
876 * interested in retrieving port ranges.
877 *
878 * Note that <addr> above may also be :
879 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
880 * - "*" => family will be AF_INET and address will be INADDR_ANY
881 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
882 * - a host name => family and address will depend on host name resolving.
883 *
Willy Tarreau24709282013-03-10 21:32:12 +0100884 * A prefix may be passed in before the address above to force the family :
885 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
886 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
887 * - "unix@" => force address to be a path to a UNIX socket even if the
888 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200889 * - 'abns@' -> force address to belong to the abstract namespace (Linux
890 * only). These sockets are just like Unix sockets but without
891 * the need for an underlying file system. The address is a
892 * string. Technically it's like a Unix socket with a zero in
893 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100894 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100895 *
mildisff5d5102015-10-26 18:50:08 +0100896 * IPv6 addresses can be declared with or without square brackets. When using
897 * square brackets for IPv6 addresses, the port separator (colon) is optional.
898 * If not using square brackets, and in order to avoid any ambiguity with
899 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
900 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
901 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100902 *
903 * If <pfx> is non-null, it is used as a string prefix before any path-based
904 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100905 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200906 * if <fqdn> is non-null, it will be filled with :
907 * - a pointer to the FQDN of the server name to resolve if there's one, and
908 * that the caller will have to free(),
909 * - NULL if there was an explicit address that doesn't require resolution.
910 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200911 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
912 * still honored so it is possible for the caller to know whether a resolution
913 * failed by clearing this flag and checking if <fqdn> was filled, indicating
914 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200915 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100916 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200917 * the address when cast to sockaddr_in and the address family is
918 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200919 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200920 * The matching protocol will be set into <proto> if non-null.
921 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200922 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
923 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100924 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200925struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
926 struct protocol **proto, char **err,
927 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100928{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100929 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100930 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200931 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100932 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100933 char *port1, *port2;
934 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200935 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200936 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200937 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100938
939 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200940 if (fqdn)
941 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200942
Willy Tarreaudad36a32013-03-11 01:20:04 +0100943 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100944 if (str2 == NULL) {
945 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100946 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100947 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200948
Willy Tarreau9f69f462015-09-08 16:01:25 +0200949 if (!*str2) {
950 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
951 goto out;
952 }
953
Willy Tarreau24709282013-03-10 21:32:12 +0100954 memset(&ss, 0, sizeof(ss));
955
Willy Tarreaue835bd82020-09-16 11:35:47 +0200956 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100957 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
958 ((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 +0200959 sock_type = ctrl_type = SOCK_DGRAM;
960 else
961 sock_type = ctrl_type = SOCK_STREAM;
962
963 if (strncmp(str2, "stream+", 7) == 0) {
964 str2 += 7;
965 sock_type = ctrl_type = SOCK_STREAM;
966 }
967 else if (strncmp(str2, "dgram+", 6) == 0) {
968 str2 += 6;
969 sock_type = ctrl_type = SOCK_DGRAM;
970 }
971
Willy Tarreau24709282013-03-10 21:32:12 +0100972 if (strncmp(str2, "unix@", 5) == 0) {
973 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200974 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100975 ss.ss_family = AF_UNIX;
976 }
Emeric Brunce325c42021-04-02 17:05:09 +0200977 else if (strncmp(str2, "uxdg@", 5) == 0) {
978 str2 += 5;
979 abstract = 0;
980 ss.ss_family = AF_UNIX;
981 sock_type = ctrl_type = SOCK_DGRAM;
982 }
983 else if (strncmp(str2, "uxst@", 5) == 0) {
984 str2 += 5;
985 abstract = 0;
986 ss.ss_family = AF_UNIX;
987 sock_type = ctrl_type = SOCK_STREAM;
988 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200989 else if (strncmp(str2, "abns@", 5) == 0) {
990 str2 += 5;
991 abstract = 1;
992 ss.ss_family = AF_UNIX;
993 }
Emeric Brunce325c42021-04-02 17:05:09 +0200994 else if (strncmp(str2, "ip@", 3) == 0) {
995 str2 += 3;
996 ss.ss_family = AF_UNSPEC;
997 }
Willy Tarreau24709282013-03-10 21:32:12 +0100998 else if (strncmp(str2, "ipv4@", 5) == 0) {
999 str2 += 5;
1000 ss.ss_family = AF_INET;
1001 }
1002 else if (strncmp(str2, "ipv6@", 5) == 0) {
1003 str2 += 5;
1004 ss.ss_family = AF_INET6;
1005 }
Emeric Brunce325c42021-04-02 17:05:09 +02001006 else if (strncmp(str2, "tcp4@", 5) == 0) {
1007 str2 += 5;
1008 ss.ss_family = AF_INET;
1009 sock_type = ctrl_type = SOCK_STREAM;
1010 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001011 else if (strncmp(str2, "udp4@", 5) == 0) {
1012 str2 += 5;
1013 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001014 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001015 }
Emeric Brunce325c42021-04-02 17:05:09 +02001016 else if (strncmp(str2, "tcp6@", 5) == 0) {
1017 str2 += 5;
1018 ss.ss_family = AF_INET6;
1019 sock_type = ctrl_type = SOCK_STREAM;
1020 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001021 else if (strncmp(str2, "udp6@", 5) == 0) {
1022 str2 += 5;
1023 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001024 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001025 }
Emeric Brunce325c42021-04-02 17:05:09 +02001026 else if (strncmp(str2, "tcp@", 4) == 0) {
1027 str2 += 4;
1028 ss.ss_family = AF_UNSPEC;
1029 sock_type = ctrl_type = SOCK_STREAM;
1030 }
Emeric Brun3835c0d2020-07-07 09:46:09 +02001031 else if (strncmp(str2, "udp@", 4) == 0) {
1032 str2 += 4;
1033 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +02001034 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +02001035 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +01001036 else if (strncmp(str2, "quic4@", 6) == 0) {
1037 str2 += 6;
1038 ss.ss_family = AF_INET;
1039 sock_type = SOCK_DGRAM;
1040 ctrl_type = SOCK_STREAM;
1041 }
1042 else if (strncmp(str2, "quic6@", 6) == 0) {
1043 str2 += 6;
1044 ss.ss_family = AF_INET6;
1045 sock_type = SOCK_DGRAM;
1046 ctrl_type = SOCK_STREAM;
1047 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001048 else if (strncmp(str2, "fd@", 3) == 0) {
1049 str2 += 3;
1050 ss.ss_family = AF_CUST_EXISTING_FD;
1051 }
1052 else if (strncmp(str2, "sockpair@", 9) == 0) {
1053 str2 += 9;
1054 ss.ss_family = AF_CUST_SOCKPAIR;
1055 }
Willy Tarreau24709282013-03-10 21:32:12 +01001056 else if (*str2 == '/') {
1057 ss.ss_family = AF_UNIX;
1058 }
1059 else
1060 ss.ss_family = AF_UNSPEC;
1061
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001062 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001063 struct sockaddr_storage ss2;
1064 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001065 char *endptr;
1066
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001067 new_fd = strtol(str2, &endptr, 10);
1068 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001069 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1070 goto out;
1071 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001072
Willy Tarreaua215be22020-09-16 10:14:16 +02001073 /* just verify that it's a socket */
1074 addr_len = sizeof(ss2);
1075 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1076 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1077 goto out;
1078 }
1079
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001080 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1081 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001082 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001083 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001084 char *endptr;
1085
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001086 new_fd = strtol(str2, &endptr, 10);
1087 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001088 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001089 goto out;
1090 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001091
Willy Tarreau6edc7222020-09-15 17:41:56 +02001092 if (opts & PA_O_SOCKET_FD) {
1093 socklen_t addr_len;
1094 int type;
1095
1096 addr_len = sizeof(ss);
1097 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1098 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1099 goto out;
1100 }
1101
1102 addr_len = sizeof(type);
1103 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001104 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001105 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1106 goto out;
1107 }
1108
1109 porta = portl = porth = get_host_port(&ss);
1110 } else if (opts & PA_O_RAW_FD) {
1111 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1112 ((struct sockaddr_in *)&ss)->sin_port = 0;
1113 } else {
1114 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1115 goto out;
1116 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001117 }
1118 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001119 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001120 int prefix_path_len;
1121 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001122 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001123
1124 /* complete unix socket path name during startup or soft-restart is
1125 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1126 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001127 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001128 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001129 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001130
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001131 adr_len = strlen(str2);
1132 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001133 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1134 goto out;
1135 }
1136
Willy Tarreauccfccef2014-05-10 01:49:15 +02001137 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001138 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001139 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001140 memcpy(un->sun_path, pfx, prefix_path_len);
1141 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001142 }
Willy Tarreau24709282013-03-10 21:32:12 +01001143 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001144 char *end = str2 + strlen(str2);
1145 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001146
mildisff5d5102015-10-26 18:50:08 +01001147 /* search for : or ] whatever comes first */
1148 for (chr = end-1; chr > str2; chr--) {
1149 if (*chr == ']' || *chr == ':')
1150 break;
1151 }
1152
1153 if (*chr == ':') {
1154 /* Found a colon before a closing-bracket, must be a port separator.
1155 * This guarantee backward compatibility.
1156 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001157 if (!(opts & PA_O_PORT_OK)) {
1158 memprintf(err, "port specification not permitted here in '%s'", str);
1159 goto out;
1160 }
mildisff5d5102015-10-26 18:50:08 +01001161 *chr++ = '\0';
1162 port1 = chr;
1163 }
1164 else {
1165 /* Either no colon and no closing-bracket
1166 * or directly ending with a closing-bracket.
1167 * However, no port.
1168 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001169 if (opts & PA_O_PORT_MAND) {
1170 memprintf(err, "missing port specification in '%s'", str);
1171 goto out;
1172 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001173 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001174 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001175
Willy Tarreau90807112020-02-25 08:16:33 +01001176 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001177 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001178 if (port2) {
1179 if (!(opts & PA_O_PORT_RANGE)) {
1180 memprintf(err, "port range not permitted here in '%s'", str);
1181 goto out;
1182 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001183 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001184 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001185 else
1186 port2 = port1;
1187 portl = atoi(port1);
1188 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001189
1190 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1191 memprintf(err, "invalid port '%s'", port1);
1192 goto out;
1193 }
1194
1195 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1196 memprintf(err, "invalid port '%s'", port2);
1197 goto out;
1198 }
1199
1200 if (portl > porth) {
1201 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1202 goto out;
1203 }
1204
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001205 porta = portl;
1206 }
1207 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001208 if (!(opts & PA_O_PORT_OFS)) {
1209 memprintf(err, "port offset not permitted here in '%s'", str);
1210 goto out;
1211 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001212 portl = atoi(port1 + 1);
1213 porta = -portl;
1214 }
1215 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001216 if (!(opts & PA_O_PORT_OFS)) {
1217 memprintf(err, "port offset not permitted here in '%s'", str);
1218 goto out;
1219 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001220 porth = atoi(port1 + 1);
1221 porta = porth;
1222 }
1223 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001224 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001225 goto out;
1226 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001227 else if (opts & PA_O_PORT_MAND) {
1228 memprintf(err, "missing port specification in '%s'", str);
1229 goto out;
1230 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001231
1232 /* first try to parse the IP without resolving. If it fails, it
1233 * tells us we need to keep a copy of the FQDN to resolve later
1234 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001235 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001236 */
1237 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001238 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1239 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001240 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1241 goto out;
1242 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001243
Willy Tarreauceccdd72016-11-02 22:27:10 +01001244 if (fqdn) {
1245 if (str2 != back)
1246 memmove(back, str2, strlen(str2) + 1);
1247 *fqdn = back;
1248 back = NULL;
1249 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001250 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001251 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001252 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001253
Willy Tarreaue835bd82020-09-16 11:35:47 +02001254 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1255 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1256 goto out;
1257 }
1258 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1259 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1260 goto out;
1261 }
1262
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001263 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001264 /* Note: if the caller asks for a proto, we must find one,
Emeric Brun26754902021-04-07 14:26:44 +02001265 * except if we inherit from a raw FD (family == AF_CUST_EXISTING_FD)
1266 * orif we return with an fqdn that will resolve later,
Willy Tarreau5fc93282020-09-16 18:25:03 +02001267 * in which case the address is not known yet (this is only
1268 * for servers actually).
1269 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001270 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001271 sock_type == SOCK_DGRAM,
1272 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001273
Emeric Brun26754902021-04-07 14:26:44 +02001274 if (!new_proto && (!fqdn || !*fqdn) && (ss.ss_family != AF_CUST_EXISTING_FD)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001275 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1276 goto out;
1277 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001278
1279 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1280 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1281 goto out;
1282 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001283 }
1284
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001285 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001286 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001287 if (port)
1288 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001289 if (low)
1290 *low = portl;
1291 if (high)
1292 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001293 if (fd)
1294 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001295 if (proto)
1296 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001297 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001298 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001299}
1300
Thayne McCombs92149f92020-11-20 01:28:26 -07001301/* converts <addr> and <port> into a string representation of the address and port. This is sort
1302 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1303 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1304 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1305 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1306 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1307 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1308 *
1309 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1310 */
1311char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1312{
1313 char buffer[INET6_ADDRSTRLEN];
1314 char *out = NULL;
1315 const void *ptr;
1316 const char *path;
1317
1318 switch (addr->ss_family) {
1319 case AF_INET:
1320 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1321 break;
1322 case AF_INET6:
1323 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1324 break;
1325 case AF_UNIX:
1326 path = ((struct sockaddr_un *)addr)->sun_path;
1327 if (path[0] == '\0') {
1328 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1329 return memprintf(&out, "abns@%.*s", max_length, path+1);
1330 } else {
1331 return strdup(path);
1332 }
1333 case AF_CUST_SOCKPAIR:
1334 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1335 default:
1336 return NULL;
1337 }
1338 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1339 if (map_ports)
1340 return memprintf(&out, "%s:%+d", buffer, port);
1341 else
1342 return memprintf(&out, "%s:%d", buffer, port);
1343}
1344
1345
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001346/* converts <str> to a struct in_addr containing a network mask. It can be
1347 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001348 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001349 */
1350int str2mask(const char *str, struct in_addr *mask)
1351{
1352 if (strchr(str, '.') != NULL) { /* dotted notation */
1353 if (!inet_pton(AF_INET, str, mask))
1354 return 0;
1355 }
1356 else { /* mask length */
1357 char *err;
1358 unsigned long len = strtol(str, &err, 10);
1359
1360 if (!*str || (err && *err) || (unsigned)len > 32)
1361 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001362
1363 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001364 }
1365 return 1;
1366}
1367
Tim Duesterhus47185172018-01-25 16:24:49 +01001368/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001369 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001370 * if the conversion succeeds otherwise zero.
1371 */
1372int str2mask6(const char *str, struct in6_addr *mask)
1373{
1374 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1375 if (!inet_pton(AF_INET6, str, mask))
1376 return 0;
1377 }
1378 else { /* mask length */
1379 char *err;
1380 unsigned long len = strtol(str, &err, 10);
1381
1382 if (!*str || (err && *err) || (unsigned)len > 128)
1383 return 0;
1384
1385 len2mask6(len, mask);
1386 }
1387 return 1;
1388}
1389
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001390/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1391 * succeeds otherwise zero.
1392 */
1393int cidr2dotted(int cidr, struct in_addr *mask) {
1394
1395 if (cidr < 0 || cidr > 32)
1396 return 0;
1397
1398 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1399 return 1;
1400}
1401
Thierry Fournier70473a52016-02-17 17:12:14 +01001402/* Convert mask from bit length form to in_addr form.
1403 * This function never fails.
1404 */
1405void len2mask4(int len, struct in_addr *addr)
1406{
1407 if (len >= 32) {
1408 addr->s_addr = 0xffffffff;
1409 return;
1410 }
1411 if (len <= 0) {
1412 addr->s_addr = 0x00000000;
1413 return;
1414 }
1415 addr->s_addr = 0xffffffff << (32 - len);
1416 addr->s_addr = htonl(addr->s_addr);
1417}
1418
1419/* Convert mask from bit length form to in6_addr form.
1420 * This function never fails.
1421 */
1422void len2mask6(int len, struct in6_addr *addr)
1423{
1424 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1425 len -= 32;
1426 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1427 len -= 32;
1428 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1429 len -= 32;
1430 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1431}
1432
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001433/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001434 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001435 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001436 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001437 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1438 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001439int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001440{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001441 __label__ out_free, out_err;
1442 char *c, *s;
1443 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001444
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001445 s = strdup(str);
1446 if (!s)
1447 return 0;
1448
Willy Tarreaubaaee002006-06-26 02:48:02 +02001449 memset(mask, 0, sizeof(*mask));
1450 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001451
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001452 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001453 *c++ = '\0';
1454 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001455 if (!str2mask(c, mask))
1456 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001457 }
1458 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001459 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001460 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001461 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001462 struct hostent *he;
1463
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001464 if (!resolve)
1465 goto out_err;
1466
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001467 if ((he = gethostbyname(s)) == NULL) {
1468 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001469 }
1470 else
1471 *addr = *(struct in_addr *) *(he->h_addr_list);
1472 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001473
1474 ret_val = 1;
1475 out_free:
1476 free(s);
1477 return ret_val;
1478 out_err:
1479 ret_val = 0;
1480 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001481}
1482
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001483
1484/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001485 * converts <str> to two struct in6_addr* which must be pre-allocated.
1486 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001487 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001488 * Returns 1 if OK, 0 if error.
1489 */
1490int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1491{
1492 char *c, *s;
1493 int ret_val = 0;
1494 char *err;
1495 unsigned long len = 128;
1496
1497 s = strdup(str);
1498 if (!s)
1499 return 0;
1500
1501 memset(mask, 0, sizeof(*mask));
1502 memset(addr, 0, sizeof(*addr));
1503
1504 if ((c = strrchr(s, '/')) != NULL) {
1505 *c++ = '\0'; /* c points to the mask */
1506 if (!*c)
1507 goto out_free;
1508
1509 len = strtoul(c, &err, 10);
1510 if ((err && *err) || (unsigned)len > 128)
1511 goto out_free;
1512 }
1513 *mask = len; /* OK we have a valid mask in <len> */
1514
1515 if (!inet_pton(AF_INET6, s, addr))
1516 goto out_free;
1517
1518 ret_val = 1;
1519 out_free:
1520 free(s);
1521 return ret_val;
1522}
1523
1524
1525/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001526 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1527 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1528 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001529 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001530int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001531{
1532 int saw_digit, octets, ch;
1533 u_char tmp[4], *tp;
1534 const char *cp = addr;
1535
1536 saw_digit = 0;
1537 octets = 0;
1538 *(tp = tmp) = 0;
1539
1540 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001541 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001542 if (digit > 9 && ch != '.')
1543 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001544 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001545 if (digit <= 9) {
1546 u_int new = *tp * 10 + digit;
1547 if (new > 255)
1548 return 0;
1549 *tp = new;
1550 if (!saw_digit) {
1551 if (++octets > 4)
1552 return 0;
1553 saw_digit = 1;
1554 }
1555 } else if (ch == '.' && saw_digit) {
1556 if (octets == 4)
1557 return 0;
1558 *++tp = 0;
1559 saw_digit = 0;
1560 } else
1561 return 0;
1562 }
1563
1564 if (octets < 4)
1565 return 0;
1566
1567 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001568 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001569}
1570
1571/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001572 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001573 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001574 * the hostname. Actually only http and https are supported. <out> can be NULL.
1575 * This function returns the consumed length. It is useful if you parse complete
1576 * url like http://host:port/path, because the consumed length corresponds to
1577 * the first character of the path. If the conversion fails, it returns -1.
1578 *
1579 * This function tries to resolve the DNS name if haproxy is in starting mode.
1580 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001581 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001582int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001583{
1584 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001585 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001586 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001587 unsigned long long int http_code = 0;
1588 int default_port;
1589 struct hostent *he;
1590 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001591
1592 /* Firstly, try to find :// pattern */
1593 while (curr < url+ulen && url_code != 0x3a2f2f) {
1594 url_code = ((url_code & 0xffff) << 8);
1595 url_code += (unsigned char)*curr++;
1596 }
1597
1598 /* Secondly, if :// pattern is found, verify parsed stuff
1599 * before pattern is matching our http pattern.
1600 * If so parse ip address and port in uri.
1601 *
1602 * WARNING: Current code doesn't support dynamic async dns resolver.
1603 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001604 if (url_code != 0x3a2f2f)
1605 return -1;
1606
1607 /* Copy scheme, and utrn to lower case. */
1608 while (cp < curr - 3)
1609 http_code = (http_code << 8) + *cp++;
1610 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001611
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001612 /* HTTP or HTTPS url matching */
1613 if (http_code == 0x2020202068747470ULL) {
1614 default_port = 80;
1615 if (out)
1616 out->scheme = SCH_HTTP;
1617 }
1618 else if (http_code == 0x2020206874747073ULL) {
1619 default_port = 443;
1620 if (out)
1621 out->scheme = SCH_HTTPS;
1622 }
1623 else
1624 return -1;
1625
1626 /* If the next char is '[', the host address is IPv6. */
1627 if (*curr == '[') {
1628 curr++;
1629
1630 /* Check trash size */
1631 if (trash.size < ulen)
1632 return -1;
1633
1634 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001635 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001636 for (end = curr;
1637 end < url + ulen && *end != ']';
1638 end++, p++)
1639 *p = *end;
1640 if (*end != ']')
1641 return -1;
1642 *p = '\0';
1643
1644 /* Update out. */
1645 if (out) {
1646 out->host = curr;
1647 out->host_len = end - curr;
1648 }
1649
1650 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001651 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001652 return -1;
1653 end++;
1654
1655 /* Decode port. */
1656 if (*end == ':') {
1657 end++;
1658 default_port = read_uint(&end, url + ulen);
1659 }
1660 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1661 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1662 return end - url;
1663 }
1664 else {
1665 /* We are looking for IP address. If you want to parse and
1666 * resolve hostname found in url, you can use str2sa_range(), but
1667 * be warned this can slow down global daemon performances
1668 * while handling lagging dns responses.
1669 */
1670 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1671 if (ret) {
1672 /* Update out. */
1673 if (out) {
1674 out->host = curr;
1675 out->host_len = ret;
1676 }
1677
1678 curr += ret;
1679
1680 /* Decode port. */
1681 if (*curr == ':') {
1682 curr++;
1683 default_port = read_uint(&curr, url + ulen);
1684 }
1685 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1686
1687 /* Set family. */
1688 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1689 return curr - url;
1690 }
1691 else if (global.mode & MODE_STARTING) {
1692 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1693 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001694 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001695
1696 /* look for : or / or end */
1697 for (end = curr;
1698 end < url + ulen && *end != '/' && *end != ':';
1699 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001700 memcpy(trash.area, curr, end - curr);
1701 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001702
1703 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001704 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001705 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001706 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001707
1708 /* Update out. */
1709 if (out) {
1710 out->host = curr;
1711 out->host_len = end - curr;
1712 }
1713
1714 /* Decode port. */
1715 if (*end == ':') {
1716 end++;
1717 default_port = read_uint(&end, url + ulen);
1718 }
1719
1720 /* Copy IP address, set port and family. */
1721 switch (he->h_addrtype) {
1722 case AF_INET:
1723 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1724 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1725 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1726 return end - url;
1727
1728 case AF_INET6:
1729 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1730 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1731 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1732 return end - url;
1733 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001734 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001735 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001736 return -1;
1737}
1738
Willy Tarreau631f01c2011-09-05 00:36:48 +02001739/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1740 * address family is returned so that it's easy for the caller to adapt to the
1741 * output format. Zero is returned if the address family is not supported. -1
1742 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1743 * supported.
1744 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001745int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001746{
1747
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001748 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001749
1750 if (size < 5)
1751 return 0;
1752 *str = '\0';
1753
1754 switch (addr->ss_family) {
1755 case AF_INET:
1756 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1757 break;
1758 case AF_INET6:
1759 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1760 break;
1761 case AF_UNIX:
1762 memcpy(str, "unix", 5);
1763 return addr->ss_family;
1764 default:
1765 return 0;
1766 }
1767
1768 if (inet_ntop(addr->ss_family, ptr, str, size))
1769 return addr->ss_family;
1770
1771 /* failed */
1772 return -1;
1773}
1774
Simon Horman75ab8bd2014-06-16 09:39:41 +09001775/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1776 * address family is returned so that it's easy for the caller to adapt to the
1777 * output format. Zero is returned if the address family is not supported. -1
1778 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1779 * supported.
1780 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001781int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001782{
1783
1784 uint16_t port;
1785
1786
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001787 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001788 return 0;
1789 *str = '\0';
1790
1791 switch (addr->ss_family) {
1792 case AF_INET:
1793 port = ((struct sockaddr_in *)addr)->sin_port;
1794 break;
1795 case AF_INET6:
1796 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1797 break;
1798 case AF_UNIX:
1799 memcpy(str, "unix", 5);
1800 return addr->ss_family;
1801 default:
1802 return 0;
1803 }
1804
1805 snprintf(str, size, "%u", ntohs(port));
1806 return addr->ss_family;
1807}
1808
Willy Tarreau16e01562016-08-09 16:46:18 +02001809/* check if the given address is local to the system or not. It will return
1810 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1811 * it is. We don't want to iterate over all interfaces for this (and it is not
1812 * portable). So instead we try to bind in UDP to this address on a free non
1813 * privileged port and to connect to the same address, port 0 (connect doesn't
1814 * care). If it succeeds, we own the address. Note that non-inet addresses are
1815 * considered local since they're most likely AF_UNIX.
1816 */
1817int addr_is_local(const struct netns_entry *ns,
1818 const struct sockaddr_storage *orig)
1819{
1820 struct sockaddr_storage addr;
1821 int result;
1822 int fd;
1823
1824 if (!is_inet_addr(orig))
1825 return 1;
1826
1827 memcpy(&addr, orig, sizeof(addr));
1828 set_host_port(&addr, 0);
1829
1830 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1831 if (fd < 0)
1832 return -1;
1833
1834 result = -1;
1835 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1836 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1837 result = 0; // fail, non-local address
1838 else
1839 result = 1; // success, local address
1840 }
1841 else {
1842 if (errno == EADDRNOTAVAIL)
1843 result = 0; // definitely not local :-)
1844 }
1845 close(fd);
1846
1847 return result;
1848}
1849
Willy Tarreaubaaee002006-06-26 02:48:02 +02001850/* will try to encode the string <string> replacing all characters tagged in
1851 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1852 * prefixed by <escape>, and will store the result between <start> (included)
1853 * and <stop> (excluded), and will always terminate the string with a '\0'
1854 * before <stop>. The position of the '\0' is returned if the conversion
1855 * completes. If bytes are missing between <start> and <stop>, then the
1856 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1857 * cannot even be stored so we return <start> without writing the 0.
1858 * The input string must also be zero-terminated.
1859 */
1860const char hextab[16] = "0123456789ABCDEF";
1861char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001862 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001863 const char *string)
1864{
1865 if (start < stop) {
1866 stop--; /* reserve one byte for the final '\0' */
1867 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001868 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001869 *start++ = *string;
1870 else {
1871 if (start + 3 >= stop)
1872 break;
1873 *start++ = escape;
1874 *start++ = hextab[(*string >> 4) & 15];
1875 *start++ = hextab[*string & 15];
1876 }
1877 string++;
1878 }
1879 *start = '\0';
1880 }
1881 return start;
1882}
1883
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001884/*
1885 * Same behavior as encode_string() above, except that it encodes chunk
1886 * <chunk> instead of a string.
1887 */
1888char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001889 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001890 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001891{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001892 char *str = chunk->area;
1893 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001894
1895 if (start < stop) {
1896 stop--; /* reserve one byte for the final '\0' */
1897 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001898 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001899 *start++ = *str;
1900 else {
1901 if (start + 3 >= stop)
1902 break;
1903 *start++ = escape;
1904 *start++ = hextab[(*str >> 4) & 15];
1905 *start++ = hextab[*str & 15];
1906 }
1907 str++;
1908 }
1909 *start = '\0';
1910 }
1911 return start;
1912}
1913
Dragan Dosen0edd1092016-02-12 13:23:02 +01001914/*
1915 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001916 * character. The input <string> must be zero-terminated. The result will
1917 * be stored between <start> (included) and <stop> (excluded). This
1918 * function will always try to terminate the resulting string with a '\0'
1919 * before <stop>, and will return its position if the conversion
1920 * completes.
1921 */
1922char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001923 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001924 const char *string)
1925{
1926 if (start < stop) {
1927 stop--; /* reserve one byte for the final '\0' */
1928 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001929 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001930 *start++ = *string;
1931 else {
1932 if (start + 2 >= stop)
1933 break;
1934 *start++ = escape;
1935 *start++ = *string;
1936 }
1937 string++;
1938 }
1939 *start = '\0';
1940 }
1941 return start;
1942}
1943
1944/*
1945 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001946 * character. <chunk> contains the input to be escaped. The result will be
1947 * stored between <start> (included) and <stop> (excluded). The function
1948 * will always try to terminate the resulting string with a '\0' before
1949 * <stop>, and will return its position if the conversion completes.
1950 */
1951char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001952 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001953 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001954{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001955 char *str = chunk->area;
1956 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001957
1958 if (start < stop) {
1959 stop--; /* reserve one byte for the final '\0' */
1960 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001961 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001962 *start++ = *str;
1963 else {
1964 if (start + 2 >= stop)
1965 break;
1966 *start++ = escape;
1967 *start++ = *str;
1968 }
1969 str++;
1970 }
1971 *start = '\0';
1972 }
1973 return start;
1974}
1975
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001976/* Check a string for using it in a CSV output format. If the string contains
1977 * one of the following four char <">, <,>, CR or LF, the string is
1978 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1979 * <str> is the input string to be escaped. The function assumes that
1980 * the input string is null-terminated.
1981 *
1982 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001983 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001984 * format.
1985 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001986 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001987 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001988 * If <quote> is 1, the converter puts the quotes only if any reserved character
1989 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001990 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001991 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001992 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001993 * The function returns the converted string on its output. If an error
1994 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001995 * for using the function directly as printf() argument.
1996 *
1997 * If the output buffer is too short to contain the input string, the result
1998 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001999 *
Willy Tarreaub631c292016-01-08 10:04:08 +01002000 * This function appends the encoding to the existing output chunk, and it
2001 * guarantees that it starts immediately at the first available character of
2002 * the chunk. Please use csv_enc() instead if you want to replace the output
2003 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002004 */
Willy Tarreau83061a82018-07-13 11:56:34 +02002005const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002006{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002007 char *end = output->area + output->size;
2008 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01002009 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002010
Willy Tarreaub631c292016-01-08 10:04:08 +01002011 if (quote == 1) {
2012 /* automatic quoting: first verify if we'll have to quote the string */
2013 if (!strpbrk(str, "\n\r,\""))
2014 quote = 0;
2015 }
2016
2017 if (quote)
2018 *ptr++ = '"';
2019
Willy Tarreau898529b2016-01-06 18:07:04 +01002020 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
2021 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002022 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01002023 ptr++;
2024 if (ptr >= end - 2) {
2025 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002026 break;
2027 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002028 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002029 }
Willy Tarreau898529b2016-01-06 18:07:04 +01002030 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002031 str++;
2032 }
2033
Willy Tarreaub631c292016-01-08 10:04:08 +01002034 if (quote)
2035 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002036
Willy Tarreau898529b2016-01-06 18:07:04 +01002037 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02002038 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01002039 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02002040}
2041
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002042/* Decode an URL-encoded string in-place. The resulting string might
2043 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002044 * aborted, the string is truncated before the issue and a negative value is
2045 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002046 * If the 'in_form' argument is non-nul the string is assumed to be part of
2047 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2048 * turned to a space. If it's zero, this will only be done after a question
2049 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002050 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002051int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002052{
2053 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002054 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002055
2056 in = string;
2057 out = string;
2058 while (*in) {
2059 switch (*in) {
2060 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002061 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002062 break;
2063 case '%' :
2064 if (!ishex(in[1]) || !ishex(in[2]))
2065 goto end;
2066 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2067 in += 2;
2068 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002069 case '?':
2070 in_form = 1;
2071 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002072 default:
2073 *out++ = *in;
2074 break;
2075 }
2076 in++;
2077 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002078 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002079 end:
2080 *out = 0;
2081 return ret;
2082}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002083
Willy Tarreau6911fa42007-03-04 18:06:08 +01002084unsigned int str2ui(const char *s)
2085{
2086 return __str2ui(s);
2087}
2088
2089unsigned int str2uic(const char *s)
2090{
2091 return __str2uic(s);
2092}
2093
2094unsigned int strl2ui(const char *s, int len)
2095{
2096 return __strl2ui(s, len);
2097}
2098
2099unsigned int strl2uic(const char *s, int len)
2100{
2101 return __strl2uic(s, len);
2102}
2103
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002104unsigned int read_uint(const char **s, const char *end)
2105{
2106 return __read_uint(s, end);
2107}
2108
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002109/* This function reads an unsigned integer from the string pointed to by <s> and
2110 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2111 * function automatically stops at <end>. If the number overflows, the 2^64-1
2112 * value is returned.
2113 */
2114unsigned long long int read_uint64(const char **s, const char *end)
2115{
2116 const char *ptr = *s;
2117 unsigned long long int i = 0, tmp;
2118 unsigned int j;
2119
2120 while (ptr < end) {
2121
2122 /* read next char */
2123 j = *ptr - '0';
2124 if (j > 9)
2125 goto read_uint64_end;
2126
2127 /* add char to the number and check overflow. */
2128 tmp = i * 10;
2129 if (tmp / 10 != i) {
2130 i = ULLONG_MAX;
2131 goto read_uint64_eat;
2132 }
2133 if (ULLONG_MAX - tmp < j) {
2134 i = ULLONG_MAX;
2135 goto read_uint64_eat;
2136 }
2137 i = tmp + j;
2138 ptr++;
2139 }
2140read_uint64_eat:
2141 /* eat each numeric char */
2142 while (ptr < end) {
2143 if ((unsigned int)(*ptr - '0') > 9)
2144 break;
2145 ptr++;
2146 }
2147read_uint64_end:
2148 *s = ptr;
2149 return i;
2150}
2151
2152/* This function reads an integer from the string pointed to by <s> and returns
2153 * it. The <s> pointer is adjusted to point to the first unread char. The function
2154 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2155 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2156 * returned.
2157 */
2158long long int read_int64(const char **s, const char *end)
2159{
2160 unsigned long long int i = 0;
2161 int neg = 0;
2162
2163 /* Look for minus char. */
2164 if (**s == '-') {
2165 neg = 1;
2166 (*s)++;
2167 }
2168 else if (**s == '+')
2169 (*s)++;
2170
2171 /* convert as positive number. */
2172 i = read_uint64(s, end);
2173
2174 if (neg) {
2175 if (i > 0x8000000000000000ULL)
2176 return LLONG_MIN;
2177 return -i;
2178 }
2179 if (i > 0x7fffffffffffffffULL)
2180 return LLONG_MAX;
2181 return i;
2182}
2183
Willy Tarreau6911fa42007-03-04 18:06:08 +01002184/* This one is 7 times faster than strtol() on athlon with checks.
2185 * It returns the value of the number composed of all valid digits read,
2186 * and can process negative numbers too.
2187 */
2188int strl2ic(const char *s, int len)
2189{
2190 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002191 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002192
2193 if (len > 0) {
2194 if (*s != '-') {
2195 /* positive number */
2196 while (len-- > 0) {
2197 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002198 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002199 if (j > 9)
2200 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002201 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002202 }
2203 } else {
2204 /* negative number */
2205 s++;
2206 while (--len > 0) {
2207 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002208 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002209 if (j > 9)
2210 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002211 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002212 }
2213 }
2214 }
2215 return i;
2216}
2217
2218
2219/* This function reads exactly <len> chars from <s> and converts them to a
2220 * signed integer which it stores into <ret>. It accurately detects any error
2221 * (truncated string, invalid chars, overflows). It is meant to be used in
2222 * applications designed for hostile environments. It returns zero when the
2223 * number has successfully been converted, non-zero otherwise. When an error
2224 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2225 * faster than strtol().
2226 */
2227int strl2irc(const char *s, int len, int *ret)
2228{
2229 int i = 0;
2230 int j;
2231
2232 if (!len)
2233 return 1;
2234
2235 if (*s != '-') {
2236 /* positive number */
2237 while (len-- > 0) {
2238 j = (*s++) - '0';
2239 if (j > 9) return 1; /* invalid char */
2240 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2241 i = i * 10;
2242 if (i + j < i) return 1; /* check for addition overflow */
2243 i = i + j;
2244 }
2245 } else {
2246 /* negative number */
2247 s++;
2248 while (--len > 0) {
2249 j = (*s++) - '0';
2250 if (j > 9) return 1; /* invalid char */
2251 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2252 i = i * 10;
2253 if (i - j > i) return 1; /* check for subtract overflow */
2254 i = i - j;
2255 }
2256 }
2257 *ret = i;
2258 return 0;
2259}
2260
2261
2262/* This function reads exactly <len> chars from <s> and converts them to a
2263 * signed integer which it stores into <ret>. It accurately detects any error
2264 * (truncated string, invalid chars, overflows). It is meant to be used in
2265 * applications designed for hostile environments. It returns zero when the
2266 * number has successfully been converted, non-zero otherwise. When an error
2267 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002268 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002269 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002270
2271int strl2llrc(const char *s, int len, long long *ret)
2272{
2273 long long i = 0;
2274 int j;
2275
2276 if (!len)
2277 return 1;
2278
2279 if (*s != '-') {
2280 /* positive number */
2281 while (len-- > 0) {
2282 j = (*s++) - '0';
2283 if (j > 9) return 1; /* invalid char */
2284 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2285 i = i * 10LL;
2286 if (i + j < i) return 1; /* check for addition overflow */
2287 i = i + j;
2288 }
2289 } else {
2290 /* negative number */
2291 s++;
2292 while (--len > 0) {
2293 j = (*s++) - '0';
2294 if (j > 9) return 1; /* invalid char */
2295 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2296 i = i * 10LL;
2297 if (i - j > i) return 1; /* check for subtract overflow */
2298 i = i - j;
2299 }
2300 }
2301 *ret = i;
2302 return 0;
2303}
2304
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002305/* This function is used with pat_parse_dotted_ver(). It converts a string
2306 * composed by two number separated by a dot. Each part must contain in 16 bits
2307 * because internally they will be represented as a 32-bit quantity stored in
2308 * a 64-bit integer. It returns zero when the number has successfully been
2309 * converted, non-zero otherwise. When an error is returned, the <ret> value
2310 * is left untouched.
2311 *
2312 * "1.3" -> 0x0000000000010003
2313 * "65535.65535" -> 0x00000000ffffffff
2314 */
2315int strl2llrc_dotted(const char *text, int len, long long *ret)
2316{
2317 const char *end = &text[len];
2318 const char *p;
2319 long long major, minor;
2320
2321 /* Look for dot. */
2322 for (p = text; p < end; p++)
2323 if (*p == '.')
2324 break;
2325
2326 /* Convert major. */
2327 if (strl2llrc(text, p - text, &major) != 0)
2328 return 1;
2329
2330 /* Check major. */
2331 if (major >= 65536)
2332 return 1;
2333
2334 /* Convert minor. */
2335 minor = 0;
2336 if (p < end)
2337 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2338 return 1;
2339
2340 /* Check minor. */
2341 if (minor >= 65536)
2342 return 1;
2343
2344 /* Compose value. */
2345 *ret = (major << 16) | (minor & 0xffff);
2346 return 0;
2347}
2348
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002349/* This function parses a time value optionally followed by a unit suffix among
2350 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2351 * expected by the caller. The computation does its best to avoid overflows.
2352 * The value is returned in <ret> if everything is fine, and a NULL is returned
2353 * by the function. In case of error, a pointer to the error is returned and
2354 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002355 * Values resulting in values larger than or equal to 2^31 after conversion are
2356 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2357 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002358 */
2359const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2360{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002361 unsigned long long imult, idiv;
2362 unsigned long long omult, odiv;
2363 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002364 const char *str = text;
2365
2366 if (!isdigit((unsigned char)*text))
2367 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002368
2369 omult = odiv = 1;
2370
2371 switch (unit_flags & TIME_UNIT_MASK) {
2372 case TIME_UNIT_US: omult = 1000000; break;
2373 case TIME_UNIT_MS: omult = 1000; break;
2374 case TIME_UNIT_S: break;
2375 case TIME_UNIT_MIN: odiv = 60; break;
2376 case TIME_UNIT_HOUR: odiv = 3600; break;
2377 case TIME_UNIT_DAY: odiv = 86400; break;
2378 default: break;
2379 }
2380
2381 value = 0;
2382
2383 while (1) {
2384 unsigned int j;
2385
2386 j = *text - '0';
2387 if (j > 9)
2388 break;
2389 text++;
2390 value *= 10;
2391 value += j;
2392 }
2393
2394 imult = idiv = 1;
2395 switch (*text) {
2396 case '\0': /* no unit = default unit */
2397 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002398 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002399 case 's': /* second = unscaled unit */
2400 break;
2401 case 'u': /* microsecond : "us" */
2402 if (text[1] == 's') {
2403 idiv = 1000000;
2404 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002405 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002406 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002407 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002408 case 'm': /* millisecond : "ms" or minute: "m" */
2409 if (text[1] == 's') {
2410 idiv = 1000;
2411 text++;
2412 } else
2413 imult = 60;
2414 break;
2415 case 'h': /* hour : "h" */
2416 imult = 3600;
2417 break;
2418 case 'd': /* day : "d" */
2419 imult = 86400;
2420 break;
2421 default:
2422 return text;
2423 break;
2424 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002425 if (*(++text) != '\0') {
2426 ha_warning("unexpected character '%c' after the timer value '%s', only "
2427 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2428 " This will be reported as an error in next versions.\n", *text, str);
2429 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002430
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002431 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002432 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2433 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2434 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2435 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2436
Willy Tarreau9faebe32019-06-07 19:00:37 +02002437 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2438 if (result >= 0x80000000)
2439 return PARSE_TIME_OVER;
2440 if (!result && value)
2441 return PARSE_TIME_UNDER;
2442 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002443 return NULL;
2444}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002445
Emeric Brun39132b22010-01-04 14:57:24 +01002446/* this function converts the string starting at <text> to an unsigned int
2447 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002448 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002449 */
2450const char *parse_size_err(const char *text, unsigned *ret) {
2451 unsigned value = 0;
2452
Christopher Faulet82635a02020-12-11 09:30:45 +01002453 if (!isdigit((unsigned char)*text))
2454 return text;
2455
Emeric Brun39132b22010-01-04 14:57:24 +01002456 while (1) {
2457 unsigned int j;
2458
2459 j = *text - '0';
2460 if (j > 9)
2461 break;
2462 if (value > ~0U / 10)
2463 return text;
2464 value *= 10;
2465 if (value > (value + j))
2466 return text;
2467 value += j;
2468 text++;
2469 }
2470
2471 switch (*text) {
2472 case '\0':
2473 break;
2474 case 'K':
2475 case 'k':
2476 if (value > ~0U >> 10)
2477 return text;
2478 value = value << 10;
2479 break;
2480 case 'M':
2481 case 'm':
2482 if (value > ~0U >> 20)
2483 return text;
2484 value = value << 20;
2485 break;
2486 case 'G':
2487 case 'g':
2488 if (value > ~0U >> 30)
2489 return text;
2490 value = value << 30;
2491 break;
2492 default:
2493 return text;
2494 }
2495
Godbach58048a22015-01-28 17:36:16 +08002496 if (*text != '\0' && *++text != '\0')
2497 return text;
2498
Emeric Brun39132b22010-01-04 14:57:24 +01002499 *ret = value;
2500 return NULL;
2501}
2502
Willy Tarreau126d4062013-12-03 17:50:47 +01002503/*
2504 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002505 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002506 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002507 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002508 */
2509int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2510{
2511 int len;
2512 const char *p = source;
2513 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002514 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002515
2516 len = strlen(source);
2517 if (len % 2) {
2518 memprintf(err, "an even number of hex digit is expected");
2519 return 0;
2520 }
2521
2522 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002523
Willy Tarreau126d4062013-12-03 17:50:47 +01002524 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002525 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002526 if (!*binstr) {
2527 memprintf(err, "out of memory while loading string pattern");
2528 return 0;
2529 }
2530 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002531 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002532 else {
2533 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002534 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002535 len, *binstrlen);
2536 return 0;
2537 }
2538 alloc = 0;
2539 }
2540 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002541
2542 i = j = 0;
2543 while (j < len) {
2544 if (!ishex(p[i++]))
2545 goto bad_input;
2546 if (!ishex(p[i++]))
2547 goto bad_input;
2548 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2549 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002550 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002551
2552bad_input:
2553 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002554 if (alloc)
2555 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002556 return 0;
2557}
2558
Willy Tarreau946ba592009-05-10 15:41:18 +02002559/* copies at most <n> characters from <src> and always terminates with '\0' */
2560char *my_strndup(const char *src, int n)
2561{
2562 int len = 0;
2563 char *ret;
2564
2565 while (len < n && src[len])
2566 len++;
2567
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002568 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002569 if (!ret)
2570 return ret;
2571 memcpy(ret, src, len);
2572 ret[len] = '\0';
2573 return ret;
2574}
2575
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002576/*
2577 * search needle in haystack
2578 * returns the pointer if found, returns NULL otherwise
2579 */
2580const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2581{
2582 const void *c = NULL;
2583 unsigned char f;
2584
2585 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2586 return NULL;
2587
2588 f = *(char *)needle;
2589 c = haystack;
2590 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2591 if ((haystacklen - (c - haystack)) < needlelen)
2592 return NULL;
2593
2594 if (memcmp(c, needle, needlelen) == 0)
2595 return c;
2596 ++c;
2597 }
2598 return NULL;
2599}
2600
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002601/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002602size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2603{
2604 size_t ret = 0;
2605
2606 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2607 str++;
2608 ret++;
2609 }
2610 return ret;
2611}
2612
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002613/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002614size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2615{
2616 size_t ret = 0;
2617
2618 while (ret < len) {
2619 if(memchr(reject, *((int *)str), rejectlen))
2620 return ret;
2621 str++;
2622 ret++;
2623 }
2624 return ret;
2625}
2626
Willy Tarreau482b00d2009-10-04 22:48:42 +02002627/* This function returns the first unused key greater than or equal to <key> in
2628 * ID tree <root>. Zero is returned if no place is found.
2629 */
2630unsigned int get_next_id(struct eb_root *root, unsigned int key)
2631{
2632 struct eb32_node *used;
2633
2634 do {
2635 used = eb32_lookup_ge(root, key);
2636 if (!used || used->key > key)
2637 return key; /* key is available */
2638 key++;
2639 } while (key);
2640 return key;
2641}
2642
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002643/* dump the full tree to <file> in DOT format for debugging purposes. Will
2644 * optionally highlight node <subj> if found, depending on operation <op> :
2645 * 0 : nothing
2646 * >0 : insertion, node/leaf are surrounded in red
2647 * <0 : removal, node/leaf are dashed with no background
2648 * Will optionally add "desc" as a label on the graph if set and non-null.
2649 */
2650void 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 +01002651{
2652 struct eb32sc_node *node;
2653 unsigned long scope = -1;
2654
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002655 fprintf(file, "digraph ebtree {\n");
2656
2657 if (desc && *desc) {
2658 fprintf(file,
2659 " fontname=\"fixed\";\n"
2660 " fontsize=8;\n"
2661 " label=\"%s\";\n", desc);
2662 }
2663
Willy Tarreaued3cda02017-11-15 15:04:05 +01002664 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002665 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2666 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002667 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2668 );
2669
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002670 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002671 (long)eb_root_to_node(root),
2672 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002673 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2674
2675 node = eb32sc_first(root, scope);
2676 while (node) {
2677 if (node->node.node_p) {
2678 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002679 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2680 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2681 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002682
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002683 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002684 (long)node,
2685 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002686 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002687
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002688 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002689 (long)node,
2690 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002691 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2692
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002693 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002694 (long)node,
2695 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002696 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2697 }
2698
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002699 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2700 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2701 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002702
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002703 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002704 (long)node,
2705 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002706 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002707 node = eb32sc_next(node, scope);
2708 }
2709 fprintf(file, "}\n");
2710}
2711
Willy Tarreau348238b2010-01-18 15:05:57 +01002712/* This function compares a sample word possibly followed by blanks to another
2713 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2714 * otherwise zero. This intends to be used when checking HTTP headers for some
2715 * values. Note that it validates a word followed only by blanks but does not
2716 * validate a word followed by blanks then other chars.
2717 */
2718int word_match(const char *sample, int slen, const char *word, int wlen)
2719{
2720 if (slen < wlen)
2721 return 0;
2722
2723 while (wlen) {
2724 char c = *sample ^ *word;
2725 if (c && c != ('A' ^ 'a'))
2726 return 0;
2727 sample++;
2728 word++;
2729 slen--;
2730 wlen--;
2731 }
2732
2733 while (slen) {
2734 if (*sample != ' ' && *sample != '\t')
2735 return 0;
2736 sample++;
2737 slen--;
2738 }
2739 return 1;
2740}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002741
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002742/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2743 * is particularly fast because it avoids expensive operations such as
2744 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002745 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002746 */
2747unsigned int inetaddr_host(const char *text)
2748{
2749 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2750 register unsigned int dig100, dig10, dig1;
2751 int s;
2752 const char *p, *d;
2753
2754 dig1 = dig10 = dig100 = ascii_zero;
2755 s = 24;
2756
2757 p = text;
2758 while (1) {
2759 if (((unsigned)(*p - '0')) <= 9) {
2760 p++;
2761 continue;
2762 }
2763
2764 /* here, we have a complete byte between <text> and <p> (exclusive) */
2765 if (p == text)
2766 goto end;
2767
2768 d = p - 1;
2769 dig1 |= (unsigned int)(*d << s);
2770 if (d == text)
2771 goto end;
2772
2773 d--;
2774 dig10 |= (unsigned int)(*d << s);
2775 if (d == text)
2776 goto end;
2777
2778 d--;
2779 dig100 |= (unsigned int)(*d << s);
2780 end:
2781 if (!s || *p != '.')
2782 break;
2783
2784 s -= 8;
2785 text = ++p;
2786 }
2787
2788 dig100 -= ascii_zero;
2789 dig10 -= ascii_zero;
2790 dig1 -= ascii_zero;
2791 return ((dig100 * 10) + dig10) * 10 + dig1;
2792}
2793
2794/*
2795 * Idem except the first unparsed character has to be passed in <stop>.
2796 */
2797unsigned int inetaddr_host_lim(const char *text, const char *stop)
2798{
2799 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2800 register unsigned int dig100, dig10, dig1;
2801 int s;
2802 const char *p, *d;
2803
2804 dig1 = dig10 = dig100 = ascii_zero;
2805 s = 24;
2806
2807 p = text;
2808 while (1) {
2809 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2810 p++;
2811 continue;
2812 }
2813
2814 /* here, we have a complete byte between <text> and <p> (exclusive) */
2815 if (p == text)
2816 goto end;
2817
2818 d = p - 1;
2819 dig1 |= (unsigned int)(*d << s);
2820 if (d == text)
2821 goto end;
2822
2823 d--;
2824 dig10 |= (unsigned int)(*d << s);
2825 if (d == text)
2826 goto end;
2827
2828 d--;
2829 dig100 |= (unsigned int)(*d << s);
2830 end:
2831 if (!s || p == stop || *p != '.')
2832 break;
2833
2834 s -= 8;
2835 text = ++p;
2836 }
2837
2838 dig100 -= ascii_zero;
2839 dig10 -= ascii_zero;
2840 dig1 -= ascii_zero;
2841 return ((dig100 * 10) + dig10) * 10 + dig1;
2842}
2843
2844/*
2845 * Idem except the pointer to first unparsed byte is returned into <ret> which
2846 * must not be NULL.
2847 */
Willy Tarreau74172752010-10-15 23:21:42 +02002848unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002849{
2850 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2851 register unsigned int dig100, dig10, dig1;
2852 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002853 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002854
2855 dig1 = dig10 = dig100 = ascii_zero;
2856 s = 24;
2857
2858 p = text;
2859 while (1) {
2860 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2861 p++;
2862 continue;
2863 }
2864
2865 /* here, we have a complete byte between <text> and <p> (exclusive) */
2866 if (p == text)
2867 goto end;
2868
2869 d = p - 1;
2870 dig1 |= (unsigned int)(*d << s);
2871 if (d == text)
2872 goto end;
2873
2874 d--;
2875 dig10 |= (unsigned int)(*d << s);
2876 if (d == text)
2877 goto end;
2878
2879 d--;
2880 dig100 |= (unsigned int)(*d << s);
2881 end:
2882 if (!s || p == stop || *p != '.')
2883 break;
2884
2885 s -= 8;
2886 text = ++p;
2887 }
2888
2889 *ret = p;
2890 dig100 -= ascii_zero;
2891 dig10 -= ascii_zero;
2892 dig1 -= ascii_zero;
2893 return ((dig100 * 10) + dig10) * 10 + dig1;
2894}
2895
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002896/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2897 * or the number of chars read in case of success. Maybe this could be replaced
2898 * by one of the functions above. Also, apparently this function does not support
2899 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002900 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002901 */
2902int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2903{
2904 const char *addr;
2905 int saw_digit, octets, ch;
2906 u_char tmp[4], *tp;
2907 const char *cp = buf;
2908
2909 saw_digit = 0;
2910 octets = 0;
2911 *(tp = tmp) = 0;
2912
2913 for (addr = buf; addr - buf < len; addr++) {
2914 unsigned char digit = (ch = *addr) - '0';
2915
2916 if (digit > 9 && ch != '.')
2917 break;
2918
2919 if (digit <= 9) {
2920 u_int new = *tp * 10 + digit;
2921
2922 if (new > 255)
2923 return 0;
2924
2925 *tp = new;
2926
2927 if (!saw_digit) {
2928 if (++octets > 4)
2929 return 0;
2930 saw_digit = 1;
2931 }
2932 } else if (ch == '.' && saw_digit) {
2933 if (octets == 4)
2934 return 0;
2935
2936 *++tp = 0;
2937 saw_digit = 0;
2938 } else
2939 return 0;
2940 }
2941
2942 if (octets < 4)
2943 return 0;
2944
2945 memcpy(&dst->s_addr, tmp, 4);
2946 return addr - cp;
2947}
2948
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002949/* This function converts the string in <buf> of the len <len> to
2950 * struct in6_addr <dst> which must be allocated by the caller.
2951 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002952 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002953 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002954int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2955{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002956 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002957 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002958
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002959 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002960 return 0;
2961
2962 memcpy(null_term_ip6, buf, len);
2963 null_term_ip6[len] = '\0';
2964
Willy Tarreau075415a2013-12-12 11:29:39 +01002965 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002966 return 0;
2967
Willy Tarreau075415a2013-12-12 11:29:39 +01002968 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002969 return 1;
2970}
2971
Willy Tarreauacf95772010-06-14 19:09:21 +02002972/* To be used to quote config arg positions. Returns the short string at <ptr>
2973 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2974 * if ptr is NULL or empty. The string is locally allocated.
2975 */
2976const char *quote_arg(const char *ptr)
2977{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002978 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002979 int i;
2980
2981 if (!ptr || !*ptr)
2982 return "end of line";
2983 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002984 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002985 val[i] = *ptr++;
2986 val[i++] = '\'';
2987 val[i] = '\0';
2988 return val;
2989}
2990
Willy Tarreau5b180202010-07-18 10:40:48 +02002991/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2992int get_std_op(const char *str)
2993{
2994 int ret = -1;
2995
2996 if (*str == 'e' && str[1] == 'q')
2997 ret = STD_OP_EQ;
2998 else if (*str == 'n' && str[1] == 'e')
2999 ret = STD_OP_NE;
3000 else if (*str == 'l') {
3001 if (str[1] == 'e') ret = STD_OP_LE;
3002 else if (str[1] == 't') ret = STD_OP_LT;
3003 }
3004 else if (*str == 'g') {
3005 if (str[1] == 'e') ret = STD_OP_GE;
3006 else if (str[1] == 't') ret = STD_OP_GT;
3007 }
3008
3009 if (ret == -1 || str[2] != '\0')
3010 return -1;
3011 return ret;
3012}
3013
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01003014/* hash a 32-bit integer to another 32-bit integer */
3015unsigned int full_hash(unsigned int a)
3016{
3017 return __full_hash(a);
3018}
3019
Willy Tarreauf3241112019-02-26 09:56:22 +01003020/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
3021 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
3022 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
3023 * a popcount variant and is described here :
3024 * https://graphics.stanford.edu/~seander/bithacks.html
3025 */
3026unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
3027{
3028 unsigned long a, b, c, d;
3029 unsigned int s;
3030 unsigned int t;
3031
3032 a = m - ((m >> 1) & ~0UL/3);
3033 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
3034 c = (b + (b >> 4)) & ~0UL/0x11;
3035 d = (c + (c >> 8)) & ~0UL/0x101;
3036
3037 r++; // make r be 1..64
3038
3039 t = 0;
3040 s = LONGBITS;
3041 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003042 unsigned long d2 = (d >> 16) >> 16;
3043 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003044 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3045 }
3046
3047 t = (d >> (s - 16)) & 0xff;
3048 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3049 t = (c >> (s - 8)) & 0xf;
3050 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3051 t = (b >> (s - 4)) & 0x7;
3052 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3053 t = (a >> (s - 2)) & 0x3;
3054 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3055 t = (m >> (s - 1)) & 0x1;
3056 s -= ((t - r) & 256) >> 8;
3057
3058 return s - 1;
3059}
3060
3061/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3062 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3063 * using mask_prep_rank_map() below.
3064 */
3065unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3066 unsigned long a, unsigned long b,
3067 unsigned long c, unsigned long d)
3068{
3069 unsigned int s;
3070 unsigned int t;
3071
3072 r++; // make r be 1..64
3073
3074 t = 0;
3075 s = LONGBITS;
3076 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003077 unsigned long d2 = (d >> 16) >> 16;
3078 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003079 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3080 }
3081
3082 t = (d >> (s - 16)) & 0xff;
3083 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3084 t = (c >> (s - 8)) & 0xf;
3085 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3086 t = (b >> (s - 4)) & 0x7;
3087 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3088 t = (a >> (s - 2)) & 0x3;
3089 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3090 t = (m >> (s - 1)) & 0x1;
3091 s -= ((t - r) & 256) >> 8;
3092
3093 return s - 1;
3094}
3095
3096/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3097 * above.
3098 */
3099void mask_prep_rank_map(unsigned long m,
3100 unsigned long *a, unsigned long *b,
3101 unsigned long *c, unsigned long *d)
3102{
3103 *a = m - ((m >> 1) & ~0UL/3);
3104 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3105 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3106 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3107}
3108
David du Colombier4f92d322011-03-24 11:09:31 +01003109/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003110 * otherwise zero. Note that <addr> may not necessarily be aligned
3111 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003112 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003113int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003114{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003115 struct in_addr addr_copy;
3116
3117 memcpy(&addr_copy, addr, sizeof(addr_copy));
3118 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003119}
3120
3121/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003122 * otherwise zero. Note that <addr> may not necessarily be aligned
3123 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003124 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003125int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003126{
3127 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003128 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003129
Willy Tarreaueec1d382016-07-13 11:59:39 +02003130 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003131 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003132 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003133 (((int *)net)[i] & ((int *)mask)[i]))
3134 return 0;
3135 return 1;
3136}
3137
3138/* RFC 4291 prefix */
3139const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3140 0x00, 0x00, 0x00, 0x00,
3141 0x00, 0x00, 0xFF, 0xFF };
3142
Joseph Herlant32b83272018-11-15 11:58:28 -08003143/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003144 * Input and output may overlap.
3145 */
David du Colombier4f92d322011-03-24 11:09:31 +01003146void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3147{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003148 struct in_addr tmp_addr;
3149
3150 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003151 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003152 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003153}
3154
Joseph Herlant32b83272018-11-15 11:58:28 -08003155/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003156 * Return true if conversion is possible and false otherwise.
3157 */
3158int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3159{
3160 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3161 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3162 sizeof(struct in_addr));
3163 return 1;
3164 }
3165
3166 return 0;
3167}
3168
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003169/* compare two struct sockaddr_storage and return:
3170 * 0 (true) if the addr is the same in both
3171 * 1 (false) if the addr is not the same in both
3172 * -1 (unable) if one of the addr is not AF_INET*
3173 */
3174int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3175{
3176 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3177 return -1;
3178
3179 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3180 return -1;
3181
3182 if (ss1->ss_family != ss2->ss_family)
3183 return 1;
3184
3185 switch (ss1->ss_family) {
3186 case AF_INET:
3187 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3188 &((struct sockaddr_in *)ss2)->sin_addr,
3189 sizeof(struct in_addr)) != 0;
3190 case AF_INET6:
3191 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3192 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3193 sizeof(struct in6_addr)) != 0;
3194 }
3195
3196 return 1;
3197}
3198
Christopher Faulet9553de72021-02-26 09:12:50 +01003199/* compare a struct sockaddr_storage to a struct net_addr and return :
3200 * 0 (true) if <addr> is matching <net>
3201 * 1 (false) if <addr> is not matching <net>
3202 * -1 (unable) if <addr> or <net> is not AF_INET*
3203 */
3204int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3205{
3206 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3207 return -1;
3208
3209 if ((net->family != AF_INET) && (net->family != AF_INET6))
3210 return -1;
3211
3212 if (addr->ss_family != net->family)
3213 return 1;
3214
3215 if (addr->ss_family == AF_INET &&
3216 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3217 return 0;
3218 else {
3219 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3220 const struct in6_addr *nip6 = &net->addr.v6.ip;
3221 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3222
3223 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3224 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3225 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3226 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3227 return 0;
3228 }
3229
3230 return 1;
3231}
3232
Baptiste Assmann08396c82016-01-31 00:27:17 +01003233/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003234 * The caller must allocate and clear <dest> before calling.
3235 * The source must be in either AF_INET or AF_INET6 family, or the destination
3236 * address will be undefined. If the destination address used to hold a port,
3237 * it is preserved, so that this function can be used to switch to another
3238 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003239 */
3240struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3241{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003242 int prev_port;
3243
3244 prev_port = get_net_port(dest);
3245 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003246 dest->ss_family = source->ss_family;
3247
3248 /* copy new addr and apply it */
3249 switch (source->ss_family) {
3250 case AF_INET:
3251 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003252 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003253 break;
3254 case AF_INET6:
3255 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 +01003256 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003257 break;
3258 }
3259
3260 return dest;
3261}
3262
William Lallemand421f5b52012-02-06 18:15:57 +01003263char *human_time(int t, short hz_div) {
3264 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3265 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003266 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003267 int cnt=2; // print two numbers
3268
3269 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003270 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003271 return rv;
3272 }
3273
3274 if (unlikely(hz_div > 1))
3275 t /= hz_div;
3276
3277 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003278 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003279 cnt--;
3280 }
3281
3282 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003283 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003284 cnt--;
3285 }
3286
3287 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003288 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003289 cnt--;
3290 }
3291
3292 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003293 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003294
3295 return rv;
3296}
3297
3298const char *monthname[12] = {
3299 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3300 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3301};
3302
3303/* date2str_log: write a date in the format :
3304 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3305 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3306 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3307 *
3308 * without using sprintf. return a pointer to the last char written (\0) or
3309 * NULL if there isn't enough space.
3310 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003311char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003312{
3313
3314 if (size < 25) /* the size is fixed: 24 chars + \0 */
3315 return NULL;
3316
3317 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003318 if (!dst)
3319 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003320 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003321
William Lallemand421f5b52012-02-06 18:15:57 +01003322 memcpy(dst, monthname[tm->tm_mon], 3); // month
3323 dst += 3;
3324 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003325
William Lallemand421f5b52012-02-06 18:15:57 +01003326 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003327 if (!dst)
3328 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003329 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003330
William Lallemand421f5b52012-02-06 18:15:57 +01003331 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003332 if (!dst)
3333 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003334 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003335
William Lallemand421f5b52012-02-06 18:15:57 +01003336 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003337 if (!dst)
3338 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003339 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003340
William Lallemand421f5b52012-02-06 18:15:57 +01003341 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003342 if (!dst)
3343 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003344 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003345
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003346 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003347 if (!dst)
3348 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003349 *dst = '\0';
3350
3351 return dst;
3352}
3353
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003354/* Base year used to compute leap years */
3355#define TM_YEAR_BASE 1900
3356
3357/* Return the difference in seconds between two times (leap seconds are ignored).
3358 * Retrieved from glibc 2.18 source code.
3359 */
3360static int my_tm_diff(const struct tm *a, const struct tm *b)
3361{
3362 /* Compute intervening leap days correctly even if year is negative.
3363 * Take care to avoid int overflow in leap day calculations,
3364 * but it's OK to assume that A and B are close to each other.
3365 */
3366 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3367 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3368 int a100 = a4 / 25 - (a4 % 25 < 0);
3369 int b100 = b4 / 25 - (b4 % 25 < 0);
3370 int a400 = a100 >> 2;
3371 int b400 = b100 >> 2;
3372 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3373 int years = a->tm_year - b->tm_year;
3374 int days = (365 * years + intervening_leap_days
3375 + (a->tm_yday - b->tm_yday));
3376 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3377 + (a->tm_min - b->tm_min))
3378 + (a->tm_sec - b->tm_sec));
3379}
3380
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003381/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003382 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003383 * The string returned has the same format as returned by strftime(... "%z", tm).
3384 * Offsets are kept in an internal cache for better performances.
3385 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003386const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003387{
3388 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003389 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003390
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003391 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003392 struct tm tm_gmt;
3393 int diff;
3394 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003395
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003396 /* Pretend DST not active if its status is unknown */
3397 if (isdst < 0)
3398 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003399
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003400 /* Fetch the offset and initialize it if needed */
3401 gmt_offset = gmt_offsets[isdst & 0x01];
3402 if (unlikely(!*gmt_offset)) {
3403 get_gmtime(t, &tm_gmt);
3404 diff = my_tm_diff(tm, &tm_gmt);
3405 if (diff < 0) {
3406 diff = -diff;
3407 *gmt_offset = '-';
3408 } else {
3409 *gmt_offset = '+';
3410 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003411 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003412 diff /= 60; /* Convert to minutes */
3413 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3414 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003415
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003416 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003417}
3418
William Lallemand421f5b52012-02-06 18:15:57 +01003419/* gmt2str_log: write a date in the format :
3420 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3421 * return a pointer to the last char written (\0) or
3422 * NULL if there isn't enough space.
3423 */
3424char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3425{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003426 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003427 return NULL;
3428
3429 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003430 if (!dst)
3431 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003432 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003433
William Lallemand421f5b52012-02-06 18:15:57 +01003434 memcpy(dst, monthname[tm->tm_mon], 3); // month
3435 dst += 3;
3436 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003437
William Lallemand421f5b52012-02-06 18:15:57 +01003438 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003439 if (!dst)
3440 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003441 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003442
William Lallemand421f5b52012-02-06 18:15:57 +01003443 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003444 if (!dst)
3445 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003446 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003447
William Lallemand421f5b52012-02-06 18:15:57 +01003448 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003449 if (!dst)
3450 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003451 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003452
William Lallemand421f5b52012-02-06 18:15:57 +01003453 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003454 if (!dst)
3455 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003456 *dst++ = ' ';
3457 *dst++ = '+';
3458 *dst++ = '0';
3459 *dst++ = '0';
3460 *dst++ = '0';
3461 *dst++ = '0';
3462 *dst = '\0';
3463
3464 return dst;
3465}
3466
Yuxans Yao4e25b012012-10-19 10:36:09 +08003467/* localdate2str_log: write a date in the format :
3468 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003469 * Both t and tm must represent the same time.
3470 * return a pointer to the last char written (\0) or
3471 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003472 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003473char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003474{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003475 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003476 if (size < 27) /* the size is fixed: 26 chars + \0 */
3477 return NULL;
3478
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003479 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003480
Yuxans Yao4e25b012012-10-19 10:36:09 +08003481 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003482 if (!dst)
3483 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003484 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003485
Yuxans Yao4e25b012012-10-19 10:36:09 +08003486 memcpy(dst, monthname[tm->tm_mon], 3); // month
3487 dst += 3;
3488 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003489
Yuxans Yao4e25b012012-10-19 10:36:09 +08003490 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003491 if (!dst)
3492 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003493 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003494
Yuxans Yao4e25b012012-10-19 10:36:09 +08003495 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003496 if (!dst)
3497 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003498 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003499
Yuxans Yao4e25b012012-10-19 10:36:09 +08003500 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003501 if (!dst)
3502 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003503 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003504
Yuxans Yao4e25b012012-10-19 10:36:09 +08003505 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003506 if (!dst)
3507 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003508 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003509
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003510 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003511 dst += 5;
3512 *dst = '\0';
3513
3514 return dst;
3515}
3516
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003517/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3518 * It is meant as a portable replacement for timegm() for use with valid inputs.
3519 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3520 */
3521time_t my_timegm(const struct tm *tm)
3522{
3523 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3524 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3525 * sum of the extra N days for elapsed months. The sum of all these N
3526 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3527 * in a 5-bit word. This means that with 60 bits we can represent a
3528 * matrix of all these values at once, which is fast and efficient to
3529 * access. The extra February day for leap years is not counted here.
3530 *
3531 * Jan : none = 0 (0)
3532 * Feb : Jan = 3 (3)
3533 * Mar : Jan..Feb = 3 (3 + 0)
3534 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3535 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3536 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3537 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3538 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3539 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3540 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3541 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3542 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3543 */
3544 uint64_t extra =
3545 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3546 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3547 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3548 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3549
3550 unsigned int y = tm->tm_year + 1900;
3551 unsigned int m = tm->tm_mon;
3552 unsigned long days = 0;
3553
3554 /* days since 1/1/1970 for full years */
3555 days += days_since_zero(y) - days_since_zero(1970);
3556
3557 /* days for full months in the current year */
3558 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3559
3560 /* count + 1 after March for leap years. A leap year is a year multiple
3561 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3562 * is leap, 1900 isn't, 1904 is.
3563 */
3564 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3565 days++;
3566
3567 days += tm->tm_mday - 1;
3568 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3569}
3570
Thierry Fournier93127942016-01-20 18:49:45 +01003571/* This function check a char. It returns true and updates
3572 * <date> and <len> pointer to the new position if the
3573 * character is found.
3574 */
3575static inline int parse_expect_char(const char **date, int *len, char c)
3576{
3577 if (*len < 1 || **date != c)
3578 return 0;
3579 (*len)--;
3580 (*date)++;
3581 return 1;
3582}
3583
3584/* This function expects a string <str> of len <l>. It return true and updates.
3585 * <date> and <len> if the string matches, otherwise, it returns false.
3586 */
3587static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3588{
3589 if (*len < l || strncmp(*date, str, l) != 0)
3590 return 0;
3591 (*len) -= l;
3592 (*date) += l;
3593 return 1;
3594}
3595
3596/* This macro converts 3 chars name in integer. */
3597#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3598
3599/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3600 * / %x54.75.65 ; "Tue", case-sensitive
3601 * / %x57.65.64 ; "Wed", case-sensitive
3602 * / %x54.68.75 ; "Thu", case-sensitive
3603 * / %x46.72.69 ; "Fri", case-sensitive
3604 * / %x53.61.74 ; "Sat", case-sensitive
3605 * / %x53.75.6E ; "Sun", case-sensitive
3606 *
3607 * This array must be alphabetically sorted
3608 */
3609static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3610{
3611 if (*len < 3)
3612 return 0;
3613 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3614 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3615 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3616 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3617 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3618 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3619 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3620 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3621 default: return 0;
3622 }
3623 *len -= 3;
3624 *date += 3;
3625 return 1;
3626}
3627
3628/* month = %x4A.61.6E ; "Jan", case-sensitive
3629 * / %x46.65.62 ; "Feb", case-sensitive
3630 * / %x4D.61.72 ; "Mar", case-sensitive
3631 * / %x41.70.72 ; "Apr", case-sensitive
3632 * / %x4D.61.79 ; "May", case-sensitive
3633 * / %x4A.75.6E ; "Jun", case-sensitive
3634 * / %x4A.75.6C ; "Jul", case-sensitive
3635 * / %x41.75.67 ; "Aug", case-sensitive
3636 * / %x53.65.70 ; "Sep", case-sensitive
3637 * / %x4F.63.74 ; "Oct", case-sensitive
3638 * / %x4E.6F.76 ; "Nov", case-sensitive
3639 * / %x44.65.63 ; "Dec", case-sensitive
3640 *
3641 * This array must be alphabetically sorted
3642 */
3643static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3644{
3645 if (*len < 3)
3646 return 0;
3647 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3648 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3649 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3650 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3651 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3652 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3653 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3654 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3655 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3656 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3657 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3658 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3659 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3660 default: return 0;
3661 }
3662 *len -= 3;
3663 *date += 3;
3664 return 1;
3665}
3666
3667/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3668 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3669 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3670 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3671 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3672 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3673 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3674 *
3675 * This array must be alphabetically sorted
3676 */
3677static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3678{
3679 if (*len < 6) /* Minimum length. */
3680 return 0;
3681 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3682 case STR2I3('M','o','n'):
3683 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3684 tm->tm_wday = 1;
3685 return 1;
3686 case STR2I3('T','u','e'):
3687 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3688 tm->tm_wday = 2;
3689 return 1;
3690 case STR2I3('W','e','d'):
3691 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3692 tm->tm_wday = 3;
3693 return 1;
3694 case STR2I3('T','h','u'):
3695 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3696 tm->tm_wday = 4;
3697 return 1;
3698 case STR2I3('F','r','i'):
3699 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3700 tm->tm_wday = 5;
3701 return 1;
3702 case STR2I3('S','a','t'):
3703 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3704 tm->tm_wday = 6;
3705 return 1;
3706 case STR2I3('S','u','n'):
3707 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3708 tm->tm_wday = 7;
3709 return 1;
3710 }
3711 return 0;
3712}
3713
3714/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3715static inline int parse_digit(const char **date, int *len, int *digit)
3716{
3717 if (*len < 1 || **date < '0' || **date > '9')
3718 return 0;
3719 *digit = (**date - '0');
3720 (*date)++;
3721 (*len)--;
3722 return 1;
3723}
3724
3725/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3726static inline int parse_2digit(const char **date, int *len, int *digit)
3727{
3728 int value;
3729
3730 RET0_UNLESS(parse_digit(date, len, &value));
3731 (*digit) = value * 10;
3732 RET0_UNLESS(parse_digit(date, len, &value));
3733 (*digit) += value;
3734
3735 return 1;
3736}
3737
3738/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3739static inline int parse_4digit(const char **date, int *len, int *digit)
3740{
3741 int value;
3742
3743 RET0_UNLESS(parse_digit(date, len, &value));
3744 (*digit) = value * 1000;
3745
3746 RET0_UNLESS(parse_digit(date, len, &value));
3747 (*digit) += value * 100;
3748
3749 RET0_UNLESS(parse_digit(date, len, &value));
3750 (*digit) += value * 10;
3751
3752 RET0_UNLESS(parse_digit(date, len, &value));
3753 (*digit) += value;
3754
3755 return 1;
3756}
3757
3758/* time-of-day = hour ":" minute ":" second
3759 * ; 00:00:00 - 23:59:60 (leap second)
3760 *
3761 * hour = 2DIGIT
3762 * minute = 2DIGIT
3763 * second = 2DIGIT
3764 */
3765static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3766{
3767 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3768 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3769 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3770 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3771 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3772 return 1;
3773}
3774
3775/* From RFC7231
3776 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3777 *
3778 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3779 * ; fixed length/zone/capitalization subset of the format
3780 * ; see Section 3.3 of [RFC5322]
3781 *
3782 *
3783 * date1 = day SP month SP year
3784 * ; e.g., 02 Jun 1982
3785 *
3786 * day = 2DIGIT
3787 * year = 4DIGIT
3788 *
3789 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3790 *
3791 * time-of-day = hour ":" minute ":" second
3792 * ; 00:00:00 - 23:59:60 (leap second)
3793 *
3794 * hour = 2DIGIT
3795 * minute = 2DIGIT
3796 * second = 2DIGIT
3797 *
3798 * DIGIT = decimal 0-9
3799 */
3800int parse_imf_date(const char *date, int len, struct tm *tm)
3801{
David Carlier327298c2016-11-20 10:42:38 +00003802 /* tm_gmtoff, if present, ought to be zero'ed */
3803 memset(tm, 0, sizeof(*tm));
3804
Thierry Fournier93127942016-01-20 18:49:45 +01003805 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3806 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3807 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3808 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3809 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3810 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3811 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3812 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3813 tm->tm_year -= 1900;
3814 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3815 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3816 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3817 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3818 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003819 return 1;
3820}
3821
3822/* From RFC7231
3823 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3824 *
3825 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3826 * date2 = day "-" month "-" 2DIGIT
3827 * ; e.g., 02-Jun-82
3828 *
3829 * day = 2DIGIT
3830 */
3831int parse_rfc850_date(const char *date, int len, struct tm *tm)
3832{
3833 int year;
3834
David Carlier327298c2016-11-20 10:42:38 +00003835 /* tm_gmtoff, if present, ought to be zero'ed */
3836 memset(tm, 0, sizeof(*tm));
3837
Thierry Fournier93127942016-01-20 18:49:45 +01003838 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3839 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3840 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3841 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3842 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3843 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3844 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3845
3846 /* year = 2DIGIT
3847 *
3848 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3849 * two-digit year, MUST interpret a timestamp that appears to be more
3850 * than 50 years in the future as representing the most recent year in
3851 * the past that had the same last two digits.
3852 */
3853 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3854
3855 /* expect SP */
3856 if (!parse_expect_char(&date, &len, ' ')) {
3857 /* Maybe we have the date with 4 digits. */
3858 RET0_UNLESS(parse_2digit(&date, &len, &year));
3859 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3860 /* expect SP */
3861 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3862 } else {
3863 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3864 * tm_year is the number of year since 1900, so for +1900, we
3865 * do nothing, and for +2000, we add 100.
3866 */
3867 if (tm->tm_year <= 60)
3868 tm->tm_year += 100;
3869 }
3870
3871 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3872 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3873 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3874 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003875
3876 return 1;
3877}
3878
3879/* From RFC7231
3880 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3881 *
3882 * asctime-date = day-name SP date3 SP time-of-day SP year
3883 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3884 * ; e.g., Jun 2
3885 *
3886 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3887 * whitespace in an HTTP-date beyond that specifically included as SP in
3888 * the grammar.
3889 */
3890int parse_asctime_date(const char *date, int len, struct tm *tm)
3891{
David Carlier327298c2016-11-20 10:42:38 +00003892 /* tm_gmtoff, if present, ought to be zero'ed */
3893 memset(tm, 0, sizeof(*tm));
3894
Thierry Fournier93127942016-01-20 18:49:45 +01003895 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3896 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3897 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3898 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3899
3900 /* expect SP and 1DIGIT or 2DIGIT */
3901 if (parse_expect_char(&date, &len, ' '))
3902 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3903 else
3904 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3905
3906 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3907 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3908 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3909 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3910 tm->tm_year -= 1900;
3911 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003912 return 1;
3913}
3914
3915/* From RFC7231
3916 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3917 *
3918 * HTTP-date = IMF-fixdate / obs-date
3919 * obs-date = rfc850-date / asctime-date
3920 *
3921 * parses an HTTP date in the RFC format and is accepted
3922 * alternatives. <date> is the strinf containing the date,
3923 * len is the len of the string. <tm> is filled with the
3924 * parsed time. We must considers this time as GMT.
3925 */
3926int parse_http_date(const char *date, int len, struct tm *tm)
3927{
3928 if (parse_imf_date(date, len, tm))
3929 return 1;
3930
3931 if (parse_rfc850_date(date, len, tm))
3932 return 1;
3933
3934 if (parse_asctime_date(date, len, tm))
3935 return 1;
3936
3937 return 0;
3938}
3939
Willy Tarreau4deeb102021-01-29 10:47:52 +01003940/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3941 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3942 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3943 * surrounded by <pfx> and <sfx> respectively if not NULL.
3944 */
3945int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3946{
3947 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3948 const char *unit;
3949
3950 if (!pfx)
3951 pfx = "";
3952 if (!sfx)
3953 sfx = "";
3954
3955 do {
3956 unit = " - "; if (val <= 0.0) break;
3957 unit = "ns"; if (val < 1000.0) break;
3958 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3959 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3960 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3961 unit = "m "; val /= 60.0; if (val < 60.0) break;
3962 unit = "h "; val /= 60.0; if (val < 24.0) break;
3963 unit = "d "; val /= 24.0; if (val < 365.0) break;
3964 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3965 unit = " inf "; val = 0.0; break;
3966 } while (0);
3967
3968 if (val <= 0.0)
3969 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
3970 else if (val < 10.0)
3971 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
3972 else if (val < 100.0)
3973 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
3974 else
3975 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
3976}
3977
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003978/* Dynamically allocates a string of the proper length to hold the formatted
3979 * output. NULL is returned on error. The caller is responsible for freeing the
3980 * memory area using free(). The resulting string is returned in <out> if the
3981 * pointer is not NULL. A previous version of <out> might be used to build the
3982 * new string, and it will be freed before returning if it is not NULL, which
3983 * makes it possible to build complex strings from iterative calls without
3984 * having to care about freeing intermediate values, as in the example below :
3985 *
3986 * memprintf(&err, "invalid argument: '%s'", arg);
3987 * ...
3988 * memprintf(&err, "parser said : <%s>\n", *err);
3989 * ...
3990 * free(*err);
3991 *
3992 * This means that <err> must be initialized to NULL before first invocation.
3993 * The return value also holds the allocated string, which eases error checking
3994 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003995 * passed instead and it will be ignored. The returned message will then also
3996 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003997 *
3998 * It is also convenient to use it without any free except the last one :
3999 * err = NULL;
4000 * if (!fct1(err)) report(*err);
4001 * if (!fct2(err)) report(*err);
4002 * if (!fct3(err)) report(*err);
4003 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02004004 *
4005 * memprintf relies on memvprintf. This last version can be called from any
4006 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004007 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004008char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004009{
4010 va_list args;
4011 char *ret = NULL;
4012 int allocated = 0;
4013 int needed = 0;
4014
Willy Tarreaueb6cead2012-09-20 19:43:14 +02004015 if (!out)
4016 return NULL;
4017
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004018 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01004019 char buf1;
4020
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004021 /* vsnprintf() will return the required length even when the
4022 * target buffer is NULL. We do this in a loop just in case
4023 * intermediate evaluations get wrong.
4024 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02004025 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01004026 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004027 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004028 if (needed < allocated) {
4029 /* Note: on Solaris 8, the first iteration always
4030 * returns -1 if allocated is zero, so we force a
4031 * retry.
4032 */
4033 if (!allocated)
4034 needed = 0;
4035 else
4036 break;
4037 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004038
Willy Tarreau1b2fed62013-04-01 22:48:54 +02004039 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02004040 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004041 } while (ret);
4042
4043 if (needed < 0) {
4044 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004045 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004046 }
4047
4048 if (out) {
4049 free(*out);
4050 *out = ret;
4051 }
4052
4053 return ret;
4054}
William Lallemand421f5b52012-02-06 18:15:57 +01004055
Christopher Faulet93a518f2017-10-24 11:25:33 +02004056char *memprintf(char **out, const char *format, ...)
4057{
4058 va_list args;
4059 char *ret = NULL;
4060
4061 va_start(args, format);
4062 ret = memvprintf(out, format, args);
4063 va_end(args);
4064
4065 return ret;
4066}
4067
Willy Tarreau21c705b2012-09-14 11:40:36 +02004068/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4069 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004070 * freed by the caller. It also supports being passed a NULL which results in the same
4071 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004072 * Example of use :
4073 * parse(cmd, &err); (callee: memprintf(&err, ...))
4074 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4075 * free(err);
4076 */
4077char *indent_msg(char **out, int level)
4078{
4079 char *ret, *in, *p;
4080 int needed = 0;
4081 int lf = 0;
4082 int lastlf = 0;
4083 int len;
4084
Willy Tarreau70eec382012-10-10 08:56:47 +02004085 if (!out || !*out)
4086 return NULL;
4087
Willy Tarreau21c705b2012-09-14 11:40:36 +02004088 in = *out - 1;
4089 while ((in = strchr(in + 1, '\n')) != NULL) {
4090 lastlf = in - *out;
4091 lf++;
4092 }
4093
4094 if (!lf) /* single line, no LF, return it as-is */
4095 return *out;
4096
4097 len = strlen(*out);
4098
4099 if (lf == 1 && lastlf == len - 1) {
4100 /* single line, LF at end, strip it and return as-is */
4101 (*out)[lastlf] = 0;
4102 return *out;
4103 }
4104
4105 /* OK now we have at least one LF, we need to process the whole string
4106 * as a multi-line string. What we'll do :
4107 * - prefix with an LF if there is none
4108 * - add <level> spaces before each line
4109 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4110 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4111 */
4112
4113 needed = 1 + level * (lf + 1) + len + 1;
4114 p = ret = malloc(needed);
4115 in = *out;
4116
4117 /* skip initial LFs */
4118 while (*in == '\n')
4119 in++;
4120
4121 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4122 while (*in) {
4123 *p++ = '\n';
4124 memset(p, ' ', level);
4125 p += level;
4126 do {
4127 *p++ = *in++;
4128 } while (*in && *in != '\n');
4129 if (*in)
4130 in++;
4131 }
4132 *p = 0;
4133
4134 free(*out);
4135 *out = ret;
4136
4137 return ret;
4138}
4139
Willy Tarreaua2c99112019-08-21 13:17:37 +02004140/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4141 * and end of lines replaced with <eol> if not 0. The first line to indent has
4142 * to be indicated in <first> (starts at zero), so that it is possible to skip
4143 * indenting the first line if it has to be appended after an existing message.
4144 * Empty strings are never indented, and NULL strings are considered empty both
4145 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4146 * character, non-zero otherwise.
4147 */
4148int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4149{
4150 int bol, lf;
4151 int pfxlen = pfx ? strlen(pfx) : 0;
4152
4153 if (!in)
4154 return 0;
4155
4156 bol = 1;
4157 lf = 0;
4158 while (*in) {
4159 if (bol && pfxlen) {
4160 if (first > 0)
4161 first--;
4162 else
4163 b_putblk(out, pfx, pfxlen);
4164 bol = 0;
4165 }
4166
4167 lf = (*in == '\n');
4168 bol |= lf;
4169 b_putchr(out, (lf && eol) ? eol : *in);
4170 in++;
4171 }
4172 return lf;
4173}
4174
Willy Tarreau9d22e562019-03-29 18:49:09 +01004175/* removes environment variable <name> from the environment as found in
4176 * environ. This is only provided as an alternative for systems without
4177 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004178 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004179 * <name> and to replace the matching pointers with the last pointer of
4180 * the array (since variables are not ordered).
4181 * It always returns 0 (success).
4182 */
4183int my_unsetenv(const char *name)
4184{
4185 extern char **environ;
4186 char **p = environ;
4187 int vars;
4188 int next;
4189 int len;
4190
4191 len = strlen(name);
4192 for (vars = 0; p[vars]; vars++)
4193 ;
4194 next = 0;
4195 while (next < vars) {
4196 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4197 next++;
4198 continue;
4199 }
4200 if (next < vars - 1)
4201 p[next] = p[vars - 1];
4202 p[--vars] = NULL;
4203 }
4204 return 0;
4205}
4206
Willy Tarreaudad36a32013-03-11 01:20:04 +01004207/* Convert occurrences of environment variables in the input string to their
4208 * corresponding value. A variable is identified as a series of alphanumeric
4209 * characters or underscores following a '$' sign. The <in> string must be
4210 * free()able. NULL returns NULL. The resulting string might be reallocated if
4211 * some expansion is made. Variable names may also be enclosed into braces if
4212 * needed (eg: to concatenate alphanum characters).
4213 */
4214char *env_expand(char *in)
4215{
4216 char *txt_beg;
4217 char *out;
4218 char *txt_end;
4219 char *var_beg;
4220 char *var_end;
4221 char *value;
4222 char *next;
4223 int out_len;
4224 int val_len;
4225
4226 if (!in)
4227 return in;
4228
4229 value = out = NULL;
4230 out_len = 0;
4231
4232 txt_beg = in;
4233 do {
4234 /* look for next '$' sign in <in> */
4235 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4236
4237 if (!*txt_end && !out) /* end and no expansion performed */
4238 return in;
4239
4240 val_len = 0;
4241 next = txt_end;
4242 if (*txt_end == '$') {
4243 char save;
4244
4245 var_beg = txt_end + 1;
4246 if (*var_beg == '{')
4247 var_beg++;
4248
4249 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004250 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004251 var_end++;
4252 }
4253
4254 next = var_end;
4255 if (*var_end == '}' && (var_beg > txt_end + 1))
4256 next++;
4257
4258 /* get value of the variable name at this location */
4259 save = *var_end;
4260 *var_end = '\0';
4261 value = getenv(var_beg);
4262 *var_end = save;
4263 val_len = value ? strlen(value) : 0;
4264 }
4265
Hubert Verstraete831962e2016-06-28 22:44:26 +02004266 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004267 if (txt_end > txt_beg) {
4268 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4269 out_len += txt_end - txt_beg;
4270 }
4271 if (val_len) {
4272 memcpy(out + out_len, value, val_len);
4273 out_len += val_len;
4274 }
4275 out[out_len] = 0;
4276 txt_beg = next;
4277 } while (*txt_beg);
4278
4279 /* here we know that <out> was allocated and that we don't need <in> anymore */
4280 free(in);
4281 return out;
4282}
4283
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004284
4285/* same as strstr() but case-insensitive and with limit length */
4286const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4287{
4288 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004289 unsigned int slen, plen;
4290 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004291
4292 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4293 return NULL;
4294
4295 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4296 return str1;
4297
4298 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4299 return NULL;
4300
4301 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 +02004302 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004303 start++;
4304 slen--;
4305 tmp1++;
4306
4307 if (tmp1 >= len_str1)
4308 return NULL;
4309
4310 /* if pattern longer than string */
4311 if (slen < plen)
4312 return NULL;
4313 }
4314
4315 sptr = start;
4316 pptr = (char *)str2;
4317
4318 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004319 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004320 sptr++;
4321 pptr++;
4322 tmp2++;
4323
4324 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4325 return start;
4326 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4327 return NULL;
4328 }
4329 }
4330 return NULL;
4331}
4332
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004333/* This function read the next valid utf8 char.
4334 * <s> is the byte srray to be decode, <len> is its length.
4335 * The function returns decoded char encoded like this:
4336 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4337 * are the length read. The decoded character is stored in <c>.
4338 */
4339unsigned char utf8_next(const char *s, int len, unsigned int *c)
4340{
4341 const unsigned char *p = (unsigned char *)s;
4342 int dec;
4343 unsigned char code = UTF8_CODE_OK;
4344
4345 if (len < 1)
4346 return UTF8_CODE_OK;
4347
4348 /* Check the type of UTF8 sequence
4349 *
4350 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4351 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4352 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4353 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4354 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4355 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4356 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4357 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4358 */
4359 switch (*p) {
4360 case 0x00 ... 0x7f:
4361 *c = *p;
4362 return UTF8_CODE_OK | 1;
4363
4364 case 0x80 ... 0xbf:
4365 *c = *p;
4366 return UTF8_CODE_BADSEQ | 1;
4367
4368 case 0xc0 ... 0xdf:
4369 if (len < 2) {
4370 *c = *p;
4371 return UTF8_CODE_BADSEQ | 1;
4372 }
4373 *c = *p & 0x1f;
4374 dec = 1;
4375 break;
4376
4377 case 0xe0 ... 0xef:
4378 if (len < 3) {
4379 *c = *p;
4380 return UTF8_CODE_BADSEQ | 1;
4381 }
4382 *c = *p & 0x0f;
4383 dec = 2;
4384 break;
4385
4386 case 0xf0 ... 0xf7:
4387 if (len < 4) {
4388 *c = *p;
4389 return UTF8_CODE_BADSEQ | 1;
4390 }
4391 *c = *p & 0x07;
4392 dec = 3;
4393 break;
4394
4395 case 0xf8 ... 0xfb:
4396 if (len < 5) {
4397 *c = *p;
4398 return UTF8_CODE_BADSEQ | 1;
4399 }
4400 *c = *p & 0x03;
4401 dec = 4;
4402 break;
4403
4404 case 0xfc ... 0xfd:
4405 if (len < 6) {
4406 *c = *p;
4407 return UTF8_CODE_BADSEQ | 1;
4408 }
4409 *c = *p & 0x01;
4410 dec = 5;
4411 break;
4412
4413 case 0xfe ... 0xff:
4414 default:
4415 *c = *p;
4416 return UTF8_CODE_BADSEQ | 1;
4417 }
4418
4419 p++;
4420
4421 while (dec > 0) {
4422
4423 /* need 0x10 for the 2 first bits */
4424 if ( ( *p & 0xc0 ) != 0x80 )
4425 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4426
4427 /* add data at char */
4428 *c = ( *c << 6 ) | ( *p & 0x3f );
4429
4430 dec--;
4431 p++;
4432 }
4433
4434 /* Check ovelong encoding.
4435 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4436 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4437 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4438 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004439 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004440 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4441 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4442 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4443 code |= UTF8_CODE_OVERLONG;
4444
4445 /* Check invalid UTF8 range. */
4446 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4447 (*c >= 0xfffe && *c <= 0xffff))
4448 code |= UTF8_CODE_INVRANGE;
4449
4450 return code | ((p-(unsigned char *)s)&0x0f);
4451}
4452
Maxime de Roucydc887852016-05-13 23:52:54 +02004453/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4454 * On failure : return 0 and <err> filled with an error message.
4455 * The caller is responsible for freeing the <err> and <str> copy
4456 * memory area using free()
4457 */
4458int list_append_word(struct list *li, const char *str, char **err)
4459{
4460 struct wordlist *wl;
4461
4462 wl = calloc(1, sizeof(*wl));
4463 if (!wl) {
4464 memprintf(err, "out of memory");
4465 goto fail_wl;
4466 }
4467
4468 wl->s = strdup(str);
4469 if (!wl->s) {
4470 memprintf(err, "out of memory");
4471 goto fail_wl_s;
4472 }
4473
Willy Tarreau2b718102021-04-21 07:32:39 +02004474 LIST_APPEND(li, &wl->list);
Maxime de Roucydc887852016-05-13 23:52:54 +02004475
4476 return 1;
4477
4478fail_wl_s:
4479 free(wl->s);
4480fail_wl:
4481 free(wl);
4482 return 0;
4483}
4484
Willy Tarreau37101052019-05-20 16:48:20 +02004485/* indicates if a memory location may safely be read or not. The trick consists
4486 * in performing a harmless syscall using this location as an input and letting
4487 * the operating system report whether it's OK or not. For this we have the
4488 * stat() syscall, which will return EFAULT when the memory location supposed
4489 * to contain the file name is not readable. If it is readable it will then
4490 * either return 0 if the area contains an existing file name, or -1 with
4491 * another code. This must not be abused, and some audit systems might detect
4492 * this as abnormal activity. It's used only for unsafe dumps.
4493 */
4494int may_access(const void *ptr)
4495{
4496 struct stat buf;
4497
4498 if (stat(ptr, &buf) == 0)
4499 return 1;
4500 if (errno == EFAULT)
4501 return 0;
4502 return 1;
4503}
4504
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004505/* print a string of text buffer to <out>. The format is :
4506 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4507 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4508 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4509 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004510int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004511{
4512 unsigned char c;
4513 int ptr = 0;
4514
4515 while (buf[ptr] && ptr < bsize) {
4516 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004517 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004518 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004519 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004520 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004521 }
4522 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004523 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004524 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004525 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004526 switch (c) {
4527 case ' ': c = ' '; break;
4528 case '\t': c = 't'; break;
4529 case '\n': c = 'n'; break;
4530 case '\r': c = 'r'; break;
4531 case '\e': c = 'e'; break;
4532 case '\\': c = '\\'; break;
4533 case '=': c = '='; break;
4534 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004535 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004536 }
4537 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004538 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004539 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004540 out->area[out->data++] = '\\';
4541 out->area[out->data++] = 'x';
4542 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4543 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004544 }
4545 ptr++;
4546 }
4547
4548 return ptr;
4549}
4550
4551/* print a buffer in hexa.
4552 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4553 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004554int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004555{
4556 unsigned char c;
4557 int ptr = 0;
4558
4559 while (ptr < bsize) {
4560 c = buf[ptr];
4561
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004562 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004563 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004564 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4565 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004566
4567 ptr++;
4568 }
4569 return ptr;
4570}
4571
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004572/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4573 * prepending each line with prefix <pfx>. The output is *not* initialized.
4574 * The output will not wrap pas the buffer's end so it is more optimal if the
4575 * caller makes sure the buffer is aligned first. A trailing zero will always
4576 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004577 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4578 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004579 */
Willy Tarreau37101052019-05-20 16:48:20 +02004580void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004581{
4582 const unsigned char *d = buf;
4583 int i, j, start;
4584
4585 d = (const unsigned char *)(((unsigned long)buf) & -16);
4586 start = ((unsigned long)buf) & 15;
4587
4588 for (i = 0; i < start + len; i += 16) {
4589 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4590
Willy Tarreau37101052019-05-20 16:48:20 +02004591 // 0: unchecked, 1: checked safe, 2: danger
4592 unsafe = !!unsafe;
4593 if (unsafe && !may_access(d + i))
4594 unsafe = 2;
4595
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004596 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004597 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004598 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004599 else if (unsafe > 1)
4600 chunk_strcat(out, "** ");
4601 else
4602 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004603
4604 if (j == 7)
4605 chunk_strcat(out, "- ");
4606 }
4607 chunk_strcat(out, " ");
4608 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004609 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004610 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004611 else if (unsafe > 1)
4612 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004613 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004614 chunk_appendf(out, "%c", d[i + j]);
4615 else
4616 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004617 }
4618 chunk_strcat(out, "\n");
4619 }
4620}
4621
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004622/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4623 * enclosed in brackets after the address itself, formatted on 14 chars
4624 * including the "0x" prefix. This is meant to be used as a prefix for code
4625 * areas. For example:
4626 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4627 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4628 * is emitted. A NULL <pfx> will be considered empty.
4629 */
4630void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4631{
4632 int ok = 0;
4633 int i;
4634
4635 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4636
4637 for (i = 0; i < n; i++) {
4638 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4639 ok = may_access(addr + i);
4640 if (ok)
4641 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4642 else
4643 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4644 }
4645}
4646
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004647/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4648 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4649 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4650 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4651 * lines are respected within the limit of 70 output chars. Lines that are
4652 * continuation of a previous truncated line begin with "+" instead of " "
4653 * after the offset. The new pointer is returned.
4654 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004655int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004656 int *line, int ptr)
4657{
4658 int end;
4659 unsigned char c;
4660
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004661 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004662 if (end > out->size)
4663 return ptr;
4664
4665 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4666
4667 while (ptr < len && ptr < bsize) {
4668 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004669 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004670 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004671 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004672 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004673 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004674 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004675 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004676 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004677 switch (c) {
4678 case '\t': c = 't'; break;
4679 case '\n': c = 'n'; break;
4680 case '\r': c = 'r'; break;
4681 case '\e': c = 'e'; break;
4682 case '\\': c = '\\'; break;
4683 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004684 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004685 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004686 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004687 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004688 out->area[out->data++] = '\\';
4689 out->area[out->data++] = 'x';
4690 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4691 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004692 }
4693 if (buf[ptr++] == '\n') {
4694 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004695 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004696 *line = ptr;
4697 return ptr;
4698 }
4699 }
4700 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004701 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004702 return ptr;
4703}
4704
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004705/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004706 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4707 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004708 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004709void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4710 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004711{
Willy Tarreau73459792017-04-11 07:58:08 +02004712 unsigned int i;
4713 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004714
4715 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4716 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004717 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004718 for (j = 0; j < 8; j++) {
4719 if (b + j >= 0 && b + j < len)
4720 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4721 else
4722 fprintf(out, " ");
4723 }
4724
4725 if (b + j >= 0 && b + j < len)
4726 fputc('-', out);
4727 else
4728 fputc(' ', out);
4729
4730 for (j = 8; j < 16; j++) {
4731 if (b + j >= 0 && b + j < len)
4732 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4733 else
4734 fprintf(out, " ");
4735 }
4736
4737 fprintf(out, " ");
4738 for (j = 0; j < 16; j++) {
4739 if (b + j >= 0 && b + j < len) {
4740 if (isprint((unsigned char)buf[b + j]))
4741 fputc((unsigned char)buf[b + j], out);
4742 else
4743 fputc('.', out);
4744 }
4745 else
4746 fputc(' ', out);
4747 }
4748 fputc('\n', out);
4749 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004750}
4751
Willy Tarreaubb869862020-04-16 10:52:41 +02004752/* Tries to report the executable path name on platforms supporting this. If
4753 * not found or not possible, returns NULL.
4754 */
4755const char *get_exec_path()
4756{
4757 const char *ret = NULL;
4758
4759#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4760 long execfn = getauxval(AT_EXECFN);
4761
4762 if (execfn && execfn != ENOENT)
4763 ret = (const char *)execfn;
4764#endif
4765 return ret;
4766}
4767
Baruch Siache1651b22020-07-24 07:52:20 +03004768#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004769/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4770 * also returns the symbol size in <size>, otherwise returns 0 there.
4771 */
4772static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4773{
4774 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004775#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004776 const ElfW(Sym) *sym;
4777
4778 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4779 if (ret)
4780 *size = sym ? sym->st_size : 0;
4781#else
4782 ret = dladdr(addr, dli);
4783 *size = 0;
4784#endif
4785 return ret;
4786}
Willy Tarreau64192392021-05-05 09:06:21 +02004787
4788/* Tries to retrieve the address of the first occurrence symbol <name>.
4789 * Note that NULL in return is not always an error as a symbol may have that
4790 * address in special situations.
4791 */
4792void *get_sym_curr_addr(const char *name)
4793{
4794 void *ptr = NULL;
4795
4796#ifdef RTLD_DEFAULT
4797 ptr = dlsym(RTLD_DEFAULT, name);
4798#endif
4799 return ptr;
4800}
4801
4802
4803/* Tries to retrieve the address of the next occurrence of symbol <name>
4804 * Note that NULL in return is not always an error as a symbol may have that
4805 * address in special situations.
4806 */
4807void *get_sym_next_addr(const char *name)
4808{
4809 void *ptr = NULL;
4810
4811#ifdef RTLD_NEXT
4812 ptr = dlsym(RTLD_NEXT, name);
Willy Tarreau9133e482020-03-04 10:19:36 +01004813#endif
Willy Tarreau64192392021-05-05 09:06:21 +02004814 return ptr;
4815}
4816
4817#else /* elf & linux & dl */
4818
4819/* no possible resolving on other platforms at the moment */
4820void *get_sym_curr_addr(const char *name)
4821{
4822 return NULL;
4823}
4824
4825void *get_sym_next_addr(const char *name)
4826{
4827 return NULL;
4828}
4829
4830#endif /* elf & linux & dl */
Willy Tarreau9133e482020-03-04 10:19:36 +01004831
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004832/* Tries to append to buffer <buf> some indications about the symbol at address
4833 * <addr> using the following form:
4834 * lib:+0xoffset (unresolvable address from lib's base)
4835 * main+0xoffset (unresolvable address from main (+/-))
4836 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4837 * name (resolved exact exec address)
4838 * lib:name (resolved exact lib address)
4839 * name+0xoffset/0xsize (resolved address within exec symbol)
4840 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4841 *
4842 * The file name (lib or executable) is limited to what lies between the last
4843 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4844 * 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 +03004845 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004846 *
4847 * The symbol's base address is returned, or NULL when unresolved, in order to
4848 * allow the caller to match it against known ones.
4849 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004850const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004851{
4852 const struct {
4853 const void *func;
4854 const char *name;
4855 } fcts[] = {
4856 { .func = process_stream, .name = "process_stream" },
4857 { .func = task_run_applet, .name = "task_run_applet" },
4858 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004859 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004860 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4861 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004862 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004863 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4864 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004865 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004866#ifdef USE_THREAD
4867 { .func = accept_queue_process, .name = "accept_queue_process" },
4868#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004869#ifdef USE_LUA
4870 { .func = hlua_process_task, .name = "hlua_process_task" },
4871#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004872#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004873 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4874 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4875#endif
4876 };
4877
Baruch Siache1651b22020-07-24 07:52:20 +03004878#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004879 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004880 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004881 const char *fname, *p;
4882#endif
4883 int i;
4884
4885 if (pfx)
4886 chunk_appendf(buf, "%s", pfx);
4887
4888 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4889 if (addr == fcts[i].func) {
4890 chunk_appendf(buf, "%s", fcts[i].name);
4891 return addr;
4892 }
4893 }
4894
Baruch Siache1651b22020-07-24 07:52:20 +03004895#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004896 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004897 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004898 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004899
4900 /* 1. prefix the library name if it's not the same object as the one
4901 * that contains the main function. The name is picked between last '/'
4902 * and first following '.'.
4903 */
4904 if (!dladdr(main, &dli_main))
4905 dli_main.dli_fbase = NULL;
4906
4907 if (dli_main.dli_fbase != dli.dli_fbase) {
4908 fname = dli.dli_fname;
4909 p = strrchr(fname, '/');
4910 if (p++)
4911 fname = p;
4912 p = strchr(fname, '.');
4913 if (!p)
4914 p = fname + strlen(fname);
4915
4916 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4917 }
4918
4919 /* 2. symbol name */
4920 if (dli.dli_sname) {
4921 /* known, dump it and return symbol's address (exact or relative) */
4922 chunk_appendf(buf, "%s", dli.dli_sname);
4923 if (addr != dli.dli_saddr) {
4924 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004925 if (size)
4926 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004927 }
4928 return dli.dli_saddr;
4929 }
4930 else if (dli_main.dli_fbase != dli.dli_fbase) {
4931 /* unresolved symbol from a known library, report relative offset */
4932 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4933 return NULL;
4934 }
Baruch Siache1651b22020-07-24 07:52:20 +03004935#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004936 unknown:
4937 /* unresolved symbol from the main file, report relative offset to main */
4938 if ((void*)addr < (void*)main)
4939 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4940 else
4941 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4942 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004943}
4944
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004945/*
4946 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004947 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004948 *
4949 * First, initializes the value with <sz> as address to 0 and initializes the
4950 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4951 * address updating <sz> pointed value to the size of this array.
4952 *
4953 * Returns 1 if succeeded, 0 if not.
4954 */
4955int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4956{
4957 unsigned int *n;
4958 const char *s, *end;
4959
4960 s = str;
4961 *sz = 0;
4962 end = str + strlen(str);
4963 *nums = n = NULL;
4964
4965 while (1) {
4966 unsigned int r;
4967
4968 if (s >= end)
4969 break;
4970
4971 r = read_uint(&s, end);
4972 /* Expected characters after having read an uint: '\0' or '.',
4973 * if '.', must not be terminal.
4974 */
Christopher Faulet4b524122021-02-11 10:42:41 +01004975 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4976 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004977 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01004978 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004979
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004980 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004981 if (!n)
4982 return 0;
4983
4984 n[(*sz)++] = r;
4985 }
4986 *nums = n;
4987
4988 return 1;
4989}
4990
Willy Tarreau4d589e72019-08-23 19:02:26 +02004991
4992/* returns the number of bytes needed to encode <v> as a varint. An inline
4993 * version exists for use with constants (__varint_bytes()).
4994 */
4995int varint_bytes(uint64_t v)
4996{
4997 int len = 1;
4998
4999 if (v >= 240) {
5000 v = (v - 240) >> 4;
5001 while (1) {
5002 len++;
5003 if (v < 128)
5004 break;
5005 v = (v - 128) >> 7;
5006 }
5007 }
5008 return len;
5009}
5010
Willy Tarreau52bf8392020-03-08 00:42:37 +01005011
5012/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01005013static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005014
5015/* This is a thread-safe implementation of xoroshiro128** described below:
5016 * http://prng.di.unimi.it/
5017 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
5018 * supports fast jumps and passes all common quality tests. It is thread-safe,
5019 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
5020 * local lock on other ones.
5021 */
5022uint64_t ha_random64()
5023{
Willy Tarreau1544c142020-03-12 00:31:18 +01005024 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
5025 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01005026
5027#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
5028 static HA_SPINLOCK_T rand_lock;
5029
5030 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
5031#endif
5032
5033 old[0] = ha_random_state[0];
5034 old[1] = ha_random_state[1];
5035
5036#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5037 do {
5038#endif
Willy Tarreau52bf8392020-03-08 00:42:37 +01005039 new[1] = old[0] ^ old[1];
5040 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
5041 new[1] = rotl64(new[1], 37); // c
5042
5043#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
5044 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
5045#else
5046 ha_random_state[0] = new[0];
5047 ha_random_state[1] = new[1];
5048#if defined(USE_THREAD)
5049 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
5050#endif
5051#endif
Willy Tarreaub2475a12021-05-09 10:26:14 +02005052 return rotl64(old[0] * 5, 7) * 9;
Willy Tarreau52bf8392020-03-08 00:42:37 +01005053}
5054
5055/* seeds the random state using up to <len> bytes from <seed>, starting with
5056 * the first non-zero byte.
5057 */
5058void ha_random_seed(const unsigned char *seed, size_t len)
5059{
5060 size_t pos;
5061
5062 /* the seed must not be all zeroes, so we pre-fill it with alternating
5063 * bits and overwrite part of them with the block starting at the first
5064 * non-zero byte from the seed.
5065 */
5066 memset(ha_random_state, 0x55, sizeof(ha_random_state));
5067
5068 for (pos = 0; pos < len; pos++)
5069 if (seed[pos] != 0)
5070 break;
5071
5072 if (pos == len)
5073 return;
5074
5075 seed += pos;
5076 len -= pos;
5077
5078 if (len > sizeof(ha_random_state))
5079 len = sizeof(ha_random_state);
5080
5081 memcpy(ha_random_state, seed, len);
5082}
5083
5084/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
5085 * and is equivalent to calling ha_random64() as many times. It is used to
5086 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5087 * different generators (i.e. different processes after a fork). The <dist>
5088 * argument is the distance to jump to and is used in a loop so it rather not
5089 * be too large if the processing time is a concern.
5090 *
5091 * BEWARE: this function is NOT thread-safe and must not be called during
5092 * concurrent accesses to ha_random64().
5093 */
5094void ha_random_jump96(uint32_t dist)
5095{
5096 while (dist--) {
5097 uint64_t s0 = 0;
5098 uint64_t s1 = 0;
5099 int b;
5100
5101 for (b = 0; b < 64; b++) {
5102 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5103 s0 ^= ha_random_state[0];
5104 s1 ^= ha_random_state[1];
5105 }
5106 ha_random64();
5107 }
5108
5109 for (b = 0; b < 64; b++) {
5110 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5111 s0 ^= ha_random_state[0];
5112 s1 ^= ha_random_state[1];
5113 }
5114 ha_random64();
5115 }
5116 ha_random_state[0] = s0;
5117 ha_random_state[1] = s1;
5118 }
5119}
5120
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005121/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5122 * bytes large.
5123 */
5124void ha_generate_uuid(struct buffer *output)
5125{
5126 uint32_t rnd[4];
5127 uint64_t last;
5128
5129 last = ha_random64();
5130 rnd[0] = last;
5131 rnd[1] = last >> 32;
5132
5133 last = ha_random64();
5134 rnd[2] = last;
5135 rnd[3] = last >> 32;
5136
5137 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5138 rnd[0],
5139 rnd[1] & 0xFFFF,
5140 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5141 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5142 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5143}
5144
5145
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005146/* only used by parse_line() below. It supports writing in place provided that
5147 * <in> is updated to the next location before calling it. In that case, the
5148 * char at <in> may be overwritten.
5149 */
5150#define EMIT_CHAR(x) \
5151 do { \
5152 char __c = (char)(x); \
5153 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5154 err |= PARSE_ERR_OVERLAP; \
5155 if (outpos >= outmax) \
5156 err |= PARSE_ERR_TOOLARGE; \
5157 if (!err) \
5158 out[outpos] = __c; \
5159 outpos++; \
5160 } while (0)
5161
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005162/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005163 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5164 * extraneous ones are not emitted but <outlen> is updated so that the caller
5165 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5166 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005167 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5168 * it is guaranteed that at least one arg will point to the zero. It is safe
5169 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005170 *
5171 * <out> may overlap with <in> provided that it never goes further, in which
5172 * case the parser will accept to perform in-place parsing and unquoting/
5173 * unescaping but only if environment variables do not lead to expansion that
5174 * causes overlapping, otherwise the input string being destroyed, the error
5175 * will not be recoverable. Note that even during out-of-place <in> will
5176 * experience temporary modifications in-place for variable resolution and must
5177 * be writable, and will also receive zeroes to delimit words when using
5178 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5179 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5180 * starting point of the first invalid character sequence or unmatched
5181 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5182 * error reporting might be difficult since zeroes will have been inserted into
5183 * the string. One solution for the caller may consist in replacing all args
5184 * delimiters with spaces in this case.
5185 */
5186uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
5187{
5188 char *quote = NULL;
5189 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005190 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005191 unsigned char hex1, hex2;
5192 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005193 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005194 size_t outpos = 0;
5195 int squote = 0;
5196 int dquote = 0;
5197 int arg = 0;
5198 uint32_t err = 0;
5199
5200 *nbargs = 0;
5201 *outlen = 0;
5202
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005203 /* argsmax may be -1 here, protecting args[] from any write */
5204 if (arg < argsmax)
5205 args[arg] = out;
5206
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005207 while (1) {
5208 if (*in >= '-' && *in != '\\') {
5209 /* speedup: directly send all regular chars starting
5210 * with '-', '.', '/', alnum etc...
5211 */
5212 EMIT_CHAR(*in++);
5213 continue;
5214 }
5215 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5216 /* end of line */
5217 break;
5218 }
5219 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5220 /* comment */
5221 break;
5222 }
5223 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5224 if (dquote) {
5225 dquote = 0;
5226 quote = NULL;
5227 }
5228 else {
5229 dquote = 1;
5230 quote = in;
5231 }
5232 in++;
5233 continue;
5234 }
5235 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5236 if (squote) {
5237 squote = 0;
5238 quote = NULL;
5239 }
5240 else {
5241 squote = 1;
5242 quote = in;
5243 }
5244 in++;
5245 continue;
5246 }
5247 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5248 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5249 * C equivalent value but only when they have a special meaning and within
5250 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5251 */
5252 char tosend = *in;
5253
5254 switch (in[1]) {
5255 case ' ':
5256 case '\\':
5257 tosend = in[1];
5258 in++;
5259 break;
5260
5261 case 't':
5262 tosend = '\t';
5263 in++;
5264 break;
5265
5266 case 'n':
5267 tosend = '\n';
5268 in++;
5269 break;
5270
5271 case 'r':
5272 tosend = '\r';
5273 in++;
5274 break;
5275
5276 case '#':
5277 /* escaping of "#" only if comments are supported */
5278 if (opts & PARSE_OPT_SHARP)
5279 in++;
5280 tosend = *in;
5281 break;
5282
5283 case '\'':
5284 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5285 if (opts & PARSE_OPT_SQUOTE && !squote)
5286 in++;
5287 tosend = *in;
5288 break;
5289
5290 case '"':
5291 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5292 if (opts & PARSE_OPT_DQUOTE && !squote)
5293 in++;
5294 tosend = *in;
5295 break;
5296
5297 case '$':
5298 /* escaping of '$' only inside double quotes and only if env supported */
5299 if (opts & PARSE_OPT_ENV && dquote)
5300 in++;
5301 tosend = *in;
5302 break;
5303
5304 case 'x':
5305 if (!ishex(in[2]) || !ishex(in[3])) {
5306 /* invalid or incomplete hex sequence */
5307 err |= PARSE_ERR_HEX;
5308 if (errptr)
5309 *errptr = in;
5310 goto leave;
5311 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005312 hex1 = toupper((unsigned char)in[2]) - '0';
5313 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005314 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5315 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5316 tosend = (hex1 << 4) + hex2;
5317 in += 3;
5318 break;
5319
5320 default:
5321 /* other combinations are not escape sequences */
5322 break;
5323 }
5324
5325 in++;
5326 EMIT_CHAR(tosend);
5327 }
5328 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5329 /* a non-escaped space is an argument separator */
5330 while (isspace((unsigned char)*in))
5331 in++;
5332 EMIT_CHAR(0);
5333 arg++;
5334 if (arg < argsmax)
5335 args[arg] = out + outpos;
5336 else
5337 err |= PARSE_ERR_TOOMANY;
5338 }
5339 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5340 /* environment variables are evaluated anywhere, or only
5341 * inside double quotes if they are supported.
5342 */
5343 char *var_name;
5344 char save_char;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005345 const char *value;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005346
5347 in++;
5348
5349 if (*in == '{')
5350 brace = in++;
5351
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005352 if (!isalpha((unsigned char)*in) && *in != '_' && *in != '.') {
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005353 /* unacceptable character in variable name */
5354 err |= PARSE_ERR_VARNAME;
5355 if (errptr)
5356 *errptr = in;
5357 goto leave;
5358 }
5359
5360 var_name = in;
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005361 if (*in == '.')
5362 in++;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005363 while (isalnum((unsigned char)*in) || *in == '_')
5364 in++;
5365
5366 save_char = *in;
5367 *in = '\0';
Willy Tarreaua46f1af2021-05-06 10:25:11 +02005368 if (unlikely(*var_name == '.')) {
5369 /* internal pseudo-variables */
5370 if (strcmp(var_name, ".LINE") == 0)
5371 value = ultoa(global.cfg_curr_line);
5372 else if (strcmp(var_name, ".FILE") == 0)
5373 value = global.cfg_curr_file;
5374 else if (strcmp(var_name, ".SECTION") == 0)
5375 value = global.cfg_curr_section;
5376 else {
5377 /* unsupported internal variable name */
5378 err |= PARSE_ERR_VARNAME;
5379 if (errptr)
5380 *errptr = var_name;
5381 goto leave;
5382 }
5383 } else {
5384 value = getenv(var_name);
5385 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005386 *in = save_char;
5387
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005388 /* support for '[*]' sequence to force word expansion,
5389 * only available inside braces */
5390 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5391 word_expand = in++;
5392
5393 if (*in++ != '*' || *in++ != ']') {
5394 err |= PARSE_ERR_WRONG_EXPAND;
5395 if (errptr)
5396 *errptr = word_expand;
5397 goto leave;
5398 }
5399 }
5400
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005401 if (brace) {
5402 if (*in != '}') {
5403 /* unmatched brace */
5404 err |= PARSE_ERR_BRACE;
5405 if (errptr)
5406 *errptr = brace;
5407 goto leave;
5408 }
5409 in++;
5410 brace = NULL;
5411 }
5412
5413 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005414 while (*value) {
5415 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005416 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005417 EMIT_CHAR(0);
5418 ++arg;
5419 if (arg < argsmax)
5420 args[arg] = out + outpos;
5421 else
5422 err |= PARSE_ERR_TOOMANY;
5423
5424 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005425 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005426 ;
5427 } else {
5428 EMIT_CHAR(*value++);
5429 }
5430 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005431 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005432 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005433 }
5434 else {
5435 /* any other regular char */
5436 EMIT_CHAR(*in++);
5437 }
5438 }
5439
5440 /* end of output string */
5441 EMIT_CHAR(0);
5442 arg++;
5443
5444 if (quote) {
5445 /* unmatched quote */
5446 err |= PARSE_ERR_QUOTE;
5447 if (errptr)
5448 *errptr = quote;
5449 goto leave;
5450 }
5451 leave:
5452 *nbargs = arg;
5453 *outlen = outpos;
5454
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005455 /* empty all trailing args by making them point to the trailing zero,
5456 * at least the last one in any case.
5457 */
5458 if (arg > argsmax)
5459 arg = argsmax;
5460
5461 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005462 args[arg++] = out + outpos - 1;
5463
5464 return err;
5465}
5466#undef EMIT_CHAR
5467
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005468/* This is used to sanitize an input line that's about to be used for error reporting.
5469 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5470 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5471 * If non-printable chars are present in the output. It returns the new offset <pos>
5472 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5473 * be at least 6 to support two "..." otherwise the result is undefined. The line
5474 * itself must have at least 7 chars allocated for the same reason.
5475 */
5476size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5477{
5478 size_t shift = 0;
5479 char *out = line;
5480 char *in = line;
5481 char *end = line + width;
5482
5483 if (pos >= width) {
5484 /* if we have to shift, we'll be out of context, so let's
5485 * try to put <pos> at the center of width.
5486 */
5487 shift = pos - width / 2;
5488 in += shift + 3;
5489 end = out + width - 3;
5490 out[0] = out[1] = out[2] = '.';
5491 out += 3;
5492 }
5493
5494 while (out < end && *in) {
5495 if (isspace((unsigned char)*in))
5496 *out++ = ' ';
5497 else if (isprint((unsigned char)*in))
5498 *out++ = *in;
5499 else
5500 *out++ = '?';
5501 in++;
5502 }
5503
5504 if (end < line + width) {
5505 out[0] = out[1] = out[2] = '.';
5506 out += 3;
5507 }
5508
5509 *out++ = 0;
5510 return pos - shift;
5511}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005512
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005513/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005514 * transitions between characters. <fp> is a 1024-entries array indexed as
5515 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005516 * 1..26=letter, 27=digit, 28=other/begin/end.
5517 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005518 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005519void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005520{
5521 const char *p;
5522 int from, to;
5523 int c;
5524
Willy Tarreauba2c4452021-03-12 09:01:52 +01005525 from = 28; // begin
5526 for (p = word; *p; p++) {
5527 c = tolower(*p);
5528 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005529 case 'a'...'z': to = c - 'a' + 1; break;
5530 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5531 case '0'...'9': to = 27; break;
5532 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005533 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005534 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005535 fp[32 * from + to]++;
5536 from = to;
5537 }
5538 to = 28; // end
5539 fp[32 * from + to]++;
5540}
5541
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005542/* Initialize array <fp> with the fingerprint of word <word> by counting the
5543 * transitions between characters. <fp> is a 1024-entries array indexed as
5544 * 32*from+to. Positions for 'from' and 'to' are:
5545 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5546 */
5547void make_word_fingerprint(uint8_t *fp, const char *word)
5548{
5549 memset(fp, 0, 1024);
5550 update_word_fingerprint(fp, word);
5551}
5552
Willy Tarreauba2c4452021-03-12 09:01:52 +01005553/* Return the distance between two word fingerprints created by function
5554 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005555 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005556 */
5557int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5558{
5559 int i, k, dist = 0;
5560
5561 for (i = 0; i < 1024; i++) {
5562 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005563 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005564 }
5565 return dist;
5566}
5567
Willy Tarreau06e69b52021-03-02 14:01:35 +01005568static int init_tools_per_thread()
5569{
5570 /* Let's make each thread start from a different position */
5571 statistical_prng_state += tid * MAX_THREADS;
5572 if (!statistical_prng_state)
5573 statistical_prng_state++;
5574 return 1;
5575}
5576REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005577
Willy Tarreaubaaee002006-06-26 02:48:02 +02005578/*
5579 * Local variables:
5580 * c-indent-level: 8
5581 * c-basic-offset: 8
5582 * End:
5583 */