blob: 38997d5f48968cdb6bd30d47ed628efea323c460 [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 Tarreau109201f2020-03-04 10:31:58 +010013#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010019#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020020#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020022#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020023#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <stdlib.h>
25#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010026#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020027#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010028#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020029#include <sys/stat.h>
30#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010031#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netinet/in.h>
33#include <arpa/inet.h>
34
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010035#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020036#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020037#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010038#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010039#include <types/global.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010040#include <proto/applet.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020041#include <proto/dns.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010042#include <proto/hlua.h>
43#include <proto/listener.h>
44#include <proto/proto_udp.h>
45#include <proto/ssl_sock.h>
46#include <proto/stream_interface.h>
47#include <proto/task.h>
48
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010049#include <eb32tree.h>
Willy Tarreaued3cda02017-11-15 15:04:05 +010050#include <eb32sctree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020051
Thierry Fournier93127942016-01-20 18:49:45 +010052/* This macro returns false if the test __x is false. Many
53 * of the following parsing function must be abort the processing
54 * if it returns 0, so this macro is useful for writing light code.
55 */
56#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
57
Willy Tarreau56adcf22012-12-23 18:00:29 +010058/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020059 * 2^64-1 = 18446744073709551615 or
60 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020061 *
62 * The HTML version needs room for adding the 25 characters
63 * '<span class="rls"></span>' around digits at positions 3N+1 in order
64 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020065 */
Christopher Faulet99bca652017-11-14 16:47:26 +010066THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
67THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020068
Willy Tarreau588297f2014-06-16 15:16:40 +020069/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
70 * to quote strings larger than a max configuration line.
71 */
Christopher Faulet99bca652017-11-14 16:47:26 +010072THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
73THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020074
Willy Tarreaubaaee002006-06-26 02:48:02 +020075/*
William Lallemande7340ec2012-01-24 11:15:39 +010076 * unsigned long long ASCII representation
77 *
78 * return the last char '\0' or NULL if no enough
79 * space in dst
80 */
81char *ulltoa(unsigned long long n, char *dst, size_t size)
82{
83 int i = 0;
84 char *res;
85
86 switch(n) {
87 case 1ULL ... 9ULL:
88 i = 0;
89 break;
90
91 case 10ULL ... 99ULL:
92 i = 1;
93 break;
94
95 case 100ULL ... 999ULL:
96 i = 2;
97 break;
98
99 case 1000ULL ... 9999ULL:
100 i = 3;
101 break;
102
103 case 10000ULL ... 99999ULL:
104 i = 4;
105 break;
106
107 case 100000ULL ... 999999ULL:
108 i = 5;
109 break;
110
111 case 1000000ULL ... 9999999ULL:
112 i = 6;
113 break;
114
115 case 10000000ULL ... 99999999ULL:
116 i = 7;
117 break;
118
119 case 100000000ULL ... 999999999ULL:
120 i = 8;
121 break;
122
123 case 1000000000ULL ... 9999999999ULL:
124 i = 9;
125 break;
126
127 case 10000000000ULL ... 99999999999ULL:
128 i = 10;
129 break;
130
131 case 100000000000ULL ... 999999999999ULL:
132 i = 11;
133 break;
134
135 case 1000000000000ULL ... 9999999999999ULL:
136 i = 12;
137 break;
138
139 case 10000000000000ULL ... 99999999999999ULL:
140 i = 13;
141 break;
142
143 case 100000000000000ULL ... 999999999999999ULL:
144 i = 14;
145 break;
146
147 case 1000000000000000ULL ... 9999999999999999ULL:
148 i = 15;
149 break;
150
151 case 10000000000000000ULL ... 99999999999999999ULL:
152 i = 16;
153 break;
154
155 case 100000000000000000ULL ... 999999999999999999ULL:
156 i = 17;
157 break;
158
159 case 1000000000000000000ULL ... 9999999999999999999ULL:
160 i = 18;
161 break;
162
163 case 10000000000000000000ULL ... ULLONG_MAX:
164 i = 19;
165 break;
166 }
167 if (i + 2 > size) // (i + 1) + '\0'
168 return NULL; // too long
169 res = dst + i + 1;
170 *res = '\0';
171 for (; i >= 0; i--) {
172 dst[i] = n % 10ULL + '0';
173 n /= 10ULL;
174 }
175 return res;
176}
177
178/*
179 * unsigned long ASCII representation
180 *
181 * return the last char '\0' or NULL if no enough
182 * space in dst
183 */
184char *ultoa_o(unsigned long n, char *dst, size_t size)
185{
186 int i = 0;
187 char *res;
188
189 switch (n) {
190 case 0U ... 9UL:
191 i = 0;
192 break;
193
194 case 10U ... 99UL:
195 i = 1;
196 break;
197
198 case 100U ... 999UL:
199 i = 2;
200 break;
201
202 case 1000U ... 9999UL:
203 i = 3;
204 break;
205
206 case 10000U ... 99999UL:
207 i = 4;
208 break;
209
210 case 100000U ... 999999UL:
211 i = 5;
212 break;
213
214 case 1000000U ... 9999999UL:
215 i = 6;
216 break;
217
218 case 10000000U ... 99999999UL:
219 i = 7;
220 break;
221
222 case 100000000U ... 999999999UL:
223 i = 8;
224 break;
225#if __WORDSIZE == 32
226
227 case 1000000000ULL ... ULONG_MAX:
228 i = 9;
229 break;
230
231#elif __WORDSIZE == 64
232
233 case 1000000000ULL ... 9999999999UL:
234 i = 9;
235 break;
236
237 case 10000000000ULL ... 99999999999UL:
238 i = 10;
239 break;
240
241 case 100000000000ULL ... 999999999999UL:
242 i = 11;
243 break;
244
245 case 1000000000000ULL ... 9999999999999UL:
246 i = 12;
247 break;
248
249 case 10000000000000ULL ... 99999999999999UL:
250 i = 13;
251 break;
252
253 case 100000000000000ULL ... 999999999999999UL:
254 i = 14;
255 break;
256
257 case 1000000000000000ULL ... 9999999999999999UL:
258 i = 15;
259 break;
260
261 case 10000000000000000ULL ... 99999999999999999UL:
262 i = 16;
263 break;
264
265 case 100000000000000000ULL ... 999999999999999999UL:
266 i = 17;
267 break;
268
269 case 1000000000000000000ULL ... 9999999999999999999UL:
270 i = 18;
271 break;
272
273 case 10000000000000000000ULL ... ULONG_MAX:
274 i = 19;
275 break;
276
277#endif
278 }
279 if (i + 2 > size) // (i + 1) + '\0'
280 return NULL; // too long
281 res = dst + i + 1;
282 *res = '\0';
283 for (; i >= 0; i--) {
284 dst[i] = n % 10U + '0';
285 n /= 10U;
286 }
287 return res;
288}
289
290/*
291 * signed long ASCII representation
292 *
293 * return the last char '\0' or NULL if no enough
294 * space in dst
295 */
296char *ltoa_o(long int n, char *dst, size_t size)
297{
298 char *pos = dst;
299
300 if (n < 0) {
301 if (size < 3)
302 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
303 *pos = '-';
304 pos++;
305 dst = ultoa_o(-n, pos, size - 1);
306 } else {
307 dst = ultoa_o(n, dst, size);
308 }
309 return dst;
310}
311
312/*
313 * signed long long ASCII representation
314 *
315 * return the last char '\0' or NULL if no enough
316 * space in dst
317 */
318char *lltoa(long long n, char *dst, size_t size)
319{
320 char *pos = dst;
321
322 if (n < 0) {
323 if (size < 3)
324 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
325 *pos = '-';
326 pos++;
327 dst = ulltoa(-n, pos, size - 1);
328 } else {
329 dst = ulltoa(n, dst, size);
330 }
331 return dst;
332}
333
334/*
335 * write a ascii representation of a unsigned into dst,
336 * return a pointer to the last character
337 * Pad the ascii representation with '0', using size.
338 */
339char *utoa_pad(unsigned int n, char *dst, size_t size)
340{
341 int i = 0;
342 char *ret;
343
344 switch(n) {
345 case 0U ... 9U:
346 i = 0;
347 break;
348
349 case 10U ... 99U:
350 i = 1;
351 break;
352
353 case 100U ... 999U:
354 i = 2;
355 break;
356
357 case 1000U ... 9999U:
358 i = 3;
359 break;
360
361 case 10000U ... 99999U:
362 i = 4;
363 break;
364
365 case 100000U ... 999999U:
366 i = 5;
367 break;
368
369 case 1000000U ... 9999999U:
370 i = 6;
371 break;
372
373 case 10000000U ... 99999999U:
374 i = 7;
375 break;
376
377 case 100000000U ... 999999999U:
378 i = 8;
379 break;
380
381 case 1000000000U ... 4294967295U:
382 i = 9;
383 break;
384 }
385 if (i + 2 > size) // (i + 1) + '\0'
386 return NULL; // too long
387 if (i < size)
388 i = size - 2; // padding - '\0'
389
390 ret = dst + i + 1;
391 *ret = '\0';
392 for (; i >= 0; i--) {
393 dst[i] = n % 10U + '0';
394 n /= 10U;
395 }
396 return ret;
397}
398
399/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200400 * copies at most <size-1> chars from <src> to <dst>. Last char is always
401 * set to 0, unless <size> is 0. The number of chars copied is returned
402 * (excluding the terminating zero).
403 * This code has been optimized for size and speed : on x86, it's 45 bytes
404 * long, uses only registers, and consumes only 4 cycles per char.
405 */
406int strlcpy2(char *dst, const char *src, int size)
407{
408 char *orig = dst;
409 if (size) {
410 while (--size && (*dst = *src)) {
411 src++; dst++;
412 }
413 *dst = 0;
414 }
415 return dst - orig;
416}
417
418/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200419 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200420 * the ascii representation for number 'n' in decimal.
421 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100422char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200423{
424 char *pos;
425
Willy Tarreau72d759c2007-10-25 12:14:10 +0200426 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200427 *pos-- = '\0';
428
429 do {
430 *pos-- = '0' + n % 10;
431 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200432 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200433 return pos + 1;
434}
435
Willy Tarreau91092e52007-10-25 16:58:42 +0200436/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200437 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200438 * the ascii representation for number 'n' in decimal.
439 */
440char *lltoa_r(long long int in, char *buffer, int size)
441{
442 char *pos;
443 int neg = 0;
444 unsigned long long int n;
445
446 pos = buffer + size - 1;
447 *pos-- = '\0';
448
449 if (in < 0) {
450 neg = 1;
451 n = -in;
452 }
453 else
454 n = in;
455
456 do {
457 *pos-- = '0' + n % 10;
458 n /= 10;
459 } while (n && pos >= buffer);
460 if (neg && pos > buffer)
461 *pos-- = '-';
462 return pos + 1;
463}
464
465/*
466 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200467 * the ascii representation for signed number 'n' in decimal.
468 */
469char *sltoa_r(long n, char *buffer, int size)
470{
471 char *pos;
472
473 if (n >= 0)
474 return ultoa_r(n, buffer, size);
475
476 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
477 *pos = '-';
478 return pos;
479}
480
481/*
482 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200483 * the ascii representation for number 'n' in decimal, formatted for
484 * HTML output with tags to create visual grouping by 3 digits. The
485 * output needs to support at least 171 characters.
486 */
487const char *ulltoh_r(unsigned long long n, char *buffer, int size)
488{
489 char *start;
490 int digit = 0;
491
492 start = buffer + size;
493 *--start = '\0';
494
495 do {
496 if (digit == 3 && start >= buffer + 7)
497 memcpy(start -= 7, "</span>", 7);
498
499 if (start >= buffer + 1) {
500 *--start = '0' + n % 10;
501 n /= 10;
502 }
503
504 if (digit == 3 && start >= buffer + 18)
505 memcpy(start -= 18, "<span class=\"rls\">", 18);
506
507 if (digit++ == 3)
508 digit = 1;
509 } while (n && start > buffer);
510 return start;
511}
512
513/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200514 * This function simply returns a locally allocated string containing the ascii
515 * representation for number 'n' in decimal, unless n is 0 in which case it
516 * returns the alternate string (or an empty string if the alternate string is
517 * NULL). It use is intended for limits reported in reports, where it's
518 * desirable not to display anything if there is no limit. Warning! it shares
519 * the same vector as ultoa_r().
520 */
521const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
522{
523 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
524}
525
Willy Tarreau588297f2014-06-16 15:16:40 +0200526/* returns a locally allocated string containing the quoted encoding of the
527 * input string. The output may be truncated to QSTR_SIZE chars, but it is
528 * guaranteed that the string will always be properly terminated. Quotes are
529 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
530 * always be at least 4 chars.
531 */
532const char *qstr(const char *str)
533{
534 char *ret = quoted_str[quoted_idx];
535 char *p, *end;
536
537 if (++quoted_idx >= NB_QSTR)
538 quoted_idx = 0;
539
540 p = ret;
541 end = ret + QSTR_SIZE;
542
543 *p++ = '"';
544
545 /* always keep 3 chars to support passing "" and the ending " */
546 while (*str && p < end - 3) {
547 if (*str == '"') {
548 *p++ = '"';
549 *p++ = '"';
550 }
551 else
552 *p++ = *str;
553 str++;
554 }
555 *p++ = '"';
556 return ret;
557}
558
Robert Tsai81ae1952007-12-05 10:47:29 +0100559/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200560 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
561 *
562 * It looks like this one would be a good candidate for inlining, but this is
563 * not interesting because it around 35 bytes long and often called multiple
564 * times within the same function.
565 */
566int ishex(char s)
567{
568 s -= '0';
569 if ((unsigned char)s <= 9)
570 return 1;
571 s -= 'A' - '0';
572 if ((unsigned char)s <= 5)
573 return 1;
574 s -= 'a' - 'A';
575 if ((unsigned char)s <= 5)
576 return 1;
577 return 0;
578}
579
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100580/* rounds <i> down to the closest value having max 2 digits */
581unsigned int round_2dig(unsigned int i)
582{
583 unsigned int mul = 1;
584
585 while (i >= 100) {
586 i /= 10;
587 mul *= 10;
588 }
589 return i * mul;
590}
591
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100592/*
593 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
594 * invalid character is found, a pointer to it is returned. If everything is
595 * fine, NULL is returned.
596 */
597const char *invalid_char(const char *name)
598{
599 if (!*name)
600 return name;
601
602 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100603 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100604 *name != '_' && *name != '-')
605 return name;
606 name++;
607 }
608 return NULL;
609}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200610
611/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200612 * Checks <name> for invalid characters. Valid chars are [_.-] and those
613 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200614 * If an invalid character is found, a pointer to it is returned.
615 * If everything is fine, NULL is returned.
616 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200617static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200618
619 if (!*name)
620 return name;
621
622 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100623 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200624 *name != '_' && *name != '-')
625 return name;
626
627 name++;
628 }
629
630 return NULL;
631}
632
633/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200634 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
635 * If an invalid character is found, a pointer to it is returned.
636 * If everything is fine, NULL is returned.
637 */
638const char *invalid_domainchar(const char *name) {
639 return __invalid_char(name, isalnum);
640}
641
642/*
643 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
644 * If an invalid character is found, a pointer to it is returned.
645 * If everything is fine, NULL is returned.
646 */
647const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200648 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200649}
650
651/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100652 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100653 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
654 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
655 * the function tries to guess the address family from the syntax. If the
656 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100657 * string is assumed to contain only an address, no port. The address can be a
658 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
659 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
660 * The return address will only have the address family and the address set,
661 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100662 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
663 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100664 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200665 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100666struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200667{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100668 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100669 /* max IPv6 length, including brackets and terminating NULL */
670 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100671 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100672
673 /* check IPv6 with square brackets */
674 if (str[0] == '[') {
675 size_t iplength = strlen(str);
676
677 if (iplength < 4) {
678 /* minimal size is 4 when using brackets "[::]" */
679 goto fail;
680 }
681 else if (iplength >= sizeof(tmpip)) {
682 /* IPv6 literal can not be larger than tmpip */
683 goto fail;
684 }
685 else {
686 if (str[iplength - 1] != ']') {
687 /* if address started with bracket, it should end with bracket */
688 goto fail;
689 }
690 else {
691 memcpy(tmpip, str + 1, iplength - 2);
692 tmpip[iplength - 2] = '\0';
693 str = tmpip;
694 }
695 }
696 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100697
Willy Tarreaufab5a432011-03-04 15:31:53 +0100698 /* Any IPv6 address */
699 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100700 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
701 sa->ss_family = AF_INET6;
702 else if (sa->ss_family != AF_INET6)
703 goto fail;
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
Willy Tarreau24709282013-03-10 21:32:12 +0100708 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100709 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100710 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
711 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
716 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100717 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
718 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100719 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100720 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100721 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100722 }
723
724 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100725 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
726 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100727 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100728 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100729 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100730 }
731
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100732 if (!resolve)
733 return NULL;
734
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200735 if (!dns_hostname_validation(str, NULL))
736 return NULL;
737
David du Colombierd5f43282011-03-17 10:40:16 +0100738#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200739 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100740 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100741 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100742
743 memset(&result, 0, sizeof(result));
744 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100745 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100746 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200747 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100748 hints.ai_protocol = 0;
749
750 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100751 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
752 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100753 else if (sa->ss_family != result->ai_family) {
754 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100755 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100756 }
Willy Tarreau24709282013-03-10 21:32:12 +0100757
David du Colombierd5f43282011-03-17 10:40:16 +0100758 switch (result->ai_family) {
759 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100760 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100761 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100762 success = 1;
763 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100764 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100765 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100766 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100767 success = 1;
768 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100769 }
770 }
771
Sean Carey58ea0392013-02-15 23:39:18 +0100772 if (result)
773 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100774
775 if (success)
776 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100777 }
David du Colombierd5f43282011-03-17 10:40:16 +0100778#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200779 /* try to resolve an IPv4/IPv6 hostname */
780 he = gethostbyname(str);
781 if (he) {
782 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
783 sa->ss_family = he->h_addrtype;
784 else if (sa->ss_family != he->h_addrtype)
785 goto fail;
786
787 switch (sa->ss_family) {
788 case AF_INET:
789 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100790 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200791 return sa;
792 case AF_INET6:
793 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100794 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200795 return sa;
796 }
797 }
798
David du Colombierd5f43282011-03-17 10:40:16 +0100799 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100800 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100801 return NULL;
802}
803
804/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100805 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
806 * range or offset consisting in two integers that the caller will have to
807 * check to find the relevant input format. The following format are supported :
808 *
809 * String format | address | port | low | high
810 * addr | <addr> | 0 | 0 | 0
811 * addr: | <addr> | 0 | 0 | 0
812 * addr:port | <addr> | <port> | <port> | <port>
813 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
814 * addr:+port | <addr> | <port> | 0 | <port>
815 * addr:-port | <addr> |-<port> | <port> | 0
816 *
817 * The detection of a port range or increment by the caller is made by
818 * comparing <low> and <high>. If both are equal, then port 0 means no port
819 * was specified. The caller may pass NULL for <low> and <high> if it is not
820 * interested in retrieving port ranges.
821 *
822 * Note that <addr> above may also be :
823 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
824 * - "*" => family will be AF_INET and address will be INADDR_ANY
825 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
826 * - a host name => family and address will depend on host name resolving.
827 *
Willy Tarreau24709282013-03-10 21:32:12 +0100828 * A prefix may be passed in before the address above to force the family :
829 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
830 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
831 * - "unix@" => force address to be a path to a UNIX socket even if the
832 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200833 * - 'abns@' -> force address to belong to the abstract namespace (Linux
834 * only). These sockets are just like Unix sockets but without
835 * the need for an underlying file system. The address is a
836 * string. Technically it's like a Unix socket with a zero in
837 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100838 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100839 *
mildisff5d5102015-10-26 18:50:08 +0100840 * IPv6 addresses can be declared with or without square brackets. When using
841 * square brackets for IPv6 addresses, the port separator (colon) is optional.
842 * If not using square brackets, and in order to avoid any ambiguity with
843 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
844 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
845 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100846 *
847 * If <pfx> is non-null, it is used as a string prefix before any path-based
848 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100849 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200850 * if <fqdn> is non-null, it will be filled with :
851 * - a pointer to the FQDN of the server name to resolve if there's one, and
852 * that the caller will have to free(),
853 * - NULL if there was an explicit address that doesn't require resolution.
854 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100855 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
856 * is null, <fqdn> is still honnored so it is possible for the caller to know
857 * whether a resolution failed by setting <resolve> to null and checking if
858 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200859 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100860 * When a file descriptor is passed, its value is put into the s_addr part of
861 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100862 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100863struct 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 +0100864{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100865 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100866 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100867 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100868 char *port1, *port2;
869 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200870 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100871
872 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200873 if (fqdn)
874 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200875
Willy Tarreaudad36a32013-03-11 01:20:04 +0100876 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100877 if (str2 == NULL) {
878 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100879 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100880 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200881
Willy Tarreau9f69f462015-09-08 16:01:25 +0200882 if (!*str2) {
883 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
884 goto out;
885 }
886
Willy Tarreau24709282013-03-10 21:32:12 +0100887 memset(&ss, 0, sizeof(ss));
888
889 if (strncmp(str2, "unix@", 5) == 0) {
890 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200891 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100892 ss.ss_family = AF_UNIX;
893 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200894 else if (strncmp(str2, "abns@", 5) == 0) {
895 str2 += 5;
896 abstract = 1;
897 ss.ss_family = AF_UNIX;
898 }
Willy Tarreau24709282013-03-10 21:32:12 +0100899 else if (strncmp(str2, "ipv4@", 5) == 0) {
900 str2 += 5;
901 ss.ss_family = AF_INET;
902 }
903 else if (strncmp(str2, "ipv6@", 5) == 0) {
904 str2 += 5;
905 ss.ss_family = AF_INET6;
906 }
907 else if (*str2 == '/') {
908 ss.ss_family = AF_UNIX;
909 }
910 else
911 ss.ss_family = AF_UNSPEC;
912
William Lallemand2fe7dd02018-09-11 16:51:29 +0200913 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
914 char *endptr;
915
916 str2 += 9;
917
918 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100919 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200920
921 if (!*str2 || *endptr) {
922 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
923 goto out;
924 }
925
926 ss.ss_family = AF_CUST_SOCKPAIR;
927
928 }
929 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100930 char *endptr;
931
932 str2 += 3;
933 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100934 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100935
936 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100937 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100938 goto out;
939 }
940
941 /* we return AF_UNSPEC if we use a file descriptor number */
942 ss.ss_family = AF_UNSPEC;
943 }
944 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +0200945 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +0100946 int prefix_path_len;
947 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200948 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100949
950 /* complete unix socket path name during startup or soft-restart is
951 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
952 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200953 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +0200954 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +0100955 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +0100956
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200957 adr_len = strlen(str2);
958 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100959 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
960 goto out;
961 }
962
Willy Tarreauccfccef2014-05-10 01:49:15 +0200963 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +0200964 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200965 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +0200966 memcpy(un->sun_path, pfx, prefix_path_len);
967 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100968 }
Willy Tarreau24709282013-03-10 21:32:12 +0100969 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100970 char *end = str2 + strlen(str2);
971 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200972
mildisff5d5102015-10-26 18:50:08 +0100973 /* search for : or ] whatever comes first */
974 for (chr = end-1; chr > str2; chr--) {
975 if (*chr == ']' || *chr == ':')
976 break;
977 }
978
979 if (*chr == ':') {
980 /* Found a colon before a closing-bracket, must be a port separator.
981 * This guarantee backward compatibility.
982 */
983 *chr++ = '\0';
984 port1 = chr;
985 }
986 else {
987 /* Either no colon and no closing-bracket
988 * or directly ending with a closing-bracket.
989 * However, no port.
990 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100991 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100992 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200993
Willy Tarreau90807112020-02-25 08:16:33 +0100994 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100995 port2 = strchr(port1, '-');
996 if (port2)
997 *port2++ = '\0';
998 else
999 port2 = port1;
1000 portl = atoi(port1);
1001 porth = atoi(port2);
1002 porta = portl;
1003 }
1004 else if (*port1 == '-') { /* negative offset */
1005 portl = atoi(port1 + 1);
1006 porta = -portl;
1007 }
1008 else if (*port1 == '+') { /* positive offset */
1009 porth = atoi(port1 + 1);
1010 porta = porth;
1011 }
1012 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001013 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001014 goto out;
1015 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001016
1017 /* first try to parse the IP without resolving. If it fails, it
1018 * tells us we need to keep a copy of the FQDN to resolve later
1019 * and to enable DNS. In this case we can proceed if <fqdn> is
1020 * set or if resolve is set, otherwise it's an error.
1021 */
1022 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001023 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001024 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1025 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1026 goto out;
1027 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001028
Willy Tarreauceccdd72016-11-02 22:27:10 +01001029 if (fqdn) {
1030 if (str2 != back)
1031 memmove(back, str2, strlen(str2) + 1);
1032 *fqdn = back;
1033 back = NULL;
1034 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001035 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001036 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001037 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001038
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001039 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001040 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001041 if (port)
1042 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001043 if (low)
1044 *low = portl;
1045 if (high)
1046 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001047 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001048 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001049}
1050
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001051/* converts <str> to a struct in_addr containing a network mask. It can be
1052 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001053 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001054 */
1055int str2mask(const char *str, struct in_addr *mask)
1056{
1057 if (strchr(str, '.') != NULL) { /* dotted notation */
1058 if (!inet_pton(AF_INET, str, mask))
1059 return 0;
1060 }
1061 else { /* mask length */
1062 char *err;
1063 unsigned long len = strtol(str, &err, 10);
1064
1065 if (!*str || (err && *err) || (unsigned)len > 32)
1066 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001067
1068 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001069 }
1070 return 1;
1071}
1072
Tim Duesterhus47185172018-01-25 16:24:49 +01001073/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001074 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001075 * if the conversion succeeds otherwise zero.
1076 */
1077int str2mask6(const char *str, struct in6_addr *mask)
1078{
1079 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1080 if (!inet_pton(AF_INET6, str, mask))
1081 return 0;
1082 }
1083 else { /* mask length */
1084 char *err;
1085 unsigned long len = strtol(str, &err, 10);
1086
1087 if (!*str || (err && *err) || (unsigned)len > 128)
1088 return 0;
1089
1090 len2mask6(len, mask);
1091 }
1092 return 1;
1093}
1094
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001095/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1096 * succeeds otherwise zero.
1097 */
1098int cidr2dotted(int cidr, struct in_addr *mask) {
1099
1100 if (cidr < 0 || cidr > 32)
1101 return 0;
1102
1103 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1104 return 1;
1105}
1106
Thierry Fournier70473a52016-02-17 17:12:14 +01001107/* Convert mask from bit length form to in_addr form.
1108 * This function never fails.
1109 */
1110void len2mask4(int len, struct in_addr *addr)
1111{
1112 if (len >= 32) {
1113 addr->s_addr = 0xffffffff;
1114 return;
1115 }
1116 if (len <= 0) {
1117 addr->s_addr = 0x00000000;
1118 return;
1119 }
1120 addr->s_addr = 0xffffffff << (32 - len);
1121 addr->s_addr = htonl(addr->s_addr);
1122}
1123
1124/* Convert mask from bit length form to in6_addr form.
1125 * This function never fails.
1126 */
1127void len2mask6(int len, struct in6_addr *addr)
1128{
1129 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1130 len -= 32;
1131 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1132 len -= 32;
1133 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1134 len -= 32;
1135 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1136}
1137
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001138/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001139 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001140 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1141 * is optionnal and either in the dotted or CIDR notation.
1142 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1143 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001144int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001145{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001146 __label__ out_free, out_err;
1147 char *c, *s;
1148 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001149
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001150 s = strdup(str);
1151 if (!s)
1152 return 0;
1153
Willy Tarreaubaaee002006-06-26 02:48:02 +02001154 memset(mask, 0, sizeof(*mask));
1155 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001156
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001157 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001158 *c++ = '\0';
1159 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001160 if (!str2mask(c, mask))
1161 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001162 }
1163 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001164 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001165 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001166 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001167 struct hostent *he;
1168
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001169 if (!resolve)
1170 goto out_err;
1171
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001172 if ((he = gethostbyname(s)) == NULL) {
1173 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001174 }
1175 else
1176 *addr = *(struct in_addr *) *(he->h_addr_list);
1177 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001178
1179 ret_val = 1;
1180 out_free:
1181 free(s);
1182 return ret_val;
1183 out_err:
1184 ret_val = 0;
1185 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001186}
1187
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001188
1189/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001190 * converts <str> to two struct in6_addr* which must be pre-allocated.
1191 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1192 * is an optionnal number of bits (128 being the default).
1193 * Returns 1 if OK, 0 if error.
1194 */
1195int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1196{
1197 char *c, *s;
1198 int ret_val = 0;
1199 char *err;
1200 unsigned long len = 128;
1201
1202 s = strdup(str);
1203 if (!s)
1204 return 0;
1205
1206 memset(mask, 0, sizeof(*mask));
1207 memset(addr, 0, sizeof(*addr));
1208
1209 if ((c = strrchr(s, '/')) != NULL) {
1210 *c++ = '\0'; /* c points to the mask */
1211 if (!*c)
1212 goto out_free;
1213
1214 len = strtoul(c, &err, 10);
1215 if ((err && *err) || (unsigned)len > 128)
1216 goto out_free;
1217 }
1218 *mask = len; /* OK we have a valid mask in <len> */
1219
1220 if (!inet_pton(AF_INET6, s, addr))
1221 goto out_free;
1222
1223 ret_val = 1;
1224 out_free:
1225 free(s);
1226 return ret_val;
1227}
1228
1229
1230/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001231 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001232 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001233int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001234{
1235 int saw_digit, octets, ch;
1236 u_char tmp[4], *tp;
1237 const char *cp = addr;
1238
1239 saw_digit = 0;
1240 octets = 0;
1241 *(tp = tmp) = 0;
1242
1243 while (*addr) {
1244 unsigned char digit = (ch = *addr++) - '0';
1245 if (digit > 9 && ch != '.')
1246 break;
1247 if (digit <= 9) {
1248 u_int new = *tp * 10 + digit;
1249 if (new > 255)
1250 return 0;
1251 *tp = new;
1252 if (!saw_digit) {
1253 if (++octets > 4)
1254 return 0;
1255 saw_digit = 1;
1256 }
1257 } else if (ch == '.' && saw_digit) {
1258 if (octets == 4)
1259 return 0;
1260 *++tp = 0;
1261 saw_digit = 0;
1262 } else
1263 return 0;
1264 }
1265
1266 if (octets < 4)
1267 return 0;
1268
1269 memcpy(&dst->s_addr, tmp, 4);
1270 return addr-cp-1;
1271}
1272
1273/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001274 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1275 * <out> contain the code of the dectected scheme, the start and length of
1276 * the hostname. Actually only http and https are supported. <out> can be NULL.
1277 * This function returns the consumed length. It is useful if you parse complete
1278 * url like http://host:port/path, because the consumed length corresponds to
1279 * the first character of the path. If the conversion fails, it returns -1.
1280 *
1281 * This function tries to resolve the DNS name if haproxy is in starting mode.
1282 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001283 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001284int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001285{
1286 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001287 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001288 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001289 unsigned long long int http_code = 0;
1290 int default_port;
1291 struct hostent *he;
1292 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001293
1294 /* Firstly, try to find :// pattern */
1295 while (curr < url+ulen && url_code != 0x3a2f2f) {
1296 url_code = ((url_code & 0xffff) << 8);
1297 url_code += (unsigned char)*curr++;
1298 }
1299
1300 /* Secondly, if :// pattern is found, verify parsed stuff
1301 * before pattern is matching our http pattern.
1302 * If so parse ip address and port in uri.
1303 *
1304 * WARNING: Current code doesn't support dynamic async dns resolver.
1305 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001306 if (url_code != 0x3a2f2f)
1307 return -1;
1308
1309 /* Copy scheme, and utrn to lower case. */
1310 while (cp < curr - 3)
1311 http_code = (http_code << 8) + *cp++;
1312 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001313
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001314 /* HTTP or HTTPS url matching */
1315 if (http_code == 0x2020202068747470ULL) {
1316 default_port = 80;
1317 if (out)
1318 out->scheme = SCH_HTTP;
1319 }
1320 else if (http_code == 0x2020206874747073ULL) {
1321 default_port = 443;
1322 if (out)
1323 out->scheme = SCH_HTTPS;
1324 }
1325 else
1326 return -1;
1327
1328 /* If the next char is '[', the host address is IPv6. */
1329 if (*curr == '[') {
1330 curr++;
1331
1332 /* Check trash size */
1333 if (trash.size < ulen)
1334 return -1;
1335
1336 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001337 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001338 for (end = curr;
1339 end < url + ulen && *end != ']';
1340 end++, p++)
1341 *p = *end;
1342 if (*end != ']')
1343 return -1;
1344 *p = '\0';
1345
1346 /* Update out. */
1347 if (out) {
1348 out->host = curr;
1349 out->host_len = end - curr;
1350 }
1351
1352 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001353 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001354 return -1;
1355 end++;
1356
1357 /* Decode port. */
1358 if (*end == ':') {
1359 end++;
1360 default_port = read_uint(&end, url + ulen);
1361 }
1362 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1363 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1364 return end - url;
1365 }
1366 else {
1367 /* We are looking for IP address. If you want to parse and
1368 * resolve hostname found in url, you can use str2sa_range(), but
1369 * be warned this can slow down global daemon performances
1370 * while handling lagging dns responses.
1371 */
1372 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1373 if (ret) {
1374 /* Update out. */
1375 if (out) {
1376 out->host = curr;
1377 out->host_len = ret;
1378 }
1379
1380 curr += ret;
1381
1382 /* Decode port. */
1383 if (*curr == ':') {
1384 curr++;
1385 default_port = read_uint(&curr, url + ulen);
1386 }
1387 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1388
1389 /* Set family. */
1390 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1391 return curr - url;
1392 }
1393 else if (global.mode & MODE_STARTING) {
1394 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1395 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001396 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001397
1398 /* look for : or / or end */
1399 for (end = curr;
1400 end < url + ulen && *end != '/' && *end != ':';
1401 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001402 memcpy(trash.area, curr, end - curr);
1403 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001404
1405 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001406 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001407 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001408 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001409
1410 /* Update out. */
1411 if (out) {
1412 out->host = curr;
1413 out->host_len = end - curr;
1414 }
1415
1416 /* Decode port. */
1417 if (*end == ':') {
1418 end++;
1419 default_port = read_uint(&end, url + ulen);
1420 }
1421
1422 /* Copy IP address, set port and family. */
1423 switch (he->h_addrtype) {
1424 case AF_INET:
1425 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1426 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1427 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1428 return end - url;
1429
1430 case AF_INET6:
1431 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1432 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1433 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1434 return end - url;
1435 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001436 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001437 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001438 return -1;
1439}
1440
Willy Tarreau631f01c2011-09-05 00:36:48 +02001441/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1442 * address family is returned so that it's easy for the caller to adapt to the
1443 * output format. Zero is returned if the address family is not supported. -1
1444 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1445 * supported.
1446 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001447int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001448{
1449
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001450 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001451
1452 if (size < 5)
1453 return 0;
1454 *str = '\0';
1455
1456 switch (addr->ss_family) {
1457 case AF_INET:
1458 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1459 break;
1460 case AF_INET6:
1461 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1462 break;
1463 case AF_UNIX:
1464 memcpy(str, "unix", 5);
1465 return addr->ss_family;
1466 default:
1467 return 0;
1468 }
1469
1470 if (inet_ntop(addr->ss_family, ptr, str, size))
1471 return addr->ss_family;
1472
1473 /* failed */
1474 return -1;
1475}
1476
Simon Horman75ab8bd2014-06-16 09:39:41 +09001477/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1478 * address family is returned so that it's easy for the caller to adapt to the
1479 * output format. Zero is returned if the address family is not supported. -1
1480 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1481 * supported.
1482 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001483int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001484{
1485
1486 uint16_t port;
1487
1488
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001489 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001490 return 0;
1491 *str = '\0';
1492
1493 switch (addr->ss_family) {
1494 case AF_INET:
1495 port = ((struct sockaddr_in *)addr)->sin_port;
1496 break;
1497 case AF_INET6:
1498 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1499 break;
1500 case AF_UNIX:
1501 memcpy(str, "unix", 5);
1502 return addr->ss_family;
1503 default:
1504 return 0;
1505 }
1506
1507 snprintf(str, size, "%u", ntohs(port));
1508 return addr->ss_family;
1509}
1510
Willy Tarreau16e01562016-08-09 16:46:18 +02001511/* check if the given address is local to the system or not. It will return
1512 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1513 * it is. We don't want to iterate over all interfaces for this (and it is not
1514 * portable). So instead we try to bind in UDP to this address on a free non
1515 * privileged port and to connect to the same address, port 0 (connect doesn't
1516 * care). If it succeeds, we own the address. Note that non-inet addresses are
1517 * considered local since they're most likely AF_UNIX.
1518 */
1519int addr_is_local(const struct netns_entry *ns,
1520 const struct sockaddr_storage *orig)
1521{
1522 struct sockaddr_storage addr;
1523 int result;
1524 int fd;
1525
1526 if (!is_inet_addr(orig))
1527 return 1;
1528
1529 memcpy(&addr, orig, sizeof(addr));
1530 set_host_port(&addr, 0);
1531
1532 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1533 if (fd < 0)
1534 return -1;
1535
1536 result = -1;
1537 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1538 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1539 result = 0; // fail, non-local address
1540 else
1541 result = 1; // success, local address
1542 }
1543 else {
1544 if (errno == EADDRNOTAVAIL)
1545 result = 0; // definitely not local :-)
1546 }
1547 close(fd);
1548
1549 return result;
1550}
1551
Willy Tarreaubaaee002006-06-26 02:48:02 +02001552/* will try to encode the string <string> replacing all characters tagged in
1553 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1554 * prefixed by <escape>, and will store the result between <start> (included)
1555 * and <stop> (excluded), and will always terminate the string with a '\0'
1556 * before <stop>. The position of the '\0' is returned if the conversion
1557 * completes. If bytes are missing between <start> and <stop>, then the
1558 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1559 * cannot even be stored so we return <start> without writing the 0.
1560 * The input string must also be zero-terminated.
1561 */
1562const char hextab[16] = "0123456789ABCDEF";
1563char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001564 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001565 const char *string)
1566{
1567 if (start < stop) {
1568 stop--; /* reserve one byte for the final '\0' */
1569 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001570 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001571 *start++ = *string;
1572 else {
1573 if (start + 3 >= stop)
1574 break;
1575 *start++ = escape;
1576 *start++ = hextab[(*string >> 4) & 15];
1577 *start++ = hextab[*string & 15];
1578 }
1579 string++;
1580 }
1581 *start = '\0';
1582 }
1583 return start;
1584}
1585
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001586/*
1587 * Same behavior as encode_string() above, except that it encodes chunk
1588 * <chunk> instead of a string.
1589 */
1590char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001591 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001592 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001593{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001594 char *str = chunk->area;
1595 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001596
1597 if (start < stop) {
1598 stop--; /* reserve one byte for the final '\0' */
1599 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001600 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001601 *start++ = *str;
1602 else {
1603 if (start + 3 >= stop)
1604 break;
1605 *start++ = escape;
1606 *start++ = hextab[(*str >> 4) & 15];
1607 *start++ = hextab[*str & 15];
1608 }
1609 str++;
1610 }
1611 *start = '\0';
1612 }
1613 return start;
1614}
1615
Dragan Dosen0edd1092016-02-12 13:23:02 +01001616/*
1617 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001618 * character. The input <string> must be zero-terminated. The result will
1619 * be stored between <start> (included) and <stop> (excluded). This
1620 * function will always try to terminate the resulting string with a '\0'
1621 * before <stop>, and will return its position if the conversion
1622 * completes.
1623 */
1624char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001625 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001626 const char *string)
1627{
1628 if (start < stop) {
1629 stop--; /* reserve one byte for the final '\0' */
1630 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001631 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001632 *start++ = *string;
1633 else {
1634 if (start + 2 >= stop)
1635 break;
1636 *start++ = escape;
1637 *start++ = *string;
1638 }
1639 string++;
1640 }
1641 *start = '\0';
1642 }
1643 return start;
1644}
1645
1646/*
1647 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001648 * character. <chunk> contains the input to be escaped. The result will be
1649 * stored between <start> (included) and <stop> (excluded). The function
1650 * will always try to terminate the resulting string with a '\0' before
1651 * <stop>, and will return its position if the conversion completes.
1652 */
1653char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001654 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001655 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001656{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001657 char *str = chunk->area;
1658 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001659
1660 if (start < stop) {
1661 stop--; /* reserve one byte for the final '\0' */
1662 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001663 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001664 *start++ = *str;
1665 else {
1666 if (start + 2 >= stop)
1667 break;
1668 *start++ = escape;
1669 *start++ = *str;
1670 }
1671 str++;
1672 }
1673 *start = '\0';
1674 }
1675 return start;
1676}
1677
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001678/* Check a string for using it in a CSV output format. If the string contains
1679 * one of the following four char <">, <,>, CR or LF, the string is
1680 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1681 * <str> is the input string to be escaped. The function assumes that
1682 * the input string is null-terminated.
1683 *
1684 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001685 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001686 * format.
1687 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001688 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001689 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001690 * If <quote> is 1, the converter puts the quotes only if any reserved character
1691 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001692 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001693 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001694 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001695 * The function returns the converted string on its output. If an error
1696 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001697 * for using the function directly as printf() argument.
1698 *
1699 * If the output buffer is too short to contain the input string, the result
1700 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001701 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001702 * This function appends the encoding to the existing output chunk, and it
1703 * guarantees that it starts immediately at the first available character of
1704 * the chunk. Please use csv_enc() instead if you want to replace the output
1705 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001706 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001707const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001708{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001709 char *end = output->area + output->size;
1710 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001711 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001712
Willy Tarreaub631c292016-01-08 10:04:08 +01001713 if (quote == 1) {
1714 /* automatic quoting: first verify if we'll have to quote the string */
1715 if (!strpbrk(str, "\n\r,\""))
1716 quote = 0;
1717 }
1718
1719 if (quote)
1720 *ptr++ = '"';
1721
Willy Tarreau898529b2016-01-06 18:07:04 +01001722 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1723 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001724 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001725 ptr++;
1726 if (ptr >= end - 2) {
1727 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001728 break;
1729 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001730 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001731 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001732 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001733 str++;
1734 }
1735
Willy Tarreaub631c292016-01-08 10:04:08 +01001736 if (quote)
1737 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001738
Willy Tarreau898529b2016-01-06 18:07:04 +01001739 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001740 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001741 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001742}
1743
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001744/* Decode an URL-encoded string in-place. The resulting string might
1745 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001746 * aborted, the string is truncated before the issue and a negative value is
1747 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001748 */
1749int url_decode(char *string)
1750{
1751 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001752 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001753
1754 in = string;
1755 out = string;
1756 while (*in) {
1757 switch (*in) {
1758 case '+' :
1759 *out++ = ' ';
1760 break;
1761 case '%' :
1762 if (!ishex(in[1]) || !ishex(in[2]))
1763 goto end;
1764 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1765 in += 2;
1766 break;
1767 default:
1768 *out++ = *in;
1769 break;
1770 }
1771 in++;
1772 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001773 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001774 end:
1775 *out = 0;
1776 return ret;
1777}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001778
Willy Tarreau6911fa42007-03-04 18:06:08 +01001779unsigned int str2ui(const char *s)
1780{
1781 return __str2ui(s);
1782}
1783
1784unsigned int str2uic(const char *s)
1785{
1786 return __str2uic(s);
1787}
1788
1789unsigned int strl2ui(const char *s, int len)
1790{
1791 return __strl2ui(s, len);
1792}
1793
1794unsigned int strl2uic(const char *s, int len)
1795{
1796 return __strl2uic(s, len);
1797}
1798
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001799unsigned int read_uint(const char **s, const char *end)
1800{
1801 return __read_uint(s, end);
1802}
1803
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001804/* This function reads an unsigned integer from the string pointed to by <s> and
1805 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1806 * function automatically stops at <end>. If the number overflows, the 2^64-1
1807 * value is returned.
1808 */
1809unsigned long long int read_uint64(const char **s, const char *end)
1810{
1811 const char *ptr = *s;
1812 unsigned long long int i = 0, tmp;
1813 unsigned int j;
1814
1815 while (ptr < end) {
1816
1817 /* read next char */
1818 j = *ptr - '0';
1819 if (j > 9)
1820 goto read_uint64_end;
1821
1822 /* add char to the number and check overflow. */
1823 tmp = i * 10;
1824 if (tmp / 10 != i) {
1825 i = ULLONG_MAX;
1826 goto read_uint64_eat;
1827 }
1828 if (ULLONG_MAX - tmp < j) {
1829 i = ULLONG_MAX;
1830 goto read_uint64_eat;
1831 }
1832 i = tmp + j;
1833 ptr++;
1834 }
1835read_uint64_eat:
1836 /* eat each numeric char */
1837 while (ptr < end) {
1838 if ((unsigned int)(*ptr - '0') > 9)
1839 break;
1840 ptr++;
1841 }
1842read_uint64_end:
1843 *s = ptr;
1844 return i;
1845}
1846
1847/* This function reads an integer from the string pointed to by <s> and returns
1848 * it. The <s> pointer is adjusted to point to the first unread char. The function
1849 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1850 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1851 * returned.
1852 */
1853long long int read_int64(const char **s, const char *end)
1854{
1855 unsigned long long int i = 0;
1856 int neg = 0;
1857
1858 /* Look for minus char. */
1859 if (**s == '-') {
1860 neg = 1;
1861 (*s)++;
1862 }
1863 else if (**s == '+')
1864 (*s)++;
1865
1866 /* convert as positive number. */
1867 i = read_uint64(s, end);
1868
1869 if (neg) {
1870 if (i > 0x8000000000000000ULL)
1871 return LLONG_MIN;
1872 return -i;
1873 }
1874 if (i > 0x7fffffffffffffffULL)
1875 return LLONG_MAX;
1876 return i;
1877}
1878
Willy Tarreau6911fa42007-03-04 18:06:08 +01001879/* This one is 7 times faster than strtol() on athlon with checks.
1880 * It returns the value of the number composed of all valid digits read,
1881 * and can process negative numbers too.
1882 */
1883int strl2ic(const char *s, int len)
1884{
1885 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001886 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001887
1888 if (len > 0) {
1889 if (*s != '-') {
1890 /* positive number */
1891 while (len-- > 0) {
1892 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001893 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001894 if (j > 9)
1895 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001896 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001897 }
1898 } else {
1899 /* negative number */
1900 s++;
1901 while (--len > 0) {
1902 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001903 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001904 if (j > 9)
1905 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001906 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001907 }
1908 }
1909 }
1910 return i;
1911}
1912
1913
1914/* This function reads exactly <len> chars from <s> and converts them to a
1915 * signed integer which it stores into <ret>. It accurately detects any error
1916 * (truncated string, invalid chars, overflows). It is meant to be used in
1917 * applications designed for hostile environments. It returns zero when the
1918 * number has successfully been converted, non-zero otherwise. When an error
1919 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1920 * faster than strtol().
1921 */
1922int strl2irc(const char *s, int len, int *ret)
1923{
1924 int i = 0;
1925 int j;
1926
1927 if (!len)
1928 return 1;
1929
1930 if (*s != '-') {
1931 /* positive number */
1932 while (len-- > 0) {
1933 j = (*s++) - '0';
1934 if (j > 9) return 1; /* invalid char */
1935 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1936 i = i * 10;
1937 if (i + j < i) return 1; /* check for addition overflow */
1938 i = i + j;
1939 }
1940 } else {
1941 /* negative number */
1942 s++;
1943 while (--len > 0) {
1944 j = (*s++) - '0';
1945 if (j > 9) return 1; /* invalid char */
1946 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1947 i = i * 10;
1948 if (i - j > i) return 1; /* check for subtract overflow */
1949 i = i - j;
1950 }
1951 }
1952 *ret = i;
1953 return 0;
1954}
1955
1956
1957/* This function reads exactly <len> chars from <s> and converts them to a
1958 * signed integer which it stores into <ret>. It accurately detects any error
1959 * (truncated string, invalid chars, overflows). It is meant to be used in
1960 * applications designed for hostile environments. It returns zero when the
1961 * number has successfully been converted, non-zero otherwise. When an error
1962 * is returned, the <ret> value is left untouched. It is about 3 times slower
1963 * than str2irc().
1964 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001965
1966int strl2llrc(const char *s, int len, long long *ret)
1967{
1968 long long i = 0;
1969 int j;
1970
1971 if (!len)
1972 return 1;
1973
1974 if (*s != '-') {
1975 /* positive number */
1976 while (len-- > 0) {
1977 j = (*s++) - '0';
1978 if (j > 9) return 1; /* invalid char */
1979 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1980 i = i * 10LL;
1981 if (i + j < i) return 1; /* check for addition overflow */
1982 i = i + j;
1983 }
1984 } else {
1985 /* negative number */
1986 s++;
1987 while (--len > 0) {
1988 j = (*s++) - '0';
1989 if (j > 9) return 1; /* invalid char */
1990 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1991 i = i * 10LL;
1992 if (i - j > i) return 1; /* check for subtract overflow */
1993 i = i - j;
1994 }
1995 }
1996 *ret = i;
1997 return 0;
1998}
1999
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002000/* This function is used with pat_parse_dotted_ver(). It converts a string
2001 * composed by two number separated by a dot. Each part must contain in 16 bits
2002 * because internally they will be represented as a 32-bit quantity stored in
2003 * a 64-bit integer. It returns zero when the number has successfully been
2004 * converted, non-zero otherwise. When an error is returned, the <ret> value
2005 * is left untouched.
2006 *
2007 * "1.3" -> 0x0000000000010003
2008 * "65535.65535" -> 0x00000000ffffffff
2009 */
2010int strl2llrc_dotted(const char *text, int len, long long *ret)
2011{
2012 const char *end = &text[len];
2013 const char *p;
2014 long long major, minor;
2015
2016 /* Look for dot. */
2017 for (p = text; p < end; p++)
2018 if (*p == '.')
2019 break;
2020
2021 /* Convert major. */
2022 if (strl2llrc(text, p - text, &major) != 0)
2023 return 1;
2024
2025 /* Check major. */
2026 if (major >= 65536)
2027 return 1;
2028
2029 /* Convert minor. */
2030 minor = 0;
2031 if (p < end)
2032 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2033 return 1;
2034
2035 /* Check minor. */
2036 if (minor >= 65536)
2037 return 1;
2038
2039 /* Compose value. */
2040 *ret = (major << 16) | (minor & 0xffff);
2041 return 0;
2042}
2043
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002044/* This function parses a time value optionally followed by a unit suffix among
2045 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2046 * expected by the caller. The computation does its best to avoid overflows.
2047 * The value is returned in <ret> if everything is fine, and a NULL is returned
2048 * by the function. In case of error, a pointer to the error is returned and
2049 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002050 * Values resulting in values larger than or equal to 2^31 after conversion are
2051 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2052 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002053 */
2054const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2055{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002056 unsigned long long imult, idiv;
2057 unsigned long long omult, odiv;
2058 unsigned long long value, result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002059
2060 omult = odiv = 1;
2061
2062 switch (unit_flags & TIME_UNIT_MASK) {
2063 case TIME_UNIT_US: omult = 1000000; break;
2064 case TIME_UNIT_MS: omult = 1000; break;
2065 case TIME_UNIT_S: break;
2066 case TIME_UNIT_MIN: odiv = 60; break;
2067 case TIME_UNIT_HOUR: odiv = 3600; break;
2068 case TIME_UNIT_DAY: odiv = 86400; break;
2069 default: break;
2070 }
2071
2072 value = 0;
2073
2074 while (1) {
2075 unsigned int j;
2076
2077 j = *text - '0';
2078 if (j > 9)
2079 break;
2080 text++;
2081 value *= 10;
2082 value += j;
2083 }
2084
2085 imult = idiv = 1;
2086 switch (*text) {
2087 case '\0': /* no unit = default unit */
2088 imult = omult = idiv = odiv = 1;
2089 break;
2090 case 's': /* second = unscaled unit */
2091 break;
2092 case 'u': /* microsecond : "us" */
2093 if (text[1] == 's') {
2094 idiv = 1000000;
2095 text++;
2096 }
2097 break;
2098 case 'm': /* millisecond : "ms" or minute: "m" */
2099 if (text[1] == 's') {
2100 idiv = 1000;
2101 text++;
2102 } else
2103 imult = 60;
2104 break;
2105 case 'h': /* hour : "h" */
2106 imult = 3600;
2107 break;
2108 case 'd': /* day : "d" */
2109 imult = 86400;
2110 break;
2111 default:
2112 return text;
2113 break;
2114 }
2115
2116 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2117 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2118 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2119 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2120
Willy Tarreau9faebe32019-06-07 19:00:37 +02002121 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2122 if (result >= 0x80000000)
2123 return PARSE_TIME_OVER;
2124 if (!result && value)
2125 return PARSE_TIME_UNDER;
2126 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002127 return NULL;
2128}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002129
Emeric Brun39132b22010-01-04 14:57:24 +01002130/* this function converts the string starting at <text> to an unsigned int
2131 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002132 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002133 */
2134const char *parse_size_err(const char *text, unsigned *ret) {
2135 unsigned value = 0;
2136
2137 while (1) {
2138 unsigned int j;
2139
2140 j = *text - '0';
2141 if (j > 9)
2142 break;
2143 if (value > ~0U / 10)
2144 return text;
2145 value *= 10;
2146 if (value > (value + j))
2147 return text;
2148 value += j;
2149 text++;
2150 }
2151
2152 switch (*text) {
2153 case '\0':
2154 break;
2155 case 'K':
2156 case 'k':
2157 if (value > ~0U >> 10)
2158 return text;
2159 value = value << 10;
2160 break;
2161 case 'M':
2162 case 'm':
2163 if (value > ~0U >> 20)
2164 return text;
2165 value = value << 20;
2166 break;
2167 case 'G':
2168 case 'g':
2169 if (value > ~0U >> 30)
2170 return text;
2171 value = value << 30;
2172 break;
2173 default:
2174 return text;
2175 }
2176
Godbach58048a22015-01-28 17:36:16 +08002177 if (*text != '\0' && *++text != '\0')
2178 return text;
2179
Emeric Brun39132b22010-01-04 14:57:24 +01002180 *ret = value;
2181 return NULL;
2182}
2183
Willy Tarreau126d4062013-12-03 17:50:47 +01002184/*
2185 * Parse binary string written in hexadecimal (source) and store the decoded
2186 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2187 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002188 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002189 */
2190int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2191{
2192 int len;
2193 const char *p = source;
2194 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002195 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002196
2197 len = strlen(source);
2198 if (len % 2) {
2199 memprintf(err, "an even number of hex digit is expected");
2200 return 0;
2201 }
2202
2203 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002204
Willy Tarreau126d4062013-12-03 17:50:47 +01002205 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002206 *binstr = calloc(len, sizeof(char));
2207 if (!*binstr) {
2208 memprintf(err, "out of memory while loading string pattern");
2209 return 0;
2210 }
2211 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002212 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002213 else {
2214 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002215 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002216 len, *binstrlen);
2217 return 0;
2218 }
2219 alloc = 0;
2220 }
2221 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002222
2223 i = j = 0;
2224 while (j < len) {
2225 if (!ishex(p[i++]))
2226 goto bad_input;
2227 if (!ishex(p[i++]))
2228 goto bad_input;
2229 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2230 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002231 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002232
2233bad_input:
2234 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002235 if (alloc) {
2236 free(*binstr);
2237 *binstr = NULL;
2238 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002239 return 0;
2240}
2241
Willy Tarreau946ba592009-05-10 15:41:18 +02002242/* copies at most <n> characters from <src> and always terminates with '\0' */
2243char *my_strndup(const char *src, int n)
2244{
2245 int len = 0;
2246 char *ret;
2247
2248 while (len < n && src[len])
2249 len++;
2250
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002251 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002252 if (!ret)
2253 return ret;
2254 memcpy(ret, src, len);
2255 ret[len] = '\0';
2256 return ret;
2257}
2258
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002259/*
2260 * search needle in haystack
2261 * returns the pointer if found, returns NULL otherwise
2262 */
2263const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2264{
2265 const void *c = NULL;
2266 unsigned char f;
2267
2268 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2269 return NULL;
2270
2271 f = *(char *)needle;
2272 c = haystack;
2273 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2274 if ((haystacklen - (c - haystack)) < needlelen)
2275 return NULL;
2276
2277 if (memcmp(c, needle, needlelen) == 0)
2278 return c;
2279 ++c;
2280 }
2281 return NULL;
2282}
2283
Willy Tarreau482b00d2009-10-04 22:48:42 +02002284/* This function returns the first unused key greater than or equal to <key> in
2285 * ID tree <root>. Zero is returned if no place is found.
2286 */
2287unsigned int get_next_id(struct eb_root *root, unsigned int key)
2288{
2289 struct eb32_node *used;
2290
2291 do {
2292 used = eb32_lookup_ge(root, key);
2293 if (!used || used->key > key)
2294 return key; /* key is available */
2295 key++;
2296 } while (key);
2297 return key;
2298}
2299
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002300/* dump the full tree to <file> in DOT format for debugging purposes. Will
2301 * optionally highlight node <subj> if found, depending on operation <op> :
2302 * 0 : nothing
2303 * >0 : insertion, node/leaf are surrounded in red
2304 * <0 : removal, node/leaf are dashed with no background
2305 * Will optionally add "desc" as a label on the graph if set and non-null.
2306 */
2307void 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 +01002308{
2309 struct eb32sc_node *node;
2310 unsigned long scope = -1;
2311
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002312 fprintf(file, "digraph ebtree {\n");
2313
2314 if (desc && *desc) {
2315 fprintf(file,
2316 " fontname=\"fixed\";\n"
2317 " fontsize=8;\n"
2318 " label=\"%s\";\n", desc);
2319 }
2320
Willy Tarreaued3cda02017-11-15 15:04:05 +01002321 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002322 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2323 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002324 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2325 );
2326
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002327 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002328 (long)eb_root_to_node(root),
2329 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002330 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2331
2332 node = eb32sc_first(root, scope);
2333 while (node) {
2334 if (node->node.node_p) {
2335 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002336 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2337 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2338 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002339
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002340 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002341 (long)node,
2342 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002343 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002344
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002345 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002346 (long)node,
2347 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002348 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2349
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002350 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002351 (long)node,
2352 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002353 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2354 }
2355
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002356 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2357 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2358 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002359
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002360 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002361 (long)node,
2362 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002363 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002364 node = eb32sc_next(node, scope);
2365 }
2366 fprintf(file, "}\n");
2367}
2368
Willy Tarreau348238b2010-01-18 15:05:57 +01002369/* This function compares a sample word possibly followed by blanks to another
2370 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2371 * otherwise zero. This intends to be used when checking HTTP headers for some
2372 * values. Note that it validates a word followed only by blanks but does not
2373 * validate a word followed by blanks then other chars.
2374 */
2375int word_match(const char *sample, int slen, const char *word, int wlen)
2376{
2377 if (slen < wlen)
2378 return 0;
2379
2380 while (wlen) {
2381 char c = *sample ^ *word;
2382 if (c && c != ('A' ^ 'a'))
2383 return 0;
2384 sample++;
2385 word++;
2386 slen--;
2387 wlen--;
2388 }
2389
2390 while (slen) {
2391 if (*sample != ' ' && *sample != '\t')
2392 return 0;
2393 sample++;
2394 slen--;
2395 }
2396 return 1;
2397}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002398
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002399/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2400 * is particularly fast because it avoids expensive operations such as
2401 * multiplies, which are optimized away at the end. It requires a properly
2402 * formated address though (3 points).
2403 */
2404unsigned int inetaddr_host(const char *text)
2405{
2406 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2407 register unsigned int dig100, dig10, dig1;
2408 int s;
2409 const char *p, *d;
2410
2411 dig1 = dig10 = dig100 = ascii_zero;
2412 s = 24;
2413
2414 p = text;
2415 while (1) {
2416 if (((unsigned)(*p - '0')) <= 9) {
2417 p++;
2418 continue;
2419 }
2420
2421 /* here, we have a complete byte between <text> and <p> (exclusive) */
2422 if (p == text)
2423 goto end;
2424
2425 d = p - 1;
2426 dig1 |= (unsigned int)(*d << s);
2427 if (d == text)
2428 goto end;
2429
2430 d--;
2431 dig10 |= (unsigned int)(*d << s);
2432 if (d == text)
2433 goto end;
2434
2435 d--;
2436 dig100 |= (unsigned int)(*d << s);
2437 end:
2438 if (!s || *p != '.')
2439 break;
2440
2441 s -= 8;
2442 text = ++p;
2443 }
2444
2445 dig100 -= ascii_zero;
2446 dig10 -= ascii_zero;
2447 dig1 -= ascii_zero;
2448 return ((dig100 * 10) + dig10) * 10 + dig1;
2449}
2450
2451/*
2452 * Idem except the first unparsed character has to be passed in <stop>.
2453 */
2454unsigned int inetaddr_host_lim(const char *text, const char *stop)
2455{
2456 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2457 register unsigned int dig100, dig10, dig1;
2458 int s;
2459 const char *p, *d;
2460
2461 dig1 = dig10 = dig100 = ascii_zero;
2462 s = 24;
2463
2464 p = text;
2465 while (1) {
2466 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2467 p++;
2468 continue;
2469 }
2470
2471 /* here, we have a complete byte between <text> and <p> (exclusive) */
2472 if (p == text)
2473 goto end;
2474
2475 d = p - 1;
2476 dig1 |= (unsigned int)(*d << s);
2477 if (d == text)
2478 goto end;
2479
2480 d--;
2481 dig10 |= (unsigned int)(*d << s);
2482 if (d == text)
2483 goto end;
2484
2485 d--;
2486 dig100 |= (unsigned int)(*d << s);
2487 end:
2488 if (!s || p == stop || *p != '.')
2489 break;
2490
2491 s -= 8;
2492 text = ++p;
2493 }
2494
2495 dig100 -= ascii_zero;
2496 dig10 -= ascii_zero;
2497 dig1 -= ascii_zero;
2498 return ((dig100 * 10) + dig10) * 10 + dig1;
2499}
2500
2501/*
2502 * Idem except the pointer to first unparsed byte is returned into <ret> which
2503 * must not be NULL.
2504 */
Willy Tarreau74172752010-10-15 23:21:42 +02002505unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002506{
2507 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2508 register unsigned int dig100, dig10, dig1;
2509 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002510 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002511
2512 dig1 = dig10 = dig100 = ascii_zero;
2513 s = 24;
2514
2515 p = text;
2516 while (1) {
2517 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2518 p++;
2519 continue;
2520 }
2521
2522 /* here, we have a complete byte between <text> and <p> (exclusive) */
2523 if (p == text)
2524 goto end;
2525
2526 d = p - 1;
2527 dig1 |= (unsigned int)(*d << s);
2528 if (d == text)
2529 goto end;
2530
2531 d--;
2532 dig10 |= (unsigned int)(*d << s);
2533 if (d == text)
2534 goto end;
2535
2536 d--;
2537 dig100 |= (unsigned int)(*d << s);
2538 end:
2539 if (!s || p == stop || *p != '.')
2540 break;
2541
2542 s -= 8;
2543 text = ++p;
2544 }
2545
2546 *ret = p;
2547 dig100 -= ascii_zero;
2548 dig10 -= ascii_zero;
2549 dig1 -= ascii_zero;
2550 return ((dig100 * 10) + dig10) * 10 + dig1;
2551}
2552
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002553/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2554 * or the number of chars read in case of success. Maybe this could be replaced
2555 * by one of the functions above. Also, apparently this function does not support
2556 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002557 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002558 */
2559int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2560{
2561 const char *addr;
2562 int saw_digit, octets, ch;
2563 u_char tmp[4], *tp;
2564 const char *cp = buf;
2565
2566 saw_digit = 0;
2567 octets = 0;
2568 *(tp = tmp) = 0;
2569
2570 for (addr = buf; addr - buf < len; addr++) {
2571 unsigned char digit = (ch = *addr) - '0';
2572
2573 if (digit > 9 && ch != '.')
2574 break;
2575
2576 if (digit <= 9) {
2577 u_int new = *tp * 10 + digit;
2578
2579 if (new > 255)
2580 return 0;
2581
2582 *tp = new;
2583
2584 if (!saw_digit) {
2585 if (++octets > 4)
2586 return 0;
2587 saw_digit = 1;
2588 }
2589 } else if (ch == '.' && saw_digit) {
2590 if (octets == 4)
2591 return 0;
2592
2593 *++tp = 0;
2594 saw_digit = 0;
2595 } else
2596 return 0;
2597 }
2598
2599 if (octets < 4)
2600 return 0;
2601
2602 memcpy(&dst->s_addr, tmp, 4);
2603 return addr - cp;
2604}
2605
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002606/* This function converts the string in <buf> of the len <len> to
2607 * struct in6_addr <dst> which must be allocated by the caller.
2608 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002609 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002610 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002611int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2612{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002613 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002614 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002615
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002616 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002617 return 0;
2618
2619 memcpy(null_term_ip6, buf, len);
2620 null_term_ip6[len] = '\0';
2621
Willy Tarreau075415a2013-12-12 11:29:39 +01002622 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002623 return 0;
2624
Willy Tarreau075415a2013-12-12 11:29:39 +01002625 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002626 return 1;
2627}
2628
Willy Tarreauacf95772010-06-14 19:09:21 +02002629/* To be used to quote config arg positions. Returns the short string at <ptr>
2630 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2631 * if ptr is NULL or empty. The string is locally allocated.
2632 */
2633const char *quote_arg(const char *ptr)
2634{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002635 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002636 int i;
2637
2638 if (!ptr || !*ptr)
2639 return "end of line";
2640 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002641 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002642 val[i] = *ptr++;
2643 val[i++] = '\'';
2644 val[i] = '\0';
2645 return val;
2646}
2647
Willy Tarreau5b180202010-07-18 10:40:48 +02002648/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2649int get_std_op(const char *str)
2650{
2651 int ret = -1;
2652
2653 if (*str == 'e' && str[1] == 'q')
2654 ret = STD_OP_EQ;
2655 else if (*str == 'n' && str[1] == 'e')
2656 ret = STD_OP_NE;
2657 else if (*str == 'l') {
2658 if (str[1] == 'e') ret = STD_OP_LE;
2659 else if (str[1] == 't') ret = STD_OP_LT;
2660 }
2661 else if (*str == 'g') {
2662 if (str[1] == 'e') ret = STD_OP_GE;
2663 else if (str[1] == 't') ret = STD_OP_GT;
2664 }
2665
2666 if (ret == -1 || str[2] != '\0')
2667 return -1;
2668 return ret;
2669}
2670
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002671/* hash a 32-bit integer to another 32-bit integer */
2672unsigned int full_hash(unsigned int a)
2673{
2674 return __full_hash(a);
2675}
2676
Willy Tarreauf3241112019-02-26 09:56:22 +01002677/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2678 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2679 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2680 * a popcount variant and is described here :
2681 * https://graphics.stanford.edu/~seander/bithacks.html
2682 */
2683unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2684{
2685 unsigned long a, b, c, d;
2686 unsigned int s;
2687 unsigned int t;
2688
2689 a = m - ((m >> 1) & ~0UL/3);
2690 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2691 c = (b + (b >> 4)) & ~0UL/0x11;
2692 d = (c + (c >> 8)) & ~0UL/0x101;
2693
2694 r++; // make r be 1..64
2695
2696 t = 0;
2697 s = LONGBITS;
2698 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002699 unsigned long d2 = (d >> 16) >> 16;
2700 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002701 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2702 }
2703
2704 t = (d >> (s - 16)) & 0xff;
2705 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2706 t = (c >> (s - 8)) & 0xf;
2707 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2708 t = (b >> (s - 4)) & 0x7;
2709 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2710 t = (a >> (s - 2)) & 0x3;
2711 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2712 t = (m >> (s - 1)) & 0x1;
2713 s -= ((t - r) & 256) >> 8;
2714
2715 return s - 1;
2716}
2717
2718/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2719 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2720 * using mask_prep_rank_map() below.
2721 */
2722unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2723 unsigned long a, unsigned long b,
2724 unsigned long c, unsigned long d)
2725{
2726 unsigned int s;
2727 unsigned int t;
2728
2729 r++; // make r be 1..64
2730
2731 t = 0;
2732 s = LONGBITS;
2733 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002734 unsigned long d2 = (d >> 16) >> 16;
2735 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002736 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2737 }
2738
2739 t = (d >> (s - 16)) & 0xff;
2740 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2741 t = (c >> (s - 8)) & 0xf;
2742 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2743 t = (b >> (s - 4)) & 0x7;
2744 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2745 t = (a >> (s - 2)) & 0x3;
2746 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2747 t = (m >> (s - 1)) & 0x1;
2748 s -= ((t - r) & 256) >> 8;
2749
2750 return s - 1;
2751}
2752
2753/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2754 * above.
2755 */
2756void mask_prep_rank_map(unsigned long m,
2757 unsigned long *a, unsigned long *b,
2758 unsigned long *c, unsigned long *d)
2759{
2760 *a = m - ((m >> 1) & ~0UL/3);
2761 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2762 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2763 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2764}
2765
David du Colombier4f92d322011-03-24 11:09:31 +01002766/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002767 * otherwise zero. Note that <addr> may not necessarily be aligned
2768 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002769 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002770int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002771{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002772 struct in_addr addr_copy;
2773
2774 memcpy(&addr_copy, addr, sizeof(addr_copy));
2775 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002776}
2777
2778/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002779 * otherwise zero. Note that <addr> may not necessarily be aligned
2780 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002781 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002782int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002783{
2784 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002785 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002786
Willy Tarreaueec1d382016-07-13 11:59:39 +02002787 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002788 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002789 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002790 (((int *)net)[i] & ((int *)mask)[i]))
2791 return 0;
2792 return 1;
2793}
2794
2795/* RFC 4291 prefix */
2796const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2797 0x00, 0x00, 0x00, 0x00,
2798 0x00, 0x00, 0xFF, 0xFF };
2799
Joseph Herlant32b83272018-11-15 11:58:28 -08002800/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002801 * Input and output may overlap.
2802 */
David du Colombier4f92d322011-03-24 11:09:31 +01002803void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2804{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002805 struct in_addr tmp_addr;
2806
2807 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002808 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002809 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002810}
2811
Joseph Herlant32b83272018-11-15 11:58:28 -08002812/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002813 * Return true if conversion is possible and false otherwise.
2814 */
2815int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2816{
2817 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2818 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2819 sizeof(struct in_addr));
2820 return 1;
2821 }
2822
2823 return 0;
2824}
2825
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002826/* compare two struct sockaddr_storage and return:
2827 * 0 (true) if the addr is the same in both
2828 * 1 (false) if the addr is not the same in both
2829 * -1 (unable) if one of the addr is not AF_INET*
2830 */
2831int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2832{
2833 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2834 return -1;
2835
2836 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2837 return -1;
2838
2839 if (ss1->ss_family != ss2->ss_family)
2840 return 1;
2841
2842 switch (ss1->ss_family) {
2843 case AF_INET:
2844 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2845 &((struct sockaddr_in *)ss2)->sin_addr,
2846 sizeof(struct in_addr)) != 0;
2847 case AF_INET6:
2848 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2849 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2850 sizeof(struct in6_addr)) != 0;
2851 }
2852
2853 return 1;
2854}
2855
Baptiste Assmann08396c82016-01-31 00:27:17 +01002856/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002857 * The caller must allocate and clear <dest> before calling.
2858 * The source must be in either AF_INET or AF_INET6 family, or the destination
2859 * address will be undefined. If the destination address used to hold a port,
2860 * it is preserved, so that this function can be used to switch to another
2861 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002862 */
2863struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2864{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002865 int prev_port;
2866
2867 prev_port = get_net_port(dest);
2868 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002869 dest->ss_family = source->ss_family;
2870
2871 /* copy new addr and apply it */
2872 switch (source->ss_family) {
2873 case AF_INET:
2874 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002875 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002876 break;
2877 case AF_INET6:
2878 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 +01002879 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002880 break;
2881 }
2882
2883 return dest;
2884}
2885
William Lallemand421f5b52012-02-06 18:15:57 +01002886char *human_time(int t, short hz_div) {
2887 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2888 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002889 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002890 int cnt=2; // print two numbers
2891
2892 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002893 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002894 return rv;
2895 }
2896
2897 if (unlikely(hz_div > 1))
2898 t /= hz_div;
2899
2900 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002901 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002902 cnt--;
2903 }
2904
2905 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002906 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002907 cnt--;
2908 }
2909
2910 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002911 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002912 cnt--;
2913 }
2914
2915 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002916 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002917
2918 return rv;
2919}
2920
2921const char *monthname[12] = {
2922 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2923 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2924};
2925
2926/* date2str_log: write a date in the format :
2927 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2928 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2929 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2930 *
2931 * without using sprintf. return a pointer to the last char written (\0) or
2932 * NULL if there isn't enough space.
2933 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002934char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002935{
2936
2937 if (size < 25) /* the size is fixed: 24 chars + \0 */
2938 return NULL;
2939
2940 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
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 memcpy(dst, monthname[tm->tm_mon], 3); // month
2946 dst += 3;
2947 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002948
William Lallemand421f5b52012-02-06 18:15:57 +01002949 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002950 if (!dst)
2951 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002952 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002953
William Lallemand421f5b52012-02-06 18:15:57 +01002954 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002955 if (!dst)
2956 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002957 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002958
William Lallemand421f5b52012-02-06 18:15:57 +01002959 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002960 if (!dst)
2961 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002962 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002963
William Lallemand421f5b52012-02-06 18:15:57 +01002964 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002965 if (!dst)
2966 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002967 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002968
Willy Tarreau7d9421d2020-02-29 09:08:02 +01002969 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002970 if (!dst)
2971 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002972 *dst = '\0';
2973
2974 return dst;
2975}
2976
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002977/* Base year used to compute leap years */
2978#define TM_YEAR_BASE 1900
2979
2980/* Return the difference in seconds between two times (leap seconds are ignored).
2981 * Retrieved from glibc 2.18 source code.
2982 */
2983static int my_tm_diff(const struct tm *a, const struct tm *b)
2984{
2985 /* Compute intervening leap days correctly even if year is negative.
2986 * Take care to avoid int overflow in leap day calculations,
2987 * but it's OK to assume that A and B are close to each other.
2988 */
2989 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2990 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2991 int a100 = a4 / 25 - (a4 % 25 < 0);
2992 int b100 = b4 / 25 - (b4 % 25 < 0);
2993 int a400 = a100 >> 2;
2994 int b400 = b100 >> 2;
2995 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2996 int years = a->tm_year - b->tm_year;
2997 int days = (365 * years + intervening_leap_days
2998 + (a->tm_yday - b->tm_yday));
2999 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3000 + (a->tm_min - b->tm_min))
3001 + (a->tm_sec - b->tm_sec));
3002}
3003
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003004/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003005 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003006 * The string returned has the same format as returned by strftime(... "%z", tm).
3007 * Offsets are kept in an internal cache for better performances.
3008 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003009const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003010{
3011 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003012 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003013
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003014 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003015 struct tm tm_gmt;
3016 int diff;
3017 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003018
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003019 /* Pretend DST not active if its status is unknown */
3020 if (isdst < 0)
3021 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003022
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003023 /* Fetch the offset and initialize it if needed */
3024 gmt_offset = gmt_offsets[isdst & 0x01];
3025 if (unlikely(!*gmt_offset)) {
3026 get_gmtime(t, &tm_gmt);
3027 diff = my_tm_diff(tm, &tm_gmt);
3028 if (diff < 0) {
3029 diff = -diff;
3030 *gmt_offset = '-';
3031 } else {
3032 *gmt_offset = '+';
3033 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003034 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003035 diff /= 60; /* Convert to minutes */
3036 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3037 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003038
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003039 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003040}
3041
William Lallemand421f5b52012-02-06 18:15:57 +01003042/* gmt2str_log: write a date in the format :
3043 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3044 * return a pointer to the last char written (\0) or
3045 * NULL if there isn't enough space.
3046 */
3047char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3048{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003049 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003050 return NULL;
3051
3052 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003053 if (!dst)
3054 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003055 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003056
William Lallemand421f5b52012-02-06 18:15:57 +01003057 memcpy(dst, monthname[tm->tm_mon], 3); // month
3058 dst += 3;
3059 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003060
William Lallemand421f5b52012-02-06 18:15:57 +01003061 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003062 if (!dst)
3063 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003064 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003065
William Lallemand421f5b52012-02-06 18:15:57 +01003066 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003067 if (!dst)
3068 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003069 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003070
William Lallemand421f5b52012-02-06 18:15:57 +01003071 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003072 if (!dst)
3073 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003074 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003075
William Lallemand421f5b52012-02-06 18:15:57 +01003076 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003077 if (!dst)
3078 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003079 *dst++ = ' ';
3080 *dst++ = '+';
3081 *dst++ = '0';
3082 *dst++ = '0';
3083 *dst++ = '0';
3084 *dst++ = '0';
3085 *dst = '\0';
3086
3087 return dst;
3088}
3089
Yuxans Yao4e25b012012-10-19 10:36:09 +08003090/* localdate2str_log: write a date in the format :
3091 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003092 * Both t and tm must represent the same time.
3093 * return a pointer to the last char written (\0) or
3094 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003095 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003096char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003097{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003098 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003099 if (size < 27) /* the size is fixed: 26 chars + \0 */
3100 return NULL;
3101
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003102 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003103
Yuxans Yao4e25b012012-10-19 10:36:09 +08003104 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
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
Yuxans Yao4e25b012012-10-19 10:36:09 +08003109 memcpy(dst, monthname[tm->tm_mon], 3); // month
3110 dst += 3;
3111 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003112
Yuxans Yao4e25b012012-10-19 10:36:09 +08003113 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003114 if (!dst)
3115 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003116 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003117
Yuxans Yao4e25b012012-10-19 10:36:09 +08003118 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003119 if (!dst)
3120 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003121 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003122
Yuxans Yao4e25b012012-10-19 10:36:09 +08003123 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003124 if (!dst)
3125 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003126 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003127
Yuxans Yao4e25b012012-10-19 10:36:09 +08003128 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003129 if (!dst)
3130 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003131 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003132
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003133 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003134 dst += 5;
3135 *dst = '\0';
3136
3137 return dst;
3138}
3139
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003140/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3141 * It is meant as a portable replacement for timegm() for use with valid inputs.
3142 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3143 */
3144time_t my_timegm(const struct tm *tm)
3145{
3146 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3147 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3148 * sum of the extra N days for elapsed months. The sum of all these N
3149 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3150 * in a 5-bit word. This means that with 60 bits we can represent a
3151 * matrix of all these values at once, which is fast and efficient to
3152 * access. The extra February day for leap years is not counted here.
3153 *
3154 * Jan : none = 0 (0)
3155 * Feb : Jan = 3 (3)
3156 * Mar : Jan..Feb = 3 (3 + 0)
3157 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3158 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3159 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3160 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3161 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3162 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3163 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3164 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3165 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3166 */
3167 uint64_t extra =
3168 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3169 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3170 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3171 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3172
3173 unsigned int y = tm->tm_year + 1900;
3174 unsigned int m = tm->tm_mon;
3175 unsigned long days = 0;
3176
3177 /* days since 1/1/1970 for full years */
3178 days += days_since_zero(y) - days_since_zero(1970);
3179
3180 /* days for full months in the current year */
3181 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3182
3183 /* count + 1 after March for leap years. A leap year is a year multiple
3184 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3185 * is leap, 1900 isn't, 1904 is.
3186 */
3187 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3188 days++;
3189
3190 days += tm->tm_mday - 1;
3191 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3192}
3193
Thierry Fournier93127942016-01-20 18:49:45 +01003194/* This function check a char. It returns true and updates
3195 * <date> and <len> pointer to the new position if the
3196 * character is found.
3197 */
3198static inline int parse_expect_char(const char **date, int *len, char c)
3199{
3200 if (*len < 1 || **date != c)
3201 return 0;
3202 (*len)--;
3203 (*date)++;
3204 return 1;
3205}
3206
3207/* This function expects a string <str> of len <l>. It return true and updates.
3208 * <date> and <len> if the string matches, otherwise, it returns false.
3209 */
3210static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3211{
3212 if (*len < l || strncmp(*date, str, l) != 0)
3213 return 0;
3214 (*len) -= l;
3215 (*date) += l;
3216 return 1;
3217}
3218
3219/* This macro converts 3 chars name in integer. */
3220#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3221
3222/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3223 * / %x54.75.65 ; "Tue", case-sensitive
3224 * / %x57.65.64 ; "Wed", case-sensitive
3225 * / %x54.68.75 ; "Thu", case-sensitive
3226 * / %x46.72.69 ; "Fri", case-sensitive
3227 * / %x53.61.74 ; "Sat", case-sensitive
3228 * / %x53.75.6E ; "Sun", case-sensitive
3229 *
3230 * This array must be alphabetically sorted
3231 */
3232static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3233{
3234 if (*len < 3)
3235 return 0;
3236 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3237 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3238 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3239 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3240 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3241 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3242 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3243 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3244 default: return 0;
3245 }
3246 *len -= 3;
3247 *date += 3;
3248 return 1;
3249}
3250
3251/* month = %x4A.61.6E ; "Jan", case-sensitive
3252 * / %x46.65.62 ; "Feb", case-sensitive
3253 * / %x4D.61.72 ; "Mar", case-sensitive
3254 * / %x41.70.72 ; "Apr", case-sensitive
3255 * / %x4D.61.79 ; "May", case-sensitive
3256 * / %x4A.75.6E ; "Jun", case-sensitive
3257 * / %x4A.75.6C ; "Jul", case-sensitive
3258 * / %x41.75.67 ; "Aug", case-sensitive
3259 * / %x53.65.70 ; "Sep", case-sensitive
3260 * / %x4F.63.74 ; "Oct", case-sensitive
3261 * / %x4E.6F.76 ; "Nov", case-sensitive
3262 * / %x44.65.63 ; "Dec", case-sensitive
3263 *
3264 * This array must be alphabetically sorted
3265 */
3266static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3267{
3268 if (*len < 3)
3269 return 0;
3270 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3271 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3272 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3273 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3274 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3275 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3276 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3277 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3278 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3279 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3280 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3281 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3282 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3283 default: return 0;
3284 }
3285 *len -= 3;
3286 *date += 3;
3287 return 1;
3288}
3289
3290/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3291 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3292 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3293 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3294 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3295 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3296 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3297 *
3298 * This array must be alphabetically sorted
3299 */
3300static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3301{
3302 if (*len < 6) /* Minimum length. */
3303 return 0;
3304 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3305 case STR2I3('M','o','n'):
3306 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3307 tm->tm_wday = 1;
3308 return 1;
3309 case STR2I3('T','u','e'):
3310 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3311 tm->tm_wday = 2;
3312 return 1;
3313 case STR2I3('W','e','d'):
3314 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3315 tm->tm_wday = 3;
3316 return 1;
3317 case STR2I3('T','h','u'):
3318 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3319 tm->tm_wday = 4;
3320 return 1;
3321 case STR2I3('F','r','i'):
3322 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3323 tm->tm_wday = 5;
3324 return 1;
3325 case STR2I3('S','a','t'):
3326 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3327 tm->tm_wday = 6;
3328 return 1;
3329 case STR2I3('S','u','n'):
3330 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3331 tm->tm_wday = 7;
3332 return 1;
3333 }
3334 return 0;
3335}
3336
3337/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3338static inline int parse_digit(const char **date, int *len, int *digit)
3339{
3340 if (*len < 1 || **date < '0' || **date > '9')
3341 return 0;
3342 *digit = (**date - '0');
3343 (*date)++;
3344 (*len)--;
3345 return 1;
3346}
3347
3348/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3349static inline int parse_2digit(const char **date, int *len, int *digit)
3350{
3351 int value;
3352
3353 RET0_UNLESS(parse_digit(date, len, &value));
3354 (*digit) = value * 10;
3355 RET0_UNLESS(parse_digit(date, len, &value));
3356 (*digit) += value;
3357
3358 return 1;
3359}
3360
3361/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3362static inline int parse_4digit(const char **date, int *len, int *digit)
3363{
3364 int value;
3365
3366 RET0_UNLESS(parse_digit(date, len, &value));
3367 (*digit) = value * 1000;
3368
3369 RET0_UNLESS(parse_digit(date, len, &value));
3370 (*digit) += value * 100;
3371
3372 RET0_UNLESS(parse_digit(date, len, &value));
3373 (*digit) += value * 10;
3374
3375 RET0_UNLESS(parse_digit(date, len, &value));
3376 (*digit) += value;
3377
3378 return 1;
3379}
3380
3381/* time-of-day = hour ":" minute ":" second
3382 * ; 00:00:00 - 23:59:60 (leap second)
3383 *
3384 * hour = 2DIGIT
3385 * minute = 2DIGIT
3386 * second = 2DIGIT
3387 */
3388static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3389{
3390 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3391 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3392 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3393 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3394 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3395 return 1;
3396}
3397
3398/* From RFC7231
3399 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3400 *
3401 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3402 * ; fixed length/zone/capitalization subset of the format
3403 * ; see Section 3.3 of [RFC5322]
3404 *
3405 *
3406 * date1 = day SP month SP year
3407 * ; e.g., 02 Jun 1982
3408 *
3409 * day = 2DIGIT
3410 * year = 4DIGIT
3411 *
3412 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3413 *
3414 * time-of-day = hour ":" minute ":" second
3415 * ; 00:00:00 - 23:59:60 (leap second)
3416 *
3417 * hour = 2DIGIT
3418 * minute = 2DIGIT
3419 * second = 2DIGIT
3420 *
3421 * DIGIT = decimal 0-9
3422 */
3423int parse_imf_date(const char *date, int len, struct tm *tm)
3424{
David Carlier327298c2016-11-20 10:42:38 +00003425 /* tm_gmtoff, if present, ought to be zero'ed */
3426 memset(tm, 0, sizeof(*tm));
3427
Thierry Fournier93127942016-01-20 18:49:45 +01003428 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3429 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3430 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3431 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3432 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3433 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3434 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3435 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3436 tm->tm_year -= 1900;
3437 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3438 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3439 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3440 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3441 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003442 return 1;
3443}
3444
3445/* From RFC7231
3446 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3447 *
3448 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3449 * date2 = day "-" month "-" 2DIGIT
3450 * ; e.g., 02-Jun-82
3451 *
3452 * day = 2DIGIT
3453 */
3454int parse_rfc850_date(const char *date, int len, struct tm *tm)
3455{
3456 int year;
3457
David Carlier327298c2016-11-20 10:42:38 +00003458 /* tm_gmtoff, if present, ought to be zero'ed */
3459 memset(tm, 0, sizeof(*tm));
3460
Thierry Fournier93127942016-01-20 18:49:45 +01003461 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3462 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3463 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3464 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3465 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3466 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3467 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3468
3469 /* year = 2DIGIT
3470 *
3471 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3472 * two-digit year, MUST interpret a timestamp that appears to be more
3473 * than 50 years in the future as representing the most recent year in
3474 * the past that had the same last two digits.
3475 */
3476 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3477
3478 /* expect SP */
3479 if (!parse_expect_char(&date, &len, ' ')) {
3480 /* Maybe we have the date with 4 digits. */
3481 RET0_UNLESS(parse_2digit(&date, &len, &year));
3482 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3483 /* expect SP */
3484 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3485 } else {
3486 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3487 * tm_year is the number of year since 1900, so for +1900, we
3488 * do nothing, and for +2000, we add 100.
3489 */
3490 if (tm->tm_year <= 60)
3491 tm->tm_year += 100;
3492 }
3493
3494 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3495 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3496 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3497 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003498
3499 return 1;
3500}
3501
3502/* From RFC7231
3503 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3504 *
3505 * asctime-date = day-name SP date3 SP time-of-day SP year
3506 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3507 * ; e.g., Jun 2
3508 *
3509 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3510 * whitespace in an HTTP-date beyond that specifically included as SP in
3511 * the grammar.
3512 */
3513int parse_asctime_date(const char *date, int len, struct tm *tm)
3514{
David Carlier327298c2016-11-20 10:42:38 +00003515 /* tm_gmtoff, if present, ought to be zero'ed */
3516 memset(tm, 0, sizeof(*tm));
3517
Thierry Fournier93127942016-01-20 18:49:45 +01003518 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3519 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3520 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3521 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3522
3523 /* expect SP and 1DIGIT or 2DIGIT */
3524 if (parse_expect_char(&date, &len, ' '))
3525 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3526 else
3527 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3528
3529 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3530 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3531 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3532 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3533 tm->tm_year -= 1900;
3534 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003535 return 1;
3536}
3537
3538/* From RFC7231
3539 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3540 *
3541 * HTTP-date = IMF-fixdate / obs-date
3542 * obs-date = rfc850-date / asctime-date
3543 *
3544 * parses an HTTP date in the RFC format and is accepted
3545 * alternatives. <date> is the strinf containing the date,
3546 * len is the len of the string. <tm> is filled with the
3547 * parsed time. We must considers this time as GMT.
3548 */
3549int parse_http_date(const char *date, int len, struct tm *tm)
3550{
3551 if (parse_imf_date(date, len, tm))
3552 return 1;
3553
3554 if (parse_rfc850_date(date, len, tm))
3555 return 1;
3556
3557 if (parse_asctime_date(date, len, tm))
3558 return 1;
3559
3560 return 0;
3561}
3562
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003563/* Dynamically allocates a string of the proper length to hold the formatted
3564 * output. NULL is returned on error. The caller is responsible for freeing the
3565 * memory area using free(). The resulting string is returned in <out> if the
3566 * pointer is not NULL. A previous version of <out> might be used to build the
3567 * new string, and it will be freed before returning if it is not NULL, which
3568 * makes it possible to build complex strings from iterative calls without
3569 * having to care about freeing intermediate values, as in the example below :
3570 *
3571 * memprintf(&err, "invalid argument: '%s'", arg);
3572 * ...
3573 * memprintf(&err, "parser said : <%s>\n", *err);
3574 * ...
3575 * free(*err);
3576 *
3577 * This means that <err> must be initialized to NULL before first invocation.
3578 * The return value also holds the allocated string, which eases error checking
3579 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003580 * passed instead and it will be ignored. The returned message will then also
3581 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003582 *
3583 * It is also convenient to use it without any free except the last one :
3584 * err = NULL;
3585 * if (!fct1(err)) report(*err);
3586 * if (!fct2(err)) report(*err);
3587 * if (!fct3(err)) report(*err);
3588 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003589 *
3590 * memprintf relies on memvprintf. This last version can be called from any
3591 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003592 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003593char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003594{
3595 va_list args;
3596 char *ret = NULL;
3597 int allocated = 0;
3598 int needed = 0;
3599
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003600 if (!out)
3601 return NULL;
3602
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003603 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003604 char buf1;
3605
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003606 /* vsnprintf() will return the required length even when the
3607 * target buffer is NULL. We do this in a loop just in case
3608 * intermediate evaluations get wrong.
3609 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003610 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003611 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003612 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003613 if (needed < allocated) {
3614 /* Note: on Solaris 8, the first iteration always
3615 * returns -1 if allocated is zero, so we force a
3616 * retry.
3617 */
3618 if (!allocated)
3619 needed = 0;
3620 else
3621 break;
3622 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003623
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003624 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003625 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003626 } while (ret);
3627
3628 if (needed < 0) {
3629 /* an error was encountered */
3630 free(ret);
3631 ret = NULL;
3632 }
3633
3634 if (out) {
3635 free(*out);
3636 *out = ret;
3637 }
3638
3639 return ret;
3640}
William Lallemand421f5b52012-02-06 18:15:57 +01003641
Christopher Faulet93a518f2017-10-24 11:25:33 +02003642char *memprintf(char **out, const char *format, ...)
3643{
3644 va_list args;
3645 char *ret = NULL;
3646
3647 va_start(args, format);
3648 ret = memvprintf(out, format, args);
3649 va_end(args);
3650
3651 return ret;
3652}
3653
Willy Tarreau21c705b2012-09-14 11:40:36 +02003654/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3655 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003656 * freed by the caller. It also supports being passed a NULL which results in the same
3657 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003658 * Example of use :
3659 * parse(cmd, &err); (callee: memprintf(&err, ...))
3660 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3661 * free(err);
3662 */
3663char *indent_msg(char **out, int level)
3664{
3665 char *ret, *in, *p;
3666 int needed = 0;
3667 int lf = 0;
3668 int lastlf = 0;
3669 int len;
3670
Willy Tarreau70eec382012-10-10 08:56:47 +02003671 if (!out || !*out)
3672 return NULL;
3673
Willy Tarreau21c705b2012-09-14 11:40:36 +02003674 in = *out - 1;
3675 while ((in = strchr(in + 1, '\n')) != NULL) {
3676 lastlf = in - *out;
3677 lf++;
3678 }
3679
3680 if (!lf) /* single line, no LF, return it as-is */
3681 return *out;
3682
3683 len = strlen(*out);
3684
3685 if (lf == 1 && lastlf == len - 1) {
3686 /* single line, LF at end, strip it and return as-is */
3687 (*out)[lastlf] = 0;
3688 return *out;
3689 }
3690
3691 /* OK now we have at least one LF, we need to process the whole string
3692 * as a multi-line string. What we'll do :
3693 * - prefix with an LF if there is none
3694 * - add <level> spaces before each line
3695 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3696 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3697 */
3698
3699 needed = 1 + level * (lf + 1) + len + 1;
3700 p = ret = malloc(needed);
3701 in = *out;
3702
3703 /* skip initial LFs */
3704 while (*in == '\n')
3705 in++;
3706
3707 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3708 while (*in) {
3709 *p++ = '\n';
3710 memset(p, ' ', level);
3711 p += level;
3712 do {
3713 *p++ = *in++;
3714 } while (*in && *in != '\n');
3715 if (*in)
3716 in++;
3717 }
3718 *p = 0;
3719
3720 free(*out);
3721 *out = ret;
3722
3723 return ret;
3724}
3725
Willy Tarreaua2c99112019-08-21 13:17:37 +02003726/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3727 * and end of lines replaced with <eol> if not 0. The first line to indent has
3728 * to be indicated in <first> (starts at zero), so that it is possible to skip
3729 * indenting the first line if it has to be appended after an existing message.
3730 * Empty strings are never indented, and NULL strings are considered empty both
3731 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3732 * character, non-zero otherwise.
3733 */
3734int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3735{
3736 int bol, lf;
3737 int pfxlen = pfx ? strlen(pfx) : 0;
3738
3739 if (!in)
3740 return 0;
3741
3742 bol = 1;
3743 lf = 0;
3744 while (*in) {
3745 if (bol && pfxlen) {
3746 if (first > 0)
3747 first--;
3748 else
3749 b_putblk(out, pfx, pfxlen);
3750 bol = 0;
3751 }
3752
3753 lf = (*in == '\n');
3754 bol |= lf;
3755 b_putchr(out, (lf && eol) ? eol : *in);
3756 in++;
3757 }
3758 return lf;
3759}
3760
Willy Tarreau9d22e562019-03-29 18:49:09 +01003761/* removes environment variable <name> from the environment as found in
3762 * environ. This is only provided as an alternative for systems without
3763 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
3764 * The principle is to scan environ for each occurence of variable name
3765 * <name> and to replace the matching pointers with the last pointer of
3766 * the array (since variables are not ordered).
3767 * It always returns 0 (success).
3768 */
3769int my_unsetenv(const char *name)
3770{
3771 extern char **environ;
3772 char **p = environ;
3773 int vars;
3774 int next;
3775 int len;
3776
3777 len = strlen(name);
3778 for (vars = 0; p[vars]; vars++)
3779 ;
3780 next = 0;
3781 while (next < vars) {
3782 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3783 next++;
3784 continue;
3785 }
3786 if (next < vars - 1)
3787 p[next] = p[vars - 1];
3788 p[--vars] = NULL;
3789 }
3790 return 0;
3791}
3792
Willy Tarreaudad36a32013-03-11 01:20:04 +01003793/* Convert occurrences of environment variables in the input string to their
3794 * corresponding value. A variable is identified as a series of alphanumeric
3795 * characters or underscores following a '$' sign. The <in> string must be
3796 * free()able. NULL returns NULL. The resulting string might be reallocated if
3797 * some expansion is made. Variable names may also be enclosed into braces if
3798 * needed (eg: to concatenate alphanum characters).
3799 */
3800char *env_expand(char *in)
3801{
3802 char *txt_beg;
3803 char *out;
3804 char *txt_end;
3805 char *var_beg;
3806 char *var_end;
3807 char *value;
3808 char *next;
3809 int out_len;
3810 int val_len;
3811
3812 if (!in)
3813 return in;
3814
3815 value = out = NULL;
3816 out_len = 0;
3817
3818 txt_beg = in;
3819 do {
3820 /* look for next '$' sign in <in> */
3821 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3822
3823 if (!*txt_end && !out) /* end and no expansion performed */
3824 return in;
3825
3826 val_len = 0;
3827 next = txt_end;
3828 if (*txt_end == '$') {
3829 char save;
3830
3831 var_beg = txt_end + 1;
3832 if (*var_beg == '{')
3833 var_beg++;
3834
3835 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01003836 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01003837 var_end++;
3838 }
3839
3840 next = var_end;
3841 if (*var_end == '}' && (var_beg > txt_end + 1))
3842 next++;
3843
3844 /* get value of the variable name at this location */
3845 save = *var_end;
3846 *var_end = '\0';
3847 value = getenv(var_beg);
3848 *var_end = save;
3849 val_len = value ? strlen(value) : 0;
3850 }
3851
Hubert Verstraete831962e2016-06-28 22:44:26 +02003852 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003853 if (txt_end > txt_beg) {
3854 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3855 out_len += txt_end - txt_beg;
3856 }
3857 if (val_len) {
3858 memcpy(out + out_len, value, val_len);
3859 out_len += val_len;
3860 }
3861 out[out_len] = 0;
3862 txt_beg = next;
3863 } while (*txt_beg);
3864
3865 /* here we know that <out> was allocated and that we don't need <in> anymore */
3866 free(in);
3867 return out;
3868}
3869
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003870
3871/* same as strstr() but case-insensitive and with limit length */
3872const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3873{
3874 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003875 unsigned int slen, plen;
3876 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003877
3878 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3879 return NULL;
3880
3881 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3882 return str1;
3883
3884 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3885 return NULL;
3886
3887 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3888 while (toupper(*start) != toupper(*str2)) {
3889 start++;
3890 slen--;
3891 tmp1++;
3892
3893 if (tmp1 >= len_str1)
3894 return NULL;
3895
3896 /* if pattern longer than string */
3897 if (slen < plen)
3898 return NULL;
3899 }
3900
3901 sptr = start;
3902 pptr = (char *)str2;
3903
3904 tmp2 = 0;
3905 while (toupper(*sptr) == toupper(*pptr)) {
3906 sptr++;
3907 pptr++;
3908 tmp2++;
3909
3910 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3911 return start;
3912 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3913 return NULL;
3914 }
3915 }
3916 return NULL;
3917}
3918
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003919/* This function read the next valid utf8 char.
3920 * <s> is the byte srray to be decode, <len> is its length.
3921 * The function returns decoded char encoded like this:
3922 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3923 * are the length read. The decoded character is stored in <c>.
3924 */
3925unsigned char utf8_next(const char *s, int len, unsigned int *c)
3926{
3927 const unsigned char *p = (unsigned char *)s;
3928 int dec;
3929 unsigned char code = UTF8_CODE_OK;
3930
3931 if (len < 1)
3932 return UTF8_CODE_OK;
3933
3934 /* Check the type of UTF8 sequence
3935 *
3936 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3937 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3938 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3939 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3940 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3941 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3942 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3943 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3944 */
3945 switch (*p) {
3946 case 0x00 ... 0x7f:
3947 *c = *p;
3948 return UTF8_CODE_OK | 1;
3949
3950 case 0x80 ... 0xbf:
3951 *c = *p;
3952 return UTF8_CODE_BADSEQ | 1;
3953
3954 case 0xc0 ... 0xdf:
3955 if (len < 2) {
3956 *c = *p;
3957 return UTF8_CODE_BADSEQ | 1;
3958 }
3959 *c = *p & 0x1f;
3960 dec = 1;
3961 break;
3962
3963 case 0xe0 ... 0xef:
3964 if (len < 3) {
3965 *c = *p;
3966 return UTF8_CODE_BADSEQ | 1;
3967 }
3968 *c = *p & 0x0f;
3969 dec = 2;
3970 break;
3971
3972 case 0xf0 ... 0xf7:
3973 if (len < 4) {
3974 *c = *p;
3975 return UTF8_CODE_BADSEQ | 1;
3976 }
3977 *c = *p & 0x07;
3978 dec = 3;
3979 break;
3980
3981 case 0xf8 ... 0xfb:
3982 if (len < 5) {
3983 *c = *p;
3984 return UTF8_CODE_BADSEQ | 1;
3985 }
3986 *c = *p & 0x03;
3987 dec = 4;
3988 break;
3989
3990 case 0xfc ... 0xfd:
3991 if (len < 6) {
3992 *c = *p;
3993 return UTF8_CODE_BADSEQ | 1;
3994 }
3995 *c = *p & 0x01;
3996 dec = 5;
3997 break;
3998
3999 case 0xfe ... 0xff:
4000 default:
4001 *c = *p;
4002 return UTF8_CODE_BADSEQ | 1;
4003 }
4004
4005 p++;
4006
4007 while (dec > 0) {
4008
4009 /* need 0x10 for the 2 first bits */
4010 if ( ( *p & 0xc0 ) != 0x80 )
4011 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4012
4013 /* add data at char */
4014 *c = ( *c << 6 ) | ( *p & 0x3f );
4015
4016 dec--;
4017 p++;
4018 }
4019
4020 /* Check ovelong encoding.
4021 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4022 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4023 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4024 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004025 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004026 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4027 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4028 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4029 code |= UTF8_CODE_OVERLONG;
4030
4031 /* Check invalid UTF8 range. */
4032 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4033 (*c >= 0xfffe && *c <= 0xffff))
4034 code |= UTF8_CODE_INVRANGE;
4035
4036 return code | ((p-(unsigned char *)s)&0x0f);
4037}
4038
Maxime de Roucydc887852016-05-13 23:52:54 +02004039/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4040 * On failure : return 0 and <err> filled with an error message.
4041 * The caller is responsible for freeing the <err> and <str> copy
4042 * memory area using free()
4043 */
4044int list_append_word(struct list *li, const char *str, char **err)
4045{
4046 struct wordlist *wl;
4047
4048 wl = calloc(1, sizeof(*wl));
4049 if (!wl) {
4050 memprintf(err, "out of memory");
4051 goto fail_wl;
4052 }
4053
4054 wl->s = strdup(str);
4055 if (!wl->s) {
4056 memprintf(err, "out of memory");
4057 goto fail_wl_s;
4058 }
4059
4060 LIST_ADDQ(li, &wl->list);
4061
4062 return 1;
4063
4064fail_wl_s:
4065 free(wl->s);
4066fail_wl:
4067 free(wl);
4068 return 0;
4069}
4070
Willy Tarreau37101052019-05-20 16:48:20 +02004071/* indicates if a memory location may safely be read or not. The trick consists
4072 * in performing a harmless syscall using this location as an input and letting
4073 * the operating system report whether it's OK or not. For this we have the
4074 * stat() syscall, which will return EFAULT when the memory location supposed
4075 * to contain the file name is not readable. If it is readable it will then
4076 * either return 0 if the area contains an existing file name, or -1 with
4077 * another code. This must not be abused, and some audit systems might detect
4078 * this as abnormal activity. It's used only for unsafe dumps.
4079 */
4080int may_access(const void *ptr)
4081{
4082 struct stat buf;
4083
4084 if (stat(ptr, &buf) == 0)
4085 return 1;
4086 if (errno == EFAULT)
4087 return 0;
4088 return 1;
4089}
4090
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004091/* print a string of text buffer to <out>. The format is :
4092 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4093 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4094 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4095 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004096int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004097{
4098 unsigned char c;
4099 int ptr = 0;
4100
4101 while (buf[ptr] && ptr < bsize) {
4102 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004103 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004104 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004105 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004106 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004107 }
4108 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004109 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004110 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004111 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004112 switch (c) {
4113 case ' ': c = ' '; break;
4114 case '\t': c = 't'; break;
4115 case '\n': c = 'n'; break;
4116 case '\r': c = 'r'; break;
4117 case '\e': c = 'e'; break;
4118 case '\\': c = '\\'; break;
4119 case '=': c = '='; break;
4120 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004121 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004122 }
4123 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004124 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004125 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004126 out->area[out->data++] = '\\';
4127 out->area[out->data++] = 'x';
4128 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4129 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004130 }
4131 ptr++;
4132 }
4133
4134 return ptr;
4135}
4136
4137/* print a buffer in hexa.
4138 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4139 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004140int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004141{
4142 unsigned char c;
4143 int ptr = 0;
4144
4145 while (ptr < bsize) {
4146 c = buf[ptr];
4147
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004148 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004149 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004150 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4151 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004152
4153 ptr++;
4154 }
4155 return ptr;
4156}
4157
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004158/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4159 * prepending each line with prefix <pfx>. The output is *not* initialized.
4160 * The output will not wrap pas the buffer's end so it is more optimal if the
4161 * caller makes sure the buffer is aligned first. A trailing zero will always
4162 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004163 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4164 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004165 */
Willy Tarreau37101052019-05-20 16:48:20 +02004166void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004167{
4168 const unsigned char *d = buf;
4169 int i, j, start;
4170
4171 d = (const unsigned char *)(((unsigned long)buf) & -16);
4172 start = ((unsigned long)buf) & 15;
4173
4174 for (i = 0; i < start + len; i += 16) {
4175 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4176
Willy Tarreau37101052019-05-20 16:48:20 +02004177 // 0: unchecked, 1: checked safe, 2: danger
4178 unsafe = !!unsafe;
4179 if (unsafe && !may_access(d + i))
4180 unsafe = 2;
4181
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004182 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004183 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004184 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004185 else if (unsafe > 1)
4186 chunk_strcat(out, "** ");
4187 else
4188 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004189
4190 if (j == 7)
4191 chunk_strcat(out, "- ");
4192 }
4193 chunk_strcat(out, " ");
4194 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004195 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004196 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004197 else if (unsafe > 1)
4198 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004199 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004200 chunk_appendf(out, "%c", d[i + j]);
4201 else
4202 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004203 }
4204 chunk_strcat(out, "\n");
4205 }
4206}
4207
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004208/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4209 * enclosed in brackets after the address itself, formatted on 14 chars
4210 * including the "0x" prefix. This is meant to be used as a prefix for code
4211 * areas. For example:
4212 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4213 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4214 * is emitted. A NULL <pfx> will be considered empty.
4215 */
4216void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4217{
4218 int ok = 0;
4219 int i;
4220
4221 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4222
4223 for (i = 0; i < n; i++) {
4224 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4225 ok = may_access(addr + i);
4226 if (ok)
4227 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4228 else
4229 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4230 }
4231}
4232
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004233/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4234 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4235 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4236 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4237 * lines are respected within the limit of 70 output chars. Lines that are
4238 * continuation of a previous truncated line begin with "+" instead of " "
4239 * after the offset. The new pointer is returned.
4240 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004241int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004242 int *line, int ptr)
4243{
4244 int end;
4245 unsigned char c;
4246
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004247 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004248 if (end > out->size)
4249 return ptr;
4250
4251 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4252
4253 while (ptr < len && ptr < bsize) {
4254 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004255 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004256 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004257 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004258 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004259 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004260 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004261 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004262 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004263 switch (c) {
4264 case '\t': c = 't'; break;
4265 case '\n': c = 'n'; break;
4266 case '\r': c = 'r'; break;
4267 case '\e': c = 'e'; break;
4268 case '\\': c = '\\'; break;
4269 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004270 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004271 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004272 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004273 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004274 out->area[out->data++] = '\\';
4275 out->area[out->data++] = 'x';
4276 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4277 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004278 }
4279 if (buf[ptr++] == '\n') {
4280 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004281 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004282 *line = ptr;
4283 return ptr;
4284 }
4285 }
4286 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004287 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004288 return ptr;
4289}
4290
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004291/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004292 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4293 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004294 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004295void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4296 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004297{
Willy Tarreau73459792017-04-11 07:58:08 +02004298 unsigned int i;
4299 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004300
4301 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4302 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004303 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004304 for (j = 0; j < 8; j++) {
4305 if (b + j >= 0 && b + j < len)
4306 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4307 else
4308 fprintf(out, " ");
4309 }
4310
4311 if (b + j >= 0 && b + j < len)
4312 fputc('-', out);
4313 else
4314 fputc(' ', out);
4315
4316 for (j = 8; j < 16; j++) {
4317 if (b + j >= 0 && b + j < len)
4318 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4319 else
4320 fprintf(out, " ");
4321 }
4322
4323 fprintf(out, " ");
4324 for (j = 0; j < 16; j++) {
4325 if (b + j >= 0 && b + j < len) {
4326 if (isprint((unsigned char)buf[b + j]))
4327 fputc((unsigned char)buf[b + j], out);
4328 else
4329 fputc('.', out);
4330 }
4331 else
4332 fputc(' ', out);
4333 }
4334 fputc('\n', out);
4335 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004336}
4337
Willy Tarreau109201f2020-03-04 10:31:58 +01004338#ifdef __ELF__
Willy Tarreau9133e482020-03-04 10:19:36 +01004339/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4340 * also returns the symbol size in <size>, otherwise returns 0 there.
4341 */
4342static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4343{
4344 int ret;
4345#ifdef __USE_GNU // most detailed one
4346 const ElfW(Sym) *sym;
4347
4348 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4349 if (ret)
4350 *size = sym ? sym->st_size : 0;
4351#else
4352 ret = dladdr(addr, dli);
4353 *size = 0;
4354#endif
4355 return ret;
4356}
4357#endif
4358
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004359/* Tries to append to buffer <buf> some indications about the symbol at address
4360 * <addr> using the following form:
4361 * lib:+0xoffset (unresolvable address from lib's base)
4362 * main+0xoffset (unresolvable address from main (+/-))
4363 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4364 * name (resolved exact exec address)
4365 * lib:name (resolved exact lib address)
4366 * name+0xoffset/0xsize (resolved address within exec symbol)
4367 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4368 *
4369 * The file name (lib or executable) is limited to what lies between the last
4370 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4371 * the output if not null. The file is not dumped when it's the same as the one
Willy Tarreau109201f2020-03-04 10:31:58 +01004372 * that contains the "main" symbol, or when __ELF__ is not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004373 *
4374 * The symbol's base address is returned, or NULL when unresolved, in order to
4375 * allow the caller to match it against known ones.
4376 */
4377void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
4378{
4379 const struct {
4380 const void *func;
4381 const char *name;
4382 } fcts[] = {
4383 { .func = process_stream, .name = "process_stream" },
4384 { .func = task_run_applet, .name = "task_run_applet" },
4385 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4386 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4387 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4388 { .func = listener_accept, .name = "listener_accept" },
4389 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4390 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4391#ifdef USE_LUA
4392 { .func = hlua_process_task, .name = "hlua_process_task" },
4393#endif
4394#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4395 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4396 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4397#endif
4398 };
4399
Willy Tarreau109201f2020-03-04 10:31:58 +01004400#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004401 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004402 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004403 const char *fname, *p;
4404#endif
4405 int i;
4406
4407 if (pfx)
4408 chunk_appendf(buf, "%s", pfx);
4409
4410 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4411 if (addr == fcts[i].func) {
4412 chunk_appendf(buf, "%s", fcts[i].name);
4413 return addr;
4414 }
4415 }
4416
Willy Tarreau109201f2020-03-04 10:31:58 +01004417#ifdef __ELF__
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004418 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004419 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004420 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004421
4422 /* 1. prefix the library name if it's not the same object as the one
4423 * that contains the main function. The name is picked between last '/'
4424 * and first following '.'.
4425 */
4426 if (!dladdr(main, &dli_main))
4427 dli_main.dli_fbase = NULL;
4428
4429 if (dli_main.dli_fbase != dli.dli_fbase) {
4430 fname = dli.dli_fname;
4431 p = strrchr(fname, '/');
4432 if (p++)
4433 fname = p;
4434 p = strchr(fname, '.');
4435 if (!p)
4436 p = fname + strlen(fname);
4437
4438 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4439 }
4440
4441 /* 2. symbol name */
4442 if (dli.dli_sname) {
4443 /* known, dump it and return symbol's address (exact or relative) */
4444 chunk_appendf(buf, "%s", dli.dli_sname);
4445 if (addr != dli.dli_saddr) {
4446 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004447 if (size)
4448 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004449 }
4450 return dli.dli_saddr;
4451 }
4452 else if (dli_main.dli_fbase != dli.dli_fbase) {
4453 /* unresolved symbol from a known library, report relative offset */
4454 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4455 return NULL;
4456 }
Willy Tarreau109201f2020-03-04 10:31:58 +01004457#endif /* __ELF__ */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004458 unknown:
4459 /* unresolved symbol from the main file, report relative offset to main */
4460 if ((void*)addr < (void*)main)
4461 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4462 else
4463 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4464 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004465}
4466
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004467/*
4468 * Allocate an array of unsigned int with <nums> as address from <str> string
4469 * made of integer sepereated by dot characters.
4470 *
4471 * First, initializes the value with <sz> as address to 0 and initializes the
4472 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4473 * address updating <sz> pointed value to the size of this array.
4474 *
4475 * Returns 1 if succeeded, 0 if not.
4476 */
4477int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4478{
4479 unsigned int *n;
4480 const char *s, *end;
4481
4482 s = str;
4483 *sz = 0;
4484 end = str + strlen(str);
4485 *nums = n = NULL;
4486
4487 while (1) {
4488 unsigned int r;
4489
4490 if (s >= end)
4491 break;
4492
4493 r = read_uint(&s, end);
4494 /* Expected characters after having read an uint: '\0' or '.',
4495 * if '.', must not be terminal.
4496 */
4497 if (*s != '\0'&& (*s++ != '.' || s == end))
4498 return 0;
4499
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004500 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004501 if (!n)
4502 return 0;
4503
4504 n[(*sz)++] = r;
4505 }
4506 *nums = n;
4507
4508 return 1;
4509}
4510
Willy Tarreau4d589e72019-08-23 19:02:26 +02004511
4512/* returns the number of bytes needed to encode <v> as a varint. An inline
4513 * version exists for use with constants (__varint_bytes()).
4514 */
4515int varint_bytes(uint64_t v)
4516{
4517 int len = 1;
4518
4519 if (v >= 240) {
4520 v = (v - 240) >> 4;
4521 while (1) {
4522 len++;
4523 if (v < 128)
4524 break;
4525 v = (v - 128) >> 7;
4526 }
4527 }
4528 return len;
4529}
4530
Willy Tarreaubaaee002006-06-26 02:48:02 +02004531/*
4532 * Local variables:
4533 * c-indent-level: 8
4534 * c-basic-offset: 8
4535 * End:
4536 */