blob: a81f5a0fca324df71205fdfae1a1c60a680684e3 [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
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010013#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020014#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020015#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020016#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020017#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020018#include <stdlib.h>
19#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010020#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020021#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010022#include <sys/socket.h>
23#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <netinet/in.h>
25#include <arpa/inet.h>
26
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010027#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020028#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020029#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010030#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010031#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020032#include <proto/dns.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010033#include <eb32tree.h>
Willy Tarreaued3cda02017-11-15 15:04:05 +010034#include <eb32sctree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035
Thierry Fournier93127942016-01-20 18:49:45 +010036/* This macro returns false if the test __x is false. Many
37 * of the following parsing function must be abort the processing
38 * if it returns 0, so this macro is useful for writing light code.
39 */
40#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
41
Willy Tarreau56adcf22012-12-23 18:00:29 +010042/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020043 * 2^64-1 = 18446744073709551615 or
44 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020045 *
46 * The HTML version needs room for adding the 25 characters
47 * '<span class="rls"></span>' around digits at positions 3N+1 in order
48 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020049 */
Christopher Faulet99bca652017-11-14 16:47:26 +010050THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
51THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020052
Willy Tarreau588297f2014-06-16 15:16:40 +020053/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
54 * to quote strings larger than a max configuration line.
55 */
Christopher Faulet99bca652017-11-14 16:47:26 +010056THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
57THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020058
Willy Tarreaubaaee002006-06-26 02:48:02 +020059/*
William Lallemande7340ec2012-01-24 11:15:39 +010060 * unsigned long long ASCII representation
61 *
62 * return the last char '\0' or NULL if no enough
63 * space in dst
64 */
65char *ulltoa(unsigned long long n, char *dst, size_t size)
66{
67 int i = 0;
68 char *res;
69
70 switch(n) {
71 case 1ULL ... 9ULL:
72 i = 0;
73 break;
74
75 case 10ULL ... 99ULL:
76 i = 1;
77 break;
78
79 case 100ULL ... 999ULL:
80 i = 2;
81 break;
82
83 case 1000ULL ... 9999ULL:
84 i = 3;
85 break;
86
87 case 10000ULL ... 99999ULL:
88 i = 4;
89 break;
90
91 case 100000ULL ... 999999ULL:
92 i = 5;
93 break;
94
95 case 1000000ULL ... 9999999ULL:
96 i = 6;
97 break;
98
99 case 10000000ULL ... 99999999ULL:
100 i = 7;
101 break;
102
103 case 100000000ULL ... 999999999ULL:
104 i = 8;
105 break;
106
107 case 1000000000ULL ... 9999999999ULL:
108 i = 9;
109 break;
110
111 case 10000000000ULL ... 99999999999ULL:
112 i = 10;
113 break;
114
115 case 100000000000ULL ... 999999999999ULL:
116 i = 11;
117 break;
118
119 case 1000000000000ULL ... 9999999999999ULL:
120 i = 12;
121 break;
122
123 case 10000000000000ULL ... 99999999999999ULL:
124 i = 13;
125 break;
126
127 case 100000000000000ULL ... 999999999999999ULL:
128 i = 14;
129 break;
130
131 case 1000000000000000ULL ... 9999999999999999ULL:
132 i = 15;
133 break;
134
135 case 10000000000000000ULL ... 99999999999999999ULL:
136 i = 16;
137 break;
138
139 case 100000000000000000ULL ... 999999999999999999ULL:
140 i = 17;
141 break;
142
143 case 1000000000000000000ULL ... 9999999999999999999ULL:
144 i = 18;
145 break;
146
147 case 10000000000000000000ULL ... ULLONG_MAX:
148 i = 19;
149 break;
150 }
151 if (i + 2 > size) // (i + 1) + '\0'
152 return NULL; // too long
153 res = dst + i + 1;
154 *res = '\0';
155 for (; i >= 0; i--) {
156 dst[i] = n % 10ULL + '0';
157 n /= 10ULL;
158 }
159 return res;
160}
161
162/*
163 * unsigned long ASCII representation
164 *
165 * return the last char '\0' or NULL if no enough
166 * space in dst
167 */
168char *ultoa_o(unsigned long n, char *dst, size_t size)
169{
170 int i = 0;
171 char *res;
172
173 switch (n) {
174 case 0U ... 9UL:
175 i = 0;
176 break;
177
178 case 10U ... 99UL:
179 i = 1;
180 break;
181
182 case 100U ... 999UL:
183 i = 2;
184 break;
185
186 case 1000U ... 9999UL:
187 i = 3;
188 break;
189
190 case 10000U ... 99999UL:
191 i = 4;
192 break;
193
194 case 100000U ... 999999UL:
195 i = 5;
196 break;
197
198 case 1000000U ... 9999999UL:
199 i = 6;
200 break;
201
202 case 10000000U ... 99999999UL:
203 i = 7;
204 break;
205
206 case 100000000U ... 999999999UL:
207 i = 8;
208 break;
209#if __WORDSIZE == 32
210
211 case 1000000000ULL ... ULONG_MAX:
212 i = 9;
213 break;
214
215#elif __WORDSIZE == 64
216
217 case 1000000000ULL ... 9999999999UL:
218 i = 9;
219 break;
220
221 case 10000000000ULL ... 99999999999UL:
222 i = 10;
223 break;
224
225 case 100000000000ULL ... 999999999999UL:
226 i = 11;
227 break;
228
229 case 1000000000000ULL ... 9999999999999UL:
230 i = 12;
231 break;
232
233 case 10000000000000ULL ... 99999999999999UL:
234 i = 13;
235 break;
236
237 case 100000000000000ULL ... 999999999999999UL:
238 i = 14;
239 break;
240
241 case 1000000000000000ULL ... 9999999999999999UL:
242 i = 15;
243 break;
244
245 case 10000000000000000ULL ... 99999999999999999UL:
246 i = 16;
247 break;
248
249 case 100000000000000000ULL ... 999999999999999999UL:
250 i = 17;
251 break;
252
253 case 1000000000000000000ULL ... 9999999999999999999UL:
254 i = 18;
255 break;
256
257 case 10000000000000000000ULL ... ULONG_MAX:
258 i = 19;
259 break;
260
261#endif
262 }
263 if (i + 2 > size) // (i + 1) + '\0'
264 return NULL; // too long
265 res = dst + i + 1;
266 *res = '\0';
267 for (; i >= 0; i--) {
268 dst[i] = n % 10U + '0';
269 n /= 10U;
270 }
271 return res;
272}
273
274/*
275 * signed long ASCII representation
276 *
277 * return the last char '\0' or NULL if no enough
278 * space in dst
279 */
280char *ltoa_o(long int n, char *dst, size_t size)
281{
282 char *pos = dst;
283
284 if (n < 0) {
285 if (size < 3)
286 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
287 *pos = '-';
288 pos++;
289 dst = ultoa_o(-n, pos, size - 1);
290 } else {
291 dst = ultoa_o(n, dst, size);
292 }
293 return dst;
294}
295
296/*
297 * signed long long ASCII representation
298 *
299 * return the last char '\0' or NULL if no enough
300 * space in dst
301 */
302char *lltoa(long long n, char *dst, size_t size)
303{
304 char *pos = dst;
305
306 if (n < 0) {
307 if (size < 3)
308 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
309 *pos = '-';
310 pos++;
311 dst = ulltoa(-n, pos, size - 1);
312 } else {
313 dst = ulltoa(n, dst, size);
314 }
315 return dst;
316}
317
318/*
319 * write a ascii representation of a unsigned into dst,
320 * return a pointer to the last character
321 * Pad the ascii representation with '0', using size.
322 */
323char *utoa_pad(unsigned int n, char *dst, size_t size)
324{
325 int i = 0;
326 char *ret;
327
328 switch(n) {
329 case 0U ... 9U:
330 i = 0;
331 break;
332
333 case 10U ... 99U:
334 i = 1;
335 break;
336
337 case 100U ... 999U:
338 i = 2;
339 break;
340
341 case 1000U ... 9999U:
342 i = 3;
343 break;
344
345 case 10000U ... 99999U:
346 i = 4;
347 break;
348
349 case 100000U ... 999999U:
350 i = 5;
351 break;
352
353 case 1000000U ... 9999999U:
354 i = 6;
355 break;
356
357 case 10000000U ... 99999999U:
358 i = 7;
359 break;
360
361 case 100000000U ... 999999999U:
362 i = 8;
363 break;
364
365 case 1000000000U ... 4294967295U:
366 i = 9;
367 break;
368 }
369 if (i + 2 > size) // (i + 1) + '\0'
370 return NULL; // too long
371 if (i < size)
372 i = size - 2; // padding - '\0'
373
374 ret = dst + i + 1;
375 *ret = '\0';
376 for (; i >= 0; i--) {
377 dst[i] = n % 10U + '0';
378 n /= 10U;
379 }
380 return ret;
381}
382
383/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200384 * copies at most <size-1> chars from <src> to <dst>. Last char is always
385 * set to 0, unless <size> is 0. The number of chars copied is returned
386 * (excluding the terminating zero).
387 * This code has been optimized for size and speed : on x86, it's 45 bytes
388 * long, uses only registers, and consumes only 4 cycles per char.
389 */
390int strlcpy2(char *dst, const char *src, int size)
391{
392 char *orig = dst;
393 if (size) {
394 while (--size && (*dst = *src)) {
395 src++; dst++;
396 }
397 *dst = 0;
398 }
399 return dst - orig;
400}
401
402/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200403 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404 * the ascii representation for number 'n' in decimal.
405 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100406char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200407{
408 char *pos;
409
Willy Tarreau72d759c2007-10-25 12:14:10 +0200410 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200411 *pos-- = '\0';
412
413 do {
414 *pos-- = '0' + n % 10;
415 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200416 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200417 return pos + 1;
418}
419
Willy Tarreau91092e52007-10-25 16:58:42 +0200420/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200421 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200422 * the ascii representation for number 'n' in decimal.
423 */
424char *lltoa_r(long long int in, char *buffer, int size)
425{
426 char *pos;
427 int neg = 0;
428 unsigned long long int n;
429
430 pos = buffer + size - 1;
431 *pos-- = '\0';
432
433 if (in < 0) {
434 neg = 1;
435 n = -in;
436 }
437 else
438 n = in;
439
440 do {
441 *pos-- = '0' + n % 10;
442 n /= 10;
443 } while (n && pos >= buffer);
444 if (neg && pos > buffer)
445 *pos-- = '-';
446 return pos + 1;
447}
448
449/*
450 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200451 * the ascii representation for signed number 'n' in decimal.
452 */
453char *sltoa_r(long n, char *buffer, int size)
454{
455 char *pos;
456
457 if (n >= 0)
458 return ultoa_r(n, buffer, size);
459
460 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
461 *pos = '-';
462 return pos;
463}
464
465/*
466 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200467 * the ascii representation for number 'n' in decimal, formatted for
468 * HTML output with tags to create visual grouping by 3 digits. The
469 * output needs to support at least 171 characters.
470 */
471const char *ulltoh_r(unsigned long long n, char *buffer, int size)
472{
473 char *start;
474 int digit = 0;
475
476 start = buffer + size;
477 *--start = '\0';
478
479 do {
480 if (digit == 3 && start >= buffer + 7)
481 memcpy(start -= 7, "</span>", 7);
482
483 if (start >= buffer + 1) {
484 *--start = '0' + n % 10;
485 n /= 10;
486 }
487
488 if (digit == 3 && start >= buffer + 18)
489 memcpy(start -= 18, "<span class=\"rls\">", 18);
490
491 if (digit++ == 3)
492 digit = 1;
493 } while (n && start > buffer);
494 return start;
495}
496
497/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200498 * This function simply returns a locally allocated string containing the ascii
499 * representation for number 'n' in decimal, unless n is 0 in which case it
500 * returns the alternate string (or an empty string if the alternate string is
501 * NULL). It use is intended for limits reported in reports, where it's
502 * desirable not to display anything if there is no limit. Warning! it shares
503 * the same vector as ultoa_r().
504 */
505const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
506{
507 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
508}
509
Willy Tarreau588297f2014-06-16 15:16:40 +0200510/* returns a locally allocated string containing the quoted encoding of the
511 * input string. The output may be truncated to QSTR_SIZE chars, but it is
512 * guaranteed that the string will always be properly terminated. Quotes are
513 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
514 * always be at least 4 chars.
515 */
516const char *qstr(const char *str)
517{
518 char *ret = quoted_str[quoted_idx];
519 char *p, *end;
520
521 if (++quoted_idx >= NB_QSTR)
522 quoted_idx = 0;
523
524 p = ret;
525 end = ret + QSTR_SIZE;
526
527 *p++ = '"';
528
529 /* always keep 3 chars to support passing "" and the ending " */
530 while (*str && p < end - 3) {
531 if (*str == '"') {
532 *p++ = '"';
533 *p++ = '"';
534 }
535 else
536 *p++ = *str;
537 str++;
538 }
539 *p++ = '"';
540 return ret;
541}
542
Robert Tsai81ae1952007-12-05 10:47:29 +0100543/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200544 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
545 *
546 * It looks like this one would be a good candidate for inlining, but this is
547 * not interesting because it around 35 bytes long and often called multiple
548 * times within the same function.
549 */
550int ishex(char s)
551{
552 s -= '0';
553 if ((unsigned char)s <= 9)
554 return 1;
555 s -= 'A' - '0';
556 if ((unsigned char)s <= 5)
557 return 1;
558 s -= 'a' - 'A';
559 if ((unsigned char)s <= 5)
560 return 1;
561 return 0;
562}
563
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100564/* rounds <i> down to the closest value having max 2 digits */
565unsigned int round_2dig(unsigned int i)
566{
567 unsigned int mul = 1;
568
569 while (i >= 100) {
570 i /= 10;
571 mul *= 10;
572 }
573 return i * mul;
574}
575
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100576/*
577 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
578 * invalid character is found, a pointer to it is returned. If everything is
579 * fine, NULL is returned.
580 */
581const char *invalid_char(const char *name)
582{
583 if (!*name)
584 return name;
585
586 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100587 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100588 *name != '_' && *name != '-')
589 return name;
590 name++;
591 }
592 return NULL;
593}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200594
595/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200596 * Checks <name> for invalid characters. Valid chars are [_.-] and those
597 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200598 * If an invalid character is found, a pointer to it is returned.
599 * If everything is fine, NULL is returned.
600 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200601static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200602
603 if (!*name)
604 return name;
605
606 while (*name) {
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200607 if (!f((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200608 *name != '_' && *name != '-')
609 return name;
610
611 name++;
612 }
613
614 return NULL;
615}
616
617/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200618 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
619 * If an invalid character is found, a pointer to it is returned.
620 * If everything is fine, NULL is returned.
621 */
622const char *invalid_domainchar(const char *name) {
623 return __invalid_char(name, isalnum);
624}
625
626/*
627 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
628 * If an invalid character is found, a pointer to it is returned.
629 * If everything is fine, NULL is returned.
630 */
631const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200632 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200633}
634
635/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100636 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100637 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
638 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
639 * the function tries to guess the address family from the syntax. If the
640 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100641 * string is assumed to contain only an address, no port. The address can be a
642 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
643 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
644 * The return address will only have the address family and the address set,
645 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100646 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
647 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100648 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200649 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100650struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200651{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100652 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100653 /* max IPv6 length, including brackets and terminating NULL */
654 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100655 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100656
657 /* check IPv6 with square brackets */
658 if (str[0] == '[') {
659 size_t iplength = strlen(str);
660
661 if (iplength < 4) {
662 /* minimal size is 4 when using brackets "[::]" */
663 goto fail;
664 }
665 else if (iplength >= sizeof(tmpip)) {
666 /* IPv6 literal can not be larger than tmpip */
667 goto fail;
668 }
669 else {
670 if (str[iplength - 1] != ']') {
671 /* if address started with bracket, it should end with bracket */
672 goto fail;
673 }
674 else {
675 memcpy(tmpip, str + 1, iplength - 2);
676 tmpip[iplength - 2] = '\0';
677 str = tmpip;
678 }
679 }
680 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100681
Willy Tarreaufab5a432011-03-04 15:31:53 +0100682 /* Any IPv6 address */
683 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100684 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
685 sa->ss_family = AF_INET6;
686 else if (sa->ss_family != AF_INET6)
687 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100688 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100689 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100690 }
691
Willy Tarreau24709282013-03-10 21:32:12 +0100692 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100693 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100694 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
695 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100696 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100697 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100698 }
699
700 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100701 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
702 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100703 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100704 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100705 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100706 }
707
708 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100709 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
710 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100711 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100712 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100713 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100714 }
715
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100716 if (!resolve)
717 return NULL;
718
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200719 if (!dns_hostname_validation(str, NULL))
720 return NULL;
721
David du Colombierd5f43282011-03-17 10:40:16 +0100722#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200723 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100724 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100725 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100726
727 memset(&result, 0, sizeof(result));
728 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100729 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100730 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200731 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100732 hints.ai_protocol = 0;
733
734 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100735 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
736 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100737 else if (sa->ss_family != result->ai_family) {
738 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100739 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100740 }
Willy Tarreau24709282013-03-10 21:32:12 +0100741
David du Colombierd5f43282011-03-17 10:40:16 +0100742 switch (result->ai_family) {
743 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100744 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100745 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100746 success = 1;
747 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100748 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100749 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100750 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100751 success = 1;
752 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100753 }
754 }
755
Sean Carey58ea0392013-02-15 23:39:18 +0100756 if (result)
757 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100758
759 if (success)
760 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100761 }
David du Colombierd5f43282011-03-17 10:40:16 +0100762#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200763 /* try to resolve an IPv4/IPv6 hostname */
764 he = gethostbyname(str);
765 if (he) {
766 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
767 sa->ss_family = he->h_addrtype;
768 else if (sa->ss_family != he->h_addrtype)
769 goto fail;
770
771 switch (sa->ss_family) {
772 case AF_INET:
773 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100774 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200775 return sa;
776 case AF_INET6:
777 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100778 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200779 return sa;
780 }
781 }
782
David du Colombierd5f43282011-03-17 10:40:16 +0100783 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100784 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100785 return NULL;
786}
787
788/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100789 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
790 * range or offset consisting in two integers that the caller will have to
791 * check to find the relevant input format. The following format are supported :
792 *
793 * String format | address | port | low | high
794 * addr | <addr> | 0 | 0 | 0
795 * addr: | <addr> | 0 | 0 | 0
796 * addr:port | <addr> | <port> | <port> | <port>
797 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
798 * addr:+port | <addr> | <port> | 0 | <port>
799 * addr:-port | <addr> |-<port> | <port> | 0
800 *
801 * The detection of a port range or increment by the caller is made by
802 * comparing <low> and <high>. If both are equal, then port 0 means no port
803 * was specified. The caller may pass NULL for <low> and <high> if it is not
804 * interested in retrieving port ranges.
805 *
806 * Note that <addr> above may also be :
807 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
808 * - "*" => family will be AF_INET and address will be INADDR_ANY
809 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
810 * - a host name => family and address will depend on host name resolving.
811 *
Willy Tarreau24709282013-03-10 21:32:12 +0100812 * A prefix may be passed in before the address above to force the family :
813 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
814 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
815 * - "unix@" => force address to be a path to a UNIX socket even if the
816 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200817 * - 'abns@' -> force address to belong to the abstract namespace (Linux
818 * only). These sockets are just like Unix sockets but without
819 * the need for an underlying file system. The address is a
820 * string. Technically it's like a Unix socket with a zero in
821 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100822 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100823 *
mildisff5d5102015-10-26 18:50:08 +0100824 * IPv6 addresses can be declared with or without square brackets. When using
825 * square brackets for IPv6 addresses, the port separator (colon) is optional.
826 * If not using square brackets, and in order to avoid any ambiguity with
827 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
828 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
829 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100830 *
831 * If <pfx> is non-null, it is used as a string prefix before any path-based
832 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100833 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200834 * if <fqdn> is non-null, it will be filled with :
835 * - a pointer to the FQDN of the server name to resolve if there's one, and
836 * that the caller will have to free(),
837 * - NULL if there was an explicit address that doesn't require resolution.
838 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100839 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
840 * is null, <fqdn> is still honnored so it is possible for the caller to know
841 * whether a resolution failed by setting <resolve> to null and checking if
842 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200843 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100844 * When a file descriptor is passed, its value is put into the s_addr part of
845 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100846 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100847struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100848{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100849 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100850 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100851 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100852 char *port1, *port2;
853 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200854 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100855
856 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200857 if (fqdn)
858 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200859
Willy Tarreaudad36a32013-03-11 01:20:04 +0100860 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100861 if (str2 == NULL) {
862 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100863 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100864 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200865
Willy Tarreau9f69f462015-09-08 16:01:25 +0200866 if (!*str2) {
867 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
868 goto out;
869 }
870
Willy Tarreau24709282013-03-10 21:32:12 +0100871 memset(&ss, 0, sizeof(ss));
872
873 if (strncmp(str2, "unix@", 5) == 0) {
874 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200875 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100876 ss.ss_family = AF_UNIX;
877 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200878 else if (strncmp(str2, "abns@", 5) == 0) {
879 str2 += 5;
880 abstract = 1;
881 ss.ss_family = AF_UNIX;
882 }
Willy Tarreau24709282013-03-10 21:32:12 +0100883 else if (strncmp(str2, "ipv4@", 5) == 0) {
884 str2 += 5;
885 ss.ss_family = AF_INET;
886 }
887 else if (strncmp(str2, "ipv6@", 5) == 0) {
888 str2 += 5;
889 ss.ss_family = AF_INET6;
890 }
891 else if (*str2 == '/') {
892 ss.ss_family = AF_UNIX;
893 }
894 else
895 ss.ss_family = AF_UNSPEC;
896
William Lallemand2fe7dd02018-09-11 16:51:29 +0200897 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
898 char *endptr;
899
900 str2 += 9;
901
902 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100903 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200904
905 if (!*str2 || *endptr) {
906 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
907 goto out;
908 }
909
910 ss.ss_family = AF_CUST_SOCKPAIR;
911
912 }
913 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100914 char *endptr;
915
916 str2 += 3;
917 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100918 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100919
920 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100921 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100922 goto out;
923 }
924
925 /* we return AF_UNSPEC if we use a file descriptor number */
926 ss.ss_family = AF_UNSPEC;
927 }
928 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100929 int prefix_path_len;
930 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200931 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100932
933 /* complete unix socket path name during startup or soft-restart is
934 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
935 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200936 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100937 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
938 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
939
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200940 adr_len = strlen(str2);
941 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100942 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
943 goto out;
944 }
945
Willy Tarreauccfccef2014-05-10 01:49:15 +0200946 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
947 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200948 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100949 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200950 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100951 }
Willy Tarreau24709282013-03-10 21:32:12 +0100952 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100953 char *end = str2 + strlen(str2);
954 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200955
mildisff5d5102015-10-26 18:50:08 +0100956 /* search for : or ] whatever comes first */
957 for (chr = end-1; chr > str2; chr--) {
958 if (*chr == ']' || *chr == ':')
959 break;
960 }
961
962 if (*chr == ':') {
963 /* Found a colon before a closing-bracket, must be a port separator.
964 * This guarantee backward compatibility.
965 */
966 *chr++ = '\0';
967 port1 = chr;
968 }
969 else {
970 /* Either no colon and no closing-bracket
971 * or directly ending with a closing-bracket.
972 * However, no port.
973 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100974 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100975 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200976
Willy Tarreaua39d1992013-04-01 20:37:42 +0200977 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100978 port2 = strchr(port1, '-');
979 if (port2)
980 *port2++ = '\0';
981 else
982 port2 = port1;
983 portl = atoi(port1);
984 porth = atoi(port2);
985 porta = portl;
986 }
987 else if (*port1 == '-') { /* negative offset */
988 portl = atoi(port1 + 1);
989 porta = -portl;
990 }
991 else if (*port1 == '+') { /* positive offset */
992 porth = atoi(port1 + 1);
993 porta = porth;
994 }
995 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100996 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100997 goto out;
998 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100999
1000 /* first try to parse the IP without resolving. If it fails, it
1001 * tells us we need to keep a copy of the FQDN to resolve later
1002 * and to enable DNS. In this case we can proceed if <fqdn> is
1003 * set or if resolve is set, otherwise it's an error.
1004 */
1005 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001006 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001007 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1008 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1009 goto out;
1010 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001011
Willy Tarreauceccdd72016-11-02 22:27:10 +01001012 if (fqdn) {
1013 if (str2 != back)
1014 memmove(back, str2, strlen(str2) + 1);
1015 *fqdn = back;
1016 back = NULL;
1017 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001018 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001019 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001020 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001021
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001022 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001023 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001024 if (port)
1025 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001026 if (low)
1027 *low = portl;
1028 if (high)
1029 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001030 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001031 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001032}
1033
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001034/* converts <str> to a struct in_addr containing a network mask. It can be
1035 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001036 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001037 */
1038int str2mask(const char *str, struct in_addr *mask)
1039{
1040 if (strchr(str, '.') != NULL) { /* dotted notation */
1041 if (!inet_pton(AF_INET, str, mask))
1042 return 0;
1043 }
1044 else { /* mask length */
1045 char *err;
1046 unsigned long len = strtol(str, &err, 10);
1047
1048 if (!*str || (err && *err) || (unsigned)len > 32)
1049 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001050
1051 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001052 }
1053 return 1;
1054}
1055
Tim Duesterhus47185172018-01-25 16:24:49 +01001056/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001057 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001058 * if the conversion succeeds otherwise zero.
1059 */
1060int str2mask6(const char *str, struct in6_addr *mask)
1061{
1062 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1063 if (!inet_pton(AF_INET6, str, mask))
1064 return 0;
1065 }
1066 else { /* mask length */
1067 char *err;
1068 unsigned long len = strtol(str, &err, 10);
1069
1070 if (!*str || (err && *err) || (unsigned)len > 128)
1071 return 0;
1072
1073 len2mask6(len, mask);
1074 }
1075 return 1;
1076}
1077
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001078/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1079 * succeeds otherwise zero.
1080 */
1081int cidr2dotted(int cidr, struct in_addr *mask) {
1082
1083 if (cidr < 0 || cidr > 32)
1084 return 0;
1085
1086 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1087 return 1;
1088}
1089
Thierry Fournier70473a52016-02-17 17:12:14 +01001090/* Convert mask from bit length form to in_addr form.
1091 * This function never fails.
1092 */
1093void len2mask4(int len, struct in_addr *addr)
1094{
1095 if (len >= 32) {
1096 addr->s_addr = 0xffffffff;
1097 return;
1098 }
1099 if (len <= 0) {
1100 addr->s_addr = 0x00000000;
1101 return;
1102 }
1103 addr->s_addr = 0xffffffff << (32 - len);
1104 addr->s_addr = htonl(addr->s_addr);
1105}
1106
1107/* Convert mask from bit length form to in6_addr form.
1108 * This function never fails.
1109 */
1110void len2mask6(int len, struct in6_addr *addr)
1111{
1112 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1113 len -= 32;
1114 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1115 len -= 32;
1116 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1117 len -= 32;
1118 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1119}
1120
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001121/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001122 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001123 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1124 * is optionnal and either in the dotted or CIDR notation.
1125 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1126 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001127int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001128{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001129 __label__ out_free, out_err;
1130 char *c, *s;
1131 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001132
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001133 s = strdup(str);
1134 if (!s)
1135 return 0;
1136
Willy Tarreaubaaee002006-06-26 02:48:02 +02001137 memset(mask, 0, sizeof(*mask));
1138 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001139
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001140 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001141 *c++ = '\0';
1142 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001143 if (!str2mask(c, mask))
1144 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001145 }
1146 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001147 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001148 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001149 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001150 struct hostent *he;
1151
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001152 if (!resolve)
1153 goto out_err;
1154
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001155 if ((he = gethostbyname(s)) == NULL) {
1156 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001157 }
1158 else
1159 *addr = *(struct in_addr *) *(he->h_addr_list);
1160 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001161
1162 ret_val = 1;
1163 out_free:
1164 free(s);
1165 return ret_val;
1166 out_err:
1167 ret_val = 0;
1168 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001169}
1170
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001171
1172/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001173 * converts <str> to two struct in6_addr* which must be pre-allocated.
1174 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1175 * is an optionnal number of bits (128 being the default).
1176 * Returns 1 if OK, 0 if error.
1177 */
1178int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1179{
1180 char *c, *s;
1181 int ret_val = 0;
1182 char *err;
1183 unsigned long len = 128;
1184
1185 s = strdup(str);
1186 if (!s)
1187 return 0;
1188
1189 memset(mask, 0, sizeof(*mask));
1190 memset(addr, 0, sizeof(*addr));
1191
1192 if ((c = strrchr(s, '/')) != NULL) {
1193 *c++ = '\0'; /* c points to the mask */
1194 if (!*c)
1195 goto out_free;
1196
1197 len = strtoul(c, &err, 10);
1198 if ((err && *err) || (unsigned)len > 128)
1199 goto out_free;
1200 }
1201 *mask = len; /* OK we have a valid mask in <len> */
1202
1203 if (!inet_pton(AF_INET6, s, addr))
1204 goto out_free;
1205
1206 ret_val = 1;
1207 out_free:
1208 free(s);
1209 return ret_val;
1210}
1211
1212
1213/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001214 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001215 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001216int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001217{
1218 int saw_digit, octets, ch;
1219 u_char tmp[4], *tp;
1220 const char *cp = addr;
1221
1222 saw_digit = 0;
1223 octets = 0;
1224 *(tp = tmp) = 0;
1225
1226 while (*addr) {
1227 unsigned char digit = (ch = *addr++) - '0';
1228 if (digit > 9 && ch != '.')
1229 break;
1230 if (digit <= 9) {
1231 u_int new = *tp * 10 + digit;
1232 if (new > 255)
1233 return 0;
1234 *tp = new;
1235 if (!saw_digit) {
1236 if (++octets > 4)
1237 return 0;
1238 saw_digit = 1;
1239 }
1240 } else if (ch == '.' && saw_digit) {
1241 if (octets == 4)
1242 return 0;
1243 *++tp = 0;
1244 saw_digit = 0;
1245 } else
1246 return 0;
1247 }
1248
1249 if (octets < 4)
1250 return 0;
1251
1252 memcpy(&dst->s_addr, tmp, 4);
1253 return addr-cp-1;
1254}
1255
1256/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001257 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1258 * <out> contain the code of the dectected scheme, the start and length of
1259 * the hostname. Actually only http and https are supported. <out> can be NULL.
1260 * This function returns the consumed length. It is useful if you parse complete
1261 * url like http://host:port/path, because the consumed length corresponds to
1262 * the first character of the path. If the conversion fails, it returns -1.
1263 *
1264 * This function tries to resolve the DNS name if haproxy is in starting mode.
1265 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001266 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001267int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001268{
1269 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001270 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001271 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001272 unsigned long long int http_code = 0;
1273 int default_port;
1274 struct hostent *he;
1275 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001276
1277 /* Firstly, try to find :// pattern */
1278 while (curr < url+ulen && url_code != 0x3a2f2f) {
1279 url_code = ((url_code & 0xffff) << 8);
1280 url_code += (unsigned char)*curr++;
1281 }
1282
1283 /* Secondly, if :// pattern is found, verify parsed stuff
1284 * before pattern is matching our http pattern.
1285 * If so parse ip address and port in uri.
1286 *
1287 * WARNING: Current code doesn't support dynamic async dns resolver.
1288 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001289 if (url_code != 0x3a2f2f)
1290 return -1;
1291
1292 /* Copy scheme, and utrn to lower case. */
1293 while (cp < curr - 3)
1294 http_code = (http_code << 8) + *cp++;
1295 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001296
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001297 /* HTTP or HTTPS url matching */
1298 if (http_code == 0x2020202068747470ULL) {
1299 default_port = 80;
1300 if (out)
1301 out->scheme = SCH_HTTP;
1302 }
1303 else if (http_code == 0x2020206874747073ULL) {
1304 default_port = 443;
1305 if (out)
1306 out->scheme = SCH_HTTPS;
1307 }
1308 else
1309 return -1;
1310
1311 /* If the next char is '[', the host address is IPv6. */
1312 if (*curr == '[') {
1313 curr++;
1314
1315 /* Check trash size */
1316 if (trash.size < ulen)
1317 return -1;
1318
1319 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001320 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001321 for (end = curr;
1322 end < url + ulen && *end != ']';
1323 end++, p++)
1324 *p = *end;
1325 if (*end != ']')
1326 return -1;
1327 *p = '\0';
1328
1329 /* Update out. */
1330 if (out) {
1331 out->host = curr;
1332 out->host_len = end - curr;
1333 }
1334
1335 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001336 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001337 return -1;
1338 end++;
1339
1340 /* Decode port. */
1341 if (*end == ':') {
1342 end++;
1343 default_port = read_uint(&end, url + ulen);
1344 }
1345 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1346 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1347 return end - url;
1348 }
1349 else {
1350 /* We are looking for IP address. If you want to parse and
1351 * resolve hostname found in url, you can use str2sa_range(), but
1352 * be warned this can slow down global daemon performances
1353 * while handling lagging dns responses.
1354 */
1355 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1356 if (ret) {
1357 /* Update out. */
1358 if (out) {
1359 out->host = curr;
1360 out->host_len = ret;
1361 }
1362
1363 curr += ret;
1364
1365 /* Decode port. */
1366 if (*curr == ':') {
1367 curr++;
1368 default_port = read_uint(&curr, url + ulen);
1369 }
1370 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1371
1372 /* Set family. */
1373 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1374 return curr - url;
1375 }
1376 else if (global.mode & MODE_STARTING) {
1377 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1378 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001379 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001380
1381 /* look for : or / or end */
1382 for (end = curr;
1383 end < url + ulen && *end != '/' && *end != ':';
1384 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001385 memcpy(trash.area, curr, end - curr);
1386 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001387
1388 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001389 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001390 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001391 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001392
1393 /* Update out. */
1394 if (out) {
1395 out->host = curr;
1396 out->host_len = end - curr;
1397 }
1398
1399 /* Decode port. */
1400 if (*end == ':') {
1401 end++;
1402 default_port = read_uint(&end, url + ulen);
1403 }
1404
1405 /* Copy IP address, set port and family. */
1406 switch (he->h_addrtype) {
1407 case AF_INET:
1408 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1409 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1410 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1411 return end - url;
1412
1413 case AF_INET6:
1414 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1415 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1416 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1417 return end - url;
1418 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001419 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001420 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001421 return -1;
1422}
1423
Willy Tarreau631f01c2011-09-05 00:36:48 +02001424/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1425 * address family is returned so that it's easy for the caller to adapt to the
1426 * output format. Zero is returned if the address family is not supported. -1
1427 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1428 * supported.
1429 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001430int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001431{
1432
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001433 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001434
1435 if (size < 5)
1436 return 0;
1437 *str = '\0';
1438
1439 switch (addr->ss_family) {
1440 case AF_INET:
1441 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1442 break;
1443 case AF_INET6:
1444 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1445 break;
1446 case AF_UNIX:
1447 memcpy(str, "unix", 5);
1448 return addr->ss_family;
1449 default:
1450 return 0;
1451 }
1452
1453 if (inet_ntop(addr->ss_family, ptr, str, size))
1454 return addr->ss_family;
1455
1456 /* failed */
1457 return -1;
1458}
1459
Simon Horman75ab8bd2014-06-16 09:39:41 +09001460/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1461 * address family is returned so that it's easy for the caller to adapt to the
1462 * output format. Zero is returned if the address family is not supported. -1
1463 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1464 * supported.
1465 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001466int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001467{
1468
1469 uint16_t port;
1470
1471
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001472 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001473 return 0;
1474 *str = '\0';
1475
1476 switch (addr->ss_family) {
1477 case AF_INET:
1478 port = ((struct sockaddr_in *)addr)->sin_port;
1479 break;
1480 case AF_INET6:
1481 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1482 break;
1483 case AF_UNIX:
1484 memcpy(str, "unix", 5);
1485 return addr->ss_family;
1486 default:
1487 return 0;
1488 }
1489
1490 snprintf(str, size, "%u", ntohs(port));
1491 return addr->ss_family;
1492}
1493
Willy Tarreau16e01562016-08-09 16:46:18 +02001494/* check if the given address is local to the system or not. It will return
1495 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1496 * it is. We don't want to iterate over all interfaces for this (and it is not
1497 * portable). So instead we try to bind in UDP to this address on a free non
1498 * privileged port and to connect to the same address, port 0 (connect doesn't
1499 * care). If it succeeds, we own the address. Note that non-inet addresses are
1500 * considered local since they're most likely AF_UNIX.
1501 */
1502int addr_is_local(const struct netns_entry *ns,
1503 const struct sockaddr_storage *orig)
1504{
1505 struct sockaddr_storage addr;
1506 int result;
1507 int fd;
1508
1509 if (!is_inet_addr(orig))
1510 return 1;
1511
1512 memcpy(&addr, orig, sizeof(addr));
1513 set_host_port(&addr, 0);
1514
1515 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1516 if (fd < 0)
1517 return -1;
1518
1519 result = -1;
1520 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1521 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1522 result = 0; // fail, non-local address
1523 else
1524 result = 1; // success, local address
1525 }
1526 else {
1527 if (errno == EADDRNOTAVAIL)
1528 result = 0; // definitely not local :-)
1529 }
1530 close(fd);
1531
1532 return result;
1533}
1534
Willy Tarreaubaaee002006-06-26 02:48:02 +02001535/* will try to encode the string <string> replacing all characters tagged in
1536 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1537 * prefixed by <escape>, and will store the result between <start> (included)
1538 * and <stop> (excluded), and will always terminate the string with a '\0'
1539 * before <stop>. The position of the '\0' is returned if the conversion
1540 * completes. If bytes are missing between <start> and <stop>, then the
1541 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1542 * cannot even be stored so we return <start> without writing the 0.
1543 * The input string must also be zero-terminated.
1544 */
1545const char hextab[16] = "0123456789ABCDEF";
1546char *encode_string(char *start, char *stop,
1547 const char escape, const fd_set *map,
1548 const char *string)
1549{
1550 if (start < stop) {
1551 stop--; /* reserve one byte for the final '\0' */
1552 while (start < stop && *string != '\0') {
1553 if (!FD_ISSET((unsigned char)(*string), map))
1554 *start++ = *string;
1555 else {
1556 if (start + 3 >= stop)
1557 break;
1558 *start++ = escape;
1559 *start++ = hextab[(*string >> 4) & 15];
1560 *start++ = hextab[*string & 15];
1561 }
1562 string++;
1563 }
1564 *start = '\0';
1565 }
1566 return start;
1567}
1568
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001569/*
1570 * Same behavior as encode_string() above, except that it encodes chunk
1571 * <chunk> instead of a string.
1572 */
1573char *encode_chunk(char *start, char *stop,
1574 const char escape, const fd_set *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001575 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001576{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001577 char *str = chunk->area;
1578 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001579
1580 if (start < stop) {
1581 stop--; /* reserve one byte for the final '\0' */
1582 while (start < stop && str < end) {
1583 if (!FD_ISSET((unsigned char)(*str), map))
1584 *start++ = *str;
1585 else {
1586 if (start + 3 >= stop)
1587 break;
1588 *start++ = escape;
1589 *start++ = hextab[(*str >> 4) & 15];
1590 *start++ = hextab[*str & 15];
1591 }
1592 str++;
1593 }
1594 *start = '\0';
1595 }
1596 return start;
1597}
1598
Dragan Dosen0edd1092016-02-12 13:23:02 +01001599/*
1600 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001601 * character. The input <string> must be zero-terminated. The result will
1602 * be stored between <start> (included) and <stop> (excluded). This
1603 * function will always try to terminate the resulting string with a '\0'
1604 * before <stop>, and will return its position if the conversion
1605 * completes.
1606 */
1607char *escape_string(char *start, char *stop,
1608 const char escape, const fd_set *map,
1609 const char *string)
1610{
1611 if (start < stop) {
1612 stop--; /* reserve one byte for the final '\0' */
1613 while (start < stop && *string != '\0') {
1614 if (!FD_ISSET((unsigned char)(*string), map))
1615 *start++ = *string;
1616 else {
1617 if (start + 2 >= stop)
1618 break;
1619 *start++ = escape;
1620 *start++ = *string;
1621 }
1622 string++;
1623 }
1624 *start = '\0';
1625 }
1626 return start;
1627}
1628
1629/*
1630 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001631 * character. <chunk> contains the input to be escaped. The result will be
1632 * stored between <start> (included) and <stop> (excluded). The function
1633 * will always try to terminate the resulting string with a '\0' before
1634 * <stop>, and will return its position if the conversion completes.
1635 */
1636char *escape_chunk(char *start, char *stop,
1637 const char escape, const fd_set *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001638 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001639{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001640 char *str = chunk->area;
1641 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001642
1643 if (start < stop) {
1644 stop--; /* reserve one byte for the final '\0' */
1645 while (start < stop && str < end) {
1646 if (!FD_ISSET((unsigned char)(*str), map))
1647 *start++ = *str;
1648 else {
1649 if (start + 2 >= stop)
1650 break;
1651 *start++ = escape;
1652 *start++ = *str;
1653 }
1654 str++;
1655 }
1656 *start = '\0';
1657 }
1658 return start;
1659}
1660
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001661/* Check a string for using it in a CSV output format. If the string contains
1662 * one of the following four char <">, <,>, CR or LF, the string is
1663 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1664 * <str> is the input string to be escaped. The function assumes that
1665 * the input string is null-terminated.
1666 *
1667 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001668 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001669 * format.
1670 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001671 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001672 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001673 * If <quote> is 1, the converter puts the quotes only if any reserved character
1674 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001675 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001676 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001677 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001678 * The function returns the converted string on its output. If an error
1679 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001680 * for using the function directly as printf() argument.
1681 *
1682 * If the output buffer is too short to contain the input string, the result
1683 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001684 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001685 * This function appends the encoding to the existing output chunk, and it
1686 * guarantees that it starts immediately at the first available character of
1687 * the chunk. Please use csv_enc() instead if you want to replace the output
1688 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001689 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001690const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001691{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001692 char *end = output->area + output->size;
1693 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001694 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001695
Willy Tarreaub631c292016-01-08 10:04:08 +01001696 if (quote == 1) {
1697 /* automatic quoting: first verify if we'll have to quote the string */
1698 if (!strpbrk(str, "\n\r,\""))
1699 quote = 0;
1700 }
1701
1702 if (quote)
1703 *ptr++ = '"';
1704
Willy Tarreau898529b2016-01-06 18:07:04 +01001705 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1706 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001707 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001708 ptr++;
1709 if (ptr >= end - 2) {
1710 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001711 break;
1712 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001713 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001714 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001715 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001716 str++;
1717 }
1718
Willy Tarreaub631c292016-01-08 10:04:08 +01001719 if (quote)
1720 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001721
Willy Tarreau898529b2016-01-06 18:07:04 +01001722 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001723 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001724 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001725}
1726
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001727/* Decode an URL-encoded string in-place. The resulting string might
1728 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001729 * aborted, the string is truncated before the issue and a negative value is
1730 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001731 */
1732int url_decode(char *string)
1733{
1734 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001735 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001736
1737 in = string;
1738 out = string;
1739 while (*in) {
1740 switch (*in) {
1741 case '+' :
1742 *out++ = ' ';
1743 break;
1744 case '%' :
1745 if (!ishex(in[1]) || !ishex(in[2]))
1746 goto end;
1747 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1748 in += 2;
1749 break;
1750 default:
1751 *out++ = *in;
1752 break;
1753 }
1754 in++;
1755 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001756 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001757 end:
1758 *out = 0;
1759 return ret;
1760}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001761
Willy Tarreau6911fa42007-03-04 18:06:08 +01001762unsigned int str2ui(const char *s)
1763{
1764 return __str2ui(s);
1765}
1766
1767unsigned int str2uic(const char *s)
1768{
1769 return __str2uic(s);
1770}
1771
1772unsigned int strl2ui(const char *s, int len)
1773{
1774 return __strl2ui(s, len);
1775}
1776
1777unsigned int strl2uic(const char *s, int len)
1778{
1779 return __strl2uic(s, len);
1780}
1781
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001782unsigned int read_uint(const char **s, const char *end)
1783{
1784 return __read_uint(s, end);
1785}
1786
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001787/* This function reads an unsigned integer from the string pointed to by <s> and
1788 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1789 * function automatically stops at <end>. If the number overflows, the 2^64-1
1790 * value is returned.
1791 */
1792unsigned long long int read_uint64(const char **s, const char *end)
1793{
1794 const char *ptr = *s;
1795 unsigned long long int i = 0, tmp;
1796 unsigned int j;
1797
1798 while (ptr < end) {
1799
1800 /* read next char */
1801 j = *ptr - '0';
1802 if (j > 9)
1803 goto read_uint64_end;
1804
1805 /* add char to the number and check overflow. */
1806 tmp = i * 10;
1807 if (tmp / 10 != i) {
1808 i = ULLONG_MAX;
1809 goto read_uint64_eat;
1810 }
1811 if (ULLONG_MAX - tmp < j) {
1812 i = ULLONG_MAX;
1813 goto read_uint64_eat;
1814 }
1815 i = tmp + j;
1816 ptr++;
1817 }
1818read_uint64_eat:
1819 /* eat each numeric char */
1820 while (ptr < end) {
1821 if ((unsigned int)(*ptr - '0') > 9)
1822 break;
1823 ptr++;
1824 }
1825read_uint64_end:
1826 *s = ptr;
1827 return i;
1828}
1829
1830/* This function reads an integer from the string pointed to by <s> and returns
1831 * it. The <s> pointer is adjusted to point to the first unread char. The function
1832 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1833 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1834 * returned.
1835 */
1836long long int read_int64(const char **s, const char *end)
1837{
1838 unsigned long long int i = 0;
1839 int neg = 0;
1840
1841 /* Look for minus char. */
1842 if (**s == '-') {
1843 neg = 1;
1844 (*s)++;
1845 }
1846 else if (**s == '+')
1847 (*s)++;
1848
1849 /* convert as positive number. */
1850 i = read_uint64(s, end);
1851
1852 if (neg) {
1853 if (i > 0x8000000000000000ULL)
1854 return LLONG_MIN;
1855 return -i;
1856 }
1857 if (i > 0x7fffffffffffffffULL)
1858 return LLONG_MAX;
1859 return i;
1860}
1861
Willy Tarreau6911fa42007-03-04 18:06:08 +01001862/* This one is 7 times faster than strtol() on athlon with checks.
1863 * It returns the value of the number composed of all valid digits read,
1864 * and can process negative numbers too.
1865 */
1866int strl2ic(const char *s, int len)
1867{
1868 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001869 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001870
1871 if (len > 0) {
1872 if (*s != '-') {
1873 /* positive number */
1874 while (len-- > 0) {
1875 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001876 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001877 if (j > 9)
1878 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001879 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001880 }
1881 } else {
1882 /* negative number */
1883 s++;
1884 while (--len > 0) {
1885 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001886 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001887 if (j > 9)
1888 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001889 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001890 }
1891 }
1892 }
1893 return i;
1894}
1895
1896
1897/* This function reads exactly <len> chars from <s> and converts them to a
1898 * signed integer which it stores into <ret>. It accurately detects any error
1899 * (truncated string, invalid chars, overflows). It is meant to be used in
1900 * applications designed for hostile environments. It returns zero when the
1901 * number has successfully been converted, non-zero otherwise. When an error
1902 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1903 * faster than strtol().
1904 */
1905int strl2irc(const char *s, int len, int *ret)
1906{
1907 int i = 0;
1908 int j;
1909
1910 if (!len)
1911 return 1;
1912
1913 if (*s != '-') {
1914 /* positive number */
1915 while (len-- > 0) {
1916 j = (*s++) - '0';
1917 if (j > 9) return 1; /* invalid char */
1918 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1919 i = i * 10;
1920 if (i + j < i) return 1; /* check for addition overflow */
1921 i = i + j;
1922 }
1923 } else {
1924 /* negative number */
1925 s++;
1926 while (--len > 0) {
1927 j = (*s++) - '0';
1928 if (j > 9) return 1; /* invalid char */
1929 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1930 i = i * 10;
1931 if (i - j > i) return 1; /* check for subtract overflow */
1932 i = i - j;
1933 }
1934 }
1935 *ret = i;
1936 return 0;
1937}
1938
1939
1940/* This function reads exactly <len> chars from <s> and converts them to a
1941 * signed integer which it stores into <ret>. It accurately detects any error
1942 * (truncated string, invalid chars, overflows). It is meant to be used in
1943 * applications designed for hostile environments. It returns zero when the
1944 * number has successfully been converted, non-zero otherwise. When an error
1945 * is returned, the <ret> value is left untouched. It is about 3 times slower
1946 * than str2irc().
1947 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001948
1949int strl2llrc(const char *s, int len, long long *ret)
1950{
1951 long long i = 0;
1952 int j;
1953
1954 if (!len)
1955 return 1;
1956
1957 if (*s != '-') {
1958 /* positive number */
1959 while (len-- > 0) {
1960 j = (*s++) - '0';
1961 if (j > 9) return 1; /* invalid char */
1962 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1963 i = i * 10LL;
1964 if (i + j < i) return 1; /* check for addition overflow */
1965 i = i + j;
1966 }
1967 } else {
1968 /* negative number */
1969 s++;
1970 while (--len > 0) {
1971 j = (*s++) - '0';
1972 if (j > 9) return 1; /* invalid char */
1973 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1974 i = i * 10LL;
1975 if (i - j > i) return 1; /* check for subtract overflow */
1976 i = i - j;
1977 }
1978 }
1979 *ret = i;
1980 return 0;
1981}
1982
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001983/* This function is used with pat_parse_dotted_ver(). It converts a string
1984 * composed by two number separated by a dot. Each part must contain in 16 bits
1985 * because internally they will be represented as a 32-bit quantity stored in
1986 * a 64-bit integer. It returns zero when the number has successfully been
1987 * converted, non-zero otherwise. When an error is returned, the <ret> value
1988 * is left untouched.
1989 *
1990 * "1.3" -> 0x0000000000010003
1991 * "65535.65535" -> 0x00000000ffffffff
1992 */
1993int strl2llrc_dotted(const char *text, int len, long long *ret)
1994{
1995 const char *end = &text[len];
1996 const char *p;
1997 long long major, minor;
1998
1999 /* Look for dot. */
2000 for (p = text; p < end; p++)
2001 if (*p == '.')
2002 break;
2003
2004 /* Convert major. */
2005 if (strl2llrc(text, p - text, &major) != 0)
2006 return 1;
2007
2008 /* Check major. */
2009 if (major >= 65536)
2010 return 1;
2011
2012 /* Convert minor. */
2013 minor = 0;
2014 if (p < end)
2015 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2016 return 1;
2017
2018 /* Check minor. */
2019 if (minor >= 65536)
2020 return 1;
2021
2022 /* Compose value. */
2023 *ret = (major << 16) | (minor & 0xffff);
2024 return 0;
2025}
2026
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002027/* This function parses a time value optionally followed by a unit suffix among
2028 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2029 * expected by the caller. The computation does its best to avoid overflows.
2030 * The value is returned in <ret> if everything is fine, and a NULL is returned
2031 * by the function. In case of error, a pointer to the error is returned and
2032 * <ret> is left untouched. Values are automatically rounded up when needed.
2033 */
2034const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2035{
2036 unsigned imult, idiv;
2037 unsigned omult, odiv;
2038 unsigned value;
2039
2040 omult = odiv = 1;
2041
2042 switch (unit_flags & TIME_UNIT_MASK) {
2043 case TIME_UNIT_US: omult = 1000000; break;
2044 case TIME_UNIT_MS: omult = 1000; break;
2045 case TIME_UNIT_S: break;
2046 case TIME_UNIT_MIN: odiv = 60; break;
2047 case TIME_UNIT_HOUR: odiv = 3600; break;
2048 case TIME_UNIT_DAY: odiv = 86400; break;
2049 default: break;
2050 }
2051
2052 value = 0;
2053
2054 while (1) {
2055 unsigned int j;
2056
2057 j = *text - '0';
2058 if (j > 9)
2059 break;
2060 text++;
2061 value *= 10;
2062 value += j;
2063 }
2064
2065 imult = idiv = 1;
2066 switch (*text) {
2067 case '\0': /* no unit = default unit */
2068 imult = omult = idiv = odiv = 1;
2069 break;
2070 case 's': /* second = unscaled unit */
2071 break;
2072 case 'u': /* microsecond : "us" */
2073 if (text[1] == 's') {
2074 idiv = 1000000;
2075 text++;
2076 }
2077 break;
2078 case 'm': /* millisecond : "ms" or minute: "m" */
2079 if (text[1] == 's') {
2080 idiv = 1000;
2081 text++;
2082 } else
2083 imult = 60;
2084 break;
2085 case 'h': /* hour : "h" */
2086 imult = 3600;
2087 break;
2088 case 'd': /* day : "d" */
2089 imult = 86400;
2090 break;
2091 default:
2092 return text;
2093 break;
2094 }
2095
2096 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2097 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2098 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2099 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2100
2101 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2102 *ret = value;
2103 return NULL;
2104}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002105
Emeric Brun39132b22010-01-04 14:57:24 +01002106/* this function converts the string starting at <text> to an unsigned int
2107 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002108 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002109 */
2110const char *parse_size_err(const char *text, unsigned *ret) {
2111 unsigned value = 0;
2112
2113 while (1) {
2114 unsigned int j;
2115
2116 j = *text - '0';
2117 if (j > 9)
2118 break;
2119 if (value > ~0U / 10)
2120 return text;
2121 value *= 10;
2122 if (value > (value + j))
2123 return text;
2124 value += j;
2125 text++;
2126 }
2127
2128 switch (*text) {
2129 case '\0':
2130 break;
2131 case 'K':
2132 case 'k':
2133 if (value > ~0U >> 10)
2134 return text;
2135 value = value << 10;
2136 break;
2137 case 'M':
2138 case 'm':
2139 if (value > ~0U >> 20)
2140 return text;
2141 value = value << 20;
2142 break;
2143 case 'G':
2144 case 'g':
2145 if (value > ~0U >> 30)
2146 return text;
2147 value = value << 30;
2148 break;
2149 default:
2150 return text;
2151 }
2152
Godbach58048a22015-01-28 17:36:16 +08002153 if (*text != '\0' && *++text != '\0')
2154 return text;
2155
Emeric Brun39132b22010-01-04 14:57:24 +01002156 *ret = value;
2157 return NULL;
2158}
2159
Willy Tarreau126d4062013-12-03 17:50:47 +01002160/*
2161 * Parse binary string written in hexadecimal (source) and store the decoded
2162 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2163 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002164 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002165 */
2166int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2167{
2168 int len;
2169 const char *p = source;
2170 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002171 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002172
2173 len = strlen(source);
2174 if (len % 2) {
2175 memprintf(err, "an even number of hex digit is expected");
2176 return 0;
2177 }
2178
2179 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002180
Willy Tarreau126d4062013-12-03 17:50:47 +01002181 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002182 *binstr = calloc(len, sizeof(char));
2183 if (!*binstr) {
2184 memprintf(err, "out of memory while loading string pattern");
2185 return 0;
2186 }
2187 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002188 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002189 else {
2190 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002191 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002192 len, *binstrlen);
2193 return 0;
2194 }
2195 alloc = 0;
2196 }
2197 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002198
2199 i = j = 0;
2200 while (j < len) {
2201 if (!ishex(p[i++]))
2202 goto bad_input;
2203 if (!ishex(p[i++]))
2204 goto bad_input;
2205 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2206 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002207 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002208
2209bad_input:
2210 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002211 if (alloc) {
2212 free(*binstr);
2213 *binstr = NULL;
2214 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002215 return 0;
2216}
2217
Willy Tarreau946ba592009-05-10 15:41:18 +02002218/* copies at most <n> characters from <src> and always terminates with '\0' */
2219char *my_strndup(const char *src, int n)
2220{
2221 int len = 0;
2222 char *ret;
2223
2224 while (len < n && src[len])
2225 len++;
2226
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002227 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002228 if (!ret)
2229 return ret;
2230 memcpy(ret, src, len);
2231 ret[len] = '\0';
2232 return ret;
2233}
2234
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002235/*
2236 * search needle in haystack
2237 * returns the pointer if found, returns NULL otherwise
2238 */
2239const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2240{
2241 const void *c = NULL;
2242 unsigned char f;
2243
2244 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2245 return NULL;
2246
2247 f = *(char *)needle;
2248 c = haystack;
2249 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2250 if ((haystacklen - (c - haystack)) < needlelen)
2251 return NULL;
2252
2253 if (memcmp(c, needle, needlelen) == 0)
2254 return c;
2255 ++c;
2256 }
2257 return NULL;
2258}
2259
Willy Tarreau482b00d2009-10-04 22:48:42 +02002260/* This function returns the first unused key greater than or equal to <key> in
2261 * ID tree <root>. Zero is returned if no place is found.
2262 */
2263unsigned int get_next_id(struct eb_root *root, unsigned int key)
2264{
2265 struct eb32_node *used;
2266
2267 do {
2268 used = eb32_lookup_ge(root, key);
2269 if (!used || used->key > key)
2270 return key; /* key is available */
2271 key++;
2272 } while (key);
2273 return key;
2274}
2275
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002276/* dump the full tree to <file> in DOT format for debugging purposes. Will
2277 * optionally highlight node <subj> if found, depending on operation <op> :
2278 * 0 : nothing
2279 * >0 : insertion, node/leaf are surrounded in red
2280 * <0 : removal, node/leaf are dashed with no background
2281 * Will optionally add "desc" as a label on the graph if set and non-null.
2282 */
2283void 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 +01002284{
2285 struct eb32sc_node *node;
2286 unsigned long scope = -1;
2287
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002288 fprintf(file, "digraph ebtree {\n");
2289
2290 if (desc && *desc) {
2291 fprintf(file,
2292 " fontname=\"fixed\";\n"
2293 " fontsize=8;\n"
2294 " label=\"%s\";\n", desc);
2295 }
2296
Willy Tarreaued3cda02017-11-15 15:04:05 +01002297 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002298 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2299 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002300 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2301 );
2302
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002303 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002304 (long)eb_root_to_node(root),
2305 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002306 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2307
2308 node = eb32sc_first(root, scope);
2309 while (node) {
2310 if (node->node.node_p) {
2311 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002312 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2313 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2314 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002315
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002316 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002317 (long)node,
2318 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002319 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002320
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002321 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002322 (long)node,
2323 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002324 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2325
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002326 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002327 (long)node,
2328 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002329 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2330 }
2331
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002332 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2333 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2334 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002335
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002336 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002337 (long)node,
2338 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002339 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002340 node = eb32sc_next(node, scope);
2341 }
2342 fprintf(file, "}\n");
2343}
2344
Willy Tarreau348238b2010-01-18 15:05:57 +01002345/* This function compares a sample word possibly followed by blanks to another
2346 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2347 * otherwise zero. This intends to be used when checking HTTP headers for some
2348 * values. Note that it validates a word followed only by blanks but does not
2349 * validate a word followed by blanks then other chars.
2350 */
2351int word_match(const char *sample, int slen, const char *word, int wlen)
2352{
2353 if (slen < wlen)
2354 return 0;
2355
2356 while (wlen) {
2357 char c = *sample ^ *word;
2358 if (c && c != ('A' ^ 'a'))
2359 return 0;
2360 sample++;
2361 word++;
2362 slen--;
2363 wlen--;
2364 }
2365
2366 while (slen) {
2367 if (*sample != ' ' && *sample != '\t')
2368 return 0;
2369 sample++;
2370 slen--;
2371 }
2372 return 1;
2373}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002374
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002375/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2376 * is particularly fast because it avoids expensive operations such as
2377 * multiplies, which are optimized away at the end. It requires a properly
2378 * formated address though (3 points).
2379 */
2380unsigned int inetaddr_host(const char *text)
2381{
2382 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2383 register unsigned int dig100, dig10, dig1;
2384 int s;
2385 const char *p, *d;
2386
2387 dig1 = dig10 = dig100 = ascii_zero;
2388 s = 24;
2389
2390 p = text;
2391 while (1) {
2392 if (((unsigned)(*p - '0')) <= 9) {
2393 p++;
2394 continue;
2395 }
2396
2397 /* here, we have a complete byte between <text> and <p> (exclusive) */
2398 if (p == text)
2399 goto end;
2400
2401 d = p - 1;
2402 dig1 |= (unsigned int)(*d << s);
2403 if (d == text)
2404 goto end;
2405
2406 d--;
2407 dig10 |= (unsigned int)(*d << s);
2408 if (d == text)
2409 goto end;
2410
2411 d--;
2412 dig100 |= (unsigned int)(*d << s);
2413 end:
2414 if (!s || *p != '.')
2415 break;
2416
2417 s -= 8;
2418 text = ++p;
2419 }
2420
2421 dig100 -= ascii_zero;
2422 dig10 -= ascii_zero;
2423 dig1 -= ascii_zero;
2424 return ((dig100 * 10) + dig10) * 10 + dig1;
2425}
2426
2427/*
2428 * Idem except the first unparsed character has to be passed in <stop>.
2429 */
2430unsigned int inetaddr_host_lim(const char *text, const char *stop)
2431{
2432 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2433 register unsigned int dig100, dig10, dig1;
2434 int s;
2435 const char *p, *d;
2436
2437 dig1 = dig10 = dig100 = ascii_zero;
2438 s = 24;
2439
2440 p = text;
2441 while (1) {
2442 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2443 p++;
2444 continue;
2445 }
2446
2447 /* here, we have a complete byte between <text> and <p> (exclusive) */
2448 if (p == text)
2449 goto end;
2450
2451 d = p - 1;
2452 dig1 |= (unsigned int)(*d << s);
2453 if (d == text)
2454 goto end;
2455
2456 d--;
2457 dig10 |= (unsigned int)(*d << s);
2458 if (d == text)
2459 goto end;
2460
2461 d--;
2462 dig100 |= (unsigned int)(*d << s);
2463 end:
2464 if (!s || p == stop || *p != '.')
2465 break;
2466
2467 s -= 8;
2468 text = ++p;
2469 }
2470
2471 dig100 -= ascii_zero;
2472 dig10 -= ascii_zero;
2473 dig1 -= ascii_zero;
2474 return ((dig100 * 10) + dig10) * 10 + dig1;
2475}
2476
2477/*
2478 * Idem except the pointer to first unparsed byte is returned into <ret> which
2479 * must not be NULL.
2480 */
Willy Tarreau74172752010-10-15 23:21:42 +02002481unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002482{
2483 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2484 register unsigned int dig100, dig10, dig1;
2485 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002486 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002487
2488 dig1 = dig10 = dig100 = ascii_zero;
2489 s = 24;
2490
2491 p = text;
2492 while (1) {
2493 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2494 p++;
2495 continue;
2496 }
2497
2498 /* here, we have a complete byte between <text> and <p> (exclusive) */
2499 if (p == text)
2500 goto end;
2501
2502 d = p - 1;
2503 dig1 |= (unsigned int)(*d << s);
2504 if (d == text)
2505 goto end;
2506
2507 d--;
2508 dig10 |= (unsigned int)(*d << s);
2509 if (d == text)
2510 goto end;
2511
2512 d--;
2513 dig100 |= (unsigned int)(*d << s);
2514 end:
2515 if (!s || p == stop || *p != '.')
2516 break;
2517
2518 s -= 8;
2519 text = ++p;
2520 }
2521
2522 *ret = p;
2523 dig100 -= ascii_zero;
2524 dig10 -= ascii_zero;
2525 dig1 -= ascii_zero;
2526 return ((dig100 * 10) + dig10) * 10 + dig1;
2527}
2528
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002529/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2530 * or the number of chars read in case of success. Maybe this could be replaced
2531 * by one of the functions above. Also, apparently this function does not support
2532 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002533 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002534 */
2535int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2536{
2537 const char *addr;
2538 int saw_digit, octets, ch;
2539 u_char tmp[4], *tp;
2540 const char *cp = buf;
2541
2542 saw_digit = 0;
2543 octets = 0;
2544 *(tp = tmp) = 0;
2545
2546 for (addr = buf; addr - buf < len; addr++) {
2547 unsigned char digit = (ch = *addr) - '0';
2548
2549 if (digit > 9 && ch != '.')
2550 break;
2551
2552 if (digit <= 9) {
2553 u_int new = *tp * 10 + digit;
2554
2555 if (new > 255)
2556 return 0;
2557
2558 *tp = new;
2559
2560 if (!saw_digit) {
2561 if (++octets > 4)
2562 return 0;
2563 saw_digit = 1;
2564 }
2565 } else if (ch == '.' && saw_digit) {
2566 if (octets == 4)
2567 return 0;
2568
2569 *++tp = 0;
2570 saw_digit = 0;
2571 } else
2572 return 0;
2573 }
2574
2575 if (octets < 4)
2576 return 0;
2577
2578 memcpy(&dst->s_addr, tmp, 4);
2579 return addr - cp;
2580}
2581
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002582/* This function converts the string in <buf> of the len <len> to
2583 * struct in6_addr <dst> which must be allocated by the caller.
2584 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002585 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002586 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002587int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2588{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002589 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002590 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002591
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002592 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002593 return 0;
2594
2595 memcpy(null_term_ip6, buf, len);
2596 null_term_ip6[len] = '\0';
2597
Willy Tarreau075415a2013-12-12 11:29:39 +01002598 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002599 return 0;
2600
Willy Tarreau075415a2013-12-12 11:29:39 +01002601 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002602 return 1;
2603}
2604
Willy Tarreauacf95772010-06-14 19:09:21 +02002605/* To be used to quote config arg positions. Returns the short string at <ptr>
2606 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2607 * if ptr is NULL or empty. The string is locally allocated.
2608 */
2609const char *quote_arg(const char *ptr)
2610{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002611 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002612 int i;
2613
2614 if (!ptr || !*ptr)
2615 return "end of line";
2616 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002617 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002618 val[i] = *ptr++;
2619 val[i++] = '\'';
2620 val[i] = '\0';
2621 return val;
2622}
2623
Willy Tarreau5b180202010-07-18 10:40:48 +02002624/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2625int get_std_op(const char *str)
2626{
2627 int ret = -1;
2628
2629 if (*str == 'e' && str[1] == 'q')
2630 ret = STD_OP_EQ;
2631 else if (*str == 'n' && str[1] == 'e')
2632 ret = STD_OP_NE;
2633 else if (*str == 'l') {
2634 if (str[1] == 'e') ret = STD_OP_LE;
2635 else if (str[1] == 't') ret = STD_OP_LT;
2636 }
2637 else if (*str == 'g') {
2638 if (str[1] == 'e') ret = STD_OP_GE;
2639 else if (str[1] == 't') ret = STD_OP_GT;
2640 }
2641
2642 if (ret == -1 || str[2] != '\0')
2643 return -1;
2644 return ret;
2645}
2646
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002647/* hash a 32-bit integer to another 32-bit integer */
2648unsigned int full_hash(unsigned int a)
2649{
2650 return __full_hash(a);
2651}
2652
Willy Tarreauf3241112019-02-26 09:56:22 +01002653/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2654 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2655 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2656 * a popcount variant and is described here :
2657 * https://graphics.stanford.edu/~seander/bithacks.html
2658 */
2659unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2660{
2661 unsigned long a, b, c, d;
2662 unsigned int s;
2663 unsigned int t;
2664
2665 a = m - ((m >> 1) & ~0UL/3);
2666 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2667 c = (b + (b >> 4)) & ~0UL/0x11;
2668 d = (c + (c >> 8)) & ~0UL/0x101;
2669
2670 r++; // make r be 1..64
2671
2672 t = 0;
2673 s = LONGBITS;
2674 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002675 unsigned long d2 = (d >> 16) >> 16;
2676 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002677 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2678 }
2679
2680 t = (d >> (s - 16)) & 0xff;
2681 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2682 t = (c >> (s - 8)) & 0xf;
2683 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2684 t = (b >> (s - 4)) & 0x7;
2685 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2686 t = (a >> (s - 2)) & 0x3;
2687 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2688 t = (m >> (s - 1)) & 0x1;
2689 s -= ((t - r) & 256) >> 8;
2690
2691 return s - 1;
2692}
2693
2694/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2695 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2696 * using mask_prep_rank_map() below.
2697 */
2698unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2699 unsigned long a, unsigned long b,
2700 unsigned long c, unsigned long d)
2701{
2702 unsigned int s;
2703 unsigned int t;
2704
2705 r++; // make r be 1..64
2706
2707 t = 0;
2708 s = LONGBITS;
2709 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002710 unsigned long d2 = (d >> 16) >> 16;
2711 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002712 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2713 }
2714
2715 t = (d >> (s - 16)) & 0xff;
2716 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2717 t = (c >> (s - 8)) & 0xf;
2718 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2719 t = (b >> (s - 4)) & 0x7;
2720 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2721 t = (a >> (s - 2)) & 0x3;
2722 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2723 t = (m >> (s - 1)) & 0x1;
2724 s -= ((t - r) & 256) >> 8;
2725
2726 return s - 1;
2727}
2728
2729/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2730 * above.
2731 */
2732void mask_prep_rank_map(unsigned long m,
2733 unsigned long *a, unsigned long *b,
2734 unsigned long *c, unsigned long *d)
2735{
2736 *a = m - ((m >> 1) & ~0UL/3);
2737 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2738 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2739 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2740}
2741
David du Colombier4f92d322011-03-24 11:09:31 +01002742/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002743 * otherwise zero. Note that <addr> may not necessarily be aligned
2744 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002745 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002746int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002747{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002748 struct in_addr addr_copy;
2749
2750 memcpy(&addr_copy, addr, sizeof(addr_copy));
2751 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002752}
2753
2754/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002755 * otherwise zero. Note that <addr> may not necessarily be aligned
2756 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002757 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002758int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002759{
2760 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002761 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002762
Willy Tarreaueec1d382016-07-13 11:59:39 +02002763 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002764 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002765 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002766 (((int *)net)[i] & ((int *)mask)[i]))
2767 return 0;
2768 return 1;
2769}
2770
2771/* RFC 4291 prefix */
2772const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2773 0x00, 0x00, 0x00, 0x00,
2774 0x00, 0x00, 0xFF, 0xFF };
2775
Joseph Herlant32b83272018-11-15 11:58:28 -08002776/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002777 * Input and output may overlap.
2778 */
David du Colombier4f92d322011-03-24 11:09:31 +01002779void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2780{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002781 struct in_addr tmp_addr;
2782
2783 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002784 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002785 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002786}
2787
Joseph Herlant32b83272018-11-15 11:58:28 -08002788/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002789 * Return true if conversion is possible and false otherwise.
2790 */
2791int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2792{
2793 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2794 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2795 sizeof(struct in_addr));
2796 return 1;
2797 }
2798
2799 return 0;
2800}
2801
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002802/* compare two struct sockaddr_storage and return:
2803 * 0 (true) if the addr is the same in both
2804 * 1 (false) if the addr is not the same in both
2805 * -1 (unable) if one of the addr is not AF_INET*
2806 */
2807int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2808{
2809 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2810 return -1;
2811
2812 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2813 return -1;
2814
2815 if (ss1->ss_family != ss2->ss_family)
2816 return 1;
2817
2818 switch (ss1->ss_family) {
2819 case AF_INET:
2820 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2821 &((struct sockaddr_in *)ss2)->sin_addr,
2822 sizeof(struct in_addr)) != 0;
2823 case AF_INET6:
2824 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2825 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2826 sizeof(struct in6_addr)) != 0;
2827 }
2828
2829 return 1;
2830}
2831
Baptiste Assmann08396c82016-01-31 00:27:17 +01002832/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002833 * The caller must allocate and clear <dest> before calling.
2834 * The source must be in either AF_INET or AF_INET6 family, or the destination
2835 * address will be undefined. If the destination address used to hold a port,
2836 * it is preserved, so that this function can be used to switch to another
2837 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002838 */
2839struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2840{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002841 int prev_port;
2842
2843 prev_port = get_net_port(dest);
2844 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002845 dest->ss_family = source->ss_family;
2846
2847 /* copy new addr and apply it */
2848 switch (source->ss_family) {
2849 case AF_INET:
2850 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002851 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002852 break;
2853 case AF_INET6:
2854 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 +01002855 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002856 break;
2857 }
2858
2859 return dest;
2860}
2861
William Lallemand421f5b52012-02-06 18:15:57 +01002862char *human_time(int t, short hz_div) {
2863 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2864 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002865 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002866 int cnt=2; // print two numbers
2867
2868 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002869 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002870 return rv;
2871 }
2872
2873 if (unlikely(hz_div > 1))
2874 t /= hz_div;
2875
2876 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002877 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002878 cnt--;
2879 }
2880
2881 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002882 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002883 cnt--;
2884 }
2885
2886 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002887 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002888 cnt--;
2889 }
2890
2891 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002892 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002893
2894 return rv;
2895}
2896
2897const char *monthname[12] = {
2898 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2899 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2900};
2901
2902/* date2str_log: write a date in the format :
2903 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2904 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2905 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2906 *
2907 * without using sprintf. return a pointer to the last char written (\0) or
2908 * NULL if there isn't enough space.
2909 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002910char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002911{
2912
2913 if (size < 25) /* the size is fixed: 24 chars + \0 */
2914 return NULL;
2915
2916 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002917 if (!dst)
2918 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002919 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002920
William Lallemand421f5b52012-02-06 18:15:57 +01002921 memcpy(dst, monthname[tm->tm_mon], 3); // month
2922 dst += 3;
2923 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002924
William Lallemand421f5b52012-02-06 18:15:57 +01002925 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002926 if (!dst)
2927 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002928 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002929
William Lallemand421f5b52012-02-06 18:15:57 +01002930 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002931 if (!dst)
2932 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002933 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002934
William Lallemand421f5b52012-02-06 18:15:57 +01002935 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002936 if (!dst)
2937 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002938 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002939
William Lallemand421f5b52012-02-06 18:15:57 +01002940 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002941 if (!dst)
2942 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002943 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002944
William Lallemand421f5b52012-02-06 18:15:57 +01002945 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002946 if (!dst)
2947 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002948 dst += 3; // only the 3 first digits
2949 *dst = '\0';
2950
2951 return dst;
2952}
2953
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002954/* Base year used to compute leap years */
2955#define TM_YEAR_BASE 1900
2956
2957/* Return the difference in seconds between two times (leap seconds are ignored).
2958 * Retrieved from glibc 2.18 source code.
2959 */
2960static int my_tm_diff(const struct tm *a, const struct tm *b)
2961{
2962 /* Compute intervening leap days correctly even if year is negative.
2963 * Take care to avoid int overflow in leap day calculations,
2964 * but it's OK to assume that A and B are close to each other.
2965 */
2966 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2967 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2968 int a100 = a4 / 25 - (a4 % 25 < 0);
2969 int b100 = b4 / 25 - (b4 % 25 < 0);
2970 int a400 = a100 >> 2;
2971 int b400 = b100 >> 2;
2972 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2973 int years = a->tm_year - b->tm_year;
2974 int days = (365 * years + intervening_leap_days
2975 + (a->tm_yday - b->tm_yday));
2976 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2977 + (a->tm_min - b->tm_min))
2978 + (a->tm_sec - b->tm_sec));
2979}
2980
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002981/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002982 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002983 * The string returned has the same format as returned by strftime(... "%z", tm).
2984 * Offsets are kept in an internal cache for better performances.
2985 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002986const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002987{
2988 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002989 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002990
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002991 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002992 struct tm tm_gmt;
2993 int diff;
2994 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002995
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002996 /* Pretend DST not active if its status is unknown */
2997 if (isdst < 0)
2998 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002999
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003000 /* Fetch the offset and initialize it if needed */
3001 gmt_offset = gmt_offsets[isdst & 0x01];
3002 if (unlikely(!*gmt_offset)) {
3003 get_gmtime(t, &tm_gmt);
3004 diff = my_tm_diff(tm, &tm_gmt);
3005 if (diff < 0) {
3006 diff = -diff;
3007 *gmt_offset = '-';
3008 } else {
3009 *gmt_offset = '+';
3010 }
3011 diff /= 60; /* Convert to minutes */
3012 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3013 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003014
3015 return gmt_offset;
3016}
3017
William Lallemand421f5b52012-02-06 18:15:57 +01003018/* gmt2str_log: write a date in the format :
3019 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3020 * return a pointer to the last char written (\0) or
3021 * NULL if there isn't enough space.
3022 */
3023char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3024{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003025 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003026 return NULL;
3027
3028 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003029 if (!dst)
3030 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003031 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003032
William Lallemand421f5b52012-02-06 18:15:57 +01003033 memcpy(dst, monthname[tm->tm_mon], 3); // month
3034 dst += 3;
3035 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003036
William Lallemand421f5b52012-02-06 18:15:57 +01003037 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003038 if (!dst)
3039 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003040 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003041
William Lallemand421f5b52012-02-06 18:15:57 +01003042 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003043 if (!dst)
3044 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003045 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003046
William Lallemand421f5b52012-02-06 18:15:57 +01003047 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003048 if (!dst)
3049 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003050 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003051
William Lallemand421f5b52012-02-06 18:15:57 +01003052 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003053 if (!dst)
3054 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003055 *dst++ = ' ';
3056 *dst++ = '+';
3057 *dst++ = '0';
3058 *dst++ = '0';
3059 *dst++ = '0';
3060 *dst++ = '0';
3061 *dst = '\0';
3062
3063 return dst;
3064}
3065
Yuxans Yao4e25b012012-10-19 10:36:09 +08003066/* localdate2str_log: write a date in the format :
3067 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003068 * Both t and tm must represent the same time.
3069 * return a pointer to the last char written (\0) or
3070 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003071 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003072char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003073{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003074 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003075 if (size < 27) /* the size is fixed: 26 chars + \0 */
3076 return NULL;
3077
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003078 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003079
Yuxans Yao4e25b012012-10-19 10:36:09 +08003080 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003081 if (!dst)
3082 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003083 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003084
Yuxans Yao4e25b012012-10-19 10:36:09 +08003085 memcpy(dst, monthname[tm->tm_mon], 3); // month
3086 dst += 3;
3087 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003088
Yuxans Yao4e25b012012-10-19 10:36:09 +08003089 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003090 if (!dst)
3091 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003092 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003093
Yuxans Yao4e25b012012-10-19 10:36:09 +08003094 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003095 if (!dst)
3096 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003097 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003098
Yuxans Yao4e25b012012-10-19 10:36:09 +08003099 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003100 if (!dst)
3101 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003102 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003103
Yuxans Yao4e25b012012-10-19 10:36:09 +08003104 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003105 if (!dst)
3106 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003107 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003108
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003109 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003110 dst += 5;
3111 *dst = '\0';
3112
3113 return dst;
3114}
3115
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003116/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3117 * It is meant as a portable replacement for timegm() for use with valid inputs.
3118 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3119 */
3120time_t my_timegm(const struct tm *tm)
3121{
3122 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3123 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3124 * sum of the extra N days for elapsed months. The sum of all these N
3125 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3126 * in a 5-bit word. This means that with 60 bits we can represent a
3127 * matrix of all these values at once, which is fast and efficient to
3128 * access. The extra February day for leap years is not counted here.
3129 *
3130 * Jan : none = 0 (0)
3131 * Feb : Jan = 3 (3)
3132 * Mar : Jan..Feb = 3 (3 + 0)
3133 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3134 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3135 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3136 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3137 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3138 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3139 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3140 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3141 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3142 */
3143 uint64_t extra =
3144 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3145 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3146 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3147 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3148
3149 unsigned int y = tm->tm_year + 1900;
3150 unsigned int m = tm->tm_mon;
3151 unsigned long days = 0;
3152
3153 /* days since 1/1/1970 for full years */
3154 days += days_since_zero(y) - days_since_zero(1970);
3155
3156 /* days for full months in the current year */
3157 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3158
3159 /* count + 1 after March for leap years. A leap year is a year multiple
3160 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3161 * is leap, 1900 isn't, 1904 is.
3162 */
3163 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3164 days++;
3165
3166 days += tm->tm_mday - 1;
3167 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3168}
3169
Thierry Fournier93127942016-01-20 18:49:45 +01003170/* This function check a char. It returns true and updates
3171 * <date> and <len> pointer to the new position if the
3172 * character is found.
3173 */
3174static inline int parse_expect_char(const char **date, int *len, char c)
3175{
3176 if (*len < 1 || **date != c)
3177 return 0;
3178 (*len)--;
3179 (*date)++;
3180 return 1;
3181}
3182
3183/* This function expects a string <str> of len <l>. It return true and updates.
3184 * <date> and <len> if the string matches, otherwise, it returns false.
3185 */
3186static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3187{
3188 if (*len < l || strncmp(*date, str, l) != 0)
3189 return 0;
3190 (*len) -= l;
3191 (*date) += l;
3192 return 1;
3193}
3194
3195/* This macro converts 3 chars name in integer. */
3196#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3197
3198/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3199 * / %x54.75.65 ; "Tue", case-sensitive
3200 * / %x57.65.64 ; "Wed", case-sensitive
3201 * / %x54.68.75 ; "Thu", case-sensitive
3202 * / %x46.72.69 ; "Fri", case-sensitive
3203 * / %x53.61.74 ; "Sat", case-sensitive
3204 * / %x53.75.6E ; "Sun", case-sensitive
3205 *
3206 * This array must be alphabetically sorted
3207 */
3208static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3209{
3210 if (*len < 3)
3211 return 0;
3212 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3213 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3214 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3215 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3216 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3217 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3218 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3219 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3220 default: return 0;
3221 }
3222 *len -= 3;
3223 *date += 3;
3224 return 1;
3225}
3226
3227/* month = %x4A.61.6E ; "Jan", case-sensitive
3228 * / %x46.65.62 ; "Feb", case-sensitive
3229 * / %x4D.61.72 ; "Mar", case-sensitive
3230 * / %x41.70.72 ; "Apr", case-sensitive
3231 * / %x4D.61.79 ; "May", case-sensitive
3232 * / %x4A.75.6E ; "Jun", case-sensitive
3233 * / %x4A.75.6C ; "Jul", case-sensitive
3234 * / %x41.75.67 ; "Aug", case-sensitive
3235 * / %x53.65.70 ; "Sep", case-sensitive
3236 * / %x4F.63.74 ; "Oct", case-sensitive
3237 * / %x4E.6F.76 ; "Nov", case-sensitive
3238 * / %x44.65.63 ; "Dec", case-sensitive
3239 *
3240 * This array must be alphabetically sorted
3241 */
3242static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3243{
3244 if (*len < 3)
3245 return 0;
3246 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3247 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3248 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3249 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3250 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3251 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3252 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3253 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3254 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3255 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3256 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3257 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3258 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3259 default: return 0;
3260 }
3261 *len -= 3;
3262 *date += 3;
3263 return 1;
3264}
3265
3266/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3267 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3268 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3269 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3270 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3271 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3272 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3273 *
3274 * This array must be alphabetically sorted
3275 */
3276static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3277{
3278 if (*len < 6) /* Minimum length. */
3279 return 0;
3280 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3281 case STR2I3('M','o','n'):
3282 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3283 tm->tm_wday = 1;
3284 return 1;
3285 case STR2I3('T','u','e'):
3286 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3287 tm->tm_wday = 2;
3288 return 1;
3289 case STR2I3('W','e','d'):
3290 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3291 tm->tm_wday = 3;
3292 return 1;
3293 case STR2I3('T','h','u'):
3294 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3295 tm->tm_wday = 4;
3296 return 1;
3297 case STR2I3('F','r','i'):
3298 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3299 tm->tm_wday = 5;
3300 return 1;
3301 case STR2I3('S','a','t'):
3302 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3303 tm->tm_wday = 6;
3304 return 1;
3305 case STR2I3('S','u','n'):
3306 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3307 tm->tm_wday = 7;
3308 return 1;
3309 }
3310 return 0;
3311}
3312
3313/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3314static inline int parse_digit(const char **date, int *len, int *digit)
3315{
3316 if (*len < 1 || **date < '0' || **date > '9')
3317 return 0;
3318 *digit = (**date - '0');
3319 (*date)++;
3320 (*len)--;
3321 return 1;
3322}
3323
3324/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3325static inline int parse_2digit(const char **date, int *len, int *digit)
3326{
3327 int value;
3328
3329 RET0_UNLESS(parse_digit(date, len, &value));
3330 (*digit) = value * 10;
3331 RET0_UNLESS(parse_digit(date, len, &value));
3332 (*digit) += value;
3333
3334 return 1;
3335}
3336
3337/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3338static inline int parse_4digit(const char **date, int *len, int *digit)
3339{
3340 int value;
3341
3342 RET0_UNLESS(parse_digit(date, len, &value));
3343 (*digit) = value * 1000;
3344
3345 RET0_UNLESS(parse_digit(date, len, &value));
3346 (*digit) += value * 100;
3347
3348 RET0_UNLESS(parse_digit(date, len, &value));
3349 (*digit) += value * 10;
3350
3351 RET0_UNLESS(parse_digit(date, len, &value));
3352 (*digit) += value;
3353
3354 return 1;
3355}
3356
3357/* time-of-day = hour ":" minute ":" second
3358 * ; 00:00:00 - 23:59:60 (leap second)
3359 *
3360 * hour = 2DIGIT
3361 * minute = 2DIGIT
3362 * second = 2DIGIT
3363 */
3364static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3365{
3366 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3367 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3368 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3369 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3370 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3371 return 1;
3372}
3373
3374/* From RFC7231
3375 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3376 *
3377 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3378 * ; fixed length/zone/capitalization subset of the format
3379 * ; see Section 3.3 of [RFC5322]
3380 *
3381 *
3382 * date1 = day SP month SP year
3383 * ; e.g., 02 Jun 1982
3384 *
3385 * day = 2DIGIT
3386 * year = 4DIGIT
3387 *
3388 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3389 *
3390 * time-of-day = hour ":" minute ":" second
3391 * ; 00:00:00 - 23:59:60 (leap second)
3392 *
3393 * hour = 2DIGIT
3394 * minute = 2DIGIT
3395 * second = 2DIGIT
3396 *
3397 * DIGIT = decimal 0-9
3398 */
3399int parse_imf_date(const char *date, int len, struct tm *tm)
3400{
David Carlier327298c2016-11-20 10:42:38 +00003401 /* tm_gmtoff, if present, ought to be zero'ed */
3402 memset(tm, 0, sizeof(*tm));
3403
Thierry Fournier93127942016-01-20 18:49:45 +01003404 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3405 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3406 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3407 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3408 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3409 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3410 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3411 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3412 tm->tm_year -= 1900;
3413 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3414 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3415 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3416 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3417 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003418 return 1;
3419}
3420
3421/* From RFC7231
3422 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3423 *
3424 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3425 * date2 = day "-" month "-" 2DIGIT
3426 * ; e.g., 02-Jun-82
3427 *
3428 * day = 2DIGIT
3429 */
3430int parse_rfc850_date(const char *date, int len, struct tm *tm)
3431{
3432 int year;
3433
David Carlier327298c2016-11-20 10:42:38 +00003434 /* tm_gmtoff, if present, ought to be zero'ed */
3435 memset(tm, 0, sizeof(*tm));
3436
Thierry Fournier93127942016-01-20 18:49:45 +01003437 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3438 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3439 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3440 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3441 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3442 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3443 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3444
3445 /* year = 2DIGIT
3446 *
3447 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3448 * two-digit year, MUST interpret a timestamp that appears to be more
3449 * than 50 years in the future as representing the most recent year in
3450 * the past that had the same last two digits.
3451 */
3452 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3453
3454 /* expect SP */
3455 if (!parse_expect_char(&date, &len, ' ')) {
3456 /* Maybe we have the date with 4 digits. */
3457 RET0_UNLESS(parse_2digit(&date, &len, &year));
3458 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3459 /* expect SP */
3460 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3461 } else {
3462 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3463 * tm_year is the number of year since 1900, so for +1900, we
3464 * do nothing, and for +2000, we add 100.
3465 */
3466 if (tm->tm_year <= 60)
3467 tm->tm_year += 100;
3468 }
3469
3470 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3471 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3472 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3473 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003474
3475 return 1;
3476}
3477
3478/* From RFC7231
3479 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3480 *
3481 * asctime-date = day-name SP date3 SP time-of-day SP year
3482 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3483 * ; e.g., Jun 2
3484 *
3485 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3486 * whitespace in an HTTP-date beyond that specifically included as SP in
3487 * the grammar.
3488 */
3489int parse_asctime_date(const char *date, int len, struct tm *tm)
3490{
David Carlier327298c2016-11-20 10:42:38 +00003491 /* tm_gmtoff, if present, ought to be zero'ed */
3492 memset(tm, 0, sizeof(*tm));
3493
Thierry Fournier93127942016-01-20 18:49:45 +01003494 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3495 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3496 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3497 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3498
3499 /* expect SP and 1DIGIT or 2DIGIT */
3500 if (parse_expect_char(&date, &len, ' '))
3501 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3502 else
3503 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3504
3505 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3506 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3507 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3508 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3509 tm->tm_year -= 1900;
3510 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003511 return 1;
3512}
3513
3514/* From RFC7231
3515 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3516 *
3517 * HTTP-date = IMF-fixdate / obs-date
3518 * obs-date = rfc850-date / asctime-date
3519 *
3520 * parses an HTTP date in the RFC format and is accepted
3521 * alternatives. <date> is the strinf containing the date,
3522 * len is the len of the string. <tm> is filled with the
3523 * parsed time. We must considers this time as GMT.
3524 */
3525int parse_http_date(const char *date, int len, struct tm *tm)
3526{
3527 if (parse_imf_date(date, len, tm))
3528 return 1;
3529
3530 if (parse_rfc850_date(date, len, tm))
3531 return 1;
3532
3533 if (parse_asctime_date(date, len, tm))
3534 return 1;
3535
3536 return 0;
3537}
3538
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003539/* Dynamically allocates a string of the proper length to hold the formatted
3540 * output. NULL is returned on error. The caller is responsible for freeing the
3541 * memory area using free(). The resulting string is returned in <out> if the
3542 * pointer is not NULL. A previous version of <out> might be used to build the
3543 * new string, and it will be freed before returning if it is not NULL, which
3544 * makes it possible to build complex strings from iterative calls without
3545 * having to care about freeing intermediate values, as in the example below :
3546 *
3547 * memprintf(&err, "invalid argument: '%s'", arg);
3548 * ...
3549 * memprintf(&err, "parser said : <%s>\n", *err);
3550 * ...
3551 * free(*err);
3552 *
3553 * This means that <err> must be initialized to NULL before first invocation.
3554 * The return value also holds the allocated string, which eases error checking
3555 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003556 * passed instead and it will be ignored. The returned message will then also
3557 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003558 *
3559 * It is also convenient to use it without any free except the last one :
3560 * err = NULL;
3561 * if (!fct1(err)) report(*err);
3562 * if (!fct2(err)) report(*err);
3563 * if (!fct3(err)) report(*err);
3564 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003565 *
3566 * memprintf relies on memvprintf. This last version can be called from any
3567 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003568 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003569char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003570{
3571 va_list args;
3572 char *ret = NULL;
3573 int allocated = 0;
3574 int needed = 0;
3575
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003576 if (!out)
3577 return NULL;
3578
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003579 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003580 char buf1;
3581
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003582 /* vsnprintf() will return the required length even when the
3583 * target buffer is NULL. We do this in a loop just in case
3584 * intermediate evaluations get wrong.
3585 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003586 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003587 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003588 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003589 if (needed < allocated) {
3590 /* Note: on Solaris 8, the first iteration always
3591 * returns -1 if allocated is zero, so we force a
3592 * retry.
3593 */
3594 if (!allocated)
3595 needed = 0;
3596 else
3597 break;
3598 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003599
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003600 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003601 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003602 } while (ret);
3603
3604 if (needed < 0) {
3605 /* an error was encountered */
3606 free(ret);
3607 ret = NULL;
3608 }
3609
3610 if (out) {
3611 free(*out);
3612 *out = ret;
3613 }
3614
3615 return ret;
3616}
William Lallemand421f5b52012-02-06 18:15:57 +01003617
Christopher Faulet93a518f2017-10-24 11:25:33 +02003618char *memprintf(char **out, const char *format, ...)
3619{
3620 va_list args;
3621 char *ret = NULL;
3622
3623 va_start(args, format);
3624 ret = memvprintf(out, format, args);
3625 va_end(args);
3626
3627 return ret;
3628}
3629
Willy Tarreau21c705b2012-09-14 11:40:36 +02003630/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3631 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003632 * freed by the caller. It also supports being passed a NULL which results in the same
3633 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003634 * Example of use :
3635 * parse(cmd, &err); (callee: memprintf(&err, ...))
3636 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3637 * free(err);
3638 */
3639char *indent_msg(char **out, int level)
3640{
3641 char *ret, *in, *p;
3642 int needed = 0;
3643 int lf = 0;
3644 int lastlf = 0;
3645 int len;
3646
Willy Tarreau70eec382012-10-10 08:56:47 +02003647 if (!out || !*out)
3648 return NULL;
3649
Willy Tarreau21c705b2012-09-14 11:40:36 +02003650 in = *out - 1;
3651 while ((in = strchr(in + 1, '\n')) != NULL) {
3652 lastlf = in - *out;
3653 lf++;
3654 }
3655
3656 if (!lf) /* single line, no LF, return it as-is */
3657 return *out;
3658
3659 len = strlen(*out);
3660
3661 if (lf == 1 && lastlf == len - 1) {
3662 /* single line, LF at end, strip it and return as-is */
3663 (*out)[lastlf] = 0;
3664 return *out;
3665 }
3666
3667 /* OK now we have at least one LF, we need to process the whole string
3668 * as a multi-line string. What we'll do :
3669 * - prefix with an LF if there is none
3670 * - add <level> spaces before each line
3671 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3672 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3673 */
3674
3675 needed = 1 + level * (lf + 1) + len + 1;
3676 p = ret = malloc(needed);
3677 in = *out;
3678
3679 /* skip initial LFs */
3680 while (*in == '\n')
3681 in++;
3682
3683 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3684 while (*in) {
3685 *p++ = '\n';
3686 memset(p, ' ', level);
3687 p += level;
3688 do {
3689 *p++ = *in++;
3690 } while (*in && *in != '\n');
3691 if (*in)
3692 in++;
3693 }
3694 *p = 0;
3695
3696 free(*out);
3697 *out = ret;
3698
3699 return ret;
3700}
3701
Willy Tarreau9d22e562019-03-29 18:49:09 +01003702/* removes environment variable <name> from the environment as found in
3703 * environ. This is only provided as an alternative for systems without
3704 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
3705 * The principle is to scan environ for each occurence of variable name
3706 * <name> and to replace the matching pointers with the last pointer of
3707 * the array (since variables are not ordered).
3708 * It always returns 0 (success).
3709 */
3710int my_unsetenv(const char *name)
3711{
3712 extern char **environ;
3713 char **p = environ;
3714 int vars;
3715 int next;
3716 int len;
3717
3718 len = strlen(name);
3719 for (vars = 0; p[vars]; vars++)
3720 ;
3721 next = 0;
3722 while (next < vars) {
3723 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3724 next++;
3725 continue;
3726 }
3727 if (next < vars - 1)
3728 p[next] = p[vars - 1];
3729 p[--vars] = NULL;
3730 }
3731 return 0;
3732}
3733
Willy Tarreaudad36a32013-03-11 01:20:04 +01003734/* Convert occurrences of environment variables in the input string to their
3735 * corresponding value. A variable is identified as a series of alphanumeric
3736 * characters or underscores following a '$' sign. The <in> string must be
3737 * free()able. NULL returns NULL. The resulting string might be reallocated if
3738 * some expansion is made. Variable names may also be enclosed into braces if
3739 * needed (eg: to concatenate alphanum characters).
3740 */
3741char *env_expand(char *in)
3742{
3743 char *txt_beg;
3744 char *out;
3745 char *txt_end;
3746 char *var_beg;
3747 char *var_end;
3748 char *value;
3749 char *next;
3750 int out_len;
3751 int val_len;
3752
3753 if (!in)
3754 return in;
3755
3756 value = out = NULL;
3757 out_len = 0;
3758
3759 txt_beg = in;
3760 do {
3761 /* look for next '$' sign in <in> */
3762 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3763
3764 if (!*txt_end && !out) /* end and no expansion performed */
3765 return in;
3766
3767 val_len = 0;
3768 next = txt_end;
3769 if (*txt_end == '$') {
3770 char save;
3771
3772 var_beg = txt_end + 1;
3773 if (*var_beg == '{')
3774 var_beg++;
3775
3776 var_end = var_beg;
3777 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3778 var_end++;
3779 }
3780
3781 next = var_end;
3782 if (*var_end == '}' && (var_beg > txt_end + 1))
3783 next++;
3784
3785 /* get value of the variable name at this location */
3786 save = *var_end;
3787 *var_end = '\0';
3788 value = getenv(var_beg);
3789 *var_end = save;
3790 val_len = value ? strlen(value) : 0;
3791 }
3792
Hubert Verstraete831962e2016-06-28 22:44:26 +02003793 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003794 if (txt_end > txt_beg) {
3795 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3796 out_len += txt_end - txt_beg;
3797 }
3798 if (val_len) {
3799 memcpy(out + out_len, value, val_len);
3800 out_len += val_len;
3801 }
3802 out[out_len] = 0;
3803 txt_beg = next;
3804 } while (*txt_beg);
3805
3806 /* here we know that <out> was allocated and that we don't need <in> anymore */
3807 free(in);
3808 return out;
3809}
3810
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003811
3812/* same as strstr() but case-insensitive and with limit length */
3813const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3814{
3815 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003816 unsigned int slen, plen;
3817 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003818
3819 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3820 return NULL;
3821
3822 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3823 return str1;
3824
3825 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3826 return NULL;
3827
3828 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3829 while (toupper(*start) != toupper(*str2)) {
3830 start++;
3831 slen--;
3832 tmp1++;
3833
3834 if (tmp1 >= len_str1)
3835 return NULL;
3836
3837 /* if pattern longer than string */
3838 if (slen < plen)
3839 return NULL;
3840 }
3841
3842 sptr = start;
3843 pptr = (char *)str2;
3844
3845 tmp2 = 0;
3846 while (toupper(*sptr) == toupper(*pptr)) {
3847 sptr++;
3848 pptr++;
3849 tmp2++;
3850
3851 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3852 return start;
3853 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3854 return NULL;
3855 }
3856 }
3857 return NULL;
3858}
3859
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003860/* This function read the next valid utf8 char.
3861 * <s> is the byte srray to be decode, <len> is its length.
3862 * The function returns decoded char encoded like this:
3863 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3864 * are the length read. The decoded character is stored in <c>.
3865 */
3866unsigned char utf8_next(const char *s, int len, unsigned int *c)
3867{
3868 const unsigned char *p = (unsigned char *)s;
3869 int dec;
3870 unsigned char code = UTF8_CODE_OK;
3871
3872 if (len < 1)
3873 return UTF8_CODE_OK;
3874
3875 /* Check the type of UTF8 sequence
3876 *
3877 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3878 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3879 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3880 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3881 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3882 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3883 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3884 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3885 */
3886 switch (*p) {
3887 case 0x00 ... 0x7f:
3888 *c = *p;
3889 return UTF8_CODE_OK | 1;
3890
3891 case 0x80 ... 0xbf:
3892 *c = *p;
3893 return UTF8_CODE_BADSEQ | 1;
3894
3895 case 0xc0 ... 0xdf:
3896 if (len < 2) {
3897 *c = *p;
3898 return UTF8_CODE_BADSEQ | 1;
3899 }
3900 *c = *p & 0x1f;
3901 dec = 1;
3902 break;
3903
3904 case 0xe0 ... 0xef:
3905 if (len < 3) {
3906 *c = *p;
3907 return UTF8_CODE_BADSEQ | 1;
3908 }
3909 *c = *p & 0x0f;
3910 dec = 2;
3911 break;
3912
3913 case 0xf0 ... 0xf7:
3914 if (len < 4) {
3915 *c = *p;
3916 return UTF8_CODE_BADSEQ | 1;
3917 }
3918 *c = *p & 0x07;
3919 dec = 3;
3920 break;
3921
3922 case 0xf8 ... 0xfb:
3923 if (len < 5) {
3924 *c = *p;
3925 return UTF8_CODE_BADSEQ | 1;
3926 }
3927 *c = *p & 0x03;
3928 dec = 4;
3929 break;
3930
3931 case 0xfc ... 0xfd:
3932 if (len < 6) {
3933 *c = *p;
3934 return UTF8_CODE_BADSEQ | 1;
3935 }
3936 *c = *p & 0x01;
3937 dec = 5;
3938 break;
3939
3940 case 0xfe ... 0xff:
3941 default:
3942 *c = *p;
3943 return UTF8_CODE_BADSEQ | 1;
3944 }
3945
3946 p++;
3947
3948 while (dec > 0) {
3949
3950 /* need 0x10 for the 2 first bits */
3951 if ( ( *p & 0xc0 ) != 0x80 )
3952 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3953
3954 /* add data at char */
3955 *c = ( *c << 6 ) | ( *p & 0x3f );
3956
3957 dec--;
3958 p++;
3959 }
3960
3961 /* Check ovelong encoding.
3962 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3963 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3964 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3965 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003966 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003967 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3968 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3969 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3970 code |= UTF8_CODE_OVERLONG;
3971
3972 /* Check invalid UTF8 range. */
3973 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3974 (*c >= 0xfffe && *c <= 0xffff))
3975 code |= UTF8_CODE_INVRANGE;
3976
3977 return code | ((p-(unsigned char *)s)&0x0f);
3978}
3979
Maxime de Roucydc887852016-05-13 23:52:54 +02003980/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3981 * On failure : return 0 and <err> filled with an error message.
3982 * The caller is responsible for freeing the <err> and <str> copy
3983 * memory area using free()
3984 */
3985int list_append_word(struct list *li, const char *str, char **err)
3986{
3987 struct wordlist *wl;
3988
3989 wl = calloc(1, sizeof(*wl));
3990 if (!wl) {
3991 memprintf(err, "out of memory");
3992 goto fail_wl;
3993 }
3994
3995 wl->s = strdup(str);
3996 if (!wl->s) {
3997 memprintf(err, "out of memory");
3998 goto fail_wl_s;
3999 }
4000
4001 LIST_ADDQ(li, &wl->list);
4002
4003 return 1;
4004
4005fail_wl_s:
4006 free(wl->s);
4007fail_wl:
4008 free(wl);
4009 return 0;
4010}
4011
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004012/* print a string of text buffer to <out>. The format is :
4013 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4014 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4015 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4016 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004017int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004018{
4019 unsigned char c;
4020 int ptr = 0;
4021
4022 while (buf[ptr] && ptr < bsize) {
4023 c = buf[ptr];
4024 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004025 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004026 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004027 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004028 }
4029 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004030 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004031 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004032 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004033 switch (c) {
4034 case ' ': c = ' '; break;
4035 case '\t': c = 't'; break;
4036 case '\n': c = 'n'; break;
4037 case '\r': c = 'r'; break;
4038 case '\e': c = 'e'; break;
4039 case '\\': c = '\\'; break;
4040 case '=': c = '='; break;
4041 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004042 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004043 }
4044 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004045 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004046 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004047 out->area[out->data++] = '\\';
4048 out->area[out->data++] = 'x';
4049 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4050 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004051 }
4052 ptr++;
4053 }
4054
4055 return ptr;
4056}
4057
4058/* print a buffer in hexa.
4059 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4060 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004061int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004062{
4063 unsigned char c;
4064 int ptr = 0;
4065
4066 while (ptr < bsize) {
4067 c = buf[ptr];
4068
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004069 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004070 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004071 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4072 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004073
4074 ptr++;
4075 }
4076 return ptr;
4077}
4078
4079/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4080 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4081 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4082 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4083 * lines are respected within the limit of 70 output chars. Lines that are
4084 * continuation of a previous truncated line begin with "+" instead of " "
4085 * after the offset. The new pointer is returned.
4086 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004087int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004088 int *line, int ptr)
4089{
4090 int end;
4091 unsigned char c;
4092
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004093 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004094 if (end > out->size)
4095 return ptr;
4096
4097 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4098
4099 while (ptr < len && ptr < bsize) {
4100 c = buf[ptr];
4101 if (isprint(c) && isascii(c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004102 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004103 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004104 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004105 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004106 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004107 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004108 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004109 switch (c) {
4110 case '\t': c = 't'; break;
4111 case '\n': c = 'n'; break;
4112 case '\r': c = 'r'; break;
4113 case '\e': c = 'e'; break;
4114 case '\\': c = '\\'; break;
4115 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004116 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004117 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004118 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004119 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004120 out->area[out->data++] = '\\';
4121 out->area[out->data++] = 'x';
4122 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4123 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004124 }
4125 if (buf[ptr++] == '\n') {
4126 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004127 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004128 *line = ptr;
4129 return ptr;
4130 }
4131 }
4132 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004133 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004134 return ptr;
4135}
4136
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004137/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004138 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4139 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004140 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004141void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4142 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004143{
Willy Tarreau73459792017-04-11 07:58:08 +02004144 unsigned int i;
4145 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004146
4147 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4148 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004149 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004150 for (j = 0; j < 8; j++) {
4151 if (b + j >= 0 && b + j < len)
4152 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4153 else
4154 fprintf(out, " ");
4155 }
4156
4157 if (b + j >= 0 && b + j < len)
4158 fputc('-', out);
4159 else
4160 fputc(' ', out);
4161
4162 for (j = 8; j < 16; j++) {
4163 if (b + j >= 0 && b + j < len)
4164 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4165 else
4166 fprintf(out, " ");
4167 }
4168
4169 fprintf(out, " ");
4170 for (j = 0; j < 16; j++) {
4171 if (b + j >= 0 && b + j < len) {
4172 if (isprint((unsigned char)buf[b + j]))
4173 fputc((unsigned char)buf[b + j], out);
4174 else
4175 fputc('.', out);
4176 }
4177 else
4178 fputc(' ', out);
4179 }
4180 fputc('\n', out);
4181 }
4182}
4183
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004184/*
4185 * Allocate an array of unsigned int with <nums> as address from <str> string
4186 * made of integer sepereated by dot characters.
4187 *
4188 * First, initializes the value with <sz> as address to 0 and initializes the
4189 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4190 * address updating <sz> pointed value to the size of this array.
4191 *
4192 * Returns 1 if succeeded, 0 if not.
4193 */
4194int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4195{
4196 unsigned int *n;
4197 const char *s, *end;
4198
4199 s = str;
4200 *sz = 0;
4201 end = str + strlen(str);
4202 *nums = n = NULL;
4203
4204 while (1) {
4205 unsigned int r;
4206
4207 if (s >= end)
4208 break;
4209
4210 r = read_uint(&s, end);
4211 /* Expected characters after having read an uint: '\0' or '.',
4212 * if '.', must not be terminal.
4213 */
4214 if (*s != '\0'&& (*s++ != '.' || s == end))
4215 return 0;
4216
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004217 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004218 if (!n)
4219 return 0;
4220
4221 n[(*sz)++] = r;
4222 }
4223 *nums = n;
4224
4225 return 1;
4226}
4227
Willy Tarreau12963822017-10-24 10:54:08 +02004228/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
4229__attribute__((weak,format(printf, 1, 2)))
4230void trace(char *msg, ...)
4231{
4232}
4233
Willy Tarreaubaaee002006-06-26 02:48:02 +02004234/*
4235 * Local variables:
4236 * c-indent-level: 8
4237 * c-basic-offset: 8
4238 * End:
4239 */