blob: a33ad9bd6f57d593f6daaf1d2a56d718db71c229 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010013#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020014#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020015#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020016#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020017#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020018#include <stdlib.h>
19#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010020#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020021#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010022#include <sys/socket.h>
23#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <netinet/in.h>
25#include <arpa/inet.h>
26
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010027#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020028#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020029#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010030#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010031#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020032#include <proto/dns.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010033#include <eb32tree.h>
Willy Tarreaued3cda02017-11-15 15:04:05 +010034#include <eb32sctree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035
Thierry Fournier93127942016-01-20 18:49:45 +010036/* This macro returns false if the test __x is false. Many
37 * of the following parsing function must be abort the processing
38 * if it returns 0, so this macro is useful for writing light code.
39 */
40#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
41
Willy Tarreau56adcf22012-12-23 18:00:29 +010042/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020043 * 2^64-1 = 18446744073709551615 or
44 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020045 *
46 * The HTML version needs room for adding the 25 characters
47 * '<span class="rls"></span>' around digits at positions 3N+1 in order
48 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020049 */
Christopher Faulet99bca652017-11-14 16:47:26 +010050THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
51THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020052
Willy Tarreau588297f2014-06-16 15:16:40 +020053/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
54 * to quote strings larger than a max configuration line.
55 */
Christopher Faulet99bca652017-11-14 16:47:26 +010056THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
57THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020058
Willy Tarreaubaaee002006-06-26 02:48:02 +020059/*
William Lallemande7340ec2012-01-24 11:15:39 +010060 * unsigned long long ASCII representation
61 *
62 * return the last char '\0' or NULL if no enough
63 * space in dst
64 */
65char *ulltoa(unsigned long long n, char *dst, size_t size)
66{
67 int i = 0;
68 char *res;
69
70 switch(n) {
71 case 1ULL ... 9ULL:
72 i = 0;
73 break;
74
75 case 10ULL ... 99ULL:
76 i = 1;
77 break;
78
79 case 100ULL ... 999ULL:
80 i = 2;
81 break;
82
83 case 1000ULL ... 9999ULL:
84 i = 3;
85 break;
86
87 case 10000ULL ... 99999ULL:
88 i = 4;
89 break;
90
91 case 100000ULL ... 999999ULL:
92 i = 5;
93 break;
94
95 case 1000000ULL ... 9999999ULL:
96 i = 6;
97 break;
98
99 case 10000000ULL ... 99999999ULL:
100 i = 7;
101 break;
102
103 case 100000000ULL ... 999999999ULL:
104 i = 8;
105 break;
106
107 case 1000000000ULL ... 9999999999ULL:
108 i = 9;
109 break;
110
111 case 10000000000ULL ... 99999999999ULL:
112 i = 10;
113 break;
114
115 case 100000000000ULL ... 999999999999ULL:
116 i = 11;
117 break;
118
119 case 1000000000000ULL ... 9999999999999ULL:
120 i = 12;
121 break;
122
123 case 10000000000000ULL ... 99999999999999ULL:
124 i = 13;
125 break;
126
127 case 100000000000000ULL ... 999999999999999ULL:
128 i = 14;
129 break;
130
131 case 1000000000000000ULL ... 9999999999999999ULL:
132 i = 15;
133 break;
134
135 case 10000000000000000ULL ... 99999999999999999ULL:
136 i = 16;
137 break;
138
139 case 100000000000000000ULL ... 999999999999999999ULL:
140 i = 17;
141 break;
142
143 case 1000000000000000000ULL ... 9999999999999999999ULL:
144 i = 18;
145 break;
146
147 case 10000000000000000000ULL ... ULLONG_MAX:
148 i = 19;
149 break;
150 }
151 if (i + 2 > size) // (i + 1) + '\0'
152 return NULL; // too long
153 res = dst + i + 1;
154 *res = '\0';
155 for (; i >= 0; i--) {
156 dst[i] = n % 10ULL + '0';
157 n /= 10ULL;
158 }
159 return res;
160}
161
162/*
163 * unsigned long ASCII representation
164 *
165 * return the last char '\0' or NULL if no enough
166 * space in dst
167 */
168char *ultoa_o(unsigned long n, char *dst, size_t size)
169{
170 int i = 0;
171 char *res;
172
173 switch (n) {
174 case 0U ... 9UL:
175 i = 0;
176 break;
177
178 case 10U ... 99UL:
179 i = 1;
180 break;
181
182 case 100U ... 999UL:
183 i = 2;
184 break;
185
186 case 1000U ... 9999UL:
187 i = 3;
188 break;
189
190 case 10000U ... 99999UL:
191 i = 4;
192 break;
193
194 case 100000U ... 999999UL:
195 i = 5;
196 break;
197
198 case 1000000U ... 9999999UL:
199 i = 6;
200 break;
201
202 case 10000000U ... 99999999UL:
203 i = 7;
204 break;
205
206 case 100000000U ... 999999999UL:
207 i = 8;
208 break;
209#if __WORDSIZE == 32
210
211 case 1000000000ULL ... ULONG_MAX:
212 i = 9;
213 break;
214
215#elif __WORDSIZE == 64
216
217 case 1000000000ULL ... 9999999999UL:
218 i = 9;
219 break;
220
221 case 10000000000ULL ... 99999999999UL:
222 i = 10;
223 break;
224
225 case 100000000000ULL ... 999999999999UL:
226 i = 11;
227 break;
228
229 case 1000000000000ULL ... 9999999999999UL:
230 i = 12;
231 break;
232
233 case 10000000000000ULL ... 99999999999999UL:
234 i = 13;
235 break;
236
237 case 100000000000000ULL ... 999999999999999UL:
238 i = 14;
239 break;
240
241 case 1000000000000000ULL ... 9999999999999999UL:
242 i = 15;
243 break;
244
245 case 10000000000000000ULL ... 99999999999999999UL:
246 i = 16;
247 break;
248
249 case 100000000000000000ULL ... 999999999999999999UL:
250 i = 17;
251 break;
252
253 case 1000000000000000000ULL ... 9999999999999999999UL:
254 i = 18;
255 break;
256
257 case 10000000000000000000ULL ... ULONG_MAX:
258 i = 19;
259 break;
260
261#endif
262 }
263 if (i + 2 > size) // (i + 1) + '\0'
264 return NULL; // too long
265 res = dst + i + 1;
266 *res = '\0';
267 for (; i >= 0; i--) {
268 dst[i] = n % 10U + '0';
269 n /= 10U;
270 }
271 return res;
272}
273
274/*
275 * signed long ASCII representation
276 *
277 * return the last char '\0' or NULL if no enough
278 * space in dst
279 */
280char *ltoa_o(long int n, char *dst, size_t size)
281{
282 char *pos = dst;
283
284 if (n < 0) {
285 if (size < 3)
286 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
287 *pos = '-';
288 pos++;
289 dst = ultoa_o(-n, pos, size - 1);
290 } else {
291 dst = ultoa_o(n, dst, size);
292 }
293 return dst;
294}
295
296/*
297 * signed long long ASCII representation
298 *
299 * return the last char '\0' or NULL if no enough
300 * space in dst
301 */
302char *lltoa(long long n, char *dst, size_t size)
303{
304 char *pos = dst;
305
306 if (n < 0) {
307 if (size < 3)
308 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
309 *pos = '-';
310 pos++;
311 dst = ulltoa(-n, pos, size - 1);
312 } else {
313 dst = ulltoa(n, dst, size);
314 }
315 return dst;
316}
317
318/*
319 * write a ascii representation of a unsigned into dst,
320 * return a pointer to the last character
321 * Pad the ascii representation with '0', using size.
322 */
323char *utoa_pad(unsigned int n, char *dst, size_t size)
324{
325 int i = 0;
326 char *ret;
327
328 switch(n) {
329 case 0U ... 9U:
330 i = 0;
331 break;
332
333 case 10U ... 99U:
334 i = 1;
335 break;
336
337 case 100U ... 999U:
338 i = 2;
339 break;
340
341 case 1000U ... 9999U:
342 i = 3;
343 break;
344
345 case 10000U ... 99999U:
346 i = 4;
347 break;
348
349 case 100000U ... 999999U:
350 i = 5;
351 break;
352
353 case 1000000U ... 9999999U:
354 i = 6;
355 break;
356
357 case 10000000U ... 99999999U:
358 i = 7;
359 break;
360
361 case 100000000U ... 999999999U:
362 i = 8;
363 break;
364
365 case 1000000000U ... 4294967295U:
366 i = 9;
367 break;
368 }
369 if (i + 2 > size) // (i + 1) + '\0'
370 return NULL; // too long
371 if (i < size)
372 i = size - 2; // padding - '\0'
373
374 ret = dst + i + 1;
375 *ret = '\0';
376 for (; i >= 0; i--) {
377 dst[i] = n % 10U + '0';
378 n /= 10U;
379 }
380 return ret;
381}
382
383/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200384 * copies at most <size-1> chars from <src> to <dst>. Last char is always
385 * set to 0, unless <size> is 0. The number of chars copied is returned
386 * (excluding the terminating zero).
387 * This code has been optimized for size and speed : on x86, it's 45 bytes
388 * long, uses only registers, and consumes only 4 cycles per char.
389 */
390int strlcpy2(char *dst, const char *src, int size)
391{
392 char *orig = dst;
393 if (size) {
394 while (--size && (*dst = *src)) {
395 src++; dst++;
396 }
397 *dst = 0;
398 }
399 return dst - orig;
400}
401
402/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200403 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404 * the ascii representation for number 'n' in decimal.
405 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100406char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200407{
408 char *pos;
409
Willy Tarreau72d759c2007-10-25 12:14:10 +0200410 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200411 *pos-- = '\0';
412
413 do {
414 *pos-- = '0' + n % 10;
415 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200416 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200417 return pos + 1;
418}
419
Willy Tarreau91092e52007-10-25 16:58:42 +0200420/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200421 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200422 * the ascii representation for number 'n' in decimal.
423 */
424char *lltoa_r(long long int in, char *buffer, int size)
425{
426 char *pos;
427 int neg = 0;
428 unsigned long long int n;
429
430 pos = buffer + size - 1;
431 *pos-- = '\0';
432
433 if (in < 0) {
434 neg = 1;
435 n = -in;
436 }
437 else
438 n = in;
439
440 do {
441 *pos-- = '0' + n % 10;
442 n /= 10;
443 } while (n && pos >= buffer);
444 if (neg && pos > buffer)
445 *pos-- = '-';
446 return pos + 1;
447}
448
449/*
450 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200451 * the ascii representation for signed number 'n' in decimal.
452 */
453char *sltoa_r(long n, char *buffer, int size)
454{
455 char *pos;
456
457 if (n >= 0)
458 return ultoa_r(n, buffer, size);
459
460 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
461 *pos = '-';
462 return pos;
463}
464
465/*
466 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200467 * the ascii representation for number 'n' in decimal, formatted for
468 * HTML output with tags to create visual grouping by 3 digits. The
469 * output needs to support at least 171 characters.
470 */
471const char *ulltoh_r(unsigned long long n, char *buffer, int size)
472{
473 char *start;
474 int digit = 0;
475
476 start = buffer + size;
477 *--start = '\0';
478
479 do {
480 if (digit == 3 && start >= buffer + 7)
481 memcpy(start -= 7, "</span>", 7);
482
483 if (start >= buffer + 1) {
484 *--start = '0' + n % 10;
485 n /= 10;
486 }
487
488 if (digit == 3 && start >= buffer + 18)
489 memcpy(start -= 18, "<span class=\"rls\">", 18);
490
491 if (digit++ == 3)
492 digit = 1;
493 } while (n && start > buffer);
494 return start;
495}
496
497/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200498 * This function simply returns a locally allocated string containing the ascii
499 * representation for number 'n' in decimal, unless n is 0 in which case it
500 * returns the alternate string (or an empty string if the alternate string is
501 * NULL). It use is intended for limits reported in reports, where it's
502 * desirable not to display anything if there is no limit. Warning! it shares
503 * the same vector as ultoa_r().
504 */
505const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
506{
507 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
508}
509
Willy Tarreau588297f2014-06-16 15:16:40 +0200510/* returns a locally allocated string containing the quoted encoding of the
511 * input string. The output may be truncated to QSTR_SIZE chars, but it is
512 * guaranteed that the string will always be properly terminated. Quotes are
513 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
514 * always be at least 4 chars.
515 */
516const char *qstr(const char *str)
517{
518 char *ret = quoted_str[quoted_idx];
519 char *p, *end;
520
521 if (++quoted_idx >= NB_QSTR)
522 quoted_idx = 0;
523
524 p = ret;
525 end = ret + QSTR_SIZE;
526
527 *p++ = '"';
528
529 /* always keep 3 chars to support passing "" and the ending " */
530 while (*str && p < end - 3) {
531 if (*str == '"') {
532 *p++ = '"';
533 *p++ = '"';
534 }
535 else
536 *p++ = *str;
537 str++;
538 }
539 *p++ = '"';
540 return ret;
541}
542
Robert Tsai81ae1952007-12-05 10:47:29 +0100543/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200544 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
545 *
546 * It looks like this one would be a good candidate for inlining, but this is
547 * not interesting because it around 35 bytes long and often called multiple
548 * times within the same function.
549 */
550int ishex(char s)
551{
552 s -= '0';
553 if ((unsigned char)s <= 9)
554 return 1;
555 s -= 'A' - '0';
556 if ((unsigned char)s <= 5)
557 return 1;
558 s -= 'a' - 'A';
559 if ((unsigned char)s <= 5)
560 return 1;
561 return 0;
562}
563
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100564/* rounds <i> down to the closest value having max 2 digits */
565unsigned int round_2dig(unsigned int i)
566{
567 unsigned int mul = 1;
568
569 while (i >= 100) {
570 i /= 10;
571 mul *= 10;
572 }
573 return i * mul;
574}
575
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100576/*
577 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
578 * invalid character is found, a pointer to it is returned. If everything is
579 * fine, NULL is returned.
580 */
581const char *invalid_char(const char *name)
582{
583 if (!*name)
584 return name;
585
586 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100587 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100588 *name != '_' && *name != '-')
589 return name;
590 name++;
591 }
592 return NULL;
593}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200594
595/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200596 * Checks <name> for invalid characters. Valid chars are [_.-] and those
597 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200598 * If an invalid character is found, a pointer to it is returned.
599 * If everything is fine, NULL is returned.
600 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200601static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200602
603 if (!*name)
604 return name;
605
606 while (*name) {
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200607 if (!f((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200608 *name != '_' && *name != '-')
609 return name;
610
611 name++;
612 }
613
614 return NULL;
615}
616
617/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200618 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
619 * If an invalid character is found, a pointer to it is returned.
620 * If everything is fine, NULL is returned.
621 */
622const char *invalid_domainchar(const char *name) {
623 return __invalid_char(name, isalnum);
624}
625
626/*
627 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
628 * If an invalid character is found, a pointer to it is returned.
629 * If everything is fine, NULL is returned.
630 */
631const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200632 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200633}
634
635/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100636 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100637 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
638 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
639 * the function tries to guess the address family from the syntax. If the
640 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100641 * string is assumed to contain only an address, no port. The address can be a
642 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
643 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
644 * The return address will only have the address family and the address set,
645 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100646 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
647 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100648 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200649 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100650struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200651{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100652 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100653 /* max IPv6 length, including brackets and terminating NULL */
654 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100655 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100656
657 /* check IPv6 with square brackets */
658 if (str[0] == '[') {
659 size_t iplength = strlen(str);
660
661 if (iplength < 4) {
662 /* minimal size is 4 when using brackets "[::]" */
663 goto fail;
664 }
665 else if (iplength >= sizeof(tmpip)) {
666 /* IPv6 literal can not be larger than tmpip */
667 goto fail;
668 }
669 else {
670 if (str[iplength - 1] != ']') {
671 /* if address started with bracket, it should end with bracket */
672 goto fail;
673 }
674 else {
675 memcpy(tmpip, str + 1, iplength - 2);
676 tmpip[iplength - 2] = '\0';
677 str = tmpip;
678 }
679 }
680 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100681
Willy Tarreaufab5a432011-03-04 15:31:53 +0100682 /* Any IPv6 address */
683 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100684 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
685 sa->ss_family = AF_INET6;
686 else if (sa->ss_family != AF_INET6)
687 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100688 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100689 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100690 }
691
Willy Tarreau24709282013-03-10 21:32:12 +0100692 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100693 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100694 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
695 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100696 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100697 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100698 }
699
700 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100701 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
702 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100703 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100704 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100705 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100706 }
707
708 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100709 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
710 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100711 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100712 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100713 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100714 }
715
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100716 if (!resolve)
717 return NULL;
718
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200719 if (!dns_hostname_validation(str, NULL))
720 return NULL;
721
David du Colombierd5f43282011-03-17 10:40:16 +0100722#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200723 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100724 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100725 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100726
727 memset(&result, 0, sizeof(result));
728 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100729 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100730 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200731 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100732 hints.ai_protocol = 0;
733
734 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100735 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
736 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100737 else if (sa->ss_family != result->ai_family) {
738 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100739 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100740 }
Willy Tarreau24709282013-03-10 21:32:12 +0100741
David du Colombierd5f43282011-03-17 10:40:16 +0100742 switch (result->ai_family) {
743 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100744 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100745 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100746 success = 1;
747 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100748 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100749 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100750 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100751 success = 1;
752 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100753 }
754 }
755
Sean Carey58ea0392013-02-15 23:39:18 +0100756 if (result)
757 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100758
759 if (success)
760 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100761 }
David du Colombierd5f43282011-03-17 10:40:16 +0100762#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200763 /* try to resolve an IPv4/IPv6 hostname */
764 he = gethostbyname(str);
765 if (he) {
766 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
767 sa->ss_family = he->h_addrtype;
768 else if (sa->ss_family != he->h_addrtype)
769 goto fail;
770
771 switch (sa->ss_family) {
772 case AF_INET:
773 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100774 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200775 return sa;
776 case AF_INET6:
777 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100778 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200779 return sa;
780 }
781 }
782
David du Colombierd5f43282011-03-17 10:40:16 +0100783 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100784 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100785 return NULL;
786}
787
788/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100789 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
790 * range or offset consisting in two integers that the caller will have to
791 * check to find the relevant input format. The following format are supported :
792 *
793 * String format | address | port | low | high
794 * addr | <addr> | 0 | 0 | 0
795 * addr: | <addr> | 0 | 0 | 0
796 * addr:port | <addr> | <port> | <port> | <port>
797 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
798 * addr:+port | <addr> | <port> | 0 | <port>
799 * addr:-port | <addr> |-<port> | <port> | 0
800 *
801 * The detection of a port range or increment by the caller is made by
802 * comparing <low> and <high>. If both are equal, then port 0 means no port
803 * was specified. The caller may pass NULL for <low> and <high> if it is not
804 * interested in retrieving port ranges.
805 *
806 * Note that <addr> above may also be :
807 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
808 * - "*" => family will be AF_INET and address will be INADDR_ANY
809 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
810 * - a host name => family and address will depend on host name resolving.
811 *
Willy Tarreau24709282013-03-10 21:32:12 +0100812 * A prefix may be passed in before the address above to force the family :
813 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
814 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
815 * - "unix@" => force address to be a path to a UNIX socket even if the
816 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200817 * - 'abns@' -> force address to belong to the abstract namespace (Linux
818 * only). These sockets are just like Unix sockets but without
819 * the need for an underlying file system. The address is a
820 * string. Technically it's like a Unix socket with a zero in
821 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100822 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100823 *
mildisff5d5102015-10-26 18:50:08 +0100824 * IPv6 addresses can be declared with or without square brackets. When using
825 * square brackets for IPv6 addresses, the port separator (colon) is optional.
826 * If not using square brackets, and in order to avoid any ambiguity with
827 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
828 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
829 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100830 *
831 * If <pfx> is non-null, it is used as a string prefix before any path-based
832 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100833 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200834 * if <fqdn> is non-null, it will be filled with :
835 * - a pointer to the FQDN of the server name to resolve if there's one, and
836 * that the caller will have to free(),
837 * - NULL if there was an explicit address that doesn't require resolution.
838 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100839 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
840 * is null, <fqdn> is still honnored so it is possible for the caller to know
841 * whether a resolution failed by setting <resolve> to null and checking if
842 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200843 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100844 * When a file descriptor is passed, its value is put into the s_addr part of
845 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100846 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100847struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100848{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100849 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100850 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100851 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100852 char *port1, *port2;
853 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200854 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100855
856 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200857 if (fqdn)
858 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200859
Willy Tarreaudad36a32013-03-11 01:20:04 +0100860 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100861 if (str2 == NULL) {
862 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100863 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100864 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200865
Willy Tarreau9f69f462015-09-08 16:01:25 +0200866 if (!*str2) {
867 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
868 goto out;
869 }
870
Willy Tarreau24709282013-03-10 21:32:12 +0100871 memset(&ss, 0, sizeof(ss));
872
873 if (strncmp(str2, "unix@", 5) == 0) {
874 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200875 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100876 ss.ss_family = AF_UNIX;
877 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200878 else if (strncmp(str2, "abns@", 5) == 0) {
879 str2 += 5;
880 abstract = 1;
881 ss.ss_family = AF_UNIX;
882 }
Willy Tarreau24709282013-03-10 21:32:12 +0100883 else if (strncmp(str2, "ipv4@", 5) == 0) {
884 str2 += 5;
885 ss.ss_family = AF_INET;
886 }
887 else if (strncmp(str2, "ipv6@", 5) == 0) {
888 str2 += 5;
889 ss.ss_family = AF_INET6;
890 }
891 else if (*str2 == '/') {
892 ss.ss_family = AF_UNIX;
893 }
894 else
895 ss.ss_family = AF_UNSPEC;
896
William Lallemand2fe7dd02018-09-11 16:51:29 +0200897 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
898 char *endptr;
899
900 str2 += 9;
901
902 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
903
904 if (!*str2 || *endptr) {
905 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
906 goto out;
907 }
908
909 ss.ss_family = AF_CUST_SOCKPAIR;
910
911 }
912 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100913 char *endptr;
914
915 str2 += 3;
916 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
917
918 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100919 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100920 goto out;
921 }
922
923 /* we return AF_UNSPEC if we use a file descriptor number */
924 ss.ss_family = AF_UNSPEC;
925 }
926 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100927 int prefix_path_len;
928 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200929 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100930
931 /* complete unix socket path name during startup or soft-restart is
932 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
933 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200934 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100935 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
936 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
937
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200938 adr_len = strlen(str2);
939 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100940 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
941 goto out;
942 }
943
Willy Tarreauccfccef2014-05-10 01:49:15 +0200944 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
945 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200946 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100947 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200948 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100949 }
Willy Tarreau24709282013-03-10 21:32:12 +0100950 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100951 char *end = str2 + strlen(str2);
952 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200953
mildisff5d5102015-10-26 18:50:08 +0100954 /* search for : or ] whatever comes first */
955 for (chr = end-1; chr > str2; chr--) {
956 if (*chr == ']' || *chr == ':')
957 break;
958 }
959
960 if (*chr == ':') {
961 /* Found a colon before a closing-bracket, must be a port separator.
962 * This guarantee backward compatibility.
963 */
964 *chr++ = '\0';
965 port1 = chr;
966 }
967 else {
968 /* Either no colon and no closing-bracket
969 * or directly ending with a closing-bracket.
970 * However, no port.
971 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100972 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100973 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200974
Willy Tarreaua39d1992013-04-01 20:37:42 +0200975 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100976 port2 = strchr(port1, '-');
977 if (port2)
978 *port2++ = '\0';
979 else
980 port2 = port1;
981 portl = atoi(port1);
982 porth = atoi(port2);
983 porta = portl;
984 }
985 else if (*port1 == '-') { /* negative offset */
986 portl = atoi(port1 + 1);
987 porta = -portl;
988 }
989 else if (*port1 == '+') { /* positive offset */
990 porth = atoi(port1 + 1);
991 porta = porth;
992 }
993 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100994 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100995 goto out;
996 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100997
998 /* first try to parse the IP without resolving. If it fails, it
999 * tells us we need to keep a copy of the FQDN to resolve later
1000 * and to enable DNS. In this case we can proceed if <fqdn> is
1001 * set or if resolve is set, otherwise it's an error.
1002 */
1003 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001004 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001005 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1006 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1007 goto out;
1008 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001009
Willy Tarreauceccdd72016-11-02 22:27:10 +01001010 if (fqdn) {
1011 if (str2 != back)
1012 memmove(back, str2, strlen(str2) + 1);
1013 *fqdn = back;
1014 back = NULL;
1015 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001016 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001017 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001018 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001019
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001020 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001021 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001022 if (port)
1023 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001024 if (low)
1025 *low = portl;
1026 if (high)
1027 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001028 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001029 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001030}
1031
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001032/* converts <str> to a struct in_addr containing a network mask. It can be
1033 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001034 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001035 */
1036int str2mask(const char *str, struct in_addr *mask)
1037{
1038 if (strchr(str, '.') != NULL) { /* dotted notation */
1039 if (!inet_pton(AF_INET, str, mask))
1040 return 0;
1041 }
1042 else { /* mask length */
1043 char *err;
1044 unsigned long len = strtol(str, &err, 10);
1045
1046 if (!*str || (err && *err) || (unsigned)len > 32)
1047 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001048
1049 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001050 }
1051 return 1;
1052}
1053
Tim Duesterhus47185172018-01-25 16:24:49 +01001054/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001055 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001056 * if the conversion succeeds otherwise zero.
1057 */
1058int str2mask6(const char *str, struct in6_addr *mask)
1059{
1060 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1061 if (!inet_pton(AF_INET6, str, mask))
1062 return 0;
1063 }
1064 else { /* mask length */
1065 char *err;
1066 unsigned long len = strtol(str, &err, 10);
1067
1068 if (!*str || (err && *err) || (unsigned)len > 128)
1069 return 0;
1070
1071 len2mask6(len, mask);
1072 }
1073 return 1;
1074}
1075
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001076/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1077 * succeeds otherwise zero.
1078 */
1079int cidr2dotted(int cidr, struct in_addr *mask) {
1080
1081 if (cidr < 0 || cidr > 32)
1082 return 0;
1083
1084 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1085 return 1;
1086}
1087
Thierry Fournier70473a52016-02-17 17:12:14 +01001088/* Convert mask from bit length form to in_addr form.
1089 * This function never fails.
1090 */
1091void len2mask4(int len, struct in_addr *addr)
1092{
1093 if (len >= 32) {
1094 addr->s_addr = 0xffffffff;
1095 return;
1096 }
1097 if (len <= 0) {
1098 addr->s_addr = 0x00000000;
1099 return;
1100 }
1101 addr->s_addr = 0xffffffff << (32 - len);
1102 addr->s_addr = htonl(addr->s_addr);
1103}
1104
1105/* Convert mask from bit length form to in6_addr form.
1106 * This function never fails.
1107 */
1108void len2mask6(int len, struct in6_addr *addr)
1109{
1110 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1111 len -= 32;
1112 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1113 len -= 32;
1114 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1115 len -= 32;
1116 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1117}
1118
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001119/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001120 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001121 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1122 * is optionnal and either in the dotted or CIDR notation.
1123 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1124 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001125int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001126{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001127 __label__ out_free, out_err;
1128 char *c, *s;
1129 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001130
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001131 s = strdup(str);
1132 if (!s)
1133 return 0;
1134
Willy Tarreaubaaee002006-06-26 02:48:02 +02001135 memset(mask, 0, sizeof(*mask));
1136 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001137
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001138 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001139 *c++ = '\0';
1140 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001141 if (!str2mask(c, mask))
1142 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001143 }
1144 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001145 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001146 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001147 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001148 struct hostent *he;
1149
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001150 if (!resolve)
1151 goto out_err;
1152
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001153 if ((he = gethostbyname(s)) == NULL) {
1154 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001155 }
1156 else
1157 *addr = *(struct in_addr *) *(he->h_addr_list);
1158 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001159
1160 ret_val = 1;
1161 out_free:
1162 free(s);
1163 return ret_val;
1164 out_err:
1165 ret_val = 0;
1166 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001167}
1168
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001169
1170/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001171 * converts <str> to two struct in6_addr* which must be pre-allocated.
1172 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1173 * is an optionnal number of bits (128 being the default).
1174 * Returns 1 if OK, 0 if error.
1175 */
1176int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1177{
1178 char *c, *s;
1179 int ret_val = 0;
1180 char *err;
1181 unsigned long len = 128;
1182
1183 s = strdup(str);
1184 if (!s)
1185 return 0;
1186
1187 memset(mask, 0, sizeof(*mask));
1188 memset(addr, 0, sizeof(*addr));
1189
1190 if ((c = strrchr(s, '/')) != NULL) {
1191 *c++ = '\0'; /* c points to the mask */
1192 if (!*c)
1193 goto out_free;
1194
1195 len = strtoul(c, &err, 10);
1196 if ((err && *err) || (unsigned)len > 128)
1197 goto out_free;
1198 }
1199 *mask = len; /* OK we have a valid mask in <len> */
1200
1201 if (!inet_pton(AF_INET6, s, addr))
1202 goto out_free;
1203
1204 ret_val = 1;
1205 out_free:
1206 free(s);
1207 return ret_val;
1208}
1209
1210
1211/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001212 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001213 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001214int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001215{
1216 int saw_digit, octets, ch;
1217 u_char tmp[4], *tp;
1218 const char *cp = addr;
1219
1220 saw_digit = 0;
1221 octets = 0;
1222 *(tp = tmp) = 0;
1223
1224 while (*addr) {
1225 unsigned char digit = (ch = *addr++) - '0';
1226 if (digit > 9 && ch != '.')
1227 break;
1228 if (digit <= 9) {
1229 u_int new = *tp * 10 + digit;
1230 if (new > 255)
1231 return 0;
1232 *tp = new;
1233 if (!saw_digit) {
1234 if (++octets > 4)
1235 return 0;
1236 saw_digit = 1;
1237 }
1238 } else if (ch == '.' && saw_digit) {
1239 if (octets == 4)
1240 return 0;
1241 *++tp = 0;
1242 saw_digit = 0;
1243 } else
1244 return 0;
1245 }
1246
1247 if (octets < 4)
1248 return 0;
1249
1250 memcpy(&dst->s_addr, tmp, 4);
1251 return addr-cp-1;
1252}
1253
1254/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001255 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1256 * <out> contain the code of the dectected scheme, the start and length of
1257 * the hostname. Actually only http and https are supported. <out> can be NULL.
1258 * This function returns the consumed length. It is useful if you parse complete
1259 * url like http://host:port/path, because the consumed length corresponds to
1260 * the first character of the path. If the conversion fails, it returns -1.
1261 *
1262 * This function tries to resolve the DNS name if haproxy is in starting mode.
1263 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001264 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001265int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001266{
1267 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001268 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001269 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001270 unsigned long long int http_code = 0;
1271 int default_port;
1272 struct hostent *he;
1273 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001274
1275 /* Firstly, try to find :// pattern */
1276 while (curr < url+ulen && url_code != 0x3a2f2f) {
1277 url_code = ((url_code & 0xffff) << 8);
1278 url_code += (unsigned char)*curr++;
1279 }
1280
1281 /* Secondly, if :// pattern is found, verify parsed stuff
1282 * before pattern is matching our http pattern.
1283 * If so parse ip address and port in uri.
1284 *
1285 * WARNING: Current code doesn't support dynamic async dns resolver.
1286 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001287 if (url_code != 0x3a2f2f)
1288 return -1;
1289
1290 /* Copy scheme, and utrn to lower case. */
1291 while (cp < curr - 3)
1292 http_code = (http_code << 8) + *cp++;
1293 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001294
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001295 /* HTTP or HTTPS url matching */
1296 if (http_code == 0x2020202068747470ULL) {
1297 default_port = 80;
1298 if (out)
1299 out->scheme = SCH_HTTP;
1300 }
1301 else if (http_code == 0x2020206874747073ULL) {
1302 default_port = 443;
1303 if (out)
1304 out->scheme = SCH_HTTPS;
1305 }
1306 else
1307 return -1;
1308
1309 /* If the next char is '[', the host address is IPv6. */
1310 if (*curr == '[') {
1311 curr++;
1312
1313 /* Check trash size */
1314 if (trash.size < ulen)
1315 return -1;
1316
1317 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001318 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001319 for (end = curr;
1320 end < url + ulen && *end != ']';
1321 end++, p++)
1322 *p = *end;
1323 if (*end != ']')
1324 return -1;
1325 *p = '\0';
1326
1327 /* Update out. */
1328 if (out) {
1329 out->host = curr;
1330 out->host_len = end - curr;
1331 }
1332
1333 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001334 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001335 return -1;
1336 end++;
1337
1338 /* Decode port. */
1339 if (*end == ':') {
1340 end++;
1341 default_port = read_uint(&end, url + ulen);
1342 }
1343 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1344 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1345 return end - url;
1346 }
1347 else {
1348 /* We are looking for IP address. If you want to parse and
1349 * resolve hostname found in url, you can use str2sa_range(), but
1350 * be warned this can slow down global daemon performances
1351 * while handling lagging dns responses.
1352 */
1353 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1354 if (ret) {
1355 /* Update out. */
1356 if (out) {
1357 out->host = curr;
1358 out->host_len = ret;
1359 }
1360
1361 curr += ret;
1362
1363 /* Decode port. */
1364 if (*curr == ':') {
1365 curr++;
1366 default_port = read_uint(&curr, url + ulen);
1367 }
1368 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1369
1370 /* Set family. */
1371 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1372 return curr - url;
1373 }
1374 else if (global.mode & MODE_STARTING) {
1375 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1376 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001377 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001378
1379 /* look for : or / or end */
1380 for (end = curr;
1381 end < url + ulen && *end != '/' && *end != ':';
1382 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001383 memcpy(trash.area, curr, end - curr);
1384 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001385
1386 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001387 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001388 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001389 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001390
1391 /* Update out. */
1392 if (out) {
1393 out->host = curr;
1394 out->host_len = end - curr;
1395 }
1396
1397 /* Decode port. */
1398 if (*end == ':') {
1399 end++;
1400 default_port = read_uint(&end, url + ulen);
1401 }
1402
1403 /* Copy IP address, set port and family. */
1404 switch (he->h_addrtype) {
1405 case AF_INET:
1406 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1407 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1408 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1409 return end - url;
1410
1411 case AF_INET6:
1412 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1413 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1414 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1415 return end - url;
1416 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001417 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001418 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001419 return -1;
1420}
1421
Willy Tarreau631f01c2011-09-05 00:36:48 +02001422/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1423 * address family is returned so that it's easy for the caller to adapt to the
1424 * output format. Zero is returned if the address family is not supported. -1
1425 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1426 * supported.
1427 */
1428int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1429{
1430
1431 void *ptr;
1432
1433 if (size < 5)
1434 return 0;
1435 *str = '\0';
1436
1437 switch (addr->ss_family) {
1438 case AF_INET:
1439 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1440 break;
1441 case AF_INET6:
1442 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1443 break;
1444 case AF_UNIX:
1445 memcpy(str, "unix", 5);
1446 return addr->ss_family;
1447 default:
1448 return 0;
1449 }
1450
1451 if (inet_ntop(addr->ss_family, ptr, str, size))
1452 return addr->ss_family;
1453
1454 /* failed */
1455 return -1;
1456}
1457
Simon Horman75ab8bd2014-06-16 09:39:41 +09001458/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1459 * address family is returned so that it's easy for the caller to adapt to the
1460 * output format. Zero is returned if the address family is not supported. -1
1461 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1462 * supported.
1463 */
1464int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1465{
1466
1467 uint16_t port;
1468
1469
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001470 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001471 return 0;
1472 *str = '\0';
1473
1474 switch (addr->ss_family) {
1475 case AF_INET:
1476 port = ((struct sockaddr_in *)addr)->sin_port;
1477 break;
1478 case AF_INET6:
1479 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1480 break;
1481 case AF_UNIX:
1482 memcpy(str, "unix", 5);
1483 return addr->ss_family;
1484 default:
1485 return 0;
1486 }
1487
1488 snprintf(str, size, "%u", ntohs(port));
1489 return addr->ss_family;
1490}
1491
Willy Tarreau16e01562016-08-09 16:46:18 +02001492/* check if the given address is local to the system or not. It will return
1493 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1494 * it is. We don't want to iterate over all interfaces for this (and it is not
1495 * portable). So instead we try to bind in UDP to this address on a free non
1496 * privileged port and to connect to the same address, port 0 (connect doesn't
1497 * care). If it succeeds, we own the address. Note that non-inet addresses are
1498 * considered local since they're most likely AF_UNIX.
1499 */
1500int addr_is_local(const struct netns_entry *ns,
1501 const struct sockaddr_storage *orig)
1502{
1503 struct sockaddr_storage addr;
1504 int result;
1505 int fd;
1506
1507 if (!is_inet_addr(orig))
1508 return 1;
1509
1510 memcpy(&addr, orig, sizeof(addr));
1511 set_host_port(&addr, 0);
1512
1513 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1514 if (fd < 0)
1515 return -1;
1516
1517 result = -1;
1518 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1519 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1520 result = 0; // fail, non-local address
1521 else
1522 result = 1; // success, local address
1523 }
1524 else {
1525 if (errno == EADDRNOTAVAIL)
1526 result = 0; // definitely not local :-)
1527 }
1528 close(fd);
1529
1530 return result;
1531}
1532
Willy Tarreaubaaee002006-06-26 02:48:02 +02001533/* will try to encode the string <string> replacing all characters tagged in
1534 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1535 * prefixed by <escape>, and will store the result between <start> (included)
1536 * and <stop> (excluded), and will always terminate the string with a '\0'
1537 * before <stop>. The position of the '\0' is returned if the conversion
1538 * completes. If bytes are missing between <start> and <stop>, then the
1539 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1540 * cannot even be stored so we return <start> without writing the 0.
1541 * The input string must also be zero-terminated.
1542 */
1543const char hextab[16] = "0123456789ABCDEF";
1544char *encode_string(char *start, char *stop,
1545 const char escape, const fd_set *map,
1546 const char *string)
1547{
1548 if (start < stop) {
1549 stop--; /* reserve one byte for the final '\0' */
1550 while (start < stop && *string != '\0') {
1551 if (!FD_ISSET((unsigned char)(*string), map))
1552 *start++ = *string;
1553 else {
1554 if (start + 3 >= stop)
1555 break;
1556 *start++ = escape;
1557 *start++ = hextab[(*string >> 4) & 15];
1558 *start++ = hextab[*string & 15];
1559 }
1560 string++;
1561 }
1562 *start = '\0';
1563 }
1564 return start;
1565}
1566
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001567/*
1568 * Same behavior as encode_string() above, except that it encodes chunk
1569 * <chunk> instead of a string.
1570 */
1571char *encode_chunk(char *start, char *stop,
1572 const char escape, const fd_set *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001573 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001574{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001575 char *str = chunk->area;
1576 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001577
1578 if (start < stop) {
1579 stop--; /* reserve one byte for the final '\0' */
1580 while (start < stop && str < end) {
1581 if (!FD_ISSET((unsigned char)(*str), map))
1582 *start++ = *str;
1583 else {
1584 if (start + 3 >= stop)
1585 break;
1586 *start++ = escape;
1587 *start++ = hextab[(*str >> 4) & 15];
1588 *start++ = hextab[*str & 15];
1589 }
1590 str++;
1591 }
1592 *start = '\0';
1593 }
1594 return start;
1595}
1596
Dragan Dosen0edd1092016-02-12 13:23:02 +01001597/*
1598 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001599 * character. The input <string> must be zero-terminated. The result will
1600 * be stored between <start> (included) and <stop> (excluded). This
1601 * function will always try to terminate the resulting string with a '\0'
1602 * before <stop>, and will return its position if the conversion
1603 * completes.
1604 */
1605char *escape_string(char *start, char *stop,
1606 const char escape, const fd_set *map,
1607 const char *string)
1608{
1609 if (start < stop) {
1610 stop--; /* reserve one byte for the final '\0' */
1611 while (start < stop && *string != '\0') {
1612 if (!FD_ISSET((unsigned char)(*string), map))
1613 *start++ = *string;
1614 else {
1615 if (start + 2 >= stop)
1616 break;
1617 *start++ = escape;
1618 *start++ = *string;
1619 }
1620 string++;
1621 }
1622 *start = '\0';
1623 }
1624 return start;
1625}
1626
1627/*
1628 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001629 * character. <chunk> contains the input to be escaped. The result will be
1630 * stored between <start> (included) and <stop> (excluded). The function
1631 * will always try to terminate the resulting string with a '\0' before
1632 * <stop>, and will return its position if the conversion completes.
1633 */
1634char *escape_chunk(char *start, char *stop,
1635 const char escape, const fd_set *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001636 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001637{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001638 char *str = chunk->area;
1639 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001640
1641 if (start < stop) {
1642 stop--; /* reserve one byte for the final '\0' */
1643 while (start < stop && str < end) {
1644 if (!FD_ISSET((unsigned char)(*str), map))
1645 *start++ = *str;
1646 else {
1647 if (start + 2 >= stop)
1648 break;
1649 *start++ = escape;
1650 *start++ = *str;
1651 }
1652 str++;
1653 }
1654 *start = '\0';
1655 }
1656 return start;
1657}
1658
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001659/* Check a string for using it in a CSV output format. If the string contains
1660 * one of the following four char <">, <,>, CR or LF, the string is
1661 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1662 * <str> is the input string to be escaped. The function assumes that
1663 * the input string is null-terminated.
1664 *
1665 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001666 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001667 * format.
1668 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001669 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001670 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001671 * If <quote> is 1, the converter puts the quotes only if any reserved character
1672 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001673 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001674 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001675 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001676 * The function returns the converted string on its output. If an error
1677 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001678 * for using the function directly as printf() argument.
1679 *
1680 * If the output buffer is too short to contain the input string, the result
1681 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001682 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001683 * This function appends the encoding to the existing output chunk, and it
1684 * guarantees that it starts immediately at the first available character of
1685 * the chunk. Please use csv_enc() instead if you want to replace the output
1686 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001687 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001688const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001689{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001690 char *end = output->area + output->size;
1691 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001692 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001693
Willy Tarreaub631c292016-01-08 10:04:08 +01001694 if (quote == 1) {
1695 /* automatic quoting: first verify if we'll have to quote the string */
1696 if (!strpbrk(str, "\n\r,\""))
1697 quote = 0;
1698 }
1699
1700 if (quote)
1701 *ptr++ = '"';
1702
Willy Tarreau898529b2016-01-06 18:07:04 +01001703 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1704 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001705 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001706 ptr++;
1707 if (ptr >= end - 2) {
1708 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001709 break;
1710 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001711 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001712 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001713 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001714 str++;
1715 }
1716
Willy Tarreaub631c292016-01-08 10:04:08 +01001717 if (quote)
1718 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001719
Willy Tarreau898529b2016-01-06 18:07:04 +01001720 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001721 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001722 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001723}
1724
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001725/* Decode an URL-encoded string in-place. The resulting string might
1726 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001727 * aborted, the string is truncated before the issue and a negative value is
1728 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001729 */
1730int url_decode(char *string)
1731{
1732 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001733 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001734
1735 in = string;
1736 out = string;
1737 while (*in) {
1738 switch (*in) {
1739 case '+' :
1740 *out++ = ' ';
1741 break;
1742 case '%' :
1743 if (!ishex(in[1]) || !ishex(in[2]))
1744 goto end;
1745 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1746 in += 2;
1747 break;
1748 default:
1749 *out++ = *in;
1750 break;
1751 }
1752 in++;
1753 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001754 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001755 end:
1756 *out = 0;
1757 return ret;
1758}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001759
Willy Tarreau6911fa42007-03-04 18:06:08 +01001760unsigned int str2ui(const char *s)
1761{
1762 return __str2ui(s);
1763}
1764
1765unsigned int str2uic(const char *s)
1766{
1767 return __str2uic(s);
1768}
1769
1770unsigned int strl2ui(const char *s, int len)
1771{
1772 return __strl2ui(s, len);
1773}
1774
1775unsigned int strl2uic(const char *s, int len)
1776{
1777 return __strl2uic(s, len);
1778}
1779
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001780unsigned int read_uint(const char **s, const char *end)
1781{
1782 return __read_uint(s, end);
1783}
1784
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001785/* This function reads an unsigned integer from the string pointed to by <s> and
1786 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1787 * function automatically stops at <end>. If the number overflows, the 2^64-1
1788 * value is returned.
1789 */
1790unsigned long long int read_uint64(const char **s, const char *end)
1791{
1792 const char *ptr = *s;
1793 unsigned long long int i = 0, tmp;
1794 unsigned int j;
1795
1796 while (ptr < end) {
1797
1798 /* read next char */
1799 j = *ptr - '0';
1800 if (j > 9)
1801 goto read_uint64_end;
1802
1803 /* add char to the number and check overflow. */
1804 tmp = i * 10;
1805 if (tmp / 10 != i) {
1806 i = ULLONG_MAX;
1807 goto read_uint64_eat;
1808 }
1809 if (ULLONG_MAX - tmp < j) {
1810 i = ULLONG_MAX;
1811 goto read_uint64_eat;
1812 }
1813 i = tmp + j;
1814 ptr++;
1815 }
1816read_uint64_eat:
1817 /* eat each numeric char */
1818 while (ptr < end) {
1819 if ((unsigned int)(*ptr - '0') > 9)
1820 break;
1821 ptr++;
1822 }
1823read_uint64_end:
1824 *s = ptr;
1825 return i;
1826}
1827
1828/* This function reads an integer from the string pointed to by <s> and returns
1829 * it. The <s> pointer is adjusted to point to the first unread char. The function
1830 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1831 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1832 * returned.
1833 */
1834long long int read_int64(const char **s, const char *end)
1835{
1836 unsigned long long int i = 0;
1837 int neg = 0;
1838
1839 /* Look for minus char. */
1840 if (**s == '-') {
1841 neg = 1;
1842 (*s)++;
1843 }
1844 else if (**s == '+')
1845 (*s)++;
1846
1847 /* convert as positive number. */
1848 i = read_uint64(s, end);
1849
1850 if (neg) {
1851 if (i > 0x8000000000000000ULL)
1852 return LLONG_MIN;
1853 return -i;
1854 }
1855 if (i > 0x7fffffffffffffffULL)
1856 return LLONG_MAX;
1857 return i;
1858}
1859
Willy Tarreau6911fa42007-03-04 18:06:08 +01001860/* This one is 7 times faster than strtol() on athlon with checks.
1861 * It returns the value of the number composed of all valid digits read,
1862 * and can process negative numbers too.
1863 */
1864int strl2ic(const char *s, int len)
1865{
1866 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001867 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001868
1869 if (len > 0) {
1870 if (*s != '-') {
1871 /* positive number */
1872 while (len-- > 0) {
1873 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001874 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001875 if (j > 9)
1876 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001877 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001878 }
1879 } else {
1880 /* negative number */
1881 s++;
1882 while (--len > 0) {
1883 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001884 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001885 if (j > 9)
1886 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001887 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001888 }
1889 }
1890 }
1891 return i;
1892}
1893
1894
1895/* This function reads exactly <len> chars from <s> and converts them to a
1896 * signed integer which it stores into <ret>. It accurately detects any error
1897 * (truncated string, invalid chars, overflows). It is meant to be used in
1898 * applications designed for hostile environments. It returns zero when the
1899 * number has successfully been converted, non-zero otherwise. When an error
1900 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1901 * faster than strtol().
1902 */
1903int strl2irc(const char *s, int len, int *ret)
1904{
1905 int i = 0;
1906 int j;
1907
1908 if (!len)
1909 return 1;
1910
1911 if (*s != '-') {
1912 /* positive number */
1913 while (len-- > 0) {
1914 j = (*s++) - '0';
1915 if (j > 9) return 1; /* invalid char */
1916 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1917 i = i * 10;
1918 if (i + j < i) return 1; /* check for addition overflow */
1919 i = i + j;
1920 }
1921 } else {
1922 /* negative number */
1923 s++;
1924 while (--len > 0) {
1925 j = (*s++) - '0';
1926 if (j > 9) return 1; /* invalid char */
1927 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1928 i = i * 10;
1929 if (i - j > i) return 1; /* check for subtract overflow */
1930 i = i - j;
1931 }
1932 }
1933 *ret = i;
1934 return 0;
1935}
1936
1937
1938/* This function reads exactly <len> chars from <s> and converts them to a
1939 * signed integer which it stores into <ret>. It accurately detects any error
1940 * (truncated string, invalid chars, overflows). It is meant to be used in
1941 * applications designed for hostile environments. It returns zero when the
1942 * number has successfully been converted, non-zero otherwise. When an error
1943 * is returned, the <ret> value is left untouched. It is about 3 times slower
1944 * than str2irc().
1945 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001946
1947int strl2llrc(const char *s, int len, long long *ret)
1948{
1949 long long i = 0;
1950 int j;
1951
1952 if (!len)
1953 return 1;
1954
1955 if (*s != '-') {
1956 /* positive number */
1957 while (len-- > 0) {
1958 j = (*s++) - '0';
1959 if (j > 9) return 1; /* invalid char */
1960 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1961 i = i * 10LL;
1962 if (i + j < i) return 1; /* check for addition overflow */
1963 i = i + j;
1964 }
1965 } else {
1966 /* negative number */
1967 s++;
1968 while (--len > 0) {
1969 j = (*s++) - '0';
1970 if (j > 9) return 1; /* invalid char */
1971 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1972 i = i * 10LL;
1973 if (i - j > i) return 1; /* check for subtract overflow */
1974 i = i - j;
1975 }
1976 }
1977 *ret = i;
1978 return 0;
1979}
1980
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001981/* This function is used with pat_parse_dotted_ver(). It converts a string
1982 * composed by two number separated by a dot. Each part must contain in 16 bits
1983 * because internally they will be represented as a 32-bit quantity stored in
1984 * a 64-bit integer. It returns zero when the number has successfully been
1985 * converted, non-zero otherwise. When an error is returned, the <ret> value
1986 * is left untouched.
1987 *
1988 * "1.3" -> 0x0000000000010003
1989 * "65535.65535" -> 0x00000000ffffffff
1990 */
1991int strl2llrc_dotted(const char *text, int len, long long *ret)
1992{
1993 const char *end = &text[len];
1994 const char *p;
1995 long long major, minor;
1996
1997 /* Look for dot. */
1998 for (p = text; p < end; p++)
1999 if (*p == '.')
2000 break;
2001
2002 /* Convert major. */
2003 if (strl2llrc(text, p - text, &major) != 0)
2004 return 1;
2005
2006 /* Check major. */
2007 if (major >= 65536)
2008 return 1;
2009
2010 /* Convert minor. */
2011 minor = 0;
2012 if (p < end)
2013 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2014 return 1;
2015
2016 /* Check minor. */
2017 if (minor >= 65536)
2018 return 1;
2019
2020 /* Compose value. */
2021 *ret = (major << 16) | (minor & 0xffff);
2022 return 0;
2023}
2024
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002025/* This function parses a time value optionally followed by a unit suffix among
2026 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2027 * expected by the caller. The computation does its best to avoid overflows.
2028 * The value is returned in <ret> if everything is fine, and a NULL is returned
2029 * by the function. In case of error, a pointer to the error is returned and
2030 * <ret> is left untouched. Values are automatically rounded up when needed.
2031 */
2032const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2033{
2034 unsigned imult, idiv;
2035 unsigned omult, odiv;
2036 unsigned value;
2037
2038 omult = odiv = 1;
2039
2040 switch (unit_flags & TIME_UNIT_MASK) {
2041 case TIME_UNIT_US: omult = 1000000; break;
2042 case TIME_UNIT_MS: omult = 1000; break;
2043 case TIME_UNIT_S: break;
2044 case TIME_UNIT_MIN: odiv = 60; break;
2045 case TIME_UNIT_HOUR: odiv = 3600; break;
2046 case TIME_UNIT_DAY: odiv = 86400; break;
2047 default: break;
2048 }
2049
2050 value = 0;
2051
2052 while (1) {
2053 unsigned int j;
2054
2055 j = *text - '0';
2056 if (j > 9)
2057 break;
2058 text++;
2059 value *= 10;
2060 value += j;
2061 }
2062
2063 imult = idiv = 1;
2064 switch (*text) {
2065 case '\0': /* no unit = default unit */
2066 imult = omult = idiv = odiv = 1;
2067 break;
2068 case 's': /* second = unscaled unit */
2069 break;
2070 case 'u': /* microsecond : "us" */
2071 if (text[1] == 's') {
2072 idiv = 1000000;
2073 text++;
2074 }
2075 break;
2076 case 'm': /* millisecond : "ms" or minute: "m" */
2077 if (text[1] == 's') {
2078 idiv = 1000;
2079 text++;
2080 } else
2081 imult = 60;
2082 break;
2083 case 'h': /* hour : "h" */
2084 imult = 3600;
2085 break;
2086 case 'd': /* day : "d" */
2087 imult = 86400;
2088 break;
2089 default:
2090 return text;
2091 break;
2092 }
2093
2094 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2095 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2096 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2097 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2098
2099 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2100 *ret = value;
2101 return NULL;
2102}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002103
Emeric Brun39132b22010-01-04 14:57:24 +01002104/* this function converts the string starting at <text> to an unsigned int
2105 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002106 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002107 */
2108const char *parse_size_err(const char *text, unsigned *ret) {
2109 unsigned value = 0;
2110
2111 while (1) {
2112 unsigned int j;
2113
2114 j = *text - '0';
2115 if (j > 9)
2116 break;
2117 if (value > ~0U / 10)
2118 return text;
2119 value *= 10;
2120 if (value > (value + j))
2121 return text;
2122 value += j;
2123 text++;
2124 }
2125
2126 switch (*text) {
2127 case '\0':
2128 break;
2129 case 'K':
2130 case 'k':
2131 if (value > ~0U >> 10)
2132 return text;
2133 value = value << 10;
2134 break;
2135 case 'M':
2136 case 'm':
2137 if (value > ~0U >> 20)
2138 return text;
2139 value = value << 20;
2140 break;
2141 case 'G':
2142 case 'g':
2143 if (value > ~0U >> 30)
2144 return text;
2145 value = value << 30;
2146 break;
2147 default:
2148 return text;
2149 }
2150
Godbach58048a22015-01-28 17:36:16 +08002151 if (*text != '\0' && *++text != '\0')
2152 return text;
2153
Emeric Brun39132b22010-01-04 14:57:24 +01002154 *ret = value;
2155 return NULL;
2156}
2157
Willy Tarreau126d4062013-12-03 17:50:47 +01002158/*
2159 * Parse binary string written in hexadecimal (source) and store the decoded
2160 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2161 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002162 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002163 */
2164int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2165{
2166 int len;
2167 const char *p = source;
2168 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002169 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002170
2171 len = strlen(source);
2172 if (len % 2) {
2173 memprintf(err, "an even number of hex digit is expected");
2174 return 0;
2175 }
2176
2177 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002178
Willy Tarreau126d4062013-12-03 17:50:47 +01002179 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002180 *binstr = calloc(len, sizeof(char));
2181 if (!*binstr) {
2182 memprintf(err, "out of memory while loading string pattern");
2183 return 0;
2184 }
2185 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002186 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002187 else {
2188 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002189 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002190 len, *binstrlen);
2191 return 0;
2192 }
2193 alloc = 0;
2194 }
2195 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002196
2197 i = j = 0;
2198 while (j < len) {
2199 if (!ishex(p[i++]))
2200 goto bad_input;
2201 if (!ishex(p[i++]))
2202 goto bad_input;
2203 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2204 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002205 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002206
2207bad_input:
2208 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002209 if (alloc) {
2210 free(*binstr);
2211 *binstr = NULL;
2212 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002213 return 0;
2214}
2215
Willy Tarreau946ba592009-05-10 15:41:18 +02002216/* copies at most <n> characters from <src> and always terminates with '\0' */
2217char *my_strndup(const char *src, int n)
2218{
2219 int len = 0;
2220 char *ret;
2221
2222 while (len < n && src[len])
2223 len++;
2224
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002225 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002226 if (!ret)
2227 return ret;
2228 memcpy(ret, src, len);
2229 ret[len] = '\0';
2230 return ret;
2231}
2232
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002233/*
2234 * search needle in haystack
2235 * returns the pointer if found, returns NULL otherwise
2236 */
2237const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2238{
2239 const void *c = NULL;
2240 unsigned char f;
2241
2242 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2243 return NULL;
2244
2245 f = *(char *)needle;
2246 c = haystack;
2247 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2248 if ((haystacklen - (c - haystack)) < needlelen)
2249 return NULL;
2250
2251 if (memcmp(c, needle, needlelen) == 0)
2252 return c;
2253 ++c;
2254 }
2255 return NULL;
2256}
2257
Willy Tarreau482b00d2009-10-04 22:48:42 +02002258/* This function returns the first unused key greater than or equal to <key> in
2259 * ID tree <root>. Zero is returned if no place is found.
2260 */
2261unsigned int get_next_id(struct eb_root *root, unsigned int key)
2262{
2263 struct eb32_node *used;
2264
2265 do {
2266 used = eb32_lookup_ge(root, key);
2267 if (!used || used->key > key)
2268 return key; /* key is available */
2269 key++;
2270 } while (key);
2271 return key;
2272}
2273
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002274/* dump the full tree to <file> in DOT format for debugging purposes. Will
2275 * optionally highlight node <subj> if found, depending on operation <op> :
2276 * 0 : nothing
2277 * >0 : insertion, node/leaf are surrounded in red
2278 * <0 : removal, node/leaf are dashed with no background
2279 * Will optionally add "desc" as a label on the graph if set and non-null.
2280 */
2281void 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 +01002282{
2283 struct eb32sc_node *node;
2284 unsigned long scope = -1;
2285
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002286 fprintf(file, "digraph ebtree {\n");
2287
2288 if (desc && *desc) {
2289 fprintf(file,
2290 " fontname=\"fixed\";\n"
2291 " fontsize=8;\n"
2292 " label=\"%s\";\n", desc);
2293 }
2294
Willy Tarreaued3cda02017-11-15 15:04:05 +01002295 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002296 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2297 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002298 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2299 );
2300
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002301 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002302 (long)eb_root_to_node(root),
2303 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002304 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2305
2306 node = eb32sc_first(root, scope);
2307 while (node) {
2308 if (node->node.node_p) {
2309 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002310 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2311 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2312 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002313
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002314 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002315 (long)node,
2316 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002317 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002318
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002319 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002320 (long)node,
2321 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002322 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2323
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002324 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002325 (long)node,
2326 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002327 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2328 }
2329
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002330 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2331 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2332 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002333
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002334 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002335 (long)node,
2336 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002337 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002338 node = eb32sc_next(node, scope);
2339 }
2340 fprintf(file, "}\n");
2341}
2342
Willy Tarreau348238b2010-01-18 15:05:57 +01002343/* This function compares a sample word possibly followed by blanks to another
2344 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2345 * otherwise zero. This intends to be used when checking HTTP headers for some
2346 * values. Note that it validates a word followed only by blanks but does not
2347 * validate a word followed by blanks then other chars.
2348 */
2349int word_match(const char *sample, int slen, const char *word, int wlen)
2350{
2351 if (slen < wlen)
2352 return 0;
2353
2354 while (wlen) {
2355 char c = *sample ^ *word;
2356 if (c && c != ('A' ^ 'a'))
2357 return 0;
2358 sample++;
2359 word++;
2360 slen--;
2361 wlen--;
2362 }
2363
2364 while (slen) {
2365 if (*sample != ' ' && *sample != '\t')
2366 return 0;
2367 sample++;
2368 slen--;
2369 }
2370 return 1;
2371}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002372
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002373/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2374 * is particularly fast because it avoids expensive operations such as
2375 * multiplies, which are optimized away at the end. It requires a properly
2376 * formated address though (3 points).
2377 */
2378unsigned int inetaddr_host(const char *text)
2379{
2380 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2381 register unsigned int dig100, dig10, dig1;
2382 int s;
2383 const char *p, *d;
2384
2385 dig1 = dig10 = dig100 = ascii_zero;
2386 s = 24;
2387
2388 p = text;
2389 while (1) {
2390 if (((unsigned)(*p - '0')) <= 9) {
2391 p++;
2392 continue;
2393 }
2394
2395 /* here, we have a complete byte between <text> and <p> (exclusive) */
2396 if (p == text)
2397 goto end;
2398
2399 d = p - 1;
2400 dig1 |= (unsigned int)(*d << s);
2401 if (d == text)
2402 goto end;
2403
2404 d--;
2405 dig10 |= (unsigned int)(*d << s);
2406 if (d == text)
2407 goto end;
2408
2409 d--;
2410 dig100 |= (unsigned int)(*d << s);
2411 end:
2412 if (!s || *p != '.')
2413 break;
2414
2415 s -= 8;
2416 text = ++p;
2417 }
2418
2419 dig100 -= ascii_zero;
2420 dig10 -= ascii_zero;
2421 dig1 -= ascii_zero;
2422 return ((dig100 * 10) + dig10) * 10 + dig1;
2423}
2424
2425/*
2426 * Idem except the first unparsed character has to be passed in <stop>.
2427 */
2428unsigned int inetaddr_host_lim(const char *text, const char *stop)
2429{
2430 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2431 register unsigned int dig100, dig10, dig1;
2432 int s;
2433 const char *p, *d;
2434
2435 dig1 = dig10 = dig100 = ascii_zero;
2436 s = 24;
2437
2438 p = text;
2439 while (1) {
2440 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2441 p++;
2442 continue;
2443 }
2444
2445 /* here, we have a complete byte between <text> and <p> (exclusive) */
2446 if (p == text)
2447 goto end;
2448
2449 d = p - 1;
2450 dig1 |= (unsigned int)(*d << s);
2451 if (d == text)
2452 goto end;
2453
2454 d--;
2455 dig10 |= (unsigned int)(*d << s);
2456 if (d == text)
2457 goto end;
2458
2459 d--;
2460 dig100 |= (unsigned int)(*d << s);
2461 end:
2462 if (!s || p == stop || *p != '.')
2463 break;
2464
2465 s -= 8;
2466 text = ++p;
2467 }
2468
2469 dig100 -= ascii_zero;
2470 dig10 -= ascii_zero;
2471 dig1 -= ascii_zero;
2472 return ((dig100 * 10) + dig10) * 10 + dig1;
2473}
2474
2475/*
2476 * Idem except the pointer to first unparsed byte is returned into <ret> which
2477 * must not be NULL.
2478 */
Willy Tarreau74172752010-10-15 23:21:42 +02002479unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002480{
2481 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2482 register unsigned int dig100, dig10, dig1;
2483 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002484 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002485
2486 dig1 = dig10 = dig100 = ascii_zero;
2487 s = 24;
2488
2489 p = text;
2490 while (1) {
2491 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2492 p++;
2493 continue;
2494 }
2495
2496 /* here, we have a complete byte between <text> and <p> (exclusive) */
2497 if (p == text)
2498 goto end;
2499
2500 d = p - 1;
2501 dig1 |= (unsigned int)(*d << s);
2502 if (d == text)
2503 goto end;
2504
2505 d--;
2506 dig10 |= (unsigned int)(*d << s);
2507 if (d == text)
2508 goto end;
2509
2510 d--;
2511 dig100 |= (unsigned int)(*d << s);
2512 end:
2513 if (!s || p == stop || *p != '.')
2514 break;
2515
2516 s -= 8;
2517 text = ++p;
2518 }
2519
2520 *ret = p;
2521 dig100 -= ascii_zero;
2522 dig10 -= ascii_zero;
2523 dig1 -= ascii_zero;
2524 return ((dig100 * 10) + dig10) * 10 + dig1;
2525}
2526
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002527/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2528 * or the number of chars read in case of success. Maybe this could be replaced
2529 * by one of the functions above. Also, apparently this function does not support
2530 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002531 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002532 */
2533int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2534{
2535 const char *addr;
2536 int saw_digit, octets, ch;
2537 u_char tmp[4], *tp;
2538 const char *cp = buf;
2539
2540 saw_digit = 0;
2541 octets = 0;
2542 *(tp = tmp) = 0;
2543
2544 for (addr = buf; addr - buf < len; addr++) {
2545 unsigned char digit = (ch = *addr) - '0';
2546
2547 if (digit > 9 && ch != '.')
2548 break;
2549
2550 if (digit <= 9) {
2551 u_int new = *tp * 10 + digit;
2552
2553 if (new > 255)
2554 return 0;
2555
2556 *tp = new;
2557
2558 if (!saw_digit) {
2559 if (++octets > 4)
2560 return 0;
2561 saw_digit = 1;
2562 }
2563 } else if (ch == '.' && saw_digit) {
2564 if (octets == 4)
2565 return 0;
2566
2567 *++tp = 0;
2568 saw_digit = 0;
2569 } else
2570 return 0;
2571 }
2572
2573 if (octets < 4)
2574 return 0;
2575
2576 memcpy(&dst->s_addr, tmp, 4);
2577 return addr - cp;
2578}
2579
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002580/* This function converts the string in <buf> of the len <len> to
2581 * struct in6_addr <dst> which must be allocated by the caller.
2582 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002583 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002584 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002585int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2586{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002587 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002588 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002589
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002590 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002591 return 0;
2592
2593 memcpy(null_term_ip6, buf, len);
2594 null_term_ip6[len] = '\0';
2595
Willy Tarreau075415a2013-12-12 11:29:39 +01002596 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002597 return 0;
2598
Willy Tarreau075415a2013-12-12 11:29:39 +01002599 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002600 return 1;
2601}
2602
Willy Tarreauacf95772010-06-14 19:09:21 +02002603/* To be used to quote config arg positions. Returns the short string at <ptr>
2604 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2605 * if ptr is NULL or empty. The string is locally allocated.
2606 */
2607const char *quote_arg(const char *ptr)
2608{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002609 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002610 int i;
2611
2612 if (!ptr || !*ptr)
2613 return "end of line";
2614 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002615 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002616 val[i] = *ptr++;
2617 val[i++] = '\'';
2618 val[i] = '\0';
2619 return val;
2620}
2621
Willy Tarreau5b180202010-07-18 10:40:48 +02002622/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2623int get_std_op(const char *str)
2624{
2625 int ret = -1;
2626
2627 if (*str == 'e' && str[1] == 'q')
2628 ret = STD_OP_EQ;
2629 else if (*str == 'n' && str[1] == 'e')
2630 ret = STD_OP_NE;
2631 else if (*str == 'l') {
2632 if (str[1] == 'e') ret = STD_OP_LE;
2633 else if (str[1] == 't') ret = STD_OP_LT;
2634 }
2635 else if (*str == 'g') {
2636 if (str[1] == 'e') ret = STD_OP_GE;
2637 else if (str[1] == 't') ret = STD_OP_GT;
2638 }
2639
2640 if (ret == -1 || str[2] != '\0')
2641 return -1;
2642 return ret;
2643}
2644
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002645/* hash a 32-bit integer to another 32-bit integer */
2646unsigned int full_hash(unsigned int a)
2647{
2648 return __full_hash(a);
2649}
2650
David du Colombier4f92d322011-03-24 11:09:31 +01002651/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002652 * otherwise zero. Note that <addr> may not necessarily be aligned
2653 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002654 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002655int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002656{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002657 struct in_addr addr_copy;
2658
2659 memcpy(&addr_copy, addr, sizeof(addr_copy));
2660 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002661}
2662
2663/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002664 * otherwise zero. Note that <addr> may not necessarily be aligned
2665 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002666 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002667int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002668{
2669 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002670 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002671
Willy Tarreaueec1d382016-07-13 11:59:39 +02002672 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002673 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002674 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002675 (((int *)net)[i] & ((int *)mask)[i]))
2676 return 0;
2677 return 1;
2678}
2679
2680/* RFC 4291 prefix */
2681const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2682 0x00, 0x00, 0x00, 0x00,
2683 0x00, 0x00, 0xFF, 0xFF };
2684
Joseph Herlant32b83272018-11-15 11:58:28 -08002685/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002686 * Input and output may overlap.
2687 */
David du Colombier4f92d322011-03-24 11:09:31 +01002688void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2689{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002690 struct in_addr tmp_addr;
2691
2692 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002693 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002694 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002695}
2696
Joseph Herlant32b83272018-11-15 11:58:28 -08002697/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002698 * Return true if conversion is possible and false otherwise.
2699 */
2700int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2701{
2702 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2703 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2704 sizeof(struct in_addr));
2705 return 1;
2706 }
2707
2708 return 0;
2709}
2710
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002711/* compare two struct sockaddr_storage and return:
2712 * 0 (true) if the addr is the same in both
2713 * 1 (false) if the addr is not the same in both
2714 * -1 (unable) if one of the addr is not AF_INET*
2715 */
2716int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2717{
2718 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2719 return -1;
2720
2721 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2722 return -1;
2723
2724 if (ss1->ss_family != ss2->ss_family)
2725 return 1;
2726
2727 switch (ss1->ss_family) {
2728 case AF_INET:
2729 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2730 &((struct sockaddr_in *)ss2)->sin_addr,
2731 sizeof(struct in_addr)) != 0;
2732 case AF_INET6:
2733 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2734 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2735 sizeof(struct in6_addr)) != 0;
2736 }
2737
2738 return 1;
2739}
2740
Baptiste Assmann08396c82016-01-31 00:27:17 +01002741/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002742 * The caller must allocate and clear <dest> before calling.
2743 * The source must be in either AF_INET or AF_INET6 family, or the destination
2744 * address will be undefined. If the destination address used to hold a port,
2745 * it is preserved, so that this function can be used to switch to another
2746 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002747 */
2748struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2749{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002750 int prev_port;
2751
2752 prev_port = get_net_port(dest);
2753 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002754 dest->ss_family = source->ss_family;
2755
2756 /* copy new addr and apply it */
2757 switch (source->ss_family) {
2758 case AF_INET:
2759 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002760 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002761 break;
2762 case AF_INET6:
2763 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 +01002764 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002765 break;
2766 }
2767
2768 return dest;
2769}
2770
William Lallemand421f5b52012-02-06 18:15:57 +01002771char *human_time(int t, short hz_div) {
2772 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2773 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002774 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002775 int cnt=2; // print two numbers
2776
2777 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002778 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002779 return rv;
2780 }
2781
2782 if (unlikely(hz_div > 1))
2783 t /= hz_div;
2784
2785 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002786 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002787 cnt--;
2788 }
2789
2790 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002791 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002792 cnt--;
2793 }
2794
2795 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002796 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002797 cnt--;
2798 }
2799
2800 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002801 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002802
2803 return rv;
2804}
2805
2806const char *monthname[12] = {
2807 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2808 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2809};
2810
2811/* date2str_log: write a date in the format :
2812 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2813 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2814 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2815 *
2816 * without using sprintf. return a pointer to the last char written (\0) or
2817 * NULL if there isn't enough space.
2818 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002819char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002820{
2821
2822 if (size < 25) /* the size is fixed: 24 chars + \0 */
2823 return NULL;
2824
2825 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2826 *dst++ = '/';
2827 memcpy(dst, monthname[tm->tm_mon], 3); // month
2828 dst += 3;
2829 *dst++ = '/';
2830 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2831 *dst++ = ':';
2832 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2833 *dst++ = ':';
2834 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2835 *dst++ = ':';
2836 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2837 *dst++ = '.';
2838 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2839 dst += 3; // only the 3 first digits
2840 *dst = '\0';
2841
2842 return dst;
2843}
2844
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002845/* Base year used to compute leap years */
2846#define TM_YEAR_BASE 1900
2847
2848/* Return the difference in seconds between two times (leap seconds are ignored).
2849 * Retrieved from glibc 2.18 source code.
2850 */
2851static int my_tm_diff(const struct tm *a, const struct tm *b)
2852{
2853 /* Compute intervening leap days correctly even if year is negative.
2854 * Take care to avoid int overflow in leap day calculations,
2855 * but it's OK to assume that A and B are close to each other.
2856 */
2857 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2858 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2859 int a100 = a4 / 25 - (a4 % 25 < 0);
2860 int b100 = b4 / 25 - (b4 % 25 < 0);
2861 int a400 = a100 >> 2;
2862 int b400 = b100 >> 2;
2863 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2864 int years = a->tm_year - b->tm_year;
2865 int days = (365 * years + intervening_leap_days
2866 + (a->tm_yday - b->tm_yday));
2867 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2868 + (a->tm_min - b->tm_min))
2869 + (a->tm_sec - b->tm_sec));
2870}
2871
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002872/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002873 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002874 * The string returned has the same format as returned by strftime(... "%z", tm).
2875 * Offsets are kept in an internal cache for better performances.
2876 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002877const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002878{
2879 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002880 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002881
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002882 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002883 struct tm tm_gmt;
2884 int diff;
2885 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002886
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002887 /* Pretend DST not active if its status is unknown */
2888 if (isdst < 0)
2889 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002890
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002891 /* Fetch the offset and initialize it if needed */
2892 gmt_offset = gmt_offsets[isdst & 0x01];
2893 if (unlikely(!*gmt_offset)) {
2894 get_gmtime(t, &tm_gmt);
2895 diff = my_tm_diff(tm, &tm_gmt);
2896 if (diff < 0) {
2897 diff = -diff;
2898 *gmt_offset = '-';
2899 } else {
2900 *gmt_offset = '+';
2901 }
2902 diff /= 60; /* Convert to minutes */
2903 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2904 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002905
2906 return gmt_offset;
2907}
2908
William Lallemand421f5b52012-02-06 18:15:57 +01002909/* gmt2str_log: write a date in the format :
2910 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2911 * return a pointer to the last char written (\0) or
2912 * NULL if there isn't enough space.
2913 */
2914char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2915{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002916 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002917 return NULL;
2918
2919 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2920 *dst++ = '/';
2921 memcpy(dst, monthname[tm->tm_mon], 3); // month
2922 dst += 3;
2923 *dst++ = '/';
2924 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2925 *dst++ = ':';
2926 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2927 *dst++ = ':';
2928 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2929 *dst++ = ':';
2930 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2931 *dst++ = ' ';
2932 *dst++ = '+';
2933 *dst++ = '0';
2934 *dst++ = '0';
2935 *dst++ = '0';
2936 *dst++ = '0';
2937 *dst = '\0';
2938
2939 return dst;
2940}
2941
Yuxans Yao4e25b012012-10-19 10:36:09 +08002942/* localdate2str_log: write a date in the format :
2943 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002944 * Both t and tm must represent the same time.
2945 * return a pointer to the last char written (\0) or
2946 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002947 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002948char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002949{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002950 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002951 if (size < 27) /* the size is fixed: 26 chars + \0 */
2952 return NULL;
2953
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002954 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002955
Yuxans Yao4e25b012012-10-19 10:36:09 +08002956 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2957 *dst++ = '/';
2958 memcpy(dst, monthname[tm->tm_mon], 3); // month
2959 dst += 3;
2960 *dst++ = '/';
2961 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2962 *dst++ = ':';
2963 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2964 *dst++ = ':';
2965 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2966 *dst++ = ':';
2967 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2968 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002969 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002970 dst += 5;
2971 *dst = '\0';
2972
2973 return dst;
2974}
2975
Willy Tarreaucb1949b2017-07-19 19:05:29 +02002976/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
2977 * It is meant as a portable replacement for timegm() for use with valid inputs.
2978 * Returns undefined results for invalid dates (eg: months out of range 0..11).
2979 */
2980time_t my_timegm(const struct tm *tm)
2981{
2982 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
2983 * is thus (current month - 1)*28 + cumulated_N[month] to count the
2984 * sum of the extra N days for elapsed months. The sum of all these N
2985 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
2986 * in a 5-bit word. This means that with 60 bits we can represent a
2987 * matrix of all these values at once, which is fast and efficient to
2988 * access. The extra February day for leap years is not counted here.
2989 *
2990 * Jan : none = 0 (0)
2991 * Feb : Jan = 3 (3)
2992 * Mar : Jan..Feb = 3 (3 + 0)
2993 * Apr : Jan..Mar = 6 (3 + 0 + 3)
2994 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
2995 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
2996 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
2997 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
2998 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
2999 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3000 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3001 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3002 */
3003 uint64_t extra =
3004 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3005 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3006 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3007 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3008
3009 unsigned int y = tm->tm_year + 1900;
3010 unsigned int m = tm->tm_mon;
3011 unsigned long days = 0;
3012
3013 /* days since 1/1/1970 for full years */
3014 days += days_since_zero(y) - days_since_zero(1970);
3015
3016 /* days for full months in the current year */
3017 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3018
3019 /* count + 1 after March for leap years. A leap year is a year multiple
3020 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3021 * is leap, 1900 isn't, 1904 is.
3022 */
3023 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3024 days++;
3025
3026 days += tm->tm_mday - 1;
3027 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3028}
3029
Thierry Fournier93127942016-01-20 18:49:45 +01003030/* This function check a char. It returns true and updates
3031 * <date> and <len> pointer to the new position if the
3032 * character is found.
3033 */
3034static inline int parse_expect_char(const char **date, int *len, char c)
3035{
3036 if (*len < 1 || **date != c)
3037 return 0;
3038 (*len)--;
3039 (*date)++;
3040 return 1;
3041}
3042
3043/* This function expects a string <str> of len <l>. It return true and updates.
3044 * <date> and <len> if the string matches, otherwise, it returns false.
3045 */
3046static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3047{
3048 if (*len < l || strncmp(*date, str, l) != 0)
3049 return 0;
3050 (*len) -= l;
3051 (*date) += l;
3052 return 1;
3053}
3054
3055/* This macro converts 3 chars name in integer. */
3056#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3057
3058/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3059 * / %x54.75.65 ; "Tue", case-sensitive
3060 * / %x57.65.64 ; "Wed", case-sensitive
3061 * / %x54.68.75 ; "Thu", case-sensitive
3062 * / %x46.72.69 ; "Fri", case-sensitive
3063 * / %x53.61.74 ; "Sat", case-sensitive
3064 * / %x53.75.6E ; "Sun", case-sensitive
3065 *
3066 * This array must be alphabetically sorted
3067 */
3068static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3069{
3070 if (*len < 3)
3071 return 0;
3072 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3073 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3074 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3075 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3076 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3077 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3078 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3079 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3080 default: return 0;
3081 }
3082 *len -= 3;
3083 *date += 3;
3084 return 1;
3085}
3086
3087/* month = %x4A.61.6E ; "Jan", case-sensitive
3088 * / %x46.65.62 ; "Feb", case-sensitive
3089 * / %x4D.61.72 ; "Mar", case-sensitive
3090 * / %x41.70.72 ; "Apr", case-sensitive
3091 * / %x4D.61.79 ; "May", case-sensitive
3092 * / %x4A.75.6E ; "Jun", case-sensitive
3093 * / %x4A.75.6C ; "Jul", case-sensitive
3094 * / %x41.75.67 ; "Aug", case-sensitive
3095 * / %x53.65.70 ; "Sep", case-sensitive
3096 * / %x4F.63.74 ; "Oct", case-sensitive
3097 * / %x4E.6F.76 ; "Nov", case-sensitive
3098 * / %x44.65.63 ; "Dec", case-sensitive
3099 *
3100 * This array must be alphabetically sorted
3101 */
3102static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3103{
3104 if (*len < 3)
3105 return 0;
3106 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3107 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3108 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3109 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3110 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3111 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3112 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3113 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3114 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3115 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3116 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3117 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3118 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3119 default: return 0;
3120 }
3121 *len -= 3;
3122 *date += 3;
3123 return 1;
3124}
3125
3126/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3127 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3128 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3129 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3130 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3131 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3132 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3133 *
3134 * This array must be alphabetically sorted
3135 */
3136static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3137{
3138 if (*len < 6) /* Minimum length. */
3139 return 0;
3140 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3141 case STR2I3('M','o','n'):
3142 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3143 tm->tm_wday = 1;
3144 return 1;
3145 case STR2I3('T','u','e'):
3146 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3147 tm->tm_wday = 2;
3148 return 1;
3149 case STR2I3('W','e','d'):
3150 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3151 tm->tm_wday = 3;
3152 return 1;
3153 case STR2I3('T','h','u'):
3154 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3155 tm->tm_wday = 4;
3156 return 1;
3157 case STR2I3('F','r','i'):
3158 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3159 tm->tm_wday = 5;
3160 return 1;
3161 case STR2I3('S','a','t'):
3162 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3163 tm->tm_wday = 6;
3164 return 1;
3165 case STR2I3('S','u','n'):
3166 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3167 tm->tm_wday = 7;
3168 return 1;
3169 }
3170 return 0;
3171}
3172
3173/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3174static inline int parse_digit(const char **date, int *len, int *digit)
3175{
3176 if (*len < 1 || **date < '0' || **date > '9')
3177 return 0;
3178 *digit = (**date - '0');
3179 (*date)++;
3180 (*len)--;
3181 return 1;
3182}
3183
3184/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3185static inline int parse_2digit(const char **date, int *len, int *digit)
3186{
3187 int value;
3188
3189 RET0_UNLESS(parse_digit(date, len, &value));
3190 (*digit) = value * 10;
3191 RET0_UNLESS(parse_digit(date, len, &value));
3192 (*digit) += value;
3193
3194 return 1;
3195}
3196
3197/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3198static inline int parse_4digit(const char **date, int *len, int *digit)
3199{
3200 int value;
3201
3202 RET0_UNLESS(parse_digit(date, len, &value));
3203 (*digit) = value * 1000;
3204
3205 RET0_UNLESS(parse_digit(date, len, &value));
3206 (*digit) += value * 100;
3207
3208 RET0_UNLESS(parse_digit(date, len, &value));
3209 (*digit) += value * 10;
3210
3211 RET0_UNLESS(parse_digit(date, len, &value));
3212 (*digit) += value;
3213
3214 return 1;
3215}
3216
3217/* time-of-day = hour ":" minute ":" second
3218 * ; 00:00:00 - 23:59:60 (leap second)
3219 *
3220 * hour = 2DIGIT
3221 * minute = 2DIGIT
3222 * second = 2DIGIT
3223 */
3224static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3225{
3226 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3227 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3228 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3229 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3230 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3231 return 1;
3232}
3233
3234/* From RFC7231
3235 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3236 *
3237 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3238 * ; fixed length/zone/capitalization subset of the format
3239 * ; see Section 3.3 of [RFC5322]
3240 *
3241 *
3242 * date1 = day SP month SP year
3243 * ; e.g., 02 Jun 1982
3244 *
3245 * day = 2DIGIT
3246 * year = 4DIGIT
3247 *
3248 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3249 *
3250 * time-of-day = hour ":" minute ":" second
3251 * ; 00:00:00 - 23:59:60 (leap second)
3252 *
3253 * hour = 2DIGIT
3254 * minute = 2DIGIT
3255 * second = 2DIGIT
3256 *
3257 * DIGIT = decimal 0-9
3258 */
3259int parse_imf_date(const char *date, int len, struct tm *tm)
3260{
David Carlier327298c2016-11-20 10:42:38 +00003261 /* tm_gmtoff, if present, ought to be zero'ed */
3262 memset(tm, 0, sizeof(*tm));
3263
Thierry Fournier93127942016-01-20 18:49:45 +01003264 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3265 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3266 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3267 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3268 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3269 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3270 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3271 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3272 tm->tm_year -= 1900;
3273 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3274 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3275 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3276 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3277 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003278 return 1;
3279}
3280
3281/* From RFC7231
3282 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3283 *
3284 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3285 * date2 = day "-" month "-" 2DIGIT
3286 * ; e.g., 02-Jun-82
3287 *
3288 * day = 2DIGIT
3289 */
3290int parse_rfc850_date(const char *date, int len, struct tm *tm)
3291{
3292 int year;
3293
David Carlier327298c2016-11-20 10:42:38 +00003294 /* tm_gmtoff, if present, ought to be zero'ed */
3295 memset(tm, 0, sizeof(*tm));
3296
Thierry Fournier93127942016-01-20 18:49:45 +01003297 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3298 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3299 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3300 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3301 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3302 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3303 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3304
3305 /* year = 2DIGIT
3306 *
3307 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3308 * two-digit year, MUST interpret a timestamp that appears to be more
3309 * than 50 years in the future as representing the most recent year in
3310 * the past that had the same last two digits.
3311 */
3312 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3313
3314 /* expect SP */
3315 if (!parse_expect_char(&date, &len, ' ')) {
3316 /* Maybe we have the date with 4 digits. */
3317 RET0_UNLESS(parse_2digit(&date, &len, &year));
3318 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3319 /* expect SP */
3320 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3321 } else {
3322 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3323 * tm_year is the number of year since 1900, so for +1900, we
3324 * do nothing, and for +2000, we add 100.
3325 */
3326 if (tm->tm_year <= 60)
3327 tm->tm_year += 100;
3328 }
3329
3330 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3331 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3332 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3333 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003334
3335 return 1;
3336}
3337
3338/* From RFC7231
3339 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3340 *
3341 * asctime-date = day-name SP date3 SP time-of-day SP year
3342 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3343 * ; e.g., Jun 2
3344 *
3345 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3346 * whitespace in an HTTP-date beyond that specifically included as SP in
3347 * the grammar.
3348 */
3349int parse_asctime_date(const char *date, int len, struct tm *tm)
3350{
David Carlier327298c2016-11-20 10:42:38 +00003351 /* tm_gmtoff, if present, ought to be zero'ed */
3352 memset(tm, 0, sizeof(*tm));
3353
Thierry Fournier93127942016-01-20 18:49:45 +01003354 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3355 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3356 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3357 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3358
3359 /* expect SP and 1DIGIT or 2DIGIT */
3360 if (parse_expect_char(&date, &len, ' '))
3361 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3362 else
3363 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3364
3365 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3366 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3367 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3368 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3369 tm->tm_year -= 1900;
3370 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003371 return 1;
3372}
3373
3374/* From RFC7231
3375 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3376 *
3377 * HTTP-date = IMF-fixdate / obs-date
3378 * obs-date = rfc850-date / asctime-date
3379 *
3380 * parses an HTTP date in the RFC format and is accepted
3381 * alternatives. <date> is the strinf containing the date,
3382 * len is the len of the string. <tm> is filled with the
3383 * parsed time. We must considers this time as GMT.
3384 */
3385int parse_http_date(const char *date, int len, struct tm *tm)
3386{
3387 if (parse_imf_date(date, len, tm))
3388 return 1;
3389
3390 if (parse_rfc850_date(date, len, tm))
3391 return 1;
3392
3393 if (parse_asctime_date(date, len, tm))
3394 return 1;
3395
3396 return 0;
3397}
3398
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003399/* Dynamically allocates a string of the proper length to hold the formatted
3400 * output. NULL is returned on error. The caller is responsible for freeing the
3401 * memory area using free(). The resulting string is returned in <out> if the
3402 * pointer is not NULL. A previous version of <out> might be used to build the
3403 * new string, and it will be freed before returning if it is not NULL, which
3404 * makes it possible to build complex strings from iterative calls without
3405 * having to care about freeing intermediate values, as in the example below :
3406 *
3407 * memprintf(&err, "invalid argument: '%s'", arg);
3408 * ...
3409 * memprintf(&err, "parser said : <%s>\n", *err);
3410 * ...
3411 * free(*err);
3412 *
3413 * This means that <err> must be initialized to NULL before first invocation.
3414 * The return value also holds the allocated string, which eases error checking
3415 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003416 * passed instead and it will be ignored. The returned message will then also
3417 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003418 *
3419 * It is also convenient to use it without any free except the last one :
3420 * err = NULL;
3421 * if (!fct1(err)) report(*err);
3422 * if (!fct2(err)) report(*err);
3423 * if (!fct3(err)) report(*err);
3424 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003425 *
3426 * memprintf relies on memvprintf. This last version can be called from any
3427 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003428 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003429char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003430{
3431 va_list args;
3432 char *ret = NULL;
3433 int allocated = 0;
3434 int needed = 0;
3435
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003436 if (!out)
3437 return NULL;
3438
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003439 do {
3440 /* vsnprintf() will return the required length even when the
3441 * target buffer is NULL. We do this in a loop just in case
3442 * intermediate evaluations get wrong.
3443 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003444 va_copy(args, orig_args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003445 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003446 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003447 if (needed < allocated) {
3448 /* Note: on Solaris 8, the first iteration always
3449 * returns -1 if allocated is zero, so we force a
3450 * retry.
3451 */
3452 if (!allocated)
3453 needed = 0;
3454 else
3455 break;
3456 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003457
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003458 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003459 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003460 } while (ret);
3461
3462 if (needed < 0) {
3463 /* an error was encountered */
3464 free(ret);
3465 ret = NULL;
3466 }
3467
3468 if (out) {
3469 free(*out);
3470 *out = ret;
3471 }
3472
3473 return ret;
3474}
William Lallemand421f5b52012-02-06 18:15:57 +01003475
Christopher Faulet93a518f2017-10-24 11:25:33 +02003476char *memprintf(char **out, const char *format, ...)
3477{
3478 va_list args;
3479 char *ret = NULL;
3480
3481 va_start(args, format);
3482 ret = memvprintf(out, format, args);
3483 va_end(args);
3484
3485 return ret;
3486}
3487
Willy Tarreau21c705b2012-09-14 11:40:36 +02003488/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3489 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003490 * freed by the caller. It also supports being passed a NULL which results in the same
3491 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003492 * Example of use :
3493 * parse(cmd, &err); (callee: memprintf(&err, ...))
3494 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3495 * free(err);
3496 */
3497char *indent_msg(char **out, int level)
3498{
3499 char *ret, *in, *p;
3500 int needed = 0;
3501 int lf = 0;
3502 int lastlf = 0;
3503 int len;
3504
Willy Tarreau70eec382012-10-10 08:56:47 +02003505 if (!out || !*out)
3506 return NULL;
3507
Willy Tarreau21c705b2012-09-14 11:40:36 +02003508 in = *out - 1;
3509 while ((in = strchr(in + 1, '\n')) != NULL) {
3510 lastlf = in - *out;
3511 lf++;
3512 }
3513
3514 if (!lf) /* single line, no LF, return it as-is */
3515 return *out;
3516
3517 len = strlen(*out);
3518
3519 if (lf == 1 && lastlf == len - 1) {
3520 /* single line, LF at end, strip it and return as-is */
3521 (*out)[lastlf] = 0;
3522 return *out;
3523 }
3524
3525 /* OK now we have at least one LF, we need to process the whole string
3526 * as a multi-line string. What we'll do :
3527 * - prefix with an LF if there is none
3528 * - add <level> spaces before each line
3529 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3530 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3531 */
3532
3533 needed = 1 + level * (lf + 1) + len + 1;
3534 p = ret = malloc(needed);
3535 in = *out;
3536
3537 /* skip initial LFs */
3538 while (*in == '\n')
3539 in++;
3540
3541 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3542 while (*in) {
3543 *p++ = '\n';
3544 memset(p, ' ', level);
3545 p += level;
3546 do {
3547 *p++ = *in++;
3548 } while (*in && *in != '\n');
3549 if (*in)
3550 in++;
3551 }
3552 *p = 0;
3553
3554 free(*out);
3555 *out = ret;
3556
3557 return ret;
3558}
3559
Willy Tarreaudad36a32013-03-11 01:20:04 +01003560/* Convert occurrences of environment variables in the input string to their
3561 * corresponding value. A variable is identified as a series of alphanumeric
3562 * characters or underscores following a '$' sign. The <in> string must be
3563 * free()able. NULL returns NULL. The resulting string might be reallocated if
3564 * some expansion is made. Variable names may also be enclosed into braces if
3565 * needed (eg: to concatenate alphanum characters).
3566 */
3567char *env_expand(char *in)
3568{
3569 char *txt_beg;
3570 char *out;
3571 char *txt_end;
3572 char *var_beg;
3573 char *var_end;
3574 char *value;
3575 char *next;
3576 int out_len;
3577 int val_len;
3578
3579 if (!in)
3580 return in;
3581
3582 value = out = NULL;
3583 out_len = 0;
3584
3585 txt_beg = in;
3586 do {
3587 /* look for next '$' sign in <in> */
3588 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3589
3590 if (!*txt_end && !out) /* end and no expansion performed */
3591 return in;
3592
3593 val_len = 0;
3594 next = txt_end;
3595 if (*txt_end == '$') {
3596 char save;
3597
3598 var_beg = txt_end + 1;
3599 if (*var_beg == '{')
3600 var_beg++;
3601
3602 var_end = var_beg;
3603 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3604 var_end++;
3605 }
3606
3607 next = var_end;
3608 if (*var_end == '}' && (var_beg > txt_end + 1))
3609 next++;
3610
3611 /* get value of the variable name at this location */
3612 save = *var_end;
3613 *var_end = '\0';
3614 value = getenv(var_beg);
3615 *var_end = save;
3616 val_len = value ? strlen(value) : 0;
3617 }
3618
Hubert Verstraete831962e2016-06-28 22:44:26 +02003619 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003620 if (txt_end > txt_beg) {
3621 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3622 out_len += txt_end - txt_beg;
3623 }
3624 if (val_len) {
3625 memcpy(out + out_len, value, val_len);
3626 out_len += val_len;
3627 }
3628 out[out_len] = 0;
3629 txt_beg = next;
3630 } while (*txt_beg);
3631
3632 /* here we know that <out> was allocated and that we don't need <in> anymore */
3633 free(in);
3634 return out;
3635}
3636
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003637
3638/* same as strstr() but case-insensitive and with limit length */
3639const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3640{
3641 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003642 unsigned int slen, plen;
3643 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003644
3645 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3646 return NULL;
3647
3648 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3649 return str1;
3650
3651 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3652 return NULL;
3653
3654 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3655 while (toupper(*start) != toupper(*str2)) {
3656 start++;
3657 slen--;
3658 tmp1++;
3659
3660 if (tmp1 >= len_str1)
3661 return NULL;
3662
3663 /* if pattern longer than string */
3664 if (slen < plen)
3665 return NULL;
3666 }
3667
3668 sptr = start;
3669 pptr = (char *)str2;
3670
3671 tmp2 = 0;
3672 while (toupper(*sptr) == toupper(*pptr)) {
3673 sptr++;
3674 pptr++;
3675 tmp2++;
3676
3677 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3678 return start;
3679 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3680 return NULL;
3681 }
3682 }
3683 return NULL;
3684}
3685
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003686/* This function read the next valid utf8 char.
3687 * <s> is the byte srray to be decode, <len> is its length.
3688 * The function returns decoded char encoded like this:
3689 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3690 * are the length read. The decoded character is stored in <c>.
3691 */
3692unsigned char utf8_next(const char *s, int len, unsigned int *c)
3693{
3694 const unsigned char *p = (unsigned char *)s;
3695 int dec;
3696 unsigned char code = UTF8_CODE_OK;
3697
3698 if (len < 1)
3699 return UTF8_CODE_OK;
3700
3701 /* Check the type of UTF8 sequence
3702 *
3703 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3704 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3705 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3706 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3707 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3708 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3709 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3710 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3711 */
3712 switch (*p) {
3713 case 0x00 ... 0x7f:
3714 *c = *p;
3715 return UTF8_CODE_OK | 1;
3716
3717 case 0x80 ... 0xbf:
3718 *c = *p;
3719 return UTF8_CODE_BADSEQ | 1;
3720
3721 case 0xc0 ... 0xdf:
3722 if (len < 2) {
3723 *c = *p;
3724 return UTF8_CODE_BADSEQ | 1;
3725 }
3726 *c = *p & 0x1f;
3727 dec = 1;
3728 break;
3729
3730 case 0xe0 ... 0xef:
3731 if (len < 3) {
3732 *c = *p;
3733 return UTF8_CODE_BADSEQ | 1;
3734 }
3735 *c = *p & 0x0f;
3736 dec = 2;
3737 break;
3738
3739 case 0xf0 ... 0xf7:
3740 if (len < 4) {
3741 *c = *p;
3742 return UTF8_CODE_BADSEQ | 1;
3743 }
3744 *c = *p & 0x07;
3745 dec = 3;
3746 break;
3747
3748 case 0xf8 ... 0xfb:
3749 if (len < 5) {
3750 *c = *p;
3751 return UTF8_CODE_BADSEQ | 1;
3752 }
3753 *c = *p & 0x03;
3754 dec = 4;
3755 break;
3756
3757 case 0xfc ... 0xfd:
3758 if (len < 6) {
3759 *c = *p;
3760 return UTF8_CODE_BADSEQ | 1;
3761 }
3762 *c = *p & 0x01;
3763 dec = 5;
3764 break;
3765
3766 case 0xfe ... 0xff:
3767 default:
3768 *c = *p;
3769 return UTF8_CODE_BADSEQ | 1;
3770 }
3771
3772 p++;
3773
3774 while (dec > 0) {
3775
3776 /* need 0x10 for the 2 first bits */
3777 if ( ( *p & 0xc0 ) != 0x80 )
3778 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3779
3780 /* add data at char */
3781 *c = ( *c << 6 ) | ( *p & 0x3f );
3782
3783 dec--;
3784 p++;
3785 }
3786
3787 /* Check ovelong encoding.
3788 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3789 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3790 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3791 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003792 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003793 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3794 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3795 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3796 code |= UTF8_CODE_OVERLONG;
3797
3798 /* Check invalid UTF8 range. */
3799 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3800 (*c >= 0xfffe && *c <= 0xffff))
3801 code |= UTF8_CODE_INVRANGE;
3802
3803 return code | ((p-(unsigned char *)s)&0x0f);
3804}
3805
Maxime de Roucydc887852016-05-13 23:52:54 +02003806/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3807 * On failure : return 0 and <err> filled with an error message.
3808 * The caller is responsible for freeing the <err> and <str> copy
3809 * memory area using free()
3810 */
3811int list_append_word(struct list *li, const char *str, char **err)
3812{
3813 struct wordlist *wl;
3814
3815 wl = calloc(1, sizeof(*wl));
3816 if (!wl) {
3817 memprintf(err, "out of memory");
3818 goto fail_wl;
3819 }
3820
3821 wl->s = strdup(str);
3822 if (!wl->s) {
3823 memprintf(err, "out of memory");
3824 goto fail_wl_s;
3825 }
3826
3827 LIST_ADDQ(li, &wl->list);
3828
3829 return 1;
3830
3831fail_wl_s:
3832 free(wl->s);
3833fail_wl:
3834 free(wl);
3835 return 0;
3836}
3837
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003838/* print a string of text buffer to <out>. The format is :
3839 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3840 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3841 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3842 */
Willy Tarreau83061a82018-07-13 11:56:34 +02003843int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003844{
3845 unsigned char c;
3846 int ptr = 0;
3847
3848 while (buf[ptr] && ptr < bsize) {
3849 c = buf[ptr];
3850 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003851 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003852 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003853 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003854 }
3855 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003856 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003857 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003858 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003859 switch (c) {
3860 case ' ': c = ' '; break;
3861 case '\t': c = 't'; break;
3862 case '\n': c = 'n'; break;
3863 case '\r': c = 'r'; break;
3864 case '\e': c = 'e'; break;
3865 case '\\': c = '\\'; break;
3866 case '=': c = '='; break;
3867 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003868 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003869 }
3870 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003871 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003872 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003873 out->area[out->data++] = '\\';
3874 out->area[out->data++] = 'x';
3875 out->area[out->data++] = hextab[(c >> 4) & 0xF];
3876 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003877 }
3878 ptr++;
3879 }
3880
3881 return ptr;
3882}
3883
3884/* print a buffer in hexa.
3885 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3886 */
Willy Tarreau83061a82018-07-13 11:56:34 +02003887int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003888{
3889 unsigned char c;
3890 int ptr = 0;
3891
3892 while (ptr < bsize) {
3893 c = buf[ptr];
3894
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003895 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003896 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003897 out->area[out->data++] = hextab[(c >> 4) & 0xF];
3898 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003899
3900 ptr++;
3901 }
3902 return ptr;
3903}
3904
3905/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3906 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3907 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3908 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3909 * lines are respected within the limit of 70 output chars. Lines that are
3910 * continuation of a previous truncated line begin with "+" instead of " "
3911 * after the offset. The new pointer is returned.
3912 */
Willy Tarreau83061a82018-07-13 11:56:34 +02003913int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003914 int *line, int ptr)
3915{
3916 int end;
3917 unsigned char c;
3918
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003919 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003920 if (end > out->size)
3921 return ptr;
3922
3923 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3924
3925 while (ptr < len && ptr < bsize) {
3926 c = buf[ptr];
3927 if (isprint(c) && isascii(c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003928 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003929 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003930 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003931 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003932 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003933 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003934 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003935 switch (c) {
3936 case '\t': c = 't'; break;
3937 case '\n': c = 'n'; break;
3938 case '\r': c = 'r'; break;
3939 case '\e': c = 'e'; break;
3940 case '\\': c = '\\'; break;
3941 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003942 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003943 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003944 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003945 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003946 out->area[out->data++] = '\\';
3947 out->area[out->data++] = 'x';
3948 out->area[out->data++] = hextab[(c >> 4) & 0xF];
3949 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003950 }
3951 if (buf[ptr++] == '\n') {
3952 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003953 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003954 *line = ptr;
3955 return ptr;
3956 }
3957 }
3958 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003959 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003960 return ptr;
3961}
3962
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003963/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02003964 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
3965 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003966 */
Willy Tarreaued936c52017-04-27 18:03:20 +02003967void debug_hexdump(FILE *out, const char *pfx, const char *buf,
3968 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003969{
Willy Tarreau73459792017-04-11 07:58:08 +02003970 unsigned int i;
3971 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003972
3973 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3974 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02003975 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003976 for (j = 0; j < 8; j++) {
3977 if (b + j >= 0 && b + j < len)
3978 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3979 else
3980 fprintf(out, " ");
3981 }
3982
3983 if (b + j >= 0 && b + j < len)
3984 fputc('-', out);
3985 else
3986 fputc(' ', out);
3987
3988 for (j = 8; j < 16; j++) {
3989 if (b + j >= 0 && b + j < len)
3990 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3991 else
3992 fprintf(out, " ");
3993 }
3994
3995 fprintf(out, " ");
3996 for (j = 0; j < 16; j++) {
3997 if (b + j >= 0 && b + j < len) {
3998 if (isprint((unsigned char)buf[b + j]))
3999 fputc((unsigned char)buf[b + j], out);
4000 else
4001 fputc('.', out);
4002 }
4003 else
4004 fputc(' ', out);
4005 }
4006 fputc('\n', out);
4007 }
4008}
4009
Willy Tarreau12963822017-10-24 10:54:08 +02004010/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
4011__attribute__((weak,format(printf, 1, 2)))
4012void trace(char *msg, ...)
4013{
4014}
4015
Willy Tarreaubaaee002006-06-26 02:48:02 +02004016/*
4017 * Local variables:
4018 * c-indent-level: 8
4019 * c-basic-offset: 8
4020 * End:
4021 */