blob: 4924ad1a097a6f6627c549b065daa8ccbe0b80f7 [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 Tarreau588297f2014-06-16 15:16:40 +0200538/* returns a locally allocated string containing the quoted encoding of the
539 * input string. The output may be truncated to QSTR_SIZE chars, but it is
540 * guaranteed that the string will always be properly terminated. Quotes are
541 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
542 * always be at least 4 chars.
543 */
544const char *qstr(const char *str)
545{
546 char *ret = quoted_str[quoted_idx];
547 char *p, *end;
548
549 if (++quoted_idx >= NB_QSTR)
550 quoted_idx = 0;
551
552 p = ret;
553 end = ret + QSTR_SIZE;
554
555 *p++ = '"';
556
557 /* always keep 3 chars to support passing "" and the ending " */
558 while (*str && p < end - 3) {
559 if (*str == '"') {
560 *p++ = '"';
561 *p++ = '"';
562 }
563 else
564 *p++ = *str;
565 str++;
566 }
567 *p++ = '"';
568 return ret;
569}
570
Robert Tsai81ae1952007-12-05 10:47:29 +0100571/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200572 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
573 *
574 * It looks like this one would be a good candidate for inlining, but this is
575 * not interesting because it around 35 bytes long and often called multiple
576 * times within the same function.
577 */
578int ishex(char s)
579{
580 s -= '0';
581 if ((unsigned char)s <= 9)
582 return 1;
583 s -= 'A' - '0';
584 if ((unsigned char)s <= 5)
585 return 1;
586 s -= 'a' - 'A';
587 if ((unsigned char)s <= 5)
588 return 1;
589 return 0;
590}
591
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100592/* rounds <i> down to the closest value having max 2 digits */
593unsigned int round_2dig(unsigned int i)
594{
595 unsigned int mul = 1;
596
597 while (i >= 100) {
598 i /= 10;
599 mul *= 10;
600 }
601 return i * mul;
602}
603
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100604/*
605 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
606 * invalid character is found, a pointer to it is returned. If everything is
607 * fine, NULL is returned.
608 */
609const char *invalid_char(const char *name)
610{
611 if (!*name)
612 return name;
613
614 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100615 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100616 *name != '_' && *name != '-')
617 return name;
618 name++;
619 }
620 return NULL;
621}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200622
623/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200624 * Checks <name> for invalid characters. Valid chars are [_.-] and those
625 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200626 * If an invalid character is found, a pointer to it is returned.
627 * If everything is fine, NULL is returned.
628 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200629static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200630
631 if (!*name)
632 return name;
633
634 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100635 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200636 *name != '_' && *name != '-')
637 return name;
638
639 name++;
640 }
641
642 return NULL;
643}
644
645/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200646 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
647 * If an invalid character is found, a pointer to it is returned.
648 * If everything is fine, NULL is returned.
649 */
650const char *invalid_domainchar(const char *name) {
651 return __invalid_char(name, isalnum);
652}
653
654/*
655 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
656 * If an invalid character is found, a pointer to it is returned.
657 * If everything is fine, NULL is returned.
658 */
659const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200660 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200661}
662
663/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100664 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100665 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
666 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
667 * the function tries to guess the address family from the syntax. If the
668 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100669 * string is assumed to contain only an address, no port. The address can be a
670 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
671 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
672 * The return address will only have the address family and the address set,
673 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100674 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
675 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100676 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200677 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100678struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200679{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100680 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100681 /* max IPv6 length, including brackets and terminating NULL */
682 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100683 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100684
685 /* check IPv6 with square brackets */
686 if (str[0] == '[') {
687 size_t iplength = strlen(str);
688
689 if (iplength < 4) {
690 /* minimal size is 4 when using brackets "[::]" */
691 goto fail;
692 }
693 else if (iplength >= sizeof(tmpip)) {
694 /* IPv6 literal can not be larger than tmpip */
695 goto fail;
696 }
697 else {
698 if (str[iplength - 1] != ']') {
699 /* if address started with bracket, it should end with bracket */
700 goto fail;
701 }
702 else {
703 memcpy(tmpip, str + 1, iplength - 2);
704 tmpip[iplength - 2] = '\0';
705 str = tmpip;
706 }
707 }
708 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100709
Willy Tarreaufab5a432011-03-04 15:31:53 +0100710 /* Any IPv6 address */
711 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100712 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
713 sa->ss_family = AF_INET6;
714 else if (sa->ss_family != AF_INET6)
715 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100716 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100717 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100718 }
719
Willy Tarreau24709282013-03-10 21:32:12 +0100720 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100721 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100722 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
723 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100724 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100726 }
727
728 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100729 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
730 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100731 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100732 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100733 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100734 }
735
736 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100737 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
738 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100739 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100740 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100741 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100742 }
743
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100744 if (!resolve)
745 return NULL;
746
Emeric Brund30e9a12020-12-23 18:49:16 +0100747 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200748 return NULL;
749
David du Colombierd5f43282011-03-17 10:40:16 +0100750#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200751 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100752 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100753 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100754
755 memset(&result, 0, sizeof(result));
756 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100757 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100758 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200759 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100760 hints.ai_protocol = 0;
761
762 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100763 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
764 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100765 else if (sa->ss_family != result->ai_family) {
766 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100767 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100768 }
Willy Tarreau24709282013-03-10 21:32:12 +0100769
David du Colombierd5f43282011-03-17 10:40:16 +0100770 switch (result->ai_family) {
771 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100772 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100773 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100774 success = 1;
775 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100776 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100777 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100778 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100779 success = 1;
780 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100781 }
782 }
783
Sean Carey58ea0392013-02-15 23:39:18 +0100784 if (result)
785 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100786
787 if (success)
788 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100789 }
David du Colombierd5f43282011-03-17 10:40:16 +0100790#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200791 /* try to resolve an IPv4/IPv6 hostname */
792 he = gethostbyname(str);
793 if (he) {
794 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
795 sa->ss_family = he->h_addrtype;
796 else if (sa->ss_family != he->h_addrtype)
797 goto fail;
798
799 switch (sa->ss_family) {
800 case AF_INET:
801 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100802 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200803 return sa;
804 case AF_INET6:
805 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100806 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200807 return sa;
808 }
809 }
810
David du Colombierd5f43282011-03-17 10:40:16 +0100811 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100812 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100813 return NULL;
814}
815
816/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100817 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
818 * range or offset consisting in two integers that the caller will have to
819 * check to find the relevant input format. The following format are supported :
820 *
821 * String format | address | port | low | high
822 * addr | <addr> | 0 | 0 | 0
823 * addr: | <addr> | 0 | 0 | 0
824 * addr:port | <addr> | <port> | <port> | <port>
825 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
826 * addr:+port | <addr> | <port> | 0 | <port>
827 * addr:-port | <addr> |-<port> | <port> | 0
828 *
829 * The detection of a port range or increment by the caller is made by
830 * comparing <low> and <high>. If both are equal, then port 0 means no port
831 * was specified. The caller may pass NULL for <low> and <high> if it is not
832 * interested in retrieving port ranges.
833 *
834 * Note that <addr> above may also be :
835 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
836 * - "*" => family will be AF_INET and address will be INADDR_ANY
837 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
838 * - a host name => family and address will depend on host name resolving.
839 *
Willy Tarreau24709282013-03-10 21:32:12 +0100840 * A prefix may be passed in before the address above to force the family :
841 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
842 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
843 * - "unix@" => force address to be a path to a UNIX socket even if the
844 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200845 * - 'abns@' -> force address to belong to the abstract namespace (Linux
846 * only). These sockets are just like Unix sockets but without
847 * the need for an underlying file system. The address is a
848 * string. Technically it's like a Unix socket with a zero in
849 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100850 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100851 *
mildisff5d5102015-10-26 18:50:08 +0100852 * IPv6 addresses can be declared with or without square brackets. When using
853 * square brackets for IPv6 addresses, the port separator (colon) is optional.
854 * If not using square brackets, and in order to avoid any ambiguity with
855 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
856 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
857 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100858 *
859 * If <pfx> is non-null, it is used as a string prefix before any path-based
860 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100861 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200862 * if <fqdn> is non-null, it will be filled with :
863 * - a pointer to the FQDN of the server name to resolve if there's one, and
864 * that the caller will have to free(),
865 * - NULL if there was an explicit address that doesn't require resolution.
866 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200867 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
868 * still honored so it is possible for the caller to know whether a resolution
869 * failed by clearing this flag and checking if <fqdn> was filled, indicating
870 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200871 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100872 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200873 * the address when cast to sockaddr_in and the address family is
874 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200875 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200876 * The matching protocol will be set into <proto> if non-null.
877 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200878 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
879 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100880 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200881struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
882 struct protocol **proto, char **err,
883 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100884{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100885 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100886 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200887 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100888 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100889 char *port1, *port2;
890 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200891 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200892 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200893 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100894
895 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200896 if (fqdn)
897 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200898
Willy Tarreaudad36a32013-03-11 01:20:04 +0100899 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100900 if (str2 == NULL) {
901 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100902 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100903 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200904
Willy Tarreau9f69f462015-09-08 16:01:25 +0200905 if (!*str2) {
906 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
907 goto out;
908 }
909
Willy Tarreau24709282013-03-10 21:32:12 +0100910 memset(&ss, 0, sizeof(ss));
911
Willy Tarreaue835bd82020-09-16 11:35:47 +0200912 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100913 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
914 ((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 +0200915 sock_type = ctrl_type = SOCK_DGRAM;
916 else
917 sock_type = ctrl_type = SOCK_STREAM;
918
919 if (strncmp(str2, "stream+", 7) == 0) {
920 str2 += 7;
921 sock_type = ctrl_type = SOCK_STREAM;
922 }
923 else if (strncmp(str2, "dgram+", 6) == 0) {
924 str2 += 6;
925 sock_type = ctrl_type = SOCK_DGRAM;
926 }
927
Willy Tarreau24709282013-03-10 21:32:12 +0100928 if (strncmp(str2, "unix@", 5) == 0) {
929 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200930 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100931 ss.ss_family = AF_UNIX;
932 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200933 else if (strncmp(str2, "abns@", 5) == 0) {
934 str2 += 5;
935 abstract = 1;
936 ss.ss_family = AF_UNIX;
937 }
Willy Tarreau24709282013-03-10 21:32:12 +0100938 else if (strncmp(str2, "ipv4@", 5) == 0) {
939 str2 += 5;
940 ss.ss_family = AF_INET;
941 }
942 else if (strncmp(str2, "ipv6@", 5) == 0) {
943 str2 += 5;
944 ss.ss_family = AF_INET6;
945 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200946 else if (strncmp(str2, "udp4@", 5) == 0) {
947 str2 += 5;
948 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200949 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200950 }
951 else if (strncmp(str2, "udp6@", 5) == 0) {
952 str2 += 5;
953 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200954 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200955 }
956 else if (strncmp(str2, "udp@", 4) == 0) {
957 str2 += 4;
958 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200959 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200960 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +0100961 else if (strncmp(str2, "quic4@", 6) == 0) {
962 str2 += 6;
963 ss.ss_family = AF_INET;
964 sock_type = SOCK_DGRAM;
965 ctrl_type = SOCK_STREAM;
966 }
967 else if (strncmp(str2, "quic6@", 6) == 0) {
968 str2 += 6;
969 ss.ss_family = AF_INET6;
970 sock_type = SOCK_DGRAM;
971 ctrl_type = SOCK_STREAM;
972 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200973 else if (strncmp(str2, "fd@", 3) == 0) {
974 str2 += 3;
975 ss.ss_family = AF_CUST_EXISTING_FD;
976 }
977 else if (strncmp(str2, "sockpair@", 9) == 0) {
978 str2 += 9;
979 ss.ss_family = AF_CUST_SOCKPAIR;
980 }
Willy Tarreau24709282013-03-10 21:32:12 +0100981 else if (*str2 == '/') {
982 ss.ss_family = AF_UNIX;
983 }
984 else
985 ss.ss_family = AF_UNSPEC;
986
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200987 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200988 struct sockaddr_storage ss2;
989 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200990 char *endptr;
991
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200992 new_fd = strtol(str2, &endptr, 10);
993 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200994 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
995 goto out;
996 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200997
Willy Tarreaua215be22020-09-16 10:14:16 +0200998 /* just verify that it's a socket */
999 addr_len = sizeof(ss2);
1000 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1001 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1002 goto out;
1003 }
1004
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001005 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1006 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001007 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001008 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001009 char *endptr;
1010
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001011 new_fd = strtol(str2, &endptr, 10);
1012 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001013 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001014 goto out;
1015 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001016
Willy Tarreau6edc7222020-09-15 17:41:56 +02001017 if (opts & PA_O_SOCKET_FD) {
1018 socklen_t addr_len;
1019 int type;
1020
1021 addr_len = sizeof(ss);
1022 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1023 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1024 goto out;
1025 }
1026
1027 addr_len = sizeof(type);
1028 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001029 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001030 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1031 goto out;
1032 }
1033
1034 porta = portl = porth = get_host_port(&ss);
1035 } else if (opts & PA_O_RAW_FD) {
1036 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1037 ((struct sockaddr_in *)&ss)->sin_port = 0;
1038 } else {
1039 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1040 goto out;
1041 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001042 }
1043 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001044 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001045 int prefix_path_len;
1046 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001047 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001048
1049 /* complete unix socket path name during startup or soft-restart is
1050 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1051 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001052 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001053 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001054 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001055
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001056 adr_len = strlen(str2);
1057 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001058 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1059 goto out;
1060 }
1061
Willy Tarreauccfccef2014-05-10 01:49:15 +02001062 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001063 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001064 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001065 memcpy(un->sun_path, pfx, prefix_path_len);
1066 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001067 }
Willy Tarreau24709282013-03-10 21:32:12 +01001068 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001069 char *end = str2 + strlen(str2);
1070 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001071
mildisff5d5102015-10-26 18:50:08 +01001072 /* search for : or ] whatever comes first */
1073 for (chr = end-1; chr > str2; chr--) {
1074 if (*chr == ']' || *chr == ':')
1075 break;
1076 }
1077
1078 if (*chr == ':') {
1079 /* Found a colon before a closing-bracket, must be a port separator.
1080 * This guarantee backward compatibility.
1081 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001082 if (!(opts & PA_O_PORT_OK)) {
1083 memprintf(err, "port specification not permitted here in '%s'", str);
1084 goto out;
1085 }
mildisff5d5102015-10-26 18:50:08 +01001086 *chr++ = '\0';
1087 port1 = chr;
1088 }
1089 else {
1090 /* Either no colon and no closing-bracket
1091 * or directly ending with a closing-bracket.
1092 * However, no port.
1093 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001094 if (opts & PA_O_PORT_MAND) {
1095 memprintf(err, "missing port specification in '%s'", str);
1096 goto out;
1097 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001098 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001099 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001100
Willy Tarreau90807112020-02-25 08:16:33 +01001101 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001102 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001103 if (port2) {
1104 if (!(opts & PA_O_PORT_RANGE)) {
1105 memprintf(err, "port range not permitted here in '%s'", str);
1106 goto out;
1107 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001108 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001109 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001110 else
1111 port2 = port1;
1112 portl = atoi(port1);
1113 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001114
1115 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1116 memprintf(err, "invalid port '%s'", port1);
1117 goto out;
1118 }
1119
1120 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1121 memprintf(err, "invalid port '%s'", port2);
1122 goto out;
1123 }
1124
1125 if (portl > porth) {
1126 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1127 goto out;
1128 }
1129
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001130 porta = portl;
1131 }
1132 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001133 if (!(opts & PA_O_PORT_OFS)) {
1134 memprintf(err, "port offset not permitted here in '%s'", str);
1135 goto out;
1136 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001137 portl = atoi(port1 + 1);
1138 porta = -portl;
1139 }
1140 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001141 if (!(opts & PA_O_PORT_OFS)) {
1142 memprintf(err, "port offset not permitted here in '%s'", str);
1143 goto out;
1144 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001145 porth = atoi(port1 + 1);
1146 porta = porth;
1147 }
1148 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001149 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001150 goto out;
1151 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001152 else if (opts & PA_O_PORT_MAND) {
1153 memprintf(err, "missing port specification in '%s'", str);
1154 goto out;
1155 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001156
1157 /* first try to parse the IP without resolving. If it fails, it
1158 * tells us we need to keep a copy of the FQDN to resolve later
1159 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001160 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001161 */
1162 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001163 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1164 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001165 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1166 goto out;
1167 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001168
Willy Tarreauceccdd72016-11-02 22:27:10 +01001169 if (fqdn) {
1170 if (str2 != back)
1171 memmove(back, str2, strlen(str2) + 1);
1172 *fqdn = back;
1173 back = NULL;
1174 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001175 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001176 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001177 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001178
Willy Tarreaue835bd82020-09-16 11:35:47 +02001179 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1180 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1181 goto out;
1182 }
1183 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1184 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1185 goto out;
1186 }
1187
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001188 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001189 /* Note: if the caller asks for a proto, we must find one,
1190 * except if we return with an fqdn that will resolve later,
1191 * in which case the address is not known yet (this is only
1192 * for servers actually).
1193 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001194 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001195 sock_type == SOCK_DGRAM,
1196 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001197
Willy Tarreau5fc93282020-09-16 18:25:03 +02001198 if (!new_proto && (!fqdn || !*fqdn)) {
1199 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1200 goto out;
1201 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001202
1203 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1204 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1205 goto out;
1206 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001207 }
1208
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001209 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001210 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001211 if (port)
1212 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001213 if (low)
1214 *low = portl;
1215 if (high)
1216 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001217 if (fd)
1218 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001219 if (proto)
1220 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001221 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001222 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001223}
1224
Thayne McCombs92149f92020-11-20 01:28:26 -07001225/* converts <addr> and <port> into a string representation of the address and port. This is sort
1226 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1227 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1228 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1229 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1230 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1231 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1232 *
1233 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1234 */
1235char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1236{
1237 char buffer[INET6_ADDRSTRLEN];
1238 char *out = NULL;
1239 const void *ptr;
1240 const char *path;
1241
1242 switch (addr->ss_family) {
1243 case AF_INET:
1244 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1245 break;
1246 case AF_INET6:
1247 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1248 break;
1249 case AF_UNIX:
1250 path = ((struct sockaddr_un *)addr)->sun_path;
1251 if (path[0] == '\0') {
1252 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1253 return memprintf(&out, "abns@%.*s", max_length, path+1);
1254 } else {
1255 return strdup(path);
1256 }
1257 case AF_CUST_SOCKPAIR:
1258 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1259 default:
1260 return NULL;
1261 }
1262 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1263 if (map_ports)
1264 return memprintf(&out, "%s:%+d", buffer, port);
1265 else
1266 return memprintf(&out, "%s:%d", buffer, port);
1267}
1268
1269
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001270/* converts <str> to a struct in_addr containing a network mask. It can be
1271 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001272 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001273 */
1274int str2mask(const char *str, struct in_addr *mask)
1275{
1276 if (strchr(str, '.') != NULL) { /* dotted notation */
1277 if (!inet_pton(AF_INET, str, mask))
1278 return 0;
1279 }
1280 else { /* mask length */
1281 char *err;
1282 unsigned long len = strtol(str, &err, 10);
1283
1284 if (!*str || (err && *err) || (unsigned)len > 32)
1285 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001286
1287 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001288 }
1289 return 1;
1290}
1291
Tim Duesterhus47185172018-01-25 16:24:49 +01001292/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001293 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001294 * if the conversion succeeds otherwise zero.
1295 */
1296int str2mask6(const char *str, struct in6_addr *mask)
1297{
1298 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1299 if (!inet_pton(AF_INET6, str, mask))
1300 return 0;
1301 }
1302 else { /* mask length */
1303 char *err;
1304 unsigned long len = strtol(str, &err, 10);
1305
1306 if (!*str || (err && *err) || (unsigned)len > 128)
1307 return 0;
1308
1309 len2mask6(len, mask);
1310 }
1311 return 1;
1312}
1313
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001314/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1315 * succeeds otherwise zero.
1316 */
1317int cidr2dotted(int cidr, struct in_addr *mask) {
1318
1319 if (cidr < 0 || cidr > 32)
1320 return 0;
1321
1322 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1323 return 1;
1324}
1325
Thierry Fournier70473a52016-02-17 17:12:14 +01001326/* Convert mask from bit length form to in_addr form.
1327 * This function never fails.
1328 */
1329void len2mask4(int len, struct in_addr *addr)
1330{
1331 if (len >= 32) {
1332 addr->s_addr = 0xffffffff;
1333 return;
1334 }
1335 if (len <= 0) {
1336 addr->s_addr = 0x00000000;
1337 return;
1338 }
1339 addr->s_addr = 0xffffffff << (32 - len);
1340 addr->s_addr = htonl(addr->s_addr);
1341}
1342
1343/* Convert mask from bit length form to in6_addr form.
1344 * This function never fails.
1345 */
1346void len2mask6(int len, struct in6_addr *addr)
1347{
1348 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1349 len -= 32;
1350 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1351 len -= 32;
1352 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1353 len -= 32;
1354 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1355}
1356
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001357/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001358 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001359 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001360 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001361 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1362 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001363int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001364{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001365 __label__ out_free, out_err;
1366 char *c, *s;
1367 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001368
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001369 s = strdup(str);
1370 if (!s)
1371 return 0;
1372
Willy Tarreaubaaee002006-06-26 02:48:02 +02001373 memset(mask, 0, sizeof(*mask));
1374 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001375
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001376 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001377 *c++ = '\0';
1378 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001379 if (!str2mask(c, mask))
1380 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001381 }
1382 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001383 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001384 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001385 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001386 struct hostent *he;
1387
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001388 if (!resolve)
1389 goto out_err;
1390
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001391 if ((he = gethostbyname(s)) == NULL) {
1392 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001393 }
1394 else
1395 *addr = *(struct in_addr *) *(he->h_addr_list);
1396 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001397
1398 ret_val = 1;
1399 out_free:
1400 free(s);
1401 return ret_val;
1402 out_err:
1403 ret_val = 0;
1404 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001405}
1406
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001407
1408/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001409 * converts <str> to two struct in6_addr* which must be pre-allocated.
1410 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001411 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001412 * Returns 1 if OK, 0 if error.
1413 */
1414int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1415{
1416 char *c, *s;
1417 int ret_val = 0;
1418 char *err;
1419 unsigned long len = 128;
1420
1421 s = strdup(str);
1422 if (!s)
1423 return 0;
1424
1425 memset(mask, 0, sizeof(*mask));
1426 memset(addr, 0, sizeof(*addr));
1427
1428 if ((c = strrchr(s, '/')) != NULL) {
1429 *c++ = '\0'; /* c points to the mask */
1430 if (!*c)
1431 goto out_free;
1432
1433 len = strtoul(c, &err, 10);
1434 if ((err && *err) || (unsigned)len > 128)
1435 goto out_free;
1436 }
1437 *mask = len; /* OK we have a valid mask in <len> */
1438
1439 if (!inet_pton(AF_INET6, s, addr))
1440 goto out_free;
1441
1442 ret_val = 1;
1443 out_free:
1444 free(s);
1445 return ret_val;
1446}
1447
1448
1449/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001450 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1451 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1452 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001453 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001454int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001455{
1456 int saw_digit, octets, ch;
1457 u_char tmp[4], *tp;
1458 const char *cp = addr;
1459
1460 saw_digit = 0;
1461 octets = 0;
1462 *(tp = tmp) = 0;
1463
1464 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001465 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001466 if (digit > 9 && ch != '.')
1467 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001468 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001469 if (digit <= 9) {
1470 u_int new = *tp * 10 + digit;
1471 if (new > 255)
1472 return 0;
1473 *tp = new;
1474 if (!saw_digit) {
1475 if (++octets > 4)
1476 return 0;
1477 saw_digit = 1;
1478 }
1479 } else if (ch == '.' && saw_digit) {
1480 if (octets == 4)
1481 return 0;
1482 *++tp = 0;
1483 saw_digit = 0;
1484 } else
1485 return 0;
1486 }
1487
1488 if (octets < 4)
1489 return 0;
1490
1491 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001492 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001493}
1494
1495/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001496 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001497 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001498 * the hostname. Actually only http and https are supported. <out> can be NULL.
1499 * This function returns the consumed length. It is useful if you parse complete
1500 * url like http://host:port/path, because the consumed length corresponds to
1501 * the first character of the path. If the conversion fails, it returns -1.
1502 *
1503 * This function tries to resolve the DNS name if haproxy is in starting mode.
1504 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001505 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001506int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001507{
1508 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001509 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001510 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001511 unsigned long long int http_code = 0;
1512 int default_port;
1513 struct hostent *he;
1514 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001515
1516 /* Firstly, try to find :// pattern */
1517 while (curr < url+ulen && url_code != 0x3a2f2f) {
1518 url_code = ((url_code & 0xffff) << 8);
1519 url_code += (unsigned char)*curr++;
1520 }
1521
1522 /* Secondly, if :// pattern is found, verify parsed stuff
1523 * before pattern is matching our http pattern.
1524 * If so parse ip address and port in uri.
1525 *
1526 * WARNING: Current code doesn't support dynamic async dns resolver.
1527 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001528 if (url_code != 0x3a2f2f)
1529 return -1;
1530
1531 /* Copy scheme, and utrn to lower case. */
1532 while (cp < curr - 3)
1533 http_code = (http_code << 8) + *cp++;
1534 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001535
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001536 /* HTTP or HTTPS url matching */
1537 if (http_code == 0x2020202068747470ULL) {
1538 default_port = 80;
1539 if (out)
1540 out->scheme = SCH_HTTP;
1541 }
1542 else if (http_code == 0x2020206874747073ULL) {
1543 default_port = 443;
1544 if (out)
1545 out->scheme = SCH_HTTPS;
1546 }
1547 else
1548 return -1;
1549
1550 /* If the next char is '[', the host address is IPv6. */
1551 if (*curr == '[') {
1552 curr++;
1553
1554 /* Check trash size */
1555 if (trash.size < ulen)
1556 return -1;
1557
1558 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001559 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001560 for (end = curr;
1561 end < url + ulen && *end != ']';
1562 end++, p++)
1563 *p = *end;
1564 if (*end != ']')
1565 return -1;
1566 *p = '\0';
1567
1568 /* Update out. */
1569 if (out) {
1570 out->host = curr;
1571 out->host_len = end - curr;
1572 }
1573
1574 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001575 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001576 return -1;
1577 end++;
1578
1579 /* Decode port. */
1580 if (*end == ':') {
1581 end++;
1582 default_port = read_uint(&end, url + ulen);
1583 }
1584 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1585 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1586 return end - url;
1587 }
1588 else {
1589 /* We are looking for IP address. If you want to parse and
1590 * resolve hostname found in url, you can use str2sa_range(), but
1591 * be warned this can slow down global daemon performances
1592 * while handling lagging dns responses.
1593 */
1594 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1595 if (ret) {
1596 /* Update out. */
1597 if (out) {
1598 out->host = curr;
1599 out->host_len = ret;
1600 }
1601
1602 curr += ret;
1603
1604 /* Decode port. */
1605 if (*curr == ':') {
1606 curr++;
1607 default_port = read_uint(&curr, url + ulen);
1608 }
1609 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1610
1611 /* Set family. */
1612 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1613 return curr - url;
1614 }
1615 else if (global.mode & MODE_STARTING) {
1616 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1617 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001618 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001619
1620 /* look for : or / or end */
1621 for (end = curr;
1622 end < url + ulen && *end != '/' && *end != ':';
1623 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001624 memcpy(trash.area, curr, end - curr);
1625 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001626
1627 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001628 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001629 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001630 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001631
1632 /* Update out. */
1633 if (out) {
1634 out->host = curr;
1635 out->host_len = end - curr;
1636 }
1637
1638 /* Decode port. */
1639 if (*end == ':') {
1640 end++;
1641 default_port = read_uint(&end, url + ulen);
1642 }
1643
1644 /* Copy IP address, set port and family. */
1645 switch (he->h_addrtype) {
1646 case AF_INET:
1647 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1648 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1649 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1650 return end - url;
1651
1652 case AF_INET6:
1653 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1654 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1655 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1656 return end - url;
1657 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001658 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001659 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001660 return -1;
1661}
1662
Willy Tarreau631f01c2011-09-05 00:36:48 +02001663/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1664 * address family is returned so that it's easy for the caller to adapt to the
1665 * output format. Zero is returned if the address family is not supported. -1
1666 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1667 * supported.
1668 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001669int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001670{
1671
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001672 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001673
1674 if (size < 5)
1675 return 0;
1676 *str = '\0';
1677
1678 switch (addr->ss_family) {
1679 case AF_INET:
1680 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1681 break;
1682 case AF_INET6:
1683 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1684 break;
1685 case AF_UNIX:
1686 memcpy(str, "unix", 5);
1687 return addr->ss_family;
1688 default:
1689 return 0;
1690 }
1691
1692 if (inet_ntop(addr->ss_family, ptr, str, size))
1693 return addr->ss_family;
1694
1695 /* failed */
1696 return -1;
1697}
1698
Simon Horman75ab8bd2014-06-16 09:39:41 +09001699/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1700 * address family is returned so that it's easy for the caller to adapt to the
1701 * output format. Zero is returned if the address family is not supported. -1
1702 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1703 * supported.
1704 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001705int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001706{
1707
1708 uint16_t port;
1709
1710
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001711 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001712 return 0;
1713 *str = '\0';
1714
1715 switch (addr->ss_family) {
1716 case AF_INET:
1717 port = ((struct sockaddr_in *)addr)->sin_port;
1718 break;
1719 case AF_INET6:
1720 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1721 break;
1722 case AF_UNIX:
1723 memcpy(str, "unix", 5);
1724 return addr->ss_family;
1725 default:
1726 return 0;
1727 }
1728
1729 snprintf(str, size, "%u", ntohs(port));
1730 return addr->ss_family;
1731}
1732
Willy Tarreau16e01562016-08-09 16:46:18 +02001733/* check if the given address is local to the system or not. It will return
1734 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1735 * it is. We don't want to iterate over all interfaces for this (and it is not
1736 * portable). So instead we try to bind in UDP to this address on a free non
1737 * privileged port and to connect to the same address, port 0 (connect doesn't
1738 * care). If it succeeds, we own the address. Note that non-inet addresses are
1739 * considered local since they're most likely AF_UNIX.
1740 */
1741int addr_is_local(const struct netns_entry *ns,
1742 const struct sockaddr_storage *orig)
1743{
1744 struct sockaddr_storage addr;
1745 int result;
1746 int fd;
1747
1748 if (!is_inet_addr(orig))
1749 return 1;
1750
1751 memcpy(&addr, orig, sizeof(addr));
1752 set_host_port(&addr, 0);
1753
1754 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1755 if (fd < 0)
1756 return -1;
1757
1758 result = -1;
1759 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1760 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1761 result = 0; // fail, non-local address
1762 else
1763 result = 1; // success, local address
1764 }
1765 else {
1766 if (errno == EADDRNOTAVAIL)
1767 result = 0; // definitely not local :-)
1768 }
1769 close(fd);
1770
1771 return result;
1772}
1773
Willy Tarreaubaaee002006-06-26 02:48:02 +02001774/* will try to encode the string <string> replacing all characters tagged in
1775 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1776 * prefixed by <escape>, and will store the result between <start> (included)
1777 * and <stop> (excluded), and will always terminate the string with a '\0'
1778 * before <stop>. The position of the '\0' is returned if the conversion
1779 * completes. If bytes are missing between <start> and <stop>, then the
1780 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1781 * cannot even be stored so we return <start> without writing the 0.
1782 * The input string must also be zero-terminated.
1783 */
1784const char hextab[16] = "0123456789ABCDEF";
1785char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001786 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001787 const char *string)
1788{
1789 if (start < stop) {
1790 stop--; /* reserve one byte for the final '\0' */
1791 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001792 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001793 *start++ = *string;
1794 else {
1795 if (start + 3 >= stop)
1796 break;
1797 *start++ = escape;
1798 *start++ = hextab[(*string >> 4) & 15];
1799 *start++ = hextab[*string & 15];
1800 }
1801 string++;
1802 }
1803 *start = '\0';
1804 }
1805 return start;
1806}
1807
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001808/*
1809 * Same behavior as encode_string() above, except that it encodes chunk
1810 * <chunk> instead of a string.
1811 */
1812char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001813 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001814 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001815{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001816 char *str = chunk->area;
1817 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001818
1819 if (start < stop) {
1820 stop--; /* reserve one byte for the final '\0' */
1821 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001822 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001823 *start++ = *str;
1824 else {
1825 if (start + 3 >= stop)
1826 break;
1827 *start++ = escape;
1828 *start++ = hextab[(*str >> 4) & 15];
1829 *start++ = hextab[*str & 15];
1830 }
1831 str++;
1832 }
1833 *start = '\0';
1834 }
1835 return start;
1836}
1837
Dragan Dosen0edd1092016-02-12 13:23:02 +01001838/*
1839 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001840 * character. The input <string> must be zero-terminated. The result will
1841 * be stored between <start> (included) and <stop> (excluded). This
1842 * function will always try to terminate the resulting string with a '\0'
1843 * before <stop>, and will return its position if the conversion
1844 * completes.
1845 */
1846char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001847 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001848 const char *string)
1849{
1850 if (start < stop) {
1851 stop--; /* reserve one byte for the final '\0' */
1852 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001853 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001854 *start++ = *string;
1855 else {
1856 if (start + 2 >= stop)
1857 break;
1858 *start++ = escape;
1859 *start++ = *string;
1860 }
1861 string++;
1862 }
1863 *start = '\0';
1864 }
1865 return start;
1866}
1867
1868/*
1869 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001870 * character. <chunk> contains the input to be escaped. The result will be
1871 * stored between <start> (included) and <stop> (excluded). The function
1872 * will always try to terminate the resulting string with a '\0' before
1873 * <stop>, and will return its position if the conversion completes.
1874 */
1875char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001876 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001877 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001878{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001879 char *str = chunk->area;
1880 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001881
1882 if (start < stop) {
1883 stop--; /* reserve one byte for the final '\0' */
1884 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001885 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001886 *start++ = *str;
1887 else {
1888 if (start + 2 >= stop)
1889 break;
1890 *start++ = escape;
1891 *start++ = *str;
1892 }
1893 str++;
1894 }
1895 *start = '\0';
1896 }
1897 return start;
1898}
1899
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001900/* Check a string for using it in a CSV output format. If the string contains
1901 * one of the following four char <">, <,>, CR or LF, the string is
1902 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1903 * <str> is the input string to be escaped. The function assumes that
1904 * the input string is null-terminated.
1905 *
1906 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001907 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001908 * format.
1909 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001910 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001911 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001912 * If <quote> is 1, the converter puts the quotes only if any reserved character
1913 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001914 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001915 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001916 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001917 * The function returns the converted string on its output. If an error
1918 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001919 * for using the function directly as printf() argument.
1920 *
1921 * If the output buffer is too short to contain the input string, the result
1922 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001923 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001924 * This function appends the encoding to the existing output chunk, and it
1925 * guarantees that it starts immediately at the first available character of
1926 * the chunk. Please use csv_enc() instead if you want to replace the output
1927 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001928 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001929const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001930{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001931 char *end = output->area + output->size;
1932 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001933 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001934
Willy Tarreaub631c292016-01-08 10:04:08 +01001935 if (quote == 1) {
1936 /* automatic quoting: first verify if we'll have to quote the string */
1937 if (!strpbrk(str, "\n\r,\""))
1938 quote = 0;
1939 }
1940
1941 if (quote)
1942 *ptr++ = '"';
1943
Willy Tarreau898529b2016-01-06 18:07:04 +01001944 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1945 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001946 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001947 ptr++;
1948 if (ptr >= end - 2) {
1949 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001950 break;
1951 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001952 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001953 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001954 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001955 str++;
1956 }
1957
Willy Tarreaub631c292016-01-08 10:04:08 +01001958 if (quote)
1959 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001960
Willy Tarreau898529b2016-01-06 18:07:04 +01001961 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001962 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001963 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001964}
1965
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001966/* Decode an URL-encoded string in-place. The resulting string might
1967 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001968 * aborted, the string is truncated before the issue and a negative value is
1969 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001970 * If the 'in_form' argument is non-nul the string is assumed to be part of
1971 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1972 * turned to a space. If it's zero, this will only be done after a question
1973 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001974 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001975int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001976{
1977 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001978 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001979
1980 in = string;
1981 out = string;
1982 while (*in) {
1983 switch (*in) {
1984 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001985 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001986 break;
1987 case '%' :
1988 if (!ishex(in[1]) || !ishex(in[2]))
1989 goto end;
1990 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1991 in += 2;
1992 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001993 case '?':
1994 in_form = 1;
1995 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001996 default:
1997 *out++ = *in;
1998 break;
1999 }
2000 in++;
2001 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002002 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002003 end:
2004 *out = 0;
2005 return ret;
2006}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002007
Willy Tarreau6911fa42007-03-04 18:06:08 +01002008unsigned int str2ui(const char *s)
2009{
2010 return __str2ui(s);
2011}
2012
2013unsigned int str2uic(const char *s)
2014{
2015 return __str2uic(s);
2016}
2017
2018unsigned int strl2ui(const char *s, int len)
2019{
2020 return __strl2ui(s, len);
2021}
2022
2023unsigned int strl2uic(const char *s, int len)
2024{
2025 return __strl2uic(s, len);
2026}
2027
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002028unsigned int read_uint(const char **s, const char *end)
2029{
2030 return __read_uint(s, end);
2031}
2032
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002033/* This function reads an unsigned integer from the string pointed to by <s> and
2034 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2035 * function automatically stops at <end>. If the number overflows, the 2^64-1
2036 * value is returned.
2037 */
2038unsigned long long int read_uint64(const char **s, const char *end)
2039{
2040 const char *ptr = *s;
2041 unsigned long long int i = 0, tmp;
2042 unsigned int j;
2043
2044 while (ptr < end) {
2045
2046 /* read next char */
2047 j = *ptr - '0';
2048 if (j > 9)
2049 goto read_uint64_end;
2050
2051 /* add char to the number and check overflow. */
2052 tmp = i * 10;
2053 if (tmp / 10 != i) {
2054 i = ULLONG_MAX;
2055 goto read_uint64_eat;
2056 }
2057 if (ULLONG_MAX - tmp < j) {
2058 i = ULLONG_MAX;
2059 goto read_uint64_eat;
2060 }
2061 i = tmp + j;
2062 ptr++;
2063 }
2064read_uint64_eat:
2065 /* eat each numeric char */
2066 while (ptr < end) {
2067 if ((unsigned int)(*ptr - '0') > 9)
2068 break;
2069 ptr++;
2070 }
2071read_uint64_end:
2072 *s = ptr;
2073 return i;
2074}
2075
2076/* This function reads an integer from the string pointed to by <s> and returns
2077 * it. The <s> pointer is adjusted to point to the first unread char. The function
2078 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2079 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2080 * returned.
2081 */
2082long long int read_int64(const char **s, const char *end)
2083{
2084 unsigned long long int i = 0;
2085 int neg = 0;
2086
2087 /* Look for minus char. */
2088 if (**s == '-') {
2089 neg = 1;
2090 (*s)++;
2091 }
2092 else if (**s == '+')
2093 (*s)++;
2094
2095 /* convert as positive number. */
2096 i = read_uint64(s, end);
2097
2098 if (neg) {
2099 if (i > 0x8000000000000000ULL)
2100 return LLONG_MIN;
2101 return -i;
2102 }
2103 if (i > 0x7fffffffffffffffULL)
2104 return LLONG_MAX;
2105 return i;
2106}
2107
Willy Tarreau6911fa42007-03-04 18:06:08 +01002108/* This one is 7 times faster than strtol() on athlon with checks.
2109 * It returns the value of the number composed of all valid digits read,
2110 * and can process negative numbers too.
2111 */
2112int strl2ic(const char *s, int len)
2113{
2114 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002115 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002116
2117 if (len > 0) {
2118 if (*s != '-') {
2119 /* positive number */
2120 while (len-- > 0) {
2121 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002122 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002123 if (j > 9)
2124 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002125 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002126 }
2127 } else {
2128 /* negative number */
2129 s++;
2130 while (--len > 0) {
2131 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002132 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002133 if (j > 9)
2134 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002135 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002136 }
2137 }
2138 }
2139 return i;
2140}
2141
2142
2143/* This function reads exactly <len> chars from <s> and converts them to a
2144 * signed integer which it stores into <ret>. It accurately detects any error
2145 * (truncated string, invalid chars, overflows). It is meant to be used in
2146 * applications designed for hostile environments. It returns zero when the
2147 * number has successfully been converted, non-zero otherwise. When an error
2148 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2149 * faster than strtol().
2150 */
2151int strl2irc(const char *s, int len, int *ret)
2152{
2153 int i = 0;
2154 int j;
2155
2156 if (!len)
2157 return 1;
2158
2159 if (*s != '-') {
2160 /* positive number */
2161 while (len-- > 0) {
2162 j = (*s++) - '0';
2163 if (j > 9) return 1; /* invalid char */
2164 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2165 i = i * 10;
2166 if (i + j < i) return 1; /* check for addition overflow */
2167 i = i + j;
2168 }
2169 } else {
2170 /* negative number */
2171 s++;
2172 while (--len > 0) {
2173 j = (*s++) - '0';
2174 if (j > 9) return 1; /* invalid char */
2175 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2176 i = i * 10;
2177 if (i - j > i) return 1; /* check for subtract overflow */
2178 i = i - j;
2179 }
2180 }
2181 *ret = i;
2182 return 0;
2183}
2184
2185
2186/* This function reads exactly <len> chars from <s> and converts them to a
2187 * signed integer which it stores into <ret>. It accurately detects any error
2188 * (truncated string, invalid chars, overflows). It is meant to be used in
2189 * applications designed for hostile environments. It returns zero when the
2190 * number has successfully been converted, non-zero otherwise. When an error
2191 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002192 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002193 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002194
2195int strl2llrc(const char *s, int len, long long *ret)
2196{
2197 long long i = 0;
2198 int j;
2199
2200 if (!len)
2201 return 1;
2202
2203 if (*s != '-') {
2204 /* positive number */
2205 while (len-- > 0) {
2206 j = (*s++) - '0';
2207 if (j > 9) return 1; /* invalid char */
2208 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2209 i = i * 10LL;
2210 if (i + j < i) return 1; /* check for addition overflow */
2211 i = i + j;
2212 }
2213 } else {
2214 /* negative number */
2215 s++;
2216 while (--len > 0) {
2217 j = (*s++) - '0';
2218 if (j > 9) return 1; /* invalid char */
2219 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2220 i = i * 10LL;
2221 if (i - j > i) return 1; /* check for subtract overflow */
2222 i = i - j;
2223 }
2224 }
2225 *ret = i;
2226 return 0;
2227}
2228
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002229/* This function is used with pat_parse_dotted_ver(). It converts a string
2230 * composed by two number separated by a dot. Each part must contain in 16 bits
2231 * because internally they will be represented as a 32-bit quantity stored in
2232 * a 64-bit integer. It returns zero when the number has successfully been
2233 * converted, non-zero otherwise. When an error is returned, the <ret> value
2234 * is left untouched.
2235 *
2236 * "1.3" -> 0x0000000000010003
2237 * "65535.65535" -> 0x00000000ffffffff
2238 */
2239int strl2llrc_dotted(const char *text, int len, long long *ret)
2240{
2241 const char *end = &text[len];
2242 const char *p;
2243 long long major, minor;
2244
2245 /* Look for dot. */
2246 for (p = text; p < end; p++)
2247 if (*p == '.')
2248 break;
2249
2250 /* Convert major. */
2251 if (strl2llrc(text, p - text, &major) != 0)
2252 return 1;
2253
2254 /* Check major. */
2255 if (major >= 65536)
2256 return 1;
2257
2258 /* Convert minor. */
2259 minor = 0;
2260 if (p < end)
2261 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2262 return 1;
2263
2264 /* Check minor. */
2265 if (minor >= 65536)
2266 return 1;
2267
2268 /* Compose value. */
2269 *ret = (major << 16) | (minor & 0xffff);
2270 return 0;
2271}
2272
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002273/* This function parses a time value optionally followed by a unit suffix among
2274 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2275 * expected by the caller. The computation does its best to avoid overflows.
2276 * The value is returned in <ret> if everything is fine, and a NULL is returned
2277 * by the function. In case of error, a pointer to the error is returned and
2278 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002279 * Values resulting in values larger than or equal to 2^31 after conversion are
2280 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2281 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002282 */
2283const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2284{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002285 unsigned long long imult, idiv;
2286 unsigned long long omult, odiv;
2287 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002288 const char *str = text;
2289
2290 if (!isdigit((unsigned char)*text))
2291 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002292
2293 omult = odiv = 1;
2294
2295 switch (unit_flags & TIME_UNIT_MASK) {
2296 case TIME_UNIT_US: omult = 1000000; break;
2297 case TIME_UNIT_MS: omult = 1000; break;
2298 case TIME_UNIT_S: break;
2299 case TIME_UNIT_MIN: odiv = 60; break;
2300 case TIME_UNIT_HOUR: odiv = 3600; break;
2301 case TIME_UNIT_DAY: odiv = 86400; break;
2302 default: break;
2303 }
2304
2305 value = 0;
2306
2307 while (1) {
2308 unsigned int j;
2309
2310 j = *text - '0';
2311 if (j > 9)
2312 break;
2313 text++;
2314 value *= 10;
2315 value += j;
2316 }
2317
2318 imult = idiv = 1;
2319 switch (*text) {
2320 case '\0': /* no unit = default unit */
2321 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002322 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002323 case 's': /* second = unscaled unit */
2324 break;
2325 case 'u': /* microsecond : "us" */
2326 if (text[1] == 's') {
2327 idiv = 1000000;
2328 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002329 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002330 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002331 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002332 case 'm': /* millisecond : "ms" or minute: "m" */
2333 if (text[1] == 's') {
2334 idiv = 1000;
2335 text++;
2336 } else
2337 imult = 60;
2338 break;
2339 case 'h': /* hour : "h" */
2340 imult = 3600;
2341 break;
2342 case 'd': /* day : "d" */
2343 imult = 86400;
2344 break;
2345 default:
2346 return text;
2347 break;
2348 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002349 if (*(++text) != '\0') {
2350 ha_warning("unexpected character '%c' after the timer value '%s', only "
2351 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2352 " This will be reported as an error in next versions.\n", *text, str);
2353 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002354
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002355 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002356 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2357 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2358 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2359 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2360
Willy Tarreau9faebe32019-06-07 19:00:37 +02002361 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2362 if (result >= 0x80000000)
2363 return PARSE_TIME_OVER;
2364 if (!result && value)
2365 return PARSE_TIME_UNDER;
2366 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002367 return NULL;
2368}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002369
Emeric Brun39132b22010-01-04 14:57:24 +01002370/* this function converts the string starting at <text> to an unsigned int
2371 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002372 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002373 */
2374const char *parse_size_err(const char *text, unsigned *ret) {
2375 unsigned value = 0;
2376
Christopher Faulet82635a02020-12-11 09:30:45 +01002377 if (!isdigit((unsigned char)*text))
2378 return text;
2379
Emeric Brun39132b22010-01-04 14:57:24 +01002380 while (1) {
2381 unsigned int j;
2382
2383 j = *text - '0';
2384 if (j > 9)
2385 break;
2386 if (value > ~0U / 10)
2387 return text;
2388 value *= 10;
2389 if (value > (value + j))
2390 return text;
2391 value += j;
2392 text++;
2393 }
2394
2395 switch (*text) {
2396 case '\0':
2397 break;
2398 case 'K':
2399 case 'k':
2400 if (value > ~0U >> 10)
2401 return text;
2402 value = value << 10;
2403 break;
2404 case 'M':
2405 case 'm':
2406 if (value > ~0U >> 20)
2407 return text;
2408 value = value << 20;
2409 break;
2410 case 'G':
2411 case 'g':
2412 if (value > ~0U >> 30)
2413 return text;
2414 value = value << 30;
2415 break;
2416 default:
2417 return text;
2418 }
2419
Godbach58048a22015-01-28 17:36:16 +08002420 if (*text != '\0' && *++text != '\0')
2421 return text;
2422
Emeric Brun39132b22010-01-04 14:57:24 +01002423 *ret = value;
2424 return NULL;
2425}
2426
Willy Tarreau126d4062013-12-03 17:50:47 +01002427/*
2428 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002429 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002430 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002431 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002432 */
2433int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2434{
2435 int len;
2436 const char *p = source;
2437 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002438 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002439
2440 len = strlen(source);
2441 if (len % 2) {
2442 memprintf(err, "an even number of hex digit is expected");
2443 return 0;
2444 }
2445
2446 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002447
Willy Tarreau126d4062013-12-03 17:50:47 +01002448 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002449 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002450 if (!*binstr) {
2451 memprintf(err, "out of memory while loading string pattern");
2452 return 0;
2453 }
2454 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002455 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002456 else {
2457 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002458 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002459 len, *binstrlen);
2460 return 0;
2461 }
2462 alloc = 0;
2463 }
2464 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002465
2466 i = j = 0;
2467 while (j < len) {
2468 if (!ishex(p[i++]))
2469 goto bad_input;
2470 if (!ishex(p[i++]))
2471 goto bad_input;
2472 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2473 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002474 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002475
2476bad_input:
2477 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002478 if (alloc)
2479 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002480 return 0;
2481}
2482
Willy Tarreau946ba592009-05-10 15:41:18 +02002483/* copies at most <n> characters from <src> and always terminates with '\0' */
2484char *my_strndup(const char *src, int n)
2485{
2486 int len = 0;
2487 char *ret;
2488
2489 while (len < n && src[len])
2490 len++;
2491
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002492 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002493 if (!ret)
2494 return ret;
2495 memcpy(ret, src, len);
2496 ret[len] = '\0';
2497 return ret;
2498}
2499
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002500/*
2501 * search needle in haystack
2502 * returns the pointer if found, returns NULL otherwise
2503 */
2504const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2505{
2506 const void *c = NULL;
2507 unsigned char f;
2508
2509 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2510 return NULL;
2511
2512 f = *(char *)needle;
2513 c = haystack;
2514 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2515 if ((haystacklen - (c - haystack)) < needlelen)
2516 return NULL;
2517
2518 if (memcmp(c, needle, needlelen) == 0)
2519 return c;
2520 ++c;
2521 }
2522 return NULL;
2523}
2524
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002525/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002526size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2527{
2528 size_t ret = 0;
2529
2530 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2531 str++;
2532 ret++;
2533 }
2534 return ret;
2535}
2536
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002537/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002538size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2539{
2540 size_t ret = 0;
2541
2542 while (ret < len) {
2543 if(memchr(reject, *((int *)str), rejectlen))
2544 return ret;
2545 str++;
2546 ret++;
2547 }
2548 return ret;
2549}
2550
Willy Tarreau482b00d2009-10-04 22:48:42 +02002551/* This function returns the first unused key greater than or equal to <key> in
2552 * ID tree <root>. Zero is returned if no place is found.
2553 */
2554unsigned int get_next_id(struct eb_root *root, unsigned int key)
2555{
2556 struct eb32_node *used;
2557
2558 do {
2559 used = eb32_lookup_ge(root, key);
2560 if (!used || used->key > key)
2561 return key; /* key is available */
2562 key++;
2563 } while (key);
2564 return key;
2565}
2566
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002567/* dump the full tree to <file> in DOT format for debugging purposes. Will
2568 * optionally highlight node <subj> if found, depending on operation <op> :
2569 * 0 : nothing
2570 * >0 : insertion, node/leaf are surrounded in red
2571 * <0 : removal, node/leaf are dashed with no background
2572 * Will optionally add "desc" as a label on the graph if set and non-null.
2573 */
2574void 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 +01002575{
2576 struct eb32sc_node *node;
2577 unsigned long scope = -1;
2578
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002579 fprintf(file, "digraph ebtree {\n");
2580
2581 if (desc && *desc) {
2582 fprintf(file,
2583 " fontname=\"fixed\";\n"
2584 " fontsize=8;\n"
2585 " label=\"%s\";\n", desc);
2586 }
2587
Willy Tarreaued3cda02017-11-15 15:04:05 +01002588 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002589 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2590 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002591 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2592 );
2593
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002594 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002595 (long)eb_root_to_node(root),
2596 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002597 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2598
2599 node = eb32sc_first(root, scope);
2600 while (node) {
2601 if (node->node.node_p) {
2602 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002603 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2604 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2605 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002606
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002607 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002608 (long)node,
2609 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002610 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002611
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002612 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002613 (long)node,
2614 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002615 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2616
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002617 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002618 (long)node,
2619 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002620 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2621 }
2622
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002623 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2624 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2625 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002626
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002627 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002628 (long)node,
2629 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002630 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002631 node = eb32sc_next(node, scope);
2632 }
2633 fprintf(file, "}\n");
2634}
2635
Willy Tarreau348238b2010-01-18 15:05:57 +01002636/* This function compares a sample word possibly followed by blanks to another
2637 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2638 * otherwise zero. This intends to be used when checking HTTP headers for some
2639 * values. Note that it validates a word followed only by blanks but does not
2640 * validate a word followed by blanks then other chars.
2641 */
2642int word_match(const char *sample, int slen, const char *word, int wlen)
2643{
2644 if (slen < wlen)
2645 return 0;
2646
2647 while (wlen) {
2648 char c = *sample ^ *word;
2649 if (c && c != ('A' ^ 'a'))
2650 return 0;
2651 sample++;
2652 word++;
2653 slen--;
2654 wlen--;
2655 }
2656
2657 while (slen) {
2658 if (*sample != ' ' && *sample != '\t')
2659 return 0;
2660 sample++;
2661 slen--;
2662 }
2663 return 1;
2664}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002665
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002666/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2667 * is particularly fast because it avoids expensive operations such as
2668 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002669 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002670 */
2671unsigned int inetaddr_host(const char *text)
2672{
2673 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2674 register unsigned int dig100, dig10, dig1;
2675 int s;
2676 const char *p, *d;
2677
2678 dig1 = dig10 = dig100 = ascii_zero;
2679 s = 24;
2680
2681 p = text;
2682 while (1) {
2683 if (((unsigned)(*p - '0')) <= 9) {
2684 p++;
2685 continue;
2686 }
2687
2688 /* here, we have a complete byte between <text> and <p> (exclusive) */
2689 if (p == text)
2690 goto end;
2691
2692 d = p - 1;
2693 dig1 |= (unsigned int)(*d << s);
2694 if (d == text)
2695 goto end;
2696
2697 d--;
2698 dig10 |= (unsigned int)(*d << s);
2699 if (d == text)
2700 goto end;
2701
2702 d--;
2703 dig100 |= (unsigned int)(*d << s);
2704 end:
2705 if (!s || *p != '.')
2706 break;
2707
2708 s -= 8;
2709 text = ++p;
2710 }
2711
2712 dig100 -= ascii_zero;
2713 dig10 -= ascii_zero;
2714 dig1 -= ascii_zero;
2715 return ((dig100 * 10) + dig10) * 10 + dig1;
2716}
2717
2718/*
2719 * Idem except the first unparsed character has to be passed in <stop>.
2720 */
2721unsigned int inetaddr_host_lim(const char *text, const char *stop)
2722{
2723 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2724 register unsigned int dig100, dig10, dig1;
2725 int s;
2726 const char *p, *d;
2727
2728 dig1 = dig10 = dig100 = ascii_zero;
2729 s = 24;
2730
2731 p = text;
2732 while (1) {
2733 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2734 p++;
2735 continue;
2736 }
2737
2738 /* here, we have a complete byte between <text> and <p> (exclusive) */
2739 if (p == text)
2740 goto end;
2741
2742 d = p - 1;
2743 dig1 |= (unsigned int)(*d << s);
2744 if (d == text)
2745 goto end;
2746
2747 d--;
2748 dig10 |= (unsigned int)(*d << s);
2749 if (d == text)
2750 goto end;
2751
2752 d--;
2753 dig100 |= (unsigned int)(*d << s);
2754 end:
2755 if (!s || p == stop || *p != '.')
2756 break;
2757
2758 s -= 8;
2759 text = ++p;
2760 }
2761
2762 dig100 -= ascii_zero;
2763 dig10 -= ascii_zero;
2764 dig1 -= ascii_zero;
2765 return ((dig100 * 10) + dig10) * 10 + dig1;
2766}
2767
2768/*
2769 * Idem except the pointer to first unparsed byte is returned into <ret> which
2770 * must not be NULL.
2771 */
Willy Tarreau74172752010-10-15 23:21:42 +02002772unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002773{
2774 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2775 register unsigned int dig100, dig10, dig1;
2776 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002777 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002778
2779 dig1 = dig10 = dig100 = ascii_zero;
2780 s = 24;
2781
2782 p = text;
2783 while (1) {
2784 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2785 p++;
2786 continue;
2787 }
2788
2789 /* here, we have a complete byte between <text> and <p> (exclusive) */
2790 if (p == text)
2791 goto end;
2792
2793 d = p - 1;
2794 dig1 |= (unsigned int)(*d << s);
2795 if (d == text)
2796 goto end;
2797
2798 d--;
2799 dig10 |= (unsigned int)(*d << s);
2800 if (d == text)
2801 goto end;
2802
2803 d--;
2804 dig100 |= (unsigned int)(*d << s);
2805 end:
2806 if (!s || p == stop || *p != '.')
2807 break;
2808
2809 s -= 8;
2810 text = ++p;
2811 }
2812
2813 *ret = p;
2814 dig100 -= ascii_zero;
2815 dig10 -= ascii_zero;
2816 dig1 -= ascii_zero;
2817 return ((dig100 * 10) + dig10) * 10 + dig1;
2818}
2819
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002820/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2821 * or the number of chars read in case of success. Maybe this could be replaced
2822 * by one of the functions above. Also, apparently this function does not support
2823 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002824 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002825 */
2826int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2827{
2828 const char *addr;
2829 int saw_digit, octets, ch;
2830 u_char tmp[4], *tp;
2831 const char *cp = buf;
2832
2833 saw_digit = 0;
2834 octets = 0;
2835 *(tp = tmp) = 0;
2836
2837 for (addr = buf; addr - buf < len; addr++) {
2838 unsigned char digit = (ch = *addr) - '0';
2839
2840 if (digit > 9 && ch != '.')
2841 break;
2842
2843 if (digit <= 9) {
2844 u_int new = *tp * 10 + digit;
2845
2846 if (new > 255)
2847 return 0;
2848
2849 *tp = new;
2850
2851 if (!saw_digit) {
2852 if (++octets > 4)
2853 return 0;
2854 saw_digit = 1;
2855 }
2856 } else if (ch == '.' && saw_digit) {
2857 if (octets == 4)
2858 return 0;
2859
2860 *++tp = 0;
2861 saw_digit = 0;
2862 } else
2863 return 0;
2864 }
2865
2866 if (octets < 4)
2867 return 0;
2868
2869 memcpy(&dst->s_addr, tmp, 4);
2870 return addr - cp;
2871}
2872
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002873/* This function converts the string in <buf> of the len <len> to
2874 * struct in6_addr <dst> which must be allocated by the caller.
2875 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002876 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002877 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002878int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2879{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002880 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002881 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002882
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002883 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002884 return 0;
2885
2886 memcpy(null_term_ip6, buf, len);
2887 null_term_ip6[len] = '\0';
2888
Willy Tarreau075415a2013-12-12 11:29:39 +01002889 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002890 return 0;
2891
Willy Tarreau075415a2013-12-12 11:29:39 +01002892 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002893 return 1;
2894}
2895
Willy Tarreauacf95772010-06-14 19:09:21 +02002896/* To be used to quote config arg positions. Returns the short string at <ptr>
2897 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2898 * if ptr is NULL or empty. The string is locally allocated.
2899 */
2900const char *quote_arg(const char *ptr)
2901{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002902 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002903 int i;
2904
2905 if (!ptr || !*ptr)
2906 return "end of line";
2907 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002908 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002909 val[i] = *ptr++;
2910 val[i++] = '\'';
2911 val[i] = '\0';
2912 return val;
2913}
2914
Willy Tarreau5b180202010-07-18 10:40:48 +02002915/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2916int get_std_op(const char *str)
2917{
2918 int ret = -1;
2919
2920 if (*str == 'e' && str[1] == 'q')
2921 ret = STD_OP_EQ;
2922 else if (*str == 'n' && str[1] == 'e')
2923 ret = STD_OP_NE;
2924 else if (*str == 'l') {
2925 if (str[1] == 'e') ret = STD_OP_LE;
2926 else if (str[1] == 't') ret = STD_OP_LT;
2927 }
2928 else if (*str == 'g') {
2929 if (str[1] == 'e') ret = STD_OP_GE;
2930 else if (str[1] == 't') ret = STD_OP_GT;
2931 }
2932
2933 if (ret == -1 || str[2] != '\0')
2934 return -1;
2935 return ret;
2936}
2937
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002938/* hash a 32-bit integer to another 32-bit integer */
2939unsigned int full_hash(unsigned int a)
2940{
2941 return __full_hash(a);
2942}
2943
Willy Tarreauf3241112019-02-26 09:56:22 +01002944/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2945 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2946 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2947 * a popcount variant and is described here :
2948 * https://graphics.stanford.edu/~seander/bithacks.html
2949 */
2950unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2951{
2952 unsigned long a, b, c, d;
2953 unsigned int s;
2954 unsigned int t;
2955
2956 a = m - ((m >> 1) & ~0UL/3);
2957 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2958 c = (b + (b >> 4)) & ~0UL/0x11;
2959 d = (c + (c >> 8)) & ~0UL/0x101;
2960
2961 r++; // make r be 1..64
2962
2963 t = 0;
2964 s = LONGBITS;
2965 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002966 unsigned long d2 = (d >> 16) >> 16;
2967 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002968 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2969 }
2970
2971 t = (d >> (s - 16)) & 0xff;
2972 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2973 t = (c >> (s - 8)) & 0xf;
2974 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2975 t = (b >> (s - 4)) & 0x7;
2976 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2977 t = (a >> (s - 2)) & 0x3;
2978 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2979 t = (m >> (s - 1)) & 0x1;
2980 s -= ((t - r) & 256) >> 8;
2981
2982 return s - 1;
2983}
2984
2985/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2986 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2987 * using mask_prep_rank_map() below.
2988 */
2989unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2990 unsigned long a, unsigned long b,
2991 unsigned long c, unsigned long d)
2992{
2993 unsigned int s;
2994 unsigned int t;
2995
2996 r++; // make r be 1..64
2997
2998 t = 0;
2999 s = LONGBITS;
3000 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003001 unsigned long d2 = (d >> 16) >> 16;
3002 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003003 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3004 }
3005
3006 t = (d >> (s - 16)) & 0xff;
3007 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3008 t = (c >> (s - 8)) & 0xf;
3009 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3010 t = (b >> (s - 4)) & 0x7;
3011 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3012 t = (a >> (s - 2)) & 0x3;
3013 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3014 t = (m >> (s - 1)) & 0x1;
3015 s -= ((t - r) & 256) >> 8;
3016
3017 return s - 1;
3018}
3019
3020/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3021 * above.
3022 */
3023void mask_prep_rank_map(unsigned long m,
3024 unsigned long *a, unsigned long *b,
3025 unsigned long *c, unsigned long *d)
3026{
3027 *a = m - ((m >> 1) & ~0UL/3);
3028 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3029 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3030 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3031}
3032
David du Colombier4f92d322011-03-24 11:09:31 +01003033/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003034 * otherwise zero. Note that <addr> may not necessarily be aligned
3035 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003036 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003037int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003038{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003039 struct in_addr addr_copy;
3040
3041 memcpy(&addr_copy, addr, sizeof(addr_copy));
3042 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003043}
3044
3045/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003046 * otherwise zero. Note that <addr> may not necessarily be aligned
3047 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003048 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003049int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003050{
3051 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003052 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003053
Willy Tarreaueec1d382016-07-13 11:59:39 +02003054 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003055 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003056 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003057 (((int *)net)[i] & ((int *)mask)[i]))
3058 return 0;
3059 return 1;
3060}
3061
3062/* RFC 4291 prefix */
3063const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3064 0x00, 0x00, 0x00, 0x00,
3065 0x00, 0x00, 0xFF, 0xFF };
3066
Joseph Herlant32b83272018-11-15 11:58:28 -08003067/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003068 * Input and output may overlap.
3069 */
David du Colombier4f92d322011-03-24 11:09:31 +01003070void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3071{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003072 struct in_addr tmp_addr;
3073
3074 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003075 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003076 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003077}
3078
Joseph Herlant32b83272018-11-15 11:58:28 -08003079/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003080 * Return true if conversion is possible and false otherwise.
3081 */
3082int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3083{
3084 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3085 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3086 sizeof(struct in_addr));
3087 return 1;
3088 }
3089
3090 return 0;
3091}
3092
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003093/* compare two struct sockaddr_storage and return:
3094 * 0 (true) if the addr is the same in both
3095 * 1 (false) if the addr is not the same in both
3096 * -1 (unable) if one of the addr is not AF_INET*
3097 */
3098int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3099{
3100 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3101 return -1;
3102
3103 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3104 return -1;
3105
3106 if (ss1->ss_family != ss2->ss_family)
3107 return 1;
3108
3109 switch (ss1->ss_family) {
3110 case AF_INET:
3111 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3112 &((struct sockaddr_in *)ss2)->sin_addr,
3113 sizeof(struct in_addr)) != 0;
3114 case AF_INET6:
3115 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3116 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3117 sizeof(struct in6_addr)) != 0;
3118 }
3119
3120 return 1;
3121}
3122
Christopher Faulet9553de72021-02-26 09:12:50 +01003123/* compare a struct sockaddr_storage to a struct net_addr and return :
3124 * 0 (true) if <addr> is matching <net>
3125 * 1 (false) if <addr> is not matching <net>
3126 * -1 (unable) if <addr> or <net> is not AF_INET*
3127 */
3128int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3129{
3130 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3131 return -1;
3132
3133 if ((net->family != AF_INET) && (net->family != AF_INET6))
3134 return -1;
3135
3136 if (addr->ss_family != net->family)
3137 return 1;
3138
3139 if (addr->ss_family == AF_INET &&
3140 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3141 return 0;
3142 else {
3143 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3144 const struct in6_addr *nip6 = &net->addr.v6.ip;
3145 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3146
3147 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3148 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3149 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3150 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3151 return 0;
3152 }
3153
3154 return 1;
3155}
3156
Baptiste Assmann08396c82016-01-31 00:27:17 +01003157/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003158 * The caller must allocate and clear <dest> before calling.
3159 * The source must be in either AF_INET or AF_INET6 family, or the destination
3160 * address will be undefined. If the destination address used to hold a port,
3161 * it is preserved, so that this function can be used to switch to another
3162 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003163 */
3164struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3165{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003166 int prev_port;
3167
3168 prev_port = get_net_port(dest);
3169 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003170 dest->ss_family = source->ss_family;
3171
3172 /* copy new addr and apply it */
3173 switch (source->ss_family) {
3174 case AF_INET:
3175 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003176 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003177 break;
3178 case AF_INET6:
3179 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 +01003180 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003181 break;
3182 }
3183
3184 return dest;
3185}
3186
William Lallemand421f5b52012-02-06 18:15:57 +01003187char *human_time(int t, short hz_div) {
3188 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3189 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003190 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003191 int cnt=2; // print two numbers
3192
3193 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003194 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003195 return rv;
3196 }
3197
3198 if (unlikely(hz_div > 1))
3199 t /= hz_div;
3200
3201 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003202 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003203 cnt--;
3204 }
3205
3206 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003207 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003208 cnt--;
3209 }
3210
3211 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003212 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003213 cnt--;
3214 }
3215
3216 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003217 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003218
3219 return rv;
3220}
3221
3222const char *monthname[12] = {
3223 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3224 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3225};
3226
3227/* date2str_log: write a date in the format :
3228 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3229 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3230 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3231 *
3232 * without using sprintf. return a pointer to the last char written (\0) or
3233 * NULL if there isn't enough space.
3234 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003235char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003236{
3237
3238 if (size < 25) /* the size is fixed: 24 chars + \0 */
3239 return NULL;
3240
3241 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003242 if (!dst)
3243 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003244 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003245
William Lallemand421f5b52012-02-06 18:15:57 +01003246 memcpy(dst, monthname[tm->tm_mon], 3); // month
3247 dst += 3;
3248 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003249
William Lallemand421f5b52012-02-06 18:15:57 +01003250 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003251 if (!dst)
3252 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003253 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003254
William Lallemand421f5b52012-02-06 18:15:57 +01003255 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003256 if (!dst)
3257 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003258 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003259
William Lallemand421f5b52012-02-06 18:15:57 +01003260 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003261 if (!dst)
3262 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003263 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003264
William Lallemand421f5b52012-02-06 18:15:57 +01003265 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003266 if (!dst)
3267 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003268 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003269
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003270 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003271 if (!dst)
3272 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003273 *dst = '\0';
3274
3275 return dst;
3276}
3277
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003278/* Base year used to compute leap years */
3279#define TM_YEAR_BASE 1900
3280
3281/* Return the difference in seconds between two times (leap seconds are ignored).
3282 * Retrieved from glibc 2.18 source code.
3283 */
3284static int my_tm_diff(const struct tm *a, const struct tm *b)
3285{
3286 /* Compute intervening leap days correctly even if year is negative.
3287 * Take care to avoid int overflow in leap day calculations,
3288 * but it's OK to assume that A and B are close to each other.
3289 */
3290 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3291 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3292 int a100 = a4 / 25 - (a4 % 25 < 0);
3293 int b100 = b4 / 25 - (b4 % 25 < 0);
3294 int a400 = a100 >> 2;
3295 int b400 = b100 >> 2;
3296 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3297 int years = a->tm_year - b->tm_year;
3298 int days = (365 * years + intervening_leap_days
3299 + (a->tm_yday - b->tm_yday));
3300 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3301 + (a->tm_min - b->tm_min))
3302 + (a->tm_sec - b->tm_sec));
3303}
3304
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003305/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003306 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003307 * The string returned has the same format as returned by strftime(... "%z", tm).
3308 * Offsets are kept in an internal cache for better performances.
3309 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003310const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003311{
3312 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003313 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003314
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003315 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003316 struct tm tm_gmt;
3317 int diff;
3318 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003319
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003320 /* Pretend DST not active if its status is unknown */
3321 if (isdst < 0)
3322 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003323
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003324 /* Fetch the offset and initialize it if needed */
3325 gmt_offset = gmt_offsets[isdst & 0x01];
3326 if (unlikely(!*gmt_offset)) {
3327 get_gmtime(t, &tm_gmt);
3328 diff = my_tm_diff(tm, &tm_gmt);
3329 if (diff < 0) {
3330 diff = -diff;
3331 *gmt_offset = '-';
3332 } else {
3333 *gmt_offset = '+';
3334 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003335 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003336 diff /= 60; /* Convert to minutes */
3337 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3338 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003339
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003340 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003341}
3342
William Lallemand421f5b52012-02-06 18:15:57 +01003343/* gmt2str_log: write a date in the format :
3344 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3345 * return a pointer to the last char written (\0) or
3346 * NULL if there isn't enough space.
3347 */
3348char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3349{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003350 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003351 return NULL;
3352
3353 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003354 if (!dst)
3355 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003356 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003357
William Lallemand421f5b52012-02-06 18:15:57 +01003358 memcpy(dst, monthname[tm->tm_mon], 3); // month
3359 dst += 3;
3360 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003361
William Lallemand421f5b52012-02-06 18:15:57 +01003362 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003363 if (!dst)
3364 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003365 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003366
William Lallemand421f5b52012-02-06 18:15:57 +01003367 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003368 if (!dst)
3369 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003370 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003371
William Lallemand421f5b52012-02-06 18:15:57 +01003372 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003373 if (!dst)
3374 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003375 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003376
William Lallemand421f5b52012-02-06 18:15:57 +01003377 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003378 if (!dst)
3379 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003380 *dst++ = ' ';
3381 *dst++ = '+';
3382 *dst++ = '0';
3383 *dst++ = '0';
3384 *dst++ = '0';
3385 *dst++ = '0';
3386 *dst = '\0';
3387
3388 return dst;
3389}
3390
Yuxans Yao4e25b012012-10-19 10:36:09 +08003391/* localdate2str_log: write a date in the format :
3392 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003393 * Both t and tm must represent the same time.
3394 * return a pointer to the last char written (\0) or
3395 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003396 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003397char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003398{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003399 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003400 if (size < 27) /* the size is fixed: 26 chars + \0 */
3401 return NULL;
3402
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003403 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003404
Yuxans Yao4e25b012012-10-19 10:36:09 +08003405 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003406 if (!dst)
3407 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003408 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003409
Yuxans Yao4e25b012012-10-19 10:36:09 +08003410 memcpy(dst, monthname[tm->tm_mon], 3); // month
3411 dst += 3;
3412 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003413
Yuxans Yao4e25b012012-10-19 10:36:09 +08003414 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003415 if (!dst)
3416 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003417 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003418
Yuxans Yao4e25b012012-10-19 10:36:09 +08003419 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003420 if (!dst)
3421 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003422 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003423
Yuxans Yao4e25b012012-10-19 10:36:09 +08003424 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003425 if (!dst)
3426 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003427 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003428
Yuxans Yao4e25b012012-10-19 10:36:09 +08003429 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003430 if (!dst)
3431 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003432 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003433
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003434 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003435 dst += 5;
3436 *dst = '\0';
3437
3438 return dst;
3439}
3440
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003441/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3442 * It is meant as a portable replacement for timegm() for use with valid inputs.
3443 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3444 */
3445time_t my_timegm(const struct tm *tm)
3446{
3447 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3448 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3449 * sum of the extra N days for elapsed months. The sum of all these N
3450 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3451 * in a 5-bit word. This means that with 60 bits we can represent a
3452 * matrix of all these values at once, which is fast and efficient to
3453 * access. The extra February day for leap years is not counted here.
3454 *
3455 * Jan : none = 0 (0)
3456 * Feb : Jan = 3 (3)
3457 * Mar : Jan..Feb = 3 (3 + 0)
3458 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3459 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3460 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3461 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3462 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3463 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3464 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3465 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3466 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3467 */
3468 uint64_t extra =
3469 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3470 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3471 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3472 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3473
3474 unsigned int y = tm->tm_year + 1900;
3475 unsigned int m = tm->tm_mon;
3476 unsigned long days = 0;
3477
3478 /* days since 1/1/1970 for full years */
3479 days += days_since_zero(y) - days_since_zero(1970);
3480
3481 /* days for full months in the current year */
3482 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3483
3484 /* count + 1 after March for leap years. A leap year is a year multiple
3485 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3486 * is leap, 1900 isn't, 1904 is.
3487 */
3488 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3489 days++;
3490
3491 days += tm->tm_mday - 1;
3492 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3493}
3494
Thierry Fournier93127942016-01-20 18:49:45 +01003495/* This function check a char. It returns true and updates
3496 * <date> and <len> pointer to the new position if the
3497 * character is found.
3498 */
3499static inline int parse_expect_char(const char **date, int *len, char c)
3500{
3501 if (*len < 1 || **date != c)
3502 return 0;
3503 (*len)--;
3504 (*date)++;
3505 return 1;
3506}
3507
3508/* This function expects a string <str> of len <l>. It return true and updates.
3509 * <date> and <len> if the string matches, otherwise, it returns false.
3510 */
3511static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3512{
3513 if (*len < l || strncmp(*date, str, l) != 0)
3514 return 0;
3515 (*len) -= l;
3516 (*date) += l;
3517 return 1;
3518}
3519
3520/* This macro converts 3 chars name in integer. */
3521#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3522
3523/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3524 * / %x54.75.65 ; "Tue", case-sensitive
3525 * / %x57.65.64 ; "Wed", case-sensitive
3526 * / %x54.68.75 ; "Thu", case-sensitive
3527 * / %x46.72.69 ; "Fri", case-sensitive
3528 * / %x53.61.74 ; "Sat", case-sensitive
3529 * / %x53.75.6E ; "Sun", case-sensitive
3530 *
3531 * This array must be alphabetically sorted
3532 */
3533static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3534{
3535 if (*len < 3)
3536 return 0;
3537 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3538 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3539 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3540 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3541 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3542 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3543 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3544 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3545 default: return 0;
3546 }
3547 *len -= 3;
3548 *date += 3;
3549 return 1;
3550}
3551
3552/* month = %x4A.61.6E ; "Jan", case-sensitive
3553 * / %x46.65.62 ; "Feb", case-sensitive
3554 * / %x4D.61.72 ; "Mar", case-sensitive
3555 * / %x41.70.72 ; "Apr", case-sensitive
3556 * / %x4D.61.79 ; "May", case-sensitive
3557 * / %x4A.75.6E ; "Jun", case-sensitive
3558 * / %x4A.75.6C ; "Jul", case-sensitive
3559 * / %x41.75.67 ; "Aug", case-sensitive
3560 * / %x53.65.70 ; "Sep", case-sensitive
3561 * / %x4F.63.74 ; "Oct", case-sensitive
3562 * / %x4E.6F.76 ; "Nov", case-sensitive
3563 * / %x44.65.63 ; "Dec", case-sensitive
3564 *
3565 * This array must be alphabetically sorted
3566 */
3567static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3568{
3569 if (*len < 3)
3570 return 0;
3571 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3572 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3573 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3574 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3575 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3576 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3577 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3578 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3579 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3580 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3581 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3582 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3583 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3584 default: return 0;
3585 }
3586 *len -= 3;
3587 *date += 3;
3588 return 1;
3589}
3590
3591/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3592 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3593 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3594 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3595 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3596 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3597 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3598 *
3599 * This array must be alphabetically sorted
3600 */
3601static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3602{
3603 if (*len < 6) /* Minimum length. */
3604 return 0;
3605 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3606 case STR2I3('M','o','n'):
3607 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3608 tm->tm_wday = 1;
3609 return 1;
3610 case STR2I3('T','u','e'):
3611 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3612 tm->tm_wday = 2;
3613 return 1;
3614 case STR2I3('W','e','d'):
3615 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3616 tm->tm_wday = 3;
3617 return 1;
3618 case STR2I3('T','h','u'):
3619 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3620 tm->tm_wday = 4;
3621 return 1;
3622 case STR2I3('F','r','i'):
3623 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3624 tm->tm_wday = 5;
3625 return 1;
3626 case STR2I3('S','a','t'):
3627 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3628 tm->tm_wday = 6;
3629 return 1;
3630 case STR2I3('S','u','n'):
3631 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3632 tm->tm_wday = 7;
3633 return 1;
3634 }
3635 return 0;
3636}
3637
3638/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3639static inline int parse_digit(const char **date, int *len, int *digit)
3640{
3641 if (*len < 1 || **date < '0' || **date > '9')
3642 return 0;
3643 *digit = (**date - '0');
3644 (*date)++;
3645 (*len)--;
3646 return 1;
3647}
3648
3649/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3650static inline int parse_2digit(const char **date, int *len, int *digit)
3651{
3652 int value;
3653
3654 RET0_UNLESS(parse_digit(date, len, &value));
3655 (*digit) = value * 10;
3656 RET0_UNLESS(parse_digit(date, len, &value));
3657 (*digit) += value;
3658
3659 return 1;
3660}
3661
3662/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3663static inline int parse_4digit(const char **date, int *len, int *digit)
3664{
3665 int value;
3666
3667 RET0_UNLESS(parse_digit(date, len, &value));
3668 (*digit) = value * 1000;
3669
3670 RET0_UNLESS(parse_digit(date, len, &value));
3671 (*digit) += value * 100;
3672
3673 RET0_UNLESS(parse_digit(date, len, &value));
3674 (*digit) += value * 10;
3675
3676 RET0_UNLESS(parse_digit(date, len, &value));
3677 (*digit) += value;
3678
3679 return 1;
3680}
3681
3682/* time-of-day = hour ":" minute ":" second
3683 * ; 00:00:00 - 23:59:60 (leap second)
3684 *
3685 * hour = 2DIGIT
3686 * minute = 2DIGIT
3687 * second = 2DIGIT
3688 */
3689static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3690{
3691 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3692 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3693 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3694 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3695 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3696 return 1;
3697}
3698
3699/* From RFC7231
3700 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3701 *
3702 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3703 * ; fixed length/zone/capitalization subset of the format
3704 * ; see Section 3.3 of [RFC5322]
3705 *
3706 *
3707 * date1 = day SP month SP year
3708 * ; e.g., 02 Jun 1982
3709 *
3710 * day = 2DIGIT
3711 * year = 4DIGIT
3712 *
3713 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3714 *
3715 * time-of-day = hour ":" minute ":" second
3716 * ; 00:00:00 - 23:59:60 (leap second)
3717 *
3718 * hour = 2DIGIT
3719 * minute = 2DIGIT
3720 * second = 2DIGIT
3721 *
3722 * DIGIT = decimal 0-9
3723 */
3724int parse_imf_date(const char *date, int len, struct tm *tm)
3725{
David Carlier327298c2016-11-20 10:42:38 +00003726 /* tm_gmtoff, if present, ought to be zero'ed */
3727 memset(tm, 0, sizeof(*tm));
3728
Thierry Fournier93127942016-01-20 18:49:45 +01003729 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3730 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3731 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3732 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3733 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3734 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3735 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3736 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3737 tm->tm_year -= 1900;
3738 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3739 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3740 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3741 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3742 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003743 return 1;
3744}
3745
3746/* From RFC7231
3747 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3748 *
3749 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3750 * date2 = day "-" month "-" 2DIGIT
3751 * ; e.g., 02-Jun-82
3752 *
3753 * day = 2DIGIT
3754 */
3755int parse_rfc850_date(const char *date, int len, struct tm *tm)
3756{
3757 int year;
3758
David Carlier327298c2016-11-20 10:42:38 +00003759 /* tm_gmtoff, if present, ought to be zero'ed */
3760 memset(tm, 0, sizeof(*tm));
3761
Thierry Fournier93127942016-01-20 18:49:45 +01003762 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3763 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3764 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3765 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3766 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3767 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3768 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3769
3770 /* year = 2DIGIT
3771 *
3772 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3773 * two-digit year, MUST interpret a timestamp that appears to be more
3774 * than 50 years in the future as representing the most recent year in
3775 * the past that had the same last two digits.
3776 */
3777 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3778
3779 /* expect SP */
3780 if (!parse_expect_char(&date, &len, ' ')) {
3781 /* Maybe we have the date with 4 digits. */
3782 RET0_UNLESS(parse_2digit(&date, &len, &year));
3783 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3784 /* expect SP */
3785 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3786 } else {
3787 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3788 * tm_year is the number of year since 1900, so for +1900, we
3789 * do nothing, and for +2000, we add 100.
3790 */
3791 if (tm->tm_year <= 60)
3792 tm->tm_year += 100;
3793 }
3794
3795 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3796 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3797 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3798 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003799
3800 return 1;
3801}
3802
3803/* From RFC7231
3804 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3805 *
3806 * asctime-date = day-name SP date3 SP time-of-day SP year
3807 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3808 * ; e.g., Jun 2
3809 *
3810 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3811 * whitespace in an HTTP-date beyond that specifically included as SP in
3812 * the grammar.
3813 */
3814int parse_asctime_date(const char *date, int len, struct tm *tm)
3815{
David Carlier327298c2016-11-20 10:42:38 +00003816 /* tm_gmtoff, if present, ought to be zero'ed */
3817 memset(tm, 0, sizeof(*tm));
3818
Thierry Fournier93127942016-01-20 18:49:45 +01003819 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3820 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3821 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3822 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3823
3824 /* expect SP and 1DIGIT or 2DIGIT */
3825 if (parse_expect_char(&date, &len, ' '))
3826 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3827 else
3828 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3829
3830 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3831 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3832 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3833 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3834 tm->tm_year -= 1900;
3835 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003836 return 1;
3837}
3838
3839/* From RFC7231
3840 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3841 *
3842 * HTTP-date = IMF-fixdate / obs-date
3843 * obs-date = rfc850-date / asctime-date
3844 *
3845 * parses an HTTP date in the RFC format and is accepted
3846 * alternatives. <date> is the strinf containing the date,
3847 * len is the len of the string. <tm> is filled with the
3848 * parsed time. We must considers this time as GMT.
3849 */
3850int parse_http_date(const char *date, int len, struct tm *tm)
3851{
3852 if (parse_imf_date(date, len, tm))
3853 return 1;
3854
3855 if (parse_rfc850_date(date, len, tm))
3856 return 1;
3857
3858 if (parse_asctime_date(date, len, tm))
3859 return 1;
3860
3861 return 0;
3862}
3863
Willy Tarreau4deeb102021-01-29 10:47:52 +01003864/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3865 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3866 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3867 * surrounded by <pfx> and <sfx> respectively if not NULL.
3868 */
3869int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3870{
3871 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3872 const char *unit;
3873
3874 if (!pfx)
3875 pfx = "";
3876 if (!sfx)
3877 sfx = "";
3878
3879 do {
3880 unit = " - "; if (val <= 0.0) break;
3881 unit = "ns"; if (val < 1000.0) break;
3882 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3883 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3884 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3885 unit = "m "; val /= 60.0; if (val < 60.0) break;
3886 unit = "h "; val /= 60.0; if (val < 24.0) break;
3887 unit = "d "; val /= 24.0; if (val < 365.0) break;
3888 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3889 unit = " inf "; val = 0.0; break;
3890 } while (0);
3891
3892 if (val <= 0.0)
3893 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
3894 else if (val < 10.0)
3895 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
3896 else if (val < 100.0)
3897 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
3898 else
3899 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
3900}
3901
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003902/* Dynamically allocates a string of the proper length to hold the formatted
3903 * output. NULL is returned on error. The caller is responsible for freeing the
3904 * memory area using free(). The resulting string is returned in <out> if the
3905 * pointer is not NULL. A previous version of <out> might be used to build the
3906 * new string, and it will be freed before returning if it is not NULL, which
3907 * makes it possible to build complex strings from iterative calls without
3908 * having to care about freeing intermediate values, as in the example below :
3909 *
3910 * memprintf(&err, "invalid argument: '%s'", arg);
3911 * ...
3912 * memprintf(&err, "parser said : <%s>\n", *err);
3913 * ...
3914 * free(*err);
3915 *
3916 * This means that <err> must be initialized to NULL before first invocation.
3917 * The return value also holds the allocated string, which eases error checking
3918 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003919 * passed instead and it will be ignored. The returned message will then also
3920 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003921 *
3922 * It is also convenient to use it without any free except the last one :
3923 * err = NULL;
3924 * if (!fct1(err)) report(*err);
3925 * if (!fct2(err)) report(*err);
3926 * if (!fct3(err)) report(*err);
3927 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003928 *
3929 * memprintf relies on memvprintf. This last version can be called from any
3930 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003931 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003932char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003933{
3934 va_list args;
3935 char *ret = NULL;
3936 int allocated = 0;
3937 int needed = 0;
3938
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003939 if (!out)
3940 return NULL;
3941
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003942 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003943 char buf1;
3944
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003945 /* vsnprintf() will return the required length even when the
3946 * target buffer is NULL. We do this in a loop just in case
3947 * intermediate evaluations get wrong.
3948 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003949 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003950 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003951 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003952 if (needed < allocated) {
3953 /* Note: on Solaris 8, the first iteration always
3954 * returns -1 if allocated is zero, so we force a
3955 * retry.
3956 */
3957 if (!allocated)
3958 needed = 0;
3959 else
3960 break;
3961 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003962
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003963 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003964 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003965 } while (ret);
3966
3967 if (needed < 0) {
3968 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01003969 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003970 }
3971
3972 if (out) {
3973 free(*out);
3974 *out = ret;
3975 }
3976
3977 return ret;
3978}
William Lallemand421f5b52012-02-06 18:15:57 +01003979
Christopher Faulet93a518f2017-10-24 11:25:33 +02003980char *memprintf(char **out, const char *format, ...)
3981{
3982 va_list args;
3983 char *ret = NULL;
3984
3985 va_start(args, format);
3986 ret = memvprintf(out, format, args);
3987 va_end(args);
3988
3989 return ret;
3990}
3991
Willy Tarreau21c705b2012-09-14 11:40:36 +02003992/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3993 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003994 * freed by the caller. It also supports being passed a NULL which results in the same
3995 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003996 * Example of use :
3997 * parse(cmd, &err); (callee: memprintf(&err, ...))
3998 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3999 * free(err);
4000 */
4001char *indent_msg(char **out, int level)
4002{
4003 char *ret, *in, *p;
4004 int needed = 0;
4005 int lf = 0;
4006 int lastlf = 0;
4007 int len;
4008
Willy Tarreau70eec382012-10-10 08:56:47 +02004009 if (!out || !*out)
4010 return NULL;
4011
Willy Tarreau21c705b2012-09-14 11:40:36 +02004012 in = *out - 1;
4013 while ((in = strchr(in + 1, '\n')) != NULL) {
4014 lastlf = in - *out;
4015 lf++;
4016 }
4017
4018 if (!lf) /* single line, no LF, return it as-is */
4019 return *out;
4020
4021 len = strlen(*out);
4022
4023 if (lf == 1 && lastlf == len - 1) {
4024 /* single line, LF at end, strip it and return as-is */
4025 (*out)[lastlf] = 0;
4026 return *out;
4027 }
4028
4029 /* OK now we have at least one LF, we need to process the whole string
4030 * as a multi-line string. What we'll do :
4031 * - prefix with an LF if there is none
4032 * - add <level> spaces before each line
4033 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4034 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4035 */
4036
4037 needed = 1 + level * (lf + 1) + len + 1;
4038 p = ret = malloc(needed);
4039 in = *out;
4040
4041 /* skip initial LFs */
4042 while (*in == '\n')
4043 in++;
4044
4045 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4046 while (*in) {
4047 *p++ = '\n';
4048 memset(p, ' ', level);
4049 p += level;
4050 do {
4051 *p++ = *in++;
4052 } while (*in && *in != '\n');
4053 if (*in)
4054 in++;
4055 }
4056 *p = 0;
4057
4058 free(*out);
4059 *out = ret;
4060
4061 return ret;
4062}
4063
Willy Tarreaua2c99112019-08-21 13:17:37 +02004064/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4065 * and end of lines replaced with <eol> if not 0. The first line to indent has
4066 * to be indicated in <first> (starts at zero), so that it is possible to skip
4067 * indenting the first line if it has to be appended after an existing message.
4068 * Empty strings are never indented, and NULL strings are considered empty both
4069 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4070 * character, non-zero otherwise.
4071 */
4072int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4073{
4074 int bol, lf;
4075 int pfxlen = pfx ? strlen(pfx) : 0;
4076
4077 if (!in)
4078 return 0;
4079
4080 bol = 1;
4081 lf = 0;
4082 while (*in) {
4083 if (bol && pfxlen) {
4084 if (first > 0)
4085 first--;
4086 else
4087 b_putblk(out, pfx, pfxlen);
4088 bol = 0;
4089 }
4090
4091 lf = (*in == '\n');
4092 bol |= lf;
4093 b_putchr(out, (lf && eol) ? eol : *in);
4094 in++;
4095 }
4096 return lf;
4097}
4098
Willy Tarreau9d22e562019-03-29 18:49:09 +01004099/* removes environment variable <name> from the environment as found in
4100 * environ. This is only provided as an alternative for systems without
4101 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004102 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004103 * <name> and to replace the matching pointers with the last pointer of
4104 * the array (since variables are not ordered).
4105 * It always returns 0 (success).
4106 */
4107int my_unsetenv(const char *name)
4108{
4109 extern char **environ;
4110 char **p = environ;
4111 int vars;
4112 int next;
4113 int len;
4114
4115 len = strlen(name);
4116 for (vars = 0; p[vars]; vars++)
4117 ;
4118 next = 0;
4119 while (next < vars) {
4120 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4121 next++;
4122 continue;
4123 }
4124 if (next < vars - 1)
4125 p[next] = p[vars - 1];
4126 p[--vars] = NULL;
4127 }
4128 return 0;
4129}
4130
Willy Tarreaudad36a32013-03-11 01:20:04 +01004131/* Convert occurrences of environment variables in the input string to their
4132 * corresponding value. A variable is identified as a series of alphanumeric
4133 * characters or underscores following a '$' sign. The <in> string must be
4134 * free()able. NULL returns NULL. The resulting string might be reallocated if
4135 * some expansion is made. Variable names may also be enclosed into braces if
4136 * needed (eg: to concatenate alphanum characters).
4137 */
4138char *env_expand(char *in)
4139{
4140 char *txt_beg;
4141 char *out;
4142 char *txt_end;
4143 char *var_beg;
4144 char *var_end;
4145 char *value;
4146 char *next;
4147 int out_len;
4148 int val_len;
4149
4150 if (!in)
4151 return in;
4152
4153 value = out = NULL;
4154 out_len = 0;
4155
4156 txt_beg = in;
4157 do {
4158 /* look for next '$' sign in <in> */
4159 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4160
4161 if (!*txt_end && !out) /* end and no expansion performed */
4162 return in;
4163
4164 val_len = 0;
4165 next = txt_end;
4166 if (*txt_end == '$') {
4167 char save;
4168
4169 var_beg = txt_end + 1;
4170 if (*var_beg == '{')
4171 var_beg++;
4172
4173 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004174 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004175 var_end++;
4176 }
4177
4178 next = var_end;
4179 if (*var_end == '}' && (var_beg > txt_end + 1))
4180 next++;
4181
4182 /* get value of the variable name at this location */
4183 save = *var_end;
4184 *var_end = '\0';
4185 value = getenv(var_beg);
4186 *var_end = save;
4187 val_len = value ? strlen(value) : 0;
4188 }
4189
Hubert Verstraete831962e2016-06-28 22:44:26 +02004190 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004191 if (txt_end > txt_beg) {
4192 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4193 out_len += txt_end - txt_beg;
4194 }
4195 if (val_len) {
4196 memcpy(out + out_len, value, val_len);
4197 out_len += val_len;
4198 }
4199 out[out_len] = 0;
4200 txt_beg = next;
4201 } while (*txt_beg);
4202
4203 /* here we know that <out> was allocated and that we don't need <in> anymore */
4204 free(in);
4205 return out;
4206}
4207
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004208
4209/* same as strstr() but case-insensitive and with limit length */
4210const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4211{
4212 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004213 unsigned int slen, plen;
4214 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004215
4216 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4217 return NULL;
4218
4219 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4220 return str1;
4221
4222 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4223 return NULL;
4224
4225 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 +02004226 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004227 start++;
4228 slen--;
4229 tmp1++;
4230
4231 if (tmp1 >= len_str1)
4232 return NULL;
4233
4234 /* if pattern longer than string */
4235 if (slen < plen)
4236 return NULL;
4237 }
4238
4239 sptr = start;
4240 pptr = (char *)str2;
4241
4242 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004243 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004244 sptr++;
4245 pptr++;
4246 tmp2++;
4247
4248 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4249 return start;
4250 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4251 return NULL;
4252 }
4253 }
4254 return NULL;
4255}
4256
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004257/* This function read the next valid utf8 char.
4258 * <s> is the byte srray to be decode, <len> is its length.
4259 * The function returns decoded char encoded like this:
4260 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4261 * are the length read. The decoded character is stored in <c>.
4262 */
4263unsigned char utf8_next(const char *s, int len, unsigned int *c)
4264{
4265 const unsigned char *p = (unsigned char *)s;
4266 int dec;
4267 unsigned char code = UTF8_CODE_OK;
4268
4269 if (len < 1)
4270 return UTF8_CODE_OK;
4271
4272 /* Check the type of UTF8 sequence
4273 *
4274 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4275 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4276 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4277 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4278 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4279 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4280 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4281 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4282 */
4283 switch (*p) {
4284 case 0x00 ... 0x7f:
4285 *c = *p;
4286 return UTF8_CODE_OK | 1;
4287
4288 case 0x80 ... 0xbf:
4289 *c = *p;
4290 return UTF8_CODE_BADSEQ | 1;
4291
4292 case 0xc0 ... 0xdf:
4293 if (len < 2) {
4294 *c = *p;
4295 return UTF8_CODE_BADSEQ | 1;
4296 }
4297 *c = *p & 0x1f;
4298 dec = 1;
4299 break;
4300
4301 case 0xe0 ... 0xef:
4302 if (len < 3) {
4303 *c = *p;
4304 return UTF8_CODE_BADSEQ | 1;
4305 }
4306 *c = *p & 0x0f;
4307 dec = 2;
4308 break;
4309
4310 case 0xf0 ... 0xf7:
4311 if (len < 4) {
4312 *c = *p;
4313 return UTF8_CODE_BADSEQ | 1;
4314 }
4315 *c = *p & 0x07;
4316 dec = 3;
4317 break;
4318
4319 case 0xf8 ... 0xfb:
4320 if (len < 5) {
4321 *c = *p;
4322 return UTF8_CODE_BADSEQ | 1;
4323 }
4324 *c = *p & 0x03;
4325 dec = 4;
4326 break;
4327
4328 case 0xfc ... 0xfd:
4329 if (len < 6) {
4330 *c = *p;
4331 return UTF8_CODE_BADSEQ | 1;
4332 }
4333 *c = *p & 0x01;
4334 dec = 5;
4335 break;
4336
4337 case 0xfe ... 0xff:
4338 default:
4339 *c = *p;
4340 return UTF8_CODE_BADSEQ | 1;
4341 }
4342
4343 p++;
4344
4345 while (dec > 0) {
4346
4347 /* need 0x10 for the 2 first bits */
4348 if ( ( *p & 0xc0 ) != 0x80 )
4349 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4350
4351 /* add data at char */
4352 *c = ( *c << 6 ) | ( *p & 0x3f );
4353
4354 dec--;
4355 p++;
4356 }
4357
4358 /* Check ovelong encoding.
4359 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4360 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4361 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4362 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004363 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004364 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4365 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4366 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4367 code |= UTF8_CODE_OVERLONG;
4368
4369 /* Check invalid UTF8 range. */
4370 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4371 (*c >= 0xfffe && *c <= 0xffff))
4372 code |= UTF8_CODE_INVRANGE;
4373
4374 return code | ((p-(unsigned char *)s)&0x0f);
4375}
4376
Maxime de Roucydc887852016-05-13 23:52:54 +02004377/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4378 * On failure : return 0 and <err> filled with an error message.
4379 * The caller is responsible for freeing the <err> and <str> copy
4380 * memory area using free()
4381 */
4382int list_append_word(struct list *li, const char *str, char **err)
4383{
4384 struct wordlist *wl;
4385
4386 wl = calloc(1, sizeof(*wl));
4387 if (!wl) {
4388 memprintf(err, "out of memory");
4389 goto fail_wl;
4390 }
4391
4392 wl->s = strdup(str);
4393 if (!wl->s) {
4394 memprintf(err, "out of memory");
4395 goto fail_wl_s;
4396 }
4397
4398 LIST_ADDQ(li, &wl->list);
4399
4400 return 1;
4401
4402fail_wl_s:
4403 free(wl->s);
4404fail_wl:
4405 free(wl);
4406 return 0;
4407}
4408
Willy Tarreau37101052019-05-20 16:48:20 +02004409/* indicates if a memory location may safely be read or not. The trick consists
4410 * in performing a harmless syscall using this location as an input and letting
4411 * the operating system report whether it's OK or not. For this we have the
4412 * stat() syscall, which will return EFAULT when the memory location supposed
4413 * to contain the file name is not readable. If it is readable it will then
4414 * either return 0 if the area contains an existing file name, or -1 with
4415 * another code. This must not be abused, and some audit systems might detect
4416 * this as abnormal activity. It's used only for unsafe dumps.
4417 */
4418int may_access(const void *ptr)
4419{
4420 struct stat buf;
4421
4422 if (stat(ptr, &buf) == 0)
4423 return 1;
4424 if (errno == EFAULT)
4425 return 0;
4426 return 1;
4427}
4428
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004429/* print a string of text buffer to <out>. The format is :
4430 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4431 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4432 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4433 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004434int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004435{
4436 unsigned char c;
4437 int ptr = 0;
4438
4439 while (buf[ptr] && ptr < bsize) {
4440 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004441 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004442 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004443 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004444 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004445 }
4446 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004447 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004448 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004449 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004450 switch (c) {
4451 case ' ': c = ' '; break;
4452 case '\t': c = 't'; break;
4453 case '\n': c = 'n'; break;
4454 case '\r': c = 'r'; break;
4455 case '\e': c = 'e'; break;
4456 case '\\': c = '\\'; break;
4457 case '=': c = '='; break;
4458 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004459 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004460 }
4461 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004462 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004463 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004464 out->area[out->data++] = '\\';
4465 out->area[out->data++] = 'x';
4466 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4467 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004468 }
4469 ptr++;
4470 }
4471
4472 return ptr;
4473}
4474
4475/* print a buffer in hexa.
4476 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4477 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004478int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004479{
4480 unsigned char c;
4481 int ptr = 0;
4482
4483 while (ptr < bsize) {
4484 c = buf[ptr];
4485
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004486 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004487 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004488 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4489 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004490
4491 ptr++;
4492 }
4493 return ptr;
4494}
4495
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004496/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4497 * prepending each line with prefix <pfx>. The output is *not* initialized.
4498 * The output will not wrap pas the buffer's end so it is more optimal if the
4499 * caller makes sure the buffer is aligned first. A trailing zero will always
4500 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004501 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4502 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004503 */
Willy Tarreau37101052019-05-20 16:48:20 +02004504void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004505{
4506 const unsigned char *d = buf;
4507 int i, j, start;
4508
4509 d = (const unsigned char *)(((unsigned long)buf) & -16);
4510 start = ((unsigned long)buf) & 15;
4511
4512 for (i = 0; i < start + len; i += 16) {
4513 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4514
Willy Tarreau37101052019-05-20 16:48:20 +02004515 // 0: unchecked, 1: checked safe, 2: danger
4516 unsafe = !!unsafe;
4517 if (unsafe && !may_access(d + i))
4518 unsafe = 2;
4519
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004520 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004521 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004522 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004523 else if (unsafe > 1)
4524 chunk_strcat(out, "** ");
4525 else
4526 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004527
4528 if (j == 7)
4529 chunk_strcat(out, "- ");
4530 }
4531 chunk_strcat(out, " ");
4532 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004533 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004534 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004535 else if (unsafe > 1)
4536 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004537 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004538 chunk_appendf(out, "%c", d[i + j]);
4539 else
4540 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004541 }
4542 chunk_strcat(out, "\n");
4543 }
4544}
4545
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004546/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4547 * enclosed in brackets after the address itself, formatted on 14 chars
4548 * including the "0x" prefix. This is meant to be used as a prefix for code
4549 * areas. For example:
4550 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4551 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4552 * is emitted. A NULL <pfx> will be considered empty.
4553 */
4554void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4555{
4556 int ok = 0;
4557 int i;
4558
4559 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4560
4561 for (i = 0; i < n; i++) {
4562 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4563 ok = may_access(addr + i);
4564 if (ok)
4565 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4566 else
4567 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4568 }
4569}
4570
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004571/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4572 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4573 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4574 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4575 * lines are respected within the limit of 70 output chars. Lines that are
4576 * continuation of a previous truncated line begin with "+" instead of " "
4577 * after the offset. The new pointer is returned.
4578 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004579int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004580 int *line, int ptr)
4581{
4582 int end;
4583 unsigned char c;
4584
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004585 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004586 if (end > out->size)
4587 return ptr;
4588
4589 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4590
4591 while (ptr < len && ptr < bsize) {
4592 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004593 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004594 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004595 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004596 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004597 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004598 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004599 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004600 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004601 switch (c) {
4602 case '\t': c = 't'; break;
4603 case '\n': c = 'n'; break;
4604 case '\r': c = 'r'; break;
4605 case '\e': c = 'e'; break;
4606 case '\\': c = '\\'; break;
4607 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004608 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004609 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004610 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004611 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004612 out->area[out->data++] = '\\';
4613 out->area[out->data++] = 'x';
4614 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4615 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004616 }
4617 if (buf[ptr++] == '\n') {
4618 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004619 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004620 *line = ptr;
4621 return ptr;
4622 }
4623 }
4624 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004625 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004626 return ptr;
4627}
4628
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004629/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004630 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4631 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004632 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004633void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4634 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004635{
Willy Tarreau73459792017-04-11 07:58:08 +02004636 unsigned int i;
4637 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004638
4639 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4640 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004641 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004642 for (j = 0; j < 8; j++) {
4643 if (b + j >= 0 && b + j < len)
4644 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4645 else
4646 fprintf(out, " ");
4647 }
4648
4649 if (b + j >= 0 && b + j < len)
4650 fputc('-', out);
4651 else
4652 fputc(' ', out);
4653
4654 for (j = 8; j < 16; j++) {
4655 if (b + j >= 0 && b + j < len)
4656 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4657 else
4658 fprintf(out, " ");
4659 }
4660
4661 fprintf(out, " ");
4662 for (j = 0; j < 16; j++) {
4663 if (b + j >= 0 && b + j < len) {
4664 if (isprint((unsigned char)buf[b + j]))
4665 fputc((unsigned char)buf[b + j], out);
4666 else
4667 fputc('.', out);
4668 }
4669 else
4670 fputc(' ', out);
4671 }
4672 fputc('\n', out);
4673 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004674}
4675
Willy Tarreaubb869862020-04-16 10:52:41 +02004676/* Tries to report the executable path name on platforms supporting this. If
4677 * not found or not possible, returns NULL.
4678 */
4679const char *get_exec_path()
4680{
4681 const char *ret = NULL;
4682
4683#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4684 long execfn = getauxval(AT_EXECFN);
4685
4686 if (execfn && execfn != ENOENT)
4687 ret = (const char *)execfn;
4688#endif
4689 return ret;
4690}
4691
Baruch Siache1651b22020-07-24 07:52:20 +03004692#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004693/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4694 * also returns the symbol size in <size>, otherwise returns 0 there.
4695 */
4696static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4697{
4698 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004699#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004700 const ElfW(Sym) *sym;
4701
4702 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4703 if (ret)
4704 *size = sym ? sym->st_size : 0;
4705#else
4706 ret = dladdr(addr, dli);
4707 *size = 0;
4708#endif
4709 return ret;
4710}
4711#endif
4712
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004713/* Tries to append to buffer <buf> some indications about the symbol at address
4714 * <addr> using the following form:
4715 * lib:+0xoffset (unresolvable address from lib's base)
4716 * main+0xoffset (unresolvable address from main (+/-))
4717 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4718 * name (resolved exact exec address)
4719 * lib:name (resolved exact lib address)
4720 * name+0xoffset/0xsize (resolved address within exec symbol)
4721 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4722 *
4723 * The file name (lib or executable) is limited to what lies between the last
4724 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4725 * 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 +03004726 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004727 *
4728 * The symbol's base address is returned, or NULL when unresolved, in order to
4729 * allow the caller to match it against known ones.
4730 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004731const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004732{
4733 const struct {
4734 const void *func;
4735 const char *name;
4736 } fcts[] = {
4737 { .func = process_stream, .name = "process_stream" },
4738 { .func = task_run_applet, .name = "task_run_applet" },
4739 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004740 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004741 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4742 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004743 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004744 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4745 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004746 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004747#ifdef USE_THREAD
4748 { .func = accept_queue_process, .name = "accept_queue_process" },
4749#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004750#ifdef USE_LUA
4751 { .func = hlua_process_task, .name = "hlua_process_task" },
4752#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004753#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004754 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4755 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4756#endif
4757 };
4758
Baruch Siache1651b22020-07-24 07:52:20 +03004759#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004760 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004761 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004762 const char *fname, *p;
4763#endif
4764 int i;
4765
4766 if (pfx)
4767 chunk_appendf(buf, "%s", pfx);
4768
4769 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4770 if (addr == fcts[i].func) {
4771 chunk_appendf(buf, "%s", fcts[i].name);
4772 return addr;
4773 }
4774 }
4775
Baruch Siache1651b22020-07-24 07:52:20 +03004776#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004777 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004778 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004779 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004780
4781 /* 1. prefix the library name if it's not the same object as the one
4782 * that contains the main function. The name is picked between last '/'
4783 * and first following '.'.
4784 */
4785 if (!dladdr(main, &dli_main))
4786 dli_main.dli_fbase = NULL;
4787
4788 if (dli_main.dli_fbase != dli.dli_fbase) {
4789 fname = dli.dli_fname;
4790 p = strrchr(fname, '/');
4791 if (p++)
4792 fname = p;
4793 p = strchr(fname, '.');
4794 if (!p)
4795 p = fname + strlen(fname);
4796
4797 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4798 }
4799
4800 /* 2. symbol name */
4801 if (dli.dli_sname) {
4802 /* known, dump it and return symbol's address (exact or relative) */
4803 chunk_appendf(buf, "%s", dli.dli_sname);
4804 if (addr != dli.dli_saddr) {
4805 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004806 if (size)
4807 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004808 }
4809 return dli.dli_saddr;
4810 }
4811 else if (dli_main.dli_fbase != dli.dli_fbase) {
4812 /* unresolved symbol from a known library, report relative offset */
4813 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4814 return NULL;
4815 }
Baruch Siache1651b22020-07-24 07:52:20 +03004816#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004817 unknown:
4818 /* unresolved symbol from the main file, report relative offset to main */
4819 if ((void*)addr < (void*)main)
4820 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4821 else
4822 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4823 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004824}
4825
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004826/*
4827 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004828 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004829 *
4830 * First, initializes the value with <sz> as address to 0 and initializes the
4831 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4832 * address updating <sz> pointed value to the size of this array.
4833 *
4834 * Returns 1 if succeeded, 0 if not.
4835 */
4836int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4837{
4838 unsigned int *n;
4839 const char *s, *end;
4840
4841 s = str;
4842 *sz = 0;
4843 end = str + strlen(str);
4844 *nums = n = NULL;
4845
4846 while (1) {
4847 unsigned int r;
4848
4849 if (s >= end)
4850 break;
4851
4852 r = read_uint(&s, end);
4853 /* Expected characters after having read an uint: '\0' or '.',
4854 * if '.', must not be terminal.
4855 */
Christopher Faulet4b524122021-02-11 10:42:41 +01004856 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4857 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004858 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01004859 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004860
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004861 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004862 if (!n)
4863 return 0;
4864
4865 n[(*sz)++] = r;
4866 }
4867 *nums = n;
4868
4869 return 1;
4870}
4871
Willy Tarreau4d589e72019-08-23 19:02:26 +02004872
4873/* returns the number of bytes needed to encode <v> as a varint. An inline
4874 * version exists for use with constants (__varint_bytes()).
4875 */
4876int varint_bytes(uint64_t v)
4877{
4878 int len = 1;
4879
4880 if (v >= 240) {
4881 v = (v - 240) >> 4;
4882 while (1) {
4883 len++;
4884 if (v < 128)
4885 break;
4886 v = (v - 128) >> 7;
4887 }
4888 }
4889 return len;
4890}
4891
Willy Tarreau52bf8392020-03-08 00:42:37 +01004892
4893/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004894static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004895
4896/* This is a thread-safe implementation of xoroshiro128** described below:
4897 * http://prng.di.unimi.it/
4898 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4899 * supports fast jumps and passes all common quality tests. It is thread-safe,
4900 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4901 * local lock on other ones.
4902 */
4903uint64_t ha_random64()
4904{
4905 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004906 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4907 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004908
4909#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4910 static HA_SPINLOCK_T rand_lock;
4911
4912 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4913#endif
4914
4915 old[0] = ha_random_state[0];
4916 old[1] = ha_random_state[1];
4917
4918#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4919 do {
4920#endif
4921 result = rotl64(old[0] * 5, 7) * 9;
4922 new[1] = old[0] ^ old[1];
4923 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4924 new[1] = rotl64(new[1], 37); // c
4925
4926#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4927 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4928#else
4929 ha_random_state[0] = new[0];
4930 ha_random_state[1] = new[1];
4931#if defined(USE_THREAD)
4932 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4933#endif
4934#endif
4935 return result;
4936}
4937
4938/* seeds the random state using up to <len> bytes from <seed>, starting with
4939 * the first non-zero byte.
4940 */
4941void ha_random_seed(const unsigned char *seed, size_t len)
4942{
4943 size_t pos;
4944
4945 /* the seed must not be all zeroes, so we pre-fill it with alternating
4946 * bits and overwrite part of them with the block starting at the first
4947 * non-zero byte from the seed.
4948 */
4949 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4950
4951 for (pos = 0; pos < len; pos++)
4952 if (seed[pos] != 0)
4953 break;
4954
4955 if (pos == len)
4956 return;
4957
4958 seed += pos;
4959 len -= pos;
4960
4961 if (len > sizeof(ha_random_state))
4962 len = sizeof(ha_random_state);
4963
4964 memcpy(ha_random_state, seed, len);
4965}
4966
4967/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4968 * and is equivalent to calling ha_random64() as many times. It is used to
4969 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4970 * different generators (i.e. different processes after a fork). The <dist>
4971 * argument is the distance to jump to and is used in a loop so it rather not
4972 * be too large if the processing time is a concern.
4973 *
4974 * BEWARE: this function is NOT thread-safe and must not be called during
4975 * concurrent accesses to ha_random64().
4976 */
4977void ha_random_jump96(uint32_t dist)
4978{
4979 while (dist--) {
4980 uint64_t s0 = 0;
4981 uint64_t s1 = 0;
4982 int b;
4983
4984 for (b = 0; b < 64; b++) {
4985 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4986 s0 ^= ha_random_state[0];
4987 s1 ^= ha_random_state[1];
4988 }
4989 ha_random64();
4990 }
4991
4992 for (b = 0; b < 64; b++) {
4993 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4994 s0 ^= ha_random_state[0];
4995 s1 ^= ha_random_state[1];
4996 }
4997 ha_random64();
4998 }
4999 ha_random_state[0] = s0;
5000 ha_random_state[1] = s1;
5001 }
5002}
5003
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005004/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5005 * bytes large.
5006 */
5007void ha_generate_uuid(struct buffer *output)
5008{
5009 uint32_t rnd[4];
5010 uint64_t last;
5011
5012 last = ha_random64();
5013 rnd[0] = last;
5014 rnd[1] = last >> 32;
5015
5016 last = ha_random64();
5017 rnd[2] = last;
5018 rnd[3] = last >> 32;
5019
5020 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5021 rnd[0],
5022 rnd[1] & 0xFFFF,
5023 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5024 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5025 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5026}
5027
5028
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005029/* only used by parse_line() below. It supports writing in place provided that
5030 * <in> is updated to the next location before calling it. In that case, the
5031 * char at <in> may be overwritten.
5032 */
5033#define EMIT_CHAR(x) \
5034 do { \
5035 char __c = (char)(x); \
5036 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5037 err |= PARSE_ERR_OVERLAP; \
5038 if (outpos >= outmax) \
5039 err |= PARSE_ERR_TOOLARGE; \
5040 if (!err) \
5041 out[outpos] = __c; \
5042 outpos++; \
5043 } while (0)
5044
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005045/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005046 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5047 * extraneous ones are not emitted but <outlen> is updated so that the caller
5048 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5049 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005050 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5051 * it is guaranteed that at least one arg will point to the zero. It is safe
5052 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005053 *
5054 * <out> may overlap with <in> provided that it never goes further, in which
5055 * case the parser will accept to perform in-place parsing and unquoting/
5056 * unescaping but only if environment variables do not lead to expansion that
5057 * causes overlapping, otherwise the input string being destroyed, the error
5058 * will not be recoverable. Note that even during out-of-place <in> will
5059 * experience temporary modifications in-place for variable resolution and must
5060 * be writable, and will also receive zeroes to delimit words when using
5061 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5062 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5063 * starting point of the first invalid character sequence or unmatched
5064 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5065 * error reporting might be difficult since zeroes will have been inserted into
5066 * the string. One solution for the caller may consist in replacing all args
5067 * delimiters with spaces in this case.
5068 */
5069uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
5070{
5071 char *quote = NULL;
5072 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005073 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005074 unsigned char hex1, hex2;
5075 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005076 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005077 size_t outpos = 0;
5078 int squote = 0;
5079 int dquote = 0;
5080 int arg = 0;
5081 uint32_t err = 0;
5082
5083 *nbargs = 0;
5084 *outlen = 0;
5085
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005086 /* argsmax may be -1 here, protecting args[] from any write */
5087 if (arg < argsmax)
5088 args[arg] = out;
5089
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005090 while (1) {
5091 if (*in >= '-' && *in != '\\') {
5092 /* speedup: directly send all regular chars starting
5093 * with '-', '.', '/', alnum etc...
5094 */
5095 EMIT_CHAR(*in++);
5096 continue;
5097 }
5098 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5099 /* end of line */
5100 break;
5101 }
5102 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5103 /* comment */
5104 break;
5105 }
5106 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5107 if (dquote) {
5108 dquote = 0;
5109 quote = NULL;
5110 }
5111 else {
5112 dquote = 1;
5113 quote = in;
5114 }
5115 in++;
5116 continue;
5117 }
5118 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5119 if (squote) {
5120 squote = 0;
5121 quote = NULL;
5122 }
5123 else {
5124 squote = 1;
5125 quote = in;
5126 }
5127 in++;
5128 continue;
5129 }
5130 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5131 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5132 * C equivalent value but only when they have a special meaning and within
5133 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5134 */
5135 char tosend = *in;
5136
5137 switch (in[1]) {
5138 case ' ':
5139 case '\\':
5140 tosend = in[1];
5141 in++;
5142 break;
5143
5144 case 't':
5145 tosend = '\t';
5146 in++;
5147 break;
5148
5149 case 'n':
5150 tosend = '\n';
5151 in++;
5152 break;
5153
5154 case 'r':
5155 tosend = '\r';
5156 in++;
5157 break;
5158
5159 case '#':
5160 /* escaping of "#" only if comments are supported */
5161 if (opts & PARSE_OPT_SHARP)
5162 in++;
5163 tosend = *in;
5164 break;
5165
5166 case '\'':
5167 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5168 if (opts & PARSE_OPT_SQUOTE && !squote)
5169 in++;
5170 tosend = *in;
5171 break;
5172
5173 case '"':
5174 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5175 if (opts & PARSE_OPT_DQUOTE && !squote)
5176 in++;
5177 tosend = *in;
5178 break;
5179
5180 case '$':
5181 /* escaping of '$' only inside double quotes and only if env supported */
5182 if (opts & PARSE_OPT_ENV && dquote)
5183 in++;
5184 tosend = *in;
5185 break;
5186
5187 case 'x':
5188 if (!ishex(in[2]) || !ishex(in[3])) {
5189 /* invalid or incomplete hex sequence */
5190 err |= PARSE_ERR_HEX;
5191 if (errptr)
5192 *errptr = in;
5193 goto leave;
5194 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005195 hex1 = toupper((unsigned char)in[2]) - '0';
5196 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005197 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5198 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5199 tosend = (hex1 << 4) + hex2;
5200 in += 3;
5201 break;
5202
5203 default:
5204 /* other combinations are not escape sequences */
5205 break;
5206 }
5207
5208 in++;
5209 EMIT_CHAR(tosend);
5210 }
5211 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5212 /* a non-escaped space is an argument separator */
5213 while (isspace((unsigned char)*in))
5214 in++;
5215 EMIT_CHAR(0);
5216 arg++;
5217 if (arg < argsmax)
5218 args[arg] = out + outpos;
5219 else
5220 err |= PARSE_ERR_TOOMANY;
5221 }
5222 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5223 /* environment variables are evaluated anywhere, or only
5224 * inside double quotes if they are supported.
5225 */
5226 char *var_name;
5227 char save_char;
5228 char *value;
5229
5230 in++;
5231
5232 if (*in == '{')
5233 brace = in++;
5234
5235 if (!isalpha((unsigned char)*in) && *in != '_') {
5236 /* unacceptable character in variable name */
5237 err |= PARSE_ERR_VARNAME;
5238 if (errptr)
5239 *errptr = in;
5240 goto leave;
5241 }
5242
5243 var_name = in;
5244 while (isalnum((unsigned char)*in) || *in == '_')
5245 in++;
5246
5247 save_char = *in;
5248 *in = '\0';
5249 value = getenv(var_name);
5250 *in = save_char;
5251
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005252 /* support for '[*]' sequence to force word expansion,
5253 * only available inside braces */
5254 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5255 word_expand = in++;
5256
5257 if (*in++ != '*' || *in++ != ']') {
5258 err |= PARSE_ERR_WRONG_EXPAND;
5259 if (errptr)
5260 *errptr = word_expand;
5261 goto leave;
5262 }
5263 }
5264
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005265 if (brace) {
5266 if (*in != '}') {
5267 /* unmatched brace */
5268 err |= PARSE_ERR_BRACE;
5269 if (errptr)
5270 *errptr = brace;
5271 goto leave;
5272 }
5273 in++;
5274 brace = NULL;
5275 }
5276
5277 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005278 while (*value) {
5279 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005280 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005281 EMIT_CHAR(0);
5282 ++arg;
5283 if (arg < argsmax)
5284 args[arg] = out + outpos;
5285 else
5286 err |= PARSE_ERR_TOOMANY;
5287
5288 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005289 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005290 ;
5291 } else {
5292 EMIT_CHAR(*value++);
5293 }
5294 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005295 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005296 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005297 }
5298 else {
5299 /* any other regular char */
5300 EMIT_CHAR(*in++);
5301 }
5302 }
5303
5304 /* end of output string */
5305 EMIT_CHAR(0);
5306 arg++;
5307
5308 if (quote) {
5309 /* unmatched quote */
5310 err |= PARSE_ERR_QUOTE;
5311 if (errptr)
5312 *errptr = quote;
5313 goto leave;
5314 }
5315 leave:
5316 *nbargs = arg;
5317 *outlen = outpos;
5318
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005319 /* empty all trailing args by making them point to the trailing zero,
5320 * at least the last one in any case.
5321 */
5322 if (arg > argsmax)
5323 arg = argsmax;
5324
5325 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005326 args[arg++] = out + outpos - 1;
5327
5328 return err;
5329}
5330#undef EMIT_CHAR
5331
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005332/* This is used to sanitize an input line that's about to be used for error reporting.
5333 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5334 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5335 * If non-printable chars are present in the output. It returns the new offset <pos>
5336 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5337 * be at least 6 to support two "..." otherwise the result is undefined. The line
5338 * itself must have at least 7 chars allocated for the same reason.
5339 */
5340size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5341{
5342 size_t shift = 0;
5343 char *out = line;
5344 char *in = line;
5345 char *end = line + width;
5346
5347 if (pos >= width) {
5348 /* if we have to shift, we'll be out of context, so let's
5349 * try to put <pos> at the center of width.
5350 */
5351 shift = pos - width / 2;
5352 in += shift + 3;
5353 end = out + width - 3;
5354 out[0] = out[1] = out[2] = '.';
5355 out += 3;
5356 }
5357
5358 while (out < end && *in) {
5359 if (isspace((unsigned char)*in))
5360 *out++ = ' ';
5361 else if (isprint((unsigned char)*in))
5362 *out++ = *in;
5363 else
5364 *out++ = '?';
5365 in++;
5366 }
5367
5368 if (end < line + width) {
5369 out[0] = out[1] = out[2] = '.';
5370 out += 3;
5371 }
5372
5373 *out++ = 0;
5374 return pos - shift;
5375}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005376
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005377/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005378 * transitions between characters. <fp> is a 1024-entries array indexed as
5379 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005380 * 1..26=letter, 27=digit, 28=other/begin/end.
5381 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005382 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005383void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005384{
5385 const char *p;
5386 int from, to;
5387 int c;
5388
Willy Tarreauba2c4452021-03-12 09:01:52 +01005389 from = 28; // begin
5390 for (p = word; *p; p++) {
5391 c = tolower(*p);
5392 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005393 case 'a'...'z': to = c - 'a' + 1; break;
5394 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5395 case '0'...'9': to = 27; break;
5396 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005397 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005398 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005399 fp[32 * from + to]++;
5400 from = to;
5401 }
5402 to = 28; // end
5403 fp[32 * from + to]++;
5404}
5405
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005406/* Initialize array <fp> with the fingerprint of word <word> by counting the
5407 * transitions between characters. <fp> is a 1024-entries array indexed as
5408 * 32*from+to. Positions for 'from' and 'to' are:
5409 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5410 */
5411void make_word_fingerprint(uint8_t *fp, const char *word)
5412{
5413 memset(fp, 0, 1024);
5414 update_word_fingerprint(fp, word);
5415}
5416
Willy Tarreauba2c4452021-03-12 09:01:52 +01005417/* Return the distance between two word fingerprints created by function
5418 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005419 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005420 */
5421int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5422{
5423 int i, k, dist = 0;
5424
5425 for (i = 0; i < 1024; i++) {
5426 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005427 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005428 }
5429 return dist;
5430}
5431
Willy Tarreau06e69b52021-03-02 14:01:35 +01005432static int init_tools_per_thread()
5433{
5434 /* Let's make each thread start from a different position */
5435 statistical_prng_state += tid * MAX_THREADS;
5436 if (!statistical_prng_state)
5437 statistical_prng_state++;
5438 return 1;
5439}
5440REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005441
Willy Tarreaubaaee002006-06-26 02:48:02 +02005442/*
5443 * Local variables:
5444 * c-indent-level: 8
5445 * c-basic-offset: 8
5446 * End:
5447 */