blob: 707e2c716664eed6021d58a6f2d0c7f465340568 [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) {
632 return __invalid_char(name, isalpha);
633}
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;
725
726 memset(&result, 0, sizeof(result));
727 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100728 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100729 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200730 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100731 hints.ai_protocol = 0;
732
733 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100734 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
735 sa->ss_family = result->ai_family;
736 else if (sa->ss_family != result->ai_family)
737 goto fail;
738
David du Colombierd5f43282011-03-17 10:40:16 +0100739 switch (result->ai_family) {
740 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100741 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100742 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100743 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100744 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100745 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100746 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100747 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100748 }
749 }
750
Sean Carey58ea0392013-02-15 23:39:18 +0100751 if (result)
752 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100753 }
David du Colombierd5f43282011-03-17 10:40:16 +0100754#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200755 /* try to resolve an IPv4/IPv6 hostname */
756 he = gethostbyname(str);
757 if (he) {
758 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
759 sa->ss_family = he->h_addrtype;
760 else if (sa->ss_family != he->h_addrtype)
761 goto fail;
762
763 switch (sa->ss_family) {
764 case AF_INET:
765 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100766 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200767 return sa;
768 case AF_INET6:
769 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100770 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200771 return sa;
772 }
773 }
774
David du Colombierd5f43282011-03-17 10:40:16 +0100775 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100776 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100777 return NULL;
778}
779
780/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100781 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
782 * range or offset consisting in two integers that the caller will have to
783 * check to find the relevant input format. The following format are supported :
784 *
785 * String format | address | port | low | high
786 * addr | <addr> | 0 | 0 | 0
787 * addr: | <addr> | 0 | 0 | 0
788 * addr:port | <addr> | <port> | <port> | <port>
789 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
790 * addr:+port | <addr> | <port> | 0 | <port>
791 * addr:-port | <addr> |-<port> | <port> | 0
792 *
793 * The detection of a port range or increment by the caller is made by
794 * comparing <low> and <high>. If both are equal, then port 0 means no port
795 * was specified. The caller may pass NULL for <low> and <high> if it is not
796 * interested in retrieving port ranges.
797 *
798 * Note that <addr> above may also be :
799 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
800 * - "*" => family will be AF_INET and address will be INADDR_ANY
801 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
802 * - a host name => family and address will depend on host name resolving.
803 *
Willy Tarreau24709282013-03-10 21:32:12 +0100804 * A prefix may be passed in before the address above to force the family :
805 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
806 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
807 * - "unix@" => force address to be a path to a UNIX socket even if the
808 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200809 * - 'abns@' -> force address to belong to the abstract namespace (Linux
810 * only). These sockets are just like Unix sockets but without
811 * the need for an underlying file system. The address is a
812 * string. Technically it's like a Unix socket with a zero in
813 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100814 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100815 *
mildisff5d5102015-10-26 18:50:08 +0100816 * IPv6 addresses can be declared with or without square brackets. When using
817 * square brackets for IPv6 addresses, the port separator (colon) is optional.
818 * If not using square brackets, and in order to avoid any ambiguity with
819 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
820 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
821 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100822 *
823 * If <pfx> is non-null, it is used as a string prefix before any path-based
824 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100825 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200826 * if <fqdn> is non-null, it will be filled with :
827 * - a pointer to the FQDN of the server name to resolve if there's one, and
828 * that the caller will have to free(),
829 * - NULL if there was an explicit address that doesn't require resolution.
830 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100831 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
832 * is null, <fqdn> is still honnored so it is possible for the caller to know
833 * whether a resolution failed by setting <resolve> to null and checking if
834 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200835 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100836 * When a file descriptor is passed, its value is put into the s_addr part of
837 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100838 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100839struct 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 +0100840{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100841 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100842 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100843 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100844 char *port1, *port2;
845 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200846 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100847
848 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200849 if (fqdn)
850 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200851
Willy Tarreaudad36a32013-03-11 01:20:04 +0100852 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100853 if (str2 == NULL) {
854 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100855 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100856 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200857
Willy Tarreau9f69f462015-09-08 16:01:25 +0200858 if (!*str2) {
859 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
860 goto out;
861 }
862
Willy Tarreau24709282013-03-10 21:32:12 +0100863 memset(&ss, 0, sizeof(ss));
864
865 if (strncmp(str2, "unix@", 5) == 0) {
866 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200867 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100868 ss.ss_family = AF_UNIX;
869 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200870 else if (strncmp(str2, "abns@", 5) == 0) {
871 str2 += 5;
872 abstract = 1;
873 ss.ss_family = AF_UNIX;
874 }
Willy Tarreau24709282013-03-10 21:32:12 +0100875 else if (strncmp(str2, "ipv4@", 5) == 0) {
876 str2 += 5;
877 ss.ss_family = AF_INET;
878 }
879 else if (strncmp(str2, "ipv6@", 5) == 0) {
880 str2 += 5;
881 ss.ss_family = AF_INET6;
882 }
883 else if (*str2 == '/') {
884 ss.ss_family = AF_UNIX;
885 }
886 else
887 ss.ss_family = AF_UNSPEC;
888
Willy Tarreau40aa0702013-03-10 23:51:38 +0100889 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
890 char *endptr;
891
892 str2 += 3;
893 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
894
895 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100896 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100897 goto out;
898 }
899
900 /* we return AF_UNSPEC if we use a file descriptor number */
901 ss.ss_family = AF_UNSPEC;
902 }
903 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100904 int prefix_path_len;
905 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200906 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100907
908 /* complete unix socket path name during startup or soft-restart is
909 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
910 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200911 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100912 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
913 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
914
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200915 adr_len = strlen(str2);
916 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100917 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
918 goto out;
919 }
920
Willy Tarreauccfccef2014-05-10 01:49:15 +0200921 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
922 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200923 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100924 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200925 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100926 }
Willy Tarreau24709282013-03-10 21:32:12 +0100927 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100928 char *end = str2 + strlen(str2);
929 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200930
mildisff5d5102015-10-26 18:50:08 +0100931 /* search for : or ] whatever comes first */
932 for (chr = end-1; chr > str2; chr--) {
933 if (*chr == ']' || *chr == ':')
934 break;
935 }
936
937 if (*chr == ':') {
938 /* Found a colon before a closing-bracket, must be a port separator.
939 * This guarantee backward compatibility.
940 */
941 *chr++ = '\0';
942 port1 = chr;
943 }
944 else {
945 /* Either no colon and no closing-bracket
946 * or directly ending with a closing-bracket.
947 * However, no port.
948 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100949 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100950 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200951
Willy Tarreaua39d1992013-04-01 20:37:42 +0200952 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100953 port2 = strchr(port1, '-');
954 if (port2)
955 *port2++ = '\0';
956 else
957 port2 = port1;
958 portl = atoi(port1);
959 porth = atoi(port2);
960 porta = portl;
961 }
962 else if (*port1 == '-') { /* negative offset */
963 portl = atoi(port1 + 1);
964 porta = -portl;
965 }
966 else if (*port1 == '+') { /* positive offset */
967 porth = atoi(port1 + 1);
968 porta = porth;
969 }
970 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100971 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100972 goto out;
973 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100974
975 /* first try to parse the IP without resolving. If it fails, it
976 * tells us we need to keep a copy of the FQDN to resolve later
977 * and to enable DNS. In this case we can proceed if <fqdn> is
978 * set or if resolve is set, otherwise it's an error.
979 */
980 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +0100981 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +0100982 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
983 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
984 goto out;
985 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200986
Willy Tarreauceccdd72016-11-02 22:27:10 +0100987 if (fqdn) {
988 if (str2 != back)
989 memmove(back, str2, strlen(str2) + 1);
990 *fqdn = back;
991 back = NULL;
992 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200993 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100994 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100995 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100996
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100997 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100998 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100999 if (port)
1000 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001001 if (low)
1002 *low = portl;
1003 if (high)
1004 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001005 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001006 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001007}
1008
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001009/* converts <str> to a struct in_addr containing a network mask. It can be
1010 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001011 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001012 */
1013int str2mask(const char *str, struct in_addr *mask)
1014{
1015 if (strchr(str, '.') != NULL) { /* dotted notation */
1016 if (!inet_pton(AF_INET, str, mask))
1017 return 0;
1018 }
1019 else { /* mask length */
1020 char *err;
1021 unsigned long len = strtol(str, &err, 10);
1022
1023 if (!*str || (err && *err) || (unsigned)len > 32)
1024 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001025
1026 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001027 }
1028 return 1;
1029}
1030
Tim Duesterhus47185172018-01-25 16:24:49 +01001031/* converts <str> to a struct in6_addr containing a network mask. It can be
1032 * passed in quadruplet form (ffff::ffff::) or in CIDR form (64). It returns 1
1033 * if the conversion succeeds otherwise zero.
1034 */
1035int str2mask6(const char *str, struct in6_addr *mask)
1036{
1037 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1038 if (!inet_pton(AF_INET6, str, mask))
1039 return 0;
1040 }
1041 else { /* mask length */
1042 char *err;
1043 unsigned long len = strtol(str, &err, 10);
1044
1045 if (!*str || (err && *err) || (unsigned)len > 128)
1046 return 0;
1047
1048 len2mask6(len, mask);
1049 }
1050 return 1;
1051}
1052
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001053/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1054 * succeeds otherwise zero.
1055 */
1056int cidr2dotted(int cidr, struct in_addr *mask) {
1057
1058 if (cidr < 0 || cidr > 32)
1059 return 0;
1060
1061 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1062 return 1;
1063}
1064
Thierry Fournier70473a52016-02-17 17:12:14 +01001065/* Convert mask from bit length form to in_addr form.
1066 * This function never fails.
1067 */
1068void len2mask4(int len, struct in_addr *addr)
1069{
1070 if (len >= 32) {
1071 addr->s_addr = 0xffffffff;
1072 return;
1073 }
1074 if (len <= 0) {
1075 addr->s_addr = 0x00000000;
1076 return;
1077 }
1078 addr->s_addr = 0xffffffff << (32 - len);
1079 addr->s_addr = htonl(addr->s_addr);
1080}
1081
1082/* Convert mask from bit length form to in6_addr form.
1083 * This function never fails.
1084 */
1085void len2mask6(int len, struct in6_addr *addr)
1086{
1087 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1088 len -= 32;
1089 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1090 len -= 32;
1091 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1092 len -= 32;
1093 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1094}
1095
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001096/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001097 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001098 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1099 * is optionnal and either in the dotted or CIDR notation.
1100 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1101 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001102int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001103{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001104 __label__ out_free, out_err;
1105 char *c, *s;
1106 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001107
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001108 s = strdup(str);
1109 if (!s)
1110 return 0;
1111
Willy Tarreaubaaee002006-06-26 02:48:02 +02001112 memset(mask, 0, sizeof(*mask));
1113 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001114
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001115 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001116 *c++ = '\0';
1117 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001118 if (!str2mask(c, mask))
1119 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001120 }
1121 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001122 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001123 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001124 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001125 struct hostent *he;
1126
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001127 if (!resolve)
1128 goto out_err;
1129
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001130 if ((he = gethostbyname(s)) == NULL) {
1131 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001132 }
1133 else
1134 *addr = *(struct in_addr *) *(he->h_addr_list);
1135 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001136
1137 ret_val = 1;
1138 out_free:
1139 free(s);
1140 return ret_val;
1141 out_err:
1142 ret_val = 0;
1143 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001144}
1145
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001146
1147/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001148 * converts <str> to two struct in6_addr* which must be pre-allocated.
1149 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1150 * is an optionnal number of bits (128 being the default).
1151 * Returns 1 if OK, 0 if error.
1152 */
1153int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1154{
1155 char *c, *s;
1156 int ret_val = 0;
1157 char *err;
1158 unsigned long len = 128;
1159
1160 s = strdup(str);
1161 if (!s)
1162 return 0;
1163
1164 memset(mask, 0, sizeof(*mask));
1165 memset(addr, 0, sizeof(*addr));
1166
1167 if ((c = strrchr(s, '/')) != NULL) {
1168 *c++ = '\0'; /* c points to the mask */
1169 if (!*c)
1170 goto out_free;
1171
1172 len = strtoul(c, &err, 10);
1173 if ((err && *err) || (unsigned)len > 128)
1174 goto out_free;
1175 }
1176 *mask = len; /* OK we have a valid mask in <len> */
1177
1178 if (!inet_pton(AF_INET6, s, addr))
1179 goto out_free;
1180
1181 ret_val = 1;
1182 out_free:
1183 free(s);
1184 return ret_val;
1185}
1186
1187
1188/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001189 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001190 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001191int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001192{
1193 int saw_digit, octets, ch;
1194 u_char tmp[4], *tp;
1195 const char *cp = addr;
1196
1197 saw_digit = 0;
1198 octets = 0;
1199 *(tp = tmp) = 0;
1200
1201 while (*addr) {
1202 unsigned char digit = (ch = *addr++) - '0';
1203 if (digit > 9 && ch != '.')
1204 break;
1205 if (digit <= 9) {
1206 u_int new = *tp * 10 + digit;
1207 if (new > 255)
1208 return 0;
1209 *tp = new;
1210 if (!saw_digit) {
1211 if (++octets > 4)
1212 return 0;
1213 saw_digit = 1;
1214 }
1215 } else if (ch == '.' && saw_digit) {
1216 if (octets == 4)
1217 return 0;
1218 *++tp = 0;
1219 saw_digit = 0;
1220 } else
1221 return 0;
1222 }
1223
1224 if (octets < 4)
1225 return 0;
1226
1227 memcpy(&dst->s_addr, tmp, 4);
1228 return addr-cp-1;
1229}
1230
1231/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001232 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1233 * <out> contain the code of the dectected scheme, the start and length of
1234 * the hostname. Actually only http and https are supported. <out> can be NULL.
1235 * This function returns the consumed length. It is useful if you parse complete
1236 * url like http://host:port/path, because the consumed length corresponds to
1237 * the first character of the path. If the conversion fails, it returns -1.
1238 *
1239 * This function tries to resolve the DNS name if haproxy is in starting mode.
1240 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001241 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001242int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001243{
1244 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001245 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001246 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001247 unsigned long long int http_code = 0;
1248 int default_port;
1249 struct hostent *he;
1250 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001251
1252 /* Firstly, try to find :// pattern */
1253 while (curr < url+ulen && url_code != 0x3a2f2f) {
1254 url_code = ((url_code & 0xffff) << 8);
1255 url_code += (unsigned char)*curr++;
1256 }
1257
1258 /* Secondly, if :// pattern is found, verify parsed stuff
1259 * before pattern is matching our http pattern.
1260 * If so parse ip address and port in uri.
1261 *
1262 * WARNING: Current code doesn't support dynamic async dns resolver.
1263 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001264 if (url_code != 0x3a2f2f)
1265 return -1;
1266
1267 /* Copy scheme, and utrn to lower case. */
1268 while (cp < curr - 3)
1269 http_code = (http_code << 8) + *cp++;
1270 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001271
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001272 /* HTTP or HTTPS url matching */
1273 if (http_code == 0x2020202068747470ULL) {
1274 default_port = 80;
1275 if (out)
1276 out->scheme = SCH_HTTP;
1277 }
1278 else if (http_code == 0x2020206874747073ULL) {
1279 default_port = 443;
1280 if (out)
1281 out->scheme = SCH_HTTPS;
1282 }
1283 else
1284 return -1;
1285
1286 /* If the next char is '[', the host address is IPv6. */
1287 if (*curr == '[') {
1288 curr++;
1289
1290 /* Check trash size */
1291 if (trash.size < ulen)
1292 return -1;
1293
1294 /* Look for ']' and copy the address in a trash buffer. */
1295 p = trash.str;
1296 for (end = curr;
1297 end < url + ulen && *end != ']';
1298 end++, p++)
1299 *p = *end;
1300 if (*end != ']')
1301 return -1;
1302 *p = '\0';
1303
1304 /* Update out. */
1305 if (out) {
1306 out->host = curr;
1307 out->host_len = end - curr;
1308 }
1309
1310 /* Try IPv6 decoding. */
1311 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1312 return -1;
1313 end++;
1314
1315 /* Decode port. */
1316 if (*end == ':') {
1317 end++;
1318 default_port = read_uint(&end, url + ulen);
1319 }
1320 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1321 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1322 return end - url;
1323 }
1324 else {
1325 /* We are looking for IP address. If you want to parse and
1326 * resolve hostname found in url, you can use str2sa_range(), but
1327 * be warned this can slow down global daemon performances
1328 * while handling lagging dns responses.
1329 */
1330 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1331 if (ret) {
1332 /* Update out. */
1333 if (out) {
1334 out->host = curr;
1335 out->host_len = ret;
1336 }
1337
1338 curr += ret;
1339
1340 /* Decode port. */
1341 if (*curr == ':') {
1342 curr++;
1343 default_port = read_uint(&curr, url + ulen);
1344 }
1345 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1346
1347 /* Set family. */
1348 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1349 return curr - url;
1350 }
1351 else if (global.mode & MODE_STARTING) {
1352 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1353 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001354 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001355
1356 /* look for : or / or end */
1357 for (end = curr;
1358 end < url + ulen && *end != '/' && *end != ':';
1359 end++);
1360 memcpy(trash.str, curr, end - curr);
1361 trash.str[end - curr] = '\0';
1362
1363 /* try to resolve an IPv4/IPv6 hostname */
1364 he = gethostbyname(trash.str);
1365 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001366 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001367
1368 /* Update out. */
1369 if (out) {
1370 out->host = curr;
1371 out->host_len = end - curr;
1372 }
1373
1374 /* Decode port. */
1375 if (*end == ':') {
1376 end++;
1377 default_port = read_uint(&end, url + ulen);
1378 }
1379
1380 /* Copy IP address, set port and family. */
1381 switch (he->h_addrtype) {
1382 case AF_INET:
1383 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1384 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1385 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1386 return end - url;
1387
1388 case AF_INET6:
1389 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1390 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1391 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1392 return end - url;
1393 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001394 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001395 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001396 return -1;
1397}
1398
Willy Tarreau631f01c2011-09-05 00:36:48 +02001399/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1400 * address family is returned so that it's easy for the caller to adapt to the
1401 * output format. Zero is returned if the address family is not supported. -1
1402 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1403 * supported.
1404 */
1405int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1406{
1407
1408 void *ptr;
1409
1410 if (size < 5)
1411 return 0;
1412 *str = '\0';
1413
1414 switch (addr->ss_family) {
1415 case AF_INET:
1416 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1417 break;
1418 case AF_INET6:
1419 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1420 break;
1421 case AF_UNIX:
1422 memcpy(str, "unix", 5);
1423 return addr->ss_family;
1424 default:
1425 return 0;
1426 }
1427
1428 if (inet_ntop(addr->ss_family, ptr, str, size))
1429 return addr->ss_family;
1430
1431 /* failed */
1432 return -1;
1433}
1434
Simon Horman75ab8bd2014-06-16 09:39:41 +09001435/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1436 * address family is returned so that it's easy for the caller to adapt to the
1437 * output format. Zero is returned if the address family is not supported. -1
1438 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1439 * supported.
1440 */
1441int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1442{
1443
1444 uint16_t port;
1445
1446
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001447 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001448 return 0;
1449 *str = '\0';
1450
1451 switch (addr->ss_family) {
1452 case AF_INET:
1453 port = ((struct sockaddr_in *)addr)->sin_port;
1454 break;
1455 case AF_INET6:
1456 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1457 break;
1458 case AF_UNIX:
1459 memcpy(str, "unix", 5);
1460 return addr->ss_family;
1461 default:
1462 return 0;
1463 }
1464
1465 snprintf(str, size, "%u", ntohs(port));
1466 return addr->ss_family;
1467}
1468
Willy Tarreau16e01562016-08-09 16:46:18 +02001469/* check if the given address is local to the system or not. It will return
1470 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1471 * it is. We don't want to iterate over all interfaces for this (and it is not
1472 * portable). So instead we try to bind in UDP to this address on a free non
1473 * privileged port and to connect to the same address, port 0 (connect doesn't
1474 * care). If it succeeds, we own the address. Note that non-inet addresses are
1475 * considered local since they're most likely AF_UNIX.
1476 */
1477int addr_is_local(const struct netns_entry *ns,
1478 const struct sockaddr_storage *orig)
1479{
1480 struct sockaddr_storage addr;
1481 int result;
1482 int fd;
1483
1484 if (!is_inet_addr(orig))
1485 return 1;
1486
1487 memcpy(&addr, orig, sizeof(addr));
1488 set_host_port(&addr, 0);
1489
1490 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1491 if (fd < 0)
1492 return -1;
1493
1494 result = -1;
1495 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1496 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1497 result = 0; // fail, non-local address
1498 else
1499 result = 1; // success, local address
1500 }
1501 else {
1502 if (errno == EADDRNOTAVAIL)
1503 result = 0; // definitely not local :-)
1504 }
1505 close(fd);
1506
1507 return result;
1508}
1509
Willy Tarreaubaaee002006-06-26 02:48:02 +02001510/* will try to encode the string <string> replacing all characters tagged in
1511 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1512 * prefixed by <escape>, and will store the result between <start> (included)
1513 * and <stop> (excluded), and will always terminate the string with a '\0'
1514 * before <stop>. The position of the '\0' is returned if the conversion
1515 * completes. If bytes are missing between <start> and <stop>, then the
1516 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1517 * cannot even be stored so we return <start> without writing the 0.
1518 * The input string must also be zero-terminated.
1519 */
1520const char hextab[16] = "0123456789ABCDEF";
1521char *encode_string(char *start, char *stop,
1522 const char escape, const fd_set *map,
1523 const char *string)
1524{
1525 if (start < stop) {
1526 stop--; /* reserve one byte for the final '\0' */
1527 while (start < stop && *string != '\0') {
1528 if (!FD_ISSET((unsigned char)(*string), map))
1529 *start++ = *string;
1530 else {
1531 if (start + 3 >= stop)
1532 break;
1533 *start++ = escape;
1534 *start++ = hextab[(*string >> 4) & 15];
1535 *start++ = hextab[*string & 15];
1536 }
1537 string++;
1538 }
1539 *start = '\0';
1540 }
1541 return start;
1542}
1543
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001544/*
1545 * Same behavior as encode_string() above, except that it encodes chunk
1546 * <chunk> instead of a string.
1547 */
1548char *encode_chunk(char *start, char *stop,
1549 const char escape, const fd_set *map,
1550 const struct chunk *chunk)
1551{
1552 char *str = chunk->str;
1553 char *end = chunk->str + chunk->len;
1554
1555 if (start < stop) {
1556 stop--; /* reserve one byte for the final '\0' */
1557 while (start < stop && str < end) {
1558 if (!FD_ISSET((unsigned char)(*str), map))
1559 *start++ = *str;
1560 else {
1561 if (start + 3 >= stop)
1562 break;
1563 *start++ = escape;
1564 *start++ = hextab[(*str >> 4) & 15];
1565 *start++ = hextab[*str & 15];
1566 }
1567 str++;
1568 }
1569 *start = '\0';
1570 }
1571 return start;
1572}
1573
Dragan Dosen0edd1092016-02-12 13:23:02 +01001574/*
1575 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001576 * character. The input <string> must be zero-terminated. The result will
1577 * be stored between <start> (included) and <stop> (excluded). This
1578 * function will always try to terminate the resulting string with a '\0'
1579 * before <stop>, and will return its position if the conversion
1580 * completes.
1581 */
1582char *escape_string(char *start, char *stop,
1583 const char escape, const fd_set *map,
1584 const char *string)
1585{
1586 if (start < stop) {
1587 stop--; /* reserve one byte for the final '\0' */
1588 while (start < stop && *string != '\0') {
1589 if (!FD_ISSET((unsigned char)(*string), map))
1590 *start++ = *string;
1591 else {
1592 if (start + 2 >= stop)
1593 break;
1594 *start++ = escape;
1595 *start++ = *string;
1596 }
1597 string++;
1598 }
1599 *start = '\0';
1600 }
1601 return start;
1602}
1603
1604/*
1605 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001606 * character. <chunk> contains the input to be escaped. The result will be
1607 * stored between <start> (included) and <stop> (excluded). The function
1608 * will always try to terminate the resulting string with a '\0' before
1609 * <stop>, and will return its position if the conversion completes.
1610 */
1611char *escape_chunk(char *start, char *stop,
1612 const char escape, const fd_set *map,
1613 const struct chunk *chunk)
1614{
1615 char *str = chunk->str;
1616 char *end = chunk->str + chunk->len;
1617
1618 if (start < stop) {
1619 stop--; /* reserve one byte for the final '\0' */
1620 while (start < stop && str < end) {
1621 if (!FD_ISSET((unsigned char)(*str), map))
1622 *start++ = *str;
1623 else {
1624 if (start + 2 >= stop)
1625 break;
1626 *start++ = escape;
1627 *start++ = *str;
1628 }
1629 str++;
1630 }
1631 *start = '\0';
1632 }
1633 return start;
1634}
1635
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001636/* Check a string for using it in a CSV output format. If the string contains
1637 * one of the following four char <">, <,>, CR or LF, the string is
1638 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1639 * <str> is the input string to be escaped. The function assumes that
1640 * the input string is null-terminated.
1641 *
1642 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001643 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001644 * format.
1645 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001646 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001647 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001648 * If <quote> is 1, the converter puts the quotes only if any reserved character
1649 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001650 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001651 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001652 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001653 * The function returns the converted string on its output. If an error
1654 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001655 * for using the function directly as printf() argument.
1656 *
1657 * If the output buffer is too short to contain the input string, the result
1658 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001659 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001660 * This function appends the encoding to the existing output chunk, and it
1661 * guarantees that it starts immediately at the first available character of
1662 * the chunk. Please use csv_enc() instead if you want to replace the output
1663 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001664 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001665const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001666{
1667 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001668 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001669 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001670
Willy Tarreaub631c292016-01-08 10:04:08 +01001671 if (quote == 1) {
1672 /* automatic quoting: first verify if we'll have to quote the string */
1673 if (!strpbrk(str, "\n\r,\""))
1674 quote = 0;
1675 }
1676
1677 if (quote)
1678 *ptr++ = '"';
1679
Willy Tarreau898529b2016-01-06 18:07:04 +01001680 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1681 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001682 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001683 ptr++;
1684 if (ptr >= end - 2) {
1685 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001686 break;
1687 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001688 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001689 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001690 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001691 str++;
1692 }
1693
Willy Tarreaub631c292016-01-08 10:04:08 +01001694 if (quote)
1695 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001696
Willy Tarreau898529b2016-01-06 18:07:04 +01001697 *ptr = '\0';
1698 output->len = ptr - output->str;
1699 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001700}
1701
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001702/* Decode an URL-encoded string in-place. The resulting string might
1703 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001704 * aborted, the string is truncated before the issue and a negative value is
1705 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001706 */
1707int url_decode(char *string)
1708{
1709 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001710 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001711
1712 in = string;
1713 out = string;
1714 while (*in) {
1715 switch (*in) {
1716 case '+' :
1717 *out++ = ' ';
1718 break;
1719 case '%' :
1720 if (!ishex(in[1]) || !ishex(in[2]))
1721 goto end;
1722 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1723 in += 2;
1724 break;
1725 default:
1726 *out++ = *in;
1727 break;
1728 }
1729 in++;
1730 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001731 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001732 end:
1733 *out = 0;
1734 return ret;
1735}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001736
Willy Tarreau6911fa42007-03-04 18:06:08 +01001737unsigned int str2ui(const char *s)
1738{
1739 return __str2ui(s);
1740}
1741
1742unsigned int str2uic(const char *s)
1743{
1744 return __str2uic(s);
1745}
1746
1747unsigned int strl2ui(const char *s, int len)
1748{
1749 return __strl2ui(s, len);
1750}
1751
1752unsigned int strl2uic(const char *s, int len)
1753{
1754 return __strl2uic(s, len);
1755}
1756
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001757unsigned int read_uint(const char **s, const char *end)
1758{
1759 return __read_uint(s, end);
1760}
1761
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001762/* This function reads an unsigned integer from the string pointed to by <s> and
1763 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1764 * function automatically stops at <end>. If the number overflows, the 2^64-1
1765 * value is returned.
1766 */
1767unsigned long long int read_uint64(const char **s, const char *end)
1768{
1769 const char *ptr = *s;
1770 unsigned long long int i = 0, tmp;
1771 unsigned int j;
1772
1773 while (ptr < end) {
1774
1775 /* read next char */
1776 j = *ptr - '0';
1777 if (j > 9)
1778 goto read_uint64_end;
1779
1780 /* add char to the number and check overflow. */
1781 tmp = i * 10;
1782 if (tmp / 10 != i) {
1783 i = ULLONG_MAX;
1784 goto read_uint64_eat;
1785 }
1786 if (ULLONG_MAX - tmp < j) {
1787 i = ULLONG_MAX;
1788 goto read_uint64_eat;
1789 }
1790 i = tmp + j;
1791 ptr++;
1792 }
1793read_uint64_eat:
1794 /* eat each numeric char */
1795 while (ptr < end) {
1796 if ((unsigned int)(*ptr - '0') > 9)
1797 break;
1798 ptr++;
1799 }
1800read_uint64_end:
1801 *s = ptr;
1802 return i;
1803}
1804
1805/* This function reads an integer from the string pointed to by <s> and returns
1806 * it. The <s> pointer is adjusted to point to the first unread char. The function
1807 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1808 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1809 * returned.
1810 */
1811long long int read_int64(const char **s, const char *end)
1812{
1813 unsigned long long int i = 0;
1814 int neg = 0;
1815
1816 /* Look for minus char. */
1817 if (**s == '-') {
1818 neg = 1;
1819 (*s)++;
1820 }
1821 else if (**s == '+')
1822 (*s)++;
1823
1824 /* convert as positive number. */
1825 i = read_uint64(s, end);
1826
1827 if (neg) {
1828 if (i > 0x8000000000000000ULL)
1829 return LLONG_MIN;
1830 return -i;
1831 }
1832 if (i > 0x7fffffffffffffffULL)
1833 return LLONG_MAX;
1834 return i;
1835}
1836
Willy Tarreau6911fa42007-03-04 18:06:08 +01001837/* This one is 7 times faster than strtol() on athlon with checks.
1838 * It returns the value of the number composed of all valid digits read,
1839 * and can process negative numbers too.
1840 */
1841int strl2ic(const char *s, int len)
1842{
1843 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001844 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001845
1846 if (len > 0) {
1847 if (*s != '-') {
1848 /* positive number */
1849 while (len-- > 0) {
1850 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001851 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001852 if (j > 9)
1853 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001854 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001855 }
1856 } else {
1857 /* negative number */
1858 s++;
1859 while (--len > 0) {
1860 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001861 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001862 if (j > 9)
1863 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001864 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001865 }
1866 }
1867 }
1868 return i;
1869}
1870
1871
1872/* This function reads exactly <len> chars from <s> and converts them to a
1873 * signed integer which it stores into <ret>. It accurately detects any error
1874 * (truncated string, invalid chars, overflows). It is meant to be used in
1875 * applications designed for hostile environments. It returns zero when the
1876 * number has successfully been converted, non-zero otherwise. When an error
1877 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1878 * faster than strtol().
1879 */
1880int strl2irc(const char *s, int len, int *ret)
1881{
1882 int i = 0;
1883 int j;
1884
1885 if (!len)
1886 return 1;
1887
1888 if (*s != '-') {
1889 /* positive number */
1890 while (len-- > 0) {
1891 j = (*s++) - '0';
1892 if (j > 9) return 1; /* invalid char */
1893 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1894 i = i * 10;
1895 if (i + j < i) return 1; /* check for addition overflow */
1896 i = i + j;
1897 }
1898 } else {
1899 /* negative number */
1900 s++;
1901 while (--len > 0) {
1902 j = (*s++) - '0';
1903 if (j > 9) return 1; /* invalid char */
1904 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1905 i = i * 10;
1906 if (i - j > i) return 1; /* check for subtract overflow */
1907 i = i - j;
1908 }
1909 }
1910 *ret = i;
1911 return 0;
1912}
1913
1914
1915/* This function reads exactly <len> chars from <s> and converts them to a
1916 * signed integer which it stores into <ret>. It accurately detects any error
1917 * (truncated string, invalid chars, overflows). It is meant to be used in
1918 * applications designed for hostile environments. It returns zero when the
1919 * number has successfully been converted, non-zero otherwise. When an error
1920 * is returned, the <ret> value is left untouched. It is about 3 times slower
1921 * than str2irc().
1922 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001923
1924int strl2llrc(const char *s, int len, long long *ret)
1925{
1926 long long i = 0;
1927 int j;
1928
1929 if (!len)
1930 return 1;
1931
1932 if (*s != '-') {
1933 /* positive number */
1934 while (len-- > 0) {
1935 j = (*s++) - '0';
1936 if (j > 9) return 1; /* invalid char */
1937 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1938 i = i * 10LL;
1939 if (i + j < i) return 1; /* check for addition overflow */
1940 i = i + j;
1941 }
1942 } else {
1943 /* negative number */
1944 s++;
1945 while (--len > 0) {
1946 j = (*s++) - '0';
1947 if (j > 9) return 1; /* invalid char */
1948 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1949 i = i * 10LL;
1950 if (i - j > i) return 1; /* check for subtract overflow */
1951 i = i - j;
1952 }
1953 }
1954 *ret = i;
1955 return 0;
1956}
1957
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001958/* This function is used with pat_parse_dotted_ver(). It converts a string
1959 * composed by two number separated by a dot. Each part must contain in 16 bits
1960 * because internally they will be represented as a 32-bit quantity stored in
1961 * a 64-bit integer. It returns zero when the number has successfully been
1962 * converted, non-zero otherwise. When an error is returned, the <ret> value
1963 * is left untouched.
1964 *
1965 * "1.3" -> 0x0000000000010003
1966 * "65535.65535" -> 0x00000000ffffffff
1967 */
1968int strl2llrc_dotted(const char *text, int len, long long *ret)
1969{
1970 const char *end = &text[len];
1971 const char *p;
1972 long long major, minor;
1973
1974 /* Look for dot. */
1975 for (p = text; p < end; p++)
1976 if (*p == '.')
1977 break;
1978
1979 /* Convert major. */
1980 if (strl2llrc(text, p - text, &major) != 0)
1981 return 1;
1982
1983 /* Check major. */
1984 if (major >= 65536)
1985 return 1;
1986
1987 /* Convert minor. */
1988 minor = 0;
1989 if (p < end)
1990 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1991 return 1;
1992
1993 /* Check minor. */
1994 if (minor >= 65536)
1995 return 1;
1996
1997 /* Compose value. */
1998 *ret = (major << 16) | (minor & 0xffff);
1999 return 0;
2000}
2001
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002002/* This function parses a time value optionally followed by a unit suffix among
2003 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2004 * expected by the caller. The computation does its best to avoid overflows.
2005 * The value is returned in <ret> if everything is fine, and a NULL is returned
2006 * by the function. In case of error, a pointer to the error is returned and
2007 * <ret> is left untouched. Values are automatically rounded up when needed.
2008 */
2009const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2010{
2011 unsigned imult, idiv;
2012 unsigned omult, odiv;
2013 unsigned value;
2014
2015 omult = odiv = 1;
2016
2017 switch (unit_flags & TIME_UNIT_MASK) {
2018 case TIME_UNIT_US: omult = 1000000; break;
2019 case TIME_UNIT_MS: omult = 1000; break;
2020 case TIME_UNIT_S: break;
2021 case TIME_UNIT_MIN: odiv = 60; break;
2022 case TIME_UNIT_HOUR: odiv = 3600; break;
2023 case TIME_UNIT_DAY: odiv = 86400; break;
2024 default: break;
2025 }
2026
2027 value = 0;
2028
2029 while (1) {
2030 unsigned int j;
2031
2032 j = *text - '0';
2033 if (j > 9)
2034 break;
2035 text++;
2036 value *= 10;
2037 value += j;
2038 }
2039
2040 imult = idiv = 1;
2041 switch (*text) {
2042 case '\0': /* no unit = default unit */
2043 imult = omult = idiv = odiv = 1;
2044 break;
2045 case 's': /* second = unscaled unit */
2046 break;
2047 case 'u': /* microsecond : "us" */
2048 if (text[1] == 's') {
2049 idiv = 1000000;
2050 text++;
2051 }
2052 break;
2053 case 'm': /* millisecond : "ms" or minute: "m" */
2054 if (text[1] == 's') {
2055 idiv = 1000;
2056 text++;
2057 } else
2058 imult = 60;
2059 break;
2060 case 'h': /* hour : "h" */
2061 imult = 3600;
2062 break;
2063 case 'd': /* day : "d" */
2064 imult = 86400;
2065 break;
2066 default:
2067 return text;
2068 break;
2069 }
2070
2071 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2072 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2073 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2074 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2075
2076 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2077 *ret = value;
2078 return NULL;
2079}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002080
Emeric Brun39132b22010-01-04 14:57:24 +01002081/* this function converts the string starting at <text> to an unsigned int
2082 * stored in <ret>. If an error is detected, the pointer to the unexpected
2083 * character is returned. If the conversio is succesful, NULL is returned.
2084 */
2085const char *parse_size_err(const char *text, unsigned *ret) {
2086 unsigned value = 0;
2087
2088 while (1) {
2089 unsigned int j;
2090
2091 j = *text - '0';
2092 if (j > 9)
2093 break;
2094 if (value > ~0U / 10)
2095 return text;
2096 value *= 10;
2097 if (value > (value + j))
2098 return text;
2099 value += j;
2100 text++;
2101 }
2102
2103 switch (*text) {
2104 case '\0':
2105 break;
2106 case 'K':
2107 case 'k':
2108 if (value > ~0U >> 10)
2109 return text;
2110 value = value << 10;
2111 break;
2112 case 'M':
2113 case 'm':
2114 if (value > ~0U >> 20)
2115 return text;
2116 value = value << 20;
2117 break;
2118 case 'G':
2119 case 'g':
2120 if (value > ~0U >> 30)
2121 return text;
2122 value = value << 30;
2123 break;
2124 default:
2125 return text;
2126 }
2127
Godbach58048a22015-01-28 17:36:16 +08002128 if (*text != '\0' && *++text != '\0')
2129 return text;
2130
Emeric Brun39132b22010-01-04 14:57:24 +01002131 *ret = value;
2132 return NULL;
2133}
2134
Willy Tarreau126d4062013-12-03 17:50:47 +01002135/*
2136 * Parse binary string written in hexadecimal (source) and store the decoded
2137 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2138 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002139 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002140 */
2141int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2142{
2143 int len;
2144 const char *p = source;
2145 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002146 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002147
2148 len = strlen(source);
2149 if (len % 2) {
2150 memprintf(err, "an even number of hex digit is expected");
2151 return 0;
2152 }
2153
2154 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002155
Willy Tarreau126d4062013-12-03 17:50:47 +01002156 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002157 *binstr = calloc(len, sizeof(char));
2158 if (!*binstr) {
2159 memprintf(err, "out of memory while loading string pattern");
2160 return 0;
2161 }
2162 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002163 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002164 else {
2165 if (*binstrlen < len) {
2166 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2167 len, *binstrlen);
2168 return 0;
2169 }
2170 alloc = 0;
2171 }
2172 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002173
2174 i = j = 0;
2175 while (j < len) {
2176 if (!ishex(p[i++]))
2177 goto bad_input;
2178 if (!ishex(p[i++]))
2179 goto bad_input;
2180 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2181 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002182 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002183
2184bad_input:
2185 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002186 if (alloc) {
2187 free(*binstr);
2188 *binstr = NULL;
2189 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002190 return 0;
2191}
2192
Willy Tarreau946ba592009-05-10 15:41:18 +02002193/* copies at most <n> characters from <src> and always terminates with '\0' */
2194char *my_strndup(const char *src, int n)
2195{
2196 int len = 0;
2197 char *ret;
2198
2199 while (len < n && src[len])
2200 len++;
2201
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002202 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002203 if (!ret)
2204 return ret;
2205 memcpy(ret, src, len);
2206 ret[len] = '\0';
2207 return ret;
2208}
2209
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002210/*
2211 * search needle in haystack
2212 * returns the pointer if found, returns NULL otherwise
2213 */
2214const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2215{
2216 const void *c = NULL;
2217 unsigned char f;
2218
2219 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2220 return NULL;
2221
2222 f = *(char *)needle;
2223 c = haystack;
2224 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2225 if ((haystacklen - (c - haystack)) < needlelen)
2226 return NULL;
2227
2228 if (memcmp(c, needle, needlelen) == 0)
2229 return c;
2230 ++c;
2231 }
2232 return NULL;
2233}
2234
Willy Tarreau482b00d2009-10-04 22:48:42 +02002235/* This function returns the first unused key greater than or equal to <key> in
2236 * ID tree <root>. Zero is returned if no place is found.
2237 */
2238unsigned int get_next_id(struct eb_root *root, unsigned int key)
2239{
2240 struct eb32_node *used;
2241
2242 do {
2243 used = eb32_lookup_ge(root, key);
2244 if (!used || used->key > key)
2245 return key; /* key is available */
2246 key++;
2247 } while (key);
2248 return key;
2249}
2250
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002251/* dump the full tree to <file> in DOT format for debugging purposes. Will
2252 * optionally highlight node <subj> if found, depending on operation <op> :
2253 * 0 : nothing
2254 * >0 : insertion, node/leaf are surrounded in red
2255 * <0 : removal, node/leaf are dashed with no background
2256 * Will optionally add "desc" as a label on the graph if set and non-null.
2257 */
2258void 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 +01002259{
2260 struct eb32sc_node *node;
2261 unsigned long scope = -1;
2262
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002263 fprintf(file, "digraph ebtree {\n");
2264
2265 if (desc && *desc) {
2266 fprintf(file,
2267 " fontname=\"fixed\";\n"
2268 " fontsize=8;\n"
2269 " label=\"%s\";\n", desc);
2270 }
2271
Willy Tarreaued3cda02017-11-15 15:04:05 +01002272 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002273 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2274 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002275 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2276 );
2277
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002278 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002279 (long)eb_root_to_node(root),
2280 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002281 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2282
2283 node = eb32sc_first(root, scope);
2284 while (node) {
2285 if (node->node.node_p) {
2286 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002287 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2288 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2289 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002290
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002291 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002292 (long)node,
2293 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002294 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002295
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002296 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002297 (long)node,
2298 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002299 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2300
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002301 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002302 (long)node,
2303 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002304 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2305 }
2306
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002307 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2308 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2309 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002310
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002311 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002312 (long)node,
2313 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002314 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002315 node = eb32sc_next(node, scope);
2316 }
2317 fprintf(file, "}\n");
2318}
2319
Willy Tarreau348238b2010-01-18 15:05:57 +01002320/* This function compares a sample word possibly followed by blanks to another
2321 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2322 * otherwise zero. This intends to be used when checking HTTP headers for some
2323 * values. Note that it validates a word followed only by blanks but does not
2324 * validate a word followed by blanks then other chars.
2325 */
2326int word_match(const char *sample, int slen, const char *word, int wlen)
2327{
2328 if (slen < wlen)
2329 return 0;
2330
2331 while (wlen) {
2332 char c = *sample ^ *word;
2333 if (c && c != ('A' ^ 'a'))
2334 return 0;
2335 sample++;
2336 word++;
2337 slen--;
2338 wlen--;
2339 }
2340
2341 while (slen) {
2342 if (*sample != ' ' && *sample != '\t')
2343 return 0;
2344 sample++;
2345 slen--;
2346 }
2347 return 1;
2348}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002349
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002350/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2351 * is particularly fast because it avoids expensive operations such as
2352 * multiplies, which are optimized away at the end. It requires a properly
2353 * formated address though (3 points).
2354 */
2355unsigned int inetaddr_host(const char *text)
2356{
2357 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2358 register unsigned int dig100, dig10, dig1;
2359 int s;
2360 const char *p, *d;
2361
2362 dig1 = dig10 = dig100 = ascii_zero;
2363 s = 24;
2364
2365 p = text;
2366 while (1) {
2367 if (((unsigned)(*p - '0')) <= 9) {
2368 p++;
2369 continue;
2370 }
2371
2372 /* here, we have a complete byte between <text> and <p> (exclusive) */
2373 if (p == text)
2374 goto end;
2375
2376 d = p - 1;
2377 dig1 |= (unsigned int)(*d << s);
2378 if (d == text)
2379 goto end;
2380
2381 d--;
2382 dig10 |= (unsigned int)(*d << s);
2383 if (d == text)
2384 goto end;
2385
2386 d--;
2387 dig100 |= (unsigned int)(*d << s);
2388 end:
2389 if (!s || *p != '.')
2390 break;
2391
2392 s -= 8;
2393 text = ++p;
2394 }
2395
2396 dig100 -= ascii_zero;
2397 dig10 -= ascii_zero;
2398 dig1 -= ascii_zero;
2399 return ((dig100 * 10) + dig10) * 10 + dig1;
2400}
2401
2402/*
2403 * Idem except the first unparsed character has to be passed in <stop>.
2404 */
2405unsigned int inetaddr_host_lim(const char *text, const char *stop)
2406{
2407 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2408 register unsigned int dig100, dig10, dig1;
2409 int s;
2410 const char *p, *d;
2411
2412 dig1 = dig10 = dig100 = ascii_zero;
2413 s = 24;
2414
2415 p = text;
2416 while (1) {
2417 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2418 p++;
2419 continue;
2420 }
2421
2422 /* here, we have a complete byte between <text> and <p> (exclusive) */
2423 if (p == text)
2424 goto end;
2425
2426 d = p - 1;
2427 dig1 |= (unsigned int)(*d << s);
2428 if (d == text)
2429 goto end;
2430
2431 d--;
2432 dig10 |= (unsigned int)(*d << s);
2433 if (d == text)
2434 goto end;
2435
2436 d--;
2437 dig100 |= (unsigned int)(*d << s);
2438 end:
2439 if (!s || p == stop || *p != '.')
2440 break;
2441
2442 s -= 8;
2443 text = ++p;
2444 }
2445
2446 dig100 -= ascii_zero;
2447 dig10 -= ascii_zero;
2448 dig1 -= ascii_zero;
2449 return ((dig100 * 10) + dig10) * 10 + dig1;
2450}
2451
2452/*
2453 * Idem except the pointer to first unparsed byte is returned into <ret> which
2454 * must not be NULL.
2455 */
Willy Tarreau74172752010-10-15 23:21:42 +02002456unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002457{
2458 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2459 register unsigned int dig100, dig10, dig1;
2460 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002461 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002462
2463 dig1 = dig10 = dig100 = ascii_zero;
2464 s = 24;
2465
2466 p = text;
2467 while (1) {
2468 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2469 p++;
2470 continue;
2471 }
2472
2473 /* here, we have a complete byte between <text> and <p> (exclusive) */
2474 if (p == text)
2475 goto end;
2476
2477 d = p - 1;
2478 dig1 |= (unsigned int)(*d << s);
2479 if (d == text)
2480 goto end;
2481
2482 d--;
2483 dig10 |= (unsigned int)(*d << s);
2484 if (d == text)
2485 goto end;
2486
2487 d--;
2488 dig100 |= (unsigned int)(*d << s);
2489 end:
2490 if (!s || p == stop || *p != '.')
2491 break;
2492
2493 s -= 8;
2494 text = ++p;
2495 }
2496
2497 *ret = p;
2498 dig100 -= ascii_zero;
2499 dig10 -= ascii_zero;
2500 dig1 -= ascii_zero;
2501 return ((dig100 * 10) + dig10) * 10 + dig1;
2502}
2503
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002504/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2505 * or the number of chars read in case of success. Maybe this could be replaced
2506 * by one of the functions above. Also, apparently this function does not support
2507 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002508 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002509 */
2510int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2511{
2512 const char *addr;
2513 int saw_digit, octets, ch;
2514 u_char tmp[4], *tp;
2515 const char *cp = buf;
2516
2517 saw_digit = 0;
2518 octets = 0;
2519 *(tp = tmp) = 0;
2520
2521 for (addr = buf; addr - buf < len; addr++) {
2522 unsigned char digit = (ch = *addr) - '0';
2523
2524 if (digit > 9 && ch != '.')
2525 break;
2526
2527 if (digit <= 9) {
2528 u_int new = *tp * 10 + digit;
2529
2530 if (new > 255)
2531 return 0;
2532
2533 *tp = new;
2534
2535 if (!saw_digit) {
2536 if (++octets > 4)
2537 return 0;
2538 saw_digit = 1;
2539 }
2540 } else if (ch == '.' && saw_digit) {
2541 if (octets == 4)
2542 return 0;
2543
2544 *++tp = 0;
2545 saw_digit = 0;
2546 } else
2547 return 0;
2548 }
2549
2550 if (octets < 4)
2551 return 0;
2552
2553 memcpy(&dst->s_addr, tmp, 4);
2554 return addr - cp;
2555}
2556
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002557/* This function converts the string in <buf> of the len <len> to
2558 * struct in6_addr <dst> which must be allocated by the caller.
2559 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002560 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002561 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002562int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2563{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002564 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002565 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002566
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002567 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002568 return 0;
2569
2570 memcpy(null_term_ip6, buf, len);
2571 null_term_ip6[len] = '\0';
2572
Willy Tarreau075415a2013-12-12 11:29:39 +01002573 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002574 return 0;
2575
Willy Tarreau075415a2013-12-12 11:29:39 +01002576 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002577 return 1;
2578}
2579
Willy Tarreauacf95772010-06-14 19:09:21 +02002580/* To be used to quote config arg positions. Returns the short string at <ptr>
2581 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2582 * if ptr is NULL or empty. The string is locally allocated.
2583 */
2584const char *quote_arg(const char *ptr)
2585{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002586 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002587 int i;
2588
2589 if (!ptr || !*ptr)
2590 return "end of line";
2591 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002592 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002593 val[i] = *ptr++;
2594 val[i++] = '\'';
2595 val[i] = '\0';
2596 return val;
2597}
2598
Willy Tarreau5b180202010-07-18 10:40:48 +02002599/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2600int get_std_op(const char *str)
2601{
2602 int ret = -1;
2603
2604 if (*str == 'e' && str[1] == 'q')
2605 ret = STD_OP_EQ;
2606 else if (*str == 'n' && str[1] == 'e')
2607 ret = STD_OP_NE;
2608 else if (*str == 'l') {
2609 if (str[1] == 'e') ret = STD_OP_LE;
2610 else if (str[1] == 't') ret = STD_OP_LT;
2611 }
2612 else if (*str == 'g') {
2613 if (str[1] == 'e') ret = STD_OP_GE;
2614 else if (str[1] == 't') ret = STD_OP_GT;
2615 }
2616
2617 if (ret == -1 || str[2] != '\0')
2618 return -1;
2619 return ret;
2620}
2621
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002622/* hash a 32-bit integer to another 32-bit integer */
2623unsigned int full_hash(unsigned int a)
2624{
2625 return __full_hash(a);
2626}
2627
David du Colombier4f92d322011-03-24 11:09:31 +01002628/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002629 * otherwise zero. Note that <addr> may not necessarily be aligned
2630 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002631 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002632int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002633{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002634 struct in_addr addr_copy;
2635
2636 memcpy(&addr_copy, addr, sizeof(addr_copy));
2637 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002638}
2639
2640/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002641 * otherwise zero. Note that <addr> may not necessarily be aligned
2642 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002643 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002644int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002645{
2646 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002647 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002648
Willy Tarreaueec1d382016-07-13 11:59:39 +02002649 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002650 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002651 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002652 (((int *)net)[i] & ((int *)mask)[i]))
2653 return 0;
2654 return 1;
2655}
2656
2657/* RFC 4291 prefix */
2658const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2659 0x00, 0x00, 0x00, 0x00,
2660 0x00, 0x00, 0xFF, 0xFF };
2661
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002662/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2663 * Input and output may overlap.
2664 */
David du Colombier4f92d322011-03-24 11:09:31 +01002665void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2666{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002667 struct in_addr tmp_addr;
2668
2669 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002670 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002671 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002672}
2673
2674/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2675 * Return true if conversion is possible and false otherwise.
2676 */
2677int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2678{
2679 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2680 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2681 sizeof(struct in_addr));
2682 return 1;
2683 }
2684
2685 return 0;
2686}
2687
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002688/* compare two struct sockaddr_storage and return:
2689 * 0 (true) if the addr is the same in both
2690 * 1 (false) if the addr is not the same in both
2691 * -1 (unable) if one of the addr is not AF_INET*
2692 */
2693int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2694{
2695 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2696 return -1;
2697
2698 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2699 return -1;
2700
2701 if (ss1->ss_family != ss2->ss_family)
2702 return 1;
2703
2704 switch (ss1->ss_family) {
2705 case AF_INET:
2706 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2707 &((struct sockaddr_in *)ss2)->sin_addr,
2708 sizeof(struct in_addr)) != 0;
2709 case AF_INET6:
2710 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2711 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2712 sizeof(struct in6_addr)) != 0;
2713 }
2714
2715 return 1;
2716}
2717
Baptiste Assmann08396c82016-01-31 00:27:17 +01002718/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002719 * The caller must allocate and clear <dest> before calling.
2720 * The source must be in either AF_INET or AF_INET6 family, or the destination
2721 * address will be undefined. If the destination address used to hold a port,
2722 * it is preserved, so that this function can be used to switch to another
2723 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002724 */
2725struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2726{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002727 int prev_port;
2728
2729 prev_port = get_net_port(dest);
2730 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002731 dest->ss_family = source->ss_family;
2732
2733 /* copy new addr and apply it */
2734 switch (source->ss_family) {
2735 case AF_INET:
2736 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002737 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002738 break;
2739 case AF_INET6:
2740 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 +01002741 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002742 break;
2743 }
2744
2745 return dest;
2746}
2747
William Lallemand421f5b52012-02-06 18:15:57 +01002748char *human_time(int t, short hz_div) {
2749 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2750 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002751 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002752 int cnt=2; // print two numbers
2753
2754 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002755 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002756 return rv;
2757 }
2758
2759 if (unlikely(hz_div > 1))
2760 t /= hz_div;
2761
2762 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002763 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002764 cnt--;
2765 }
2766
2767 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002768 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002769 cnt--;
2770 }
2771
2772 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002773 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002774 cnt--;
2775 }
2776
2777 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002778 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002779
2780 return rv;
2781}
2782
2783const char *monthname[12] = {
2784 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2785 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2786};
2787
2788/* date2str_log: write a date in the format :
2789 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2790 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2791 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2792 *
2793 * without using sprintf. return a pointer to the last char written (\0) or
2794 * NULL if there isn't enough space.
2795 */
2796char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2797{
2798
2799 if (size < 25) /* the size is fixed: 24 chars + \0 */
2800 return NULL;
2801
2802 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2803 *dst++ = '/';
2804 memcpy(dst, monthname[tm->tm_mon], 3); // month
2805 dst += 3;
2806 *dst++ = '/';
2807 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2808 *dst++ = ':';
2809 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2810 *dst++ = ':';
2811 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2812 *dst++ = ':';
2813 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2814 *dst++ = '.';
2815 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2816 dst += 3; // only the 3 first digits
2817 *dst = '\0';
2818
2819 return dst;
2820}
2821
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002822/* Base year used to compute leap years */
2823#define TM_YEAR_BASE 1900
2824
2825/* Return the difference in seconds between two times (leap seconds are ignored).
2826 * Retrieved from glibc 2.18 source code.
2827 */
2828static int my_tm_diff(const struct tm *a, const struct tm *b)
2829{
2830 /* Compute intervening leap days correctly even if year is negative.
2831 * Take care to avoid int overflow in leap day calculations,
2832 * but it's OK to assume that A and B are close to each other.
2833 */
2834 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2835 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2836 int a100 = a4 / 25 - (a4 % 25 < 0);
2837 int b100 = b4 / 25 - (b4 % 25 < 0);
2838 int a400 = a100 >> 2;
2839 int b400 = b100 >> 2;
2840 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2841 int years = a->tm_year - b->tm_year;
2842 int days = (365 * years + intervening_leap_days
2843 + (a->tm_yday - b->tm_yday));
2844 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2845 + (a->tm_min - b->tm_min))
2846 + (a->tm_sec - b->tm_sec));
2847}
2848
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002849/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002850 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002851 * The string returned has the same format as returned by strftime(... "%z", tm).
2852 * Offsets are kept in an internal cache for better performances.
2853 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002854const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002855{
2856 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002857 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002858
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002859 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002860 struct tm tm_gmt;
2861 int diff;
2862 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002863
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002864 /* Pretend DST not active if its status is unknown */
2865 if (isdst < 0)
2866 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002867
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002868 /* Fetch the offset and initialize it if needed */
2869 gmt_offset = gmt_offsets[isdst & 0x01];
2870 if (unlikely(!*gmt_offset)) {
2871 get_gmtime(t, &tm_gmt);
2872 diff = my_tm_diff(tm, &tm_gmt);
2873 if (diff < 0) {
2874 diff = -diff;
2875 *gmt_offset = '-';
2876 } else {
2877 *gmt_offset = '+';
2878 }
2879 diff /= 60; /* Convert to minutes */
2880 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2881 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002882
2883 return gmt_offset;
2884}
2885
William Lallemand421f5b52012-02-06 18:15:57 +01002886/* gmt2str_log: write a date in the format :
2887 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2888 * return a pointer to the last char written (\0) or
2889 * NULL if there isn't enough space.
2890 */
2891char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2892{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002893 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002894 return NULL;
2895
2896 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2897 *dst++ = '/';
2898 memcpy(dst, monthname[tm->tm_mon], 3); // month
2899 dst += 3;
2900 *dst++ = '/';
2901 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2902 *dst++ = ':';
2903 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2904 *dst++ = ':';
2905 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2906 *dst++ = ':';
2907 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2908 *dst++ = ' ';
2909 *dst++ = '+';
2910 *dst++ = '0';
2911 *dst++ = '0';
2912 *dst++ = '0';
2913 *dst++ = '0';
2914 *dst = '\0';
2915
2916 return dst;
2917}
2918
Yuxans Yao4e25b012012-10-19 10:36:09 +08002919/* localdate2str_log: write a date in the format :
2920 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002921 * Both t and tm must represent the same time.
2922 * return a pointer to the last char written (\0) or
2923 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002924 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002925char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002926{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002927 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002928 if (size < 27) /* the size is fixed: 26 chars + \0 */
2929 return NULL;
2930
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002931 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002932
Yuxans Yao4e25b012012-10-19 10:36:09 +08002933 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2934 *dst++ = '/';
2935 memcpy(dst, monthname[tm->tm_mon], 3); // month
2936 dst += 3;
2937 *dst++ = '/';
2938 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2939 *dst++ = ':';
2940 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2941 *dst++ = ':';
2942 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2943 *dst++ = ':';
2944 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2945 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002946 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002947 dst += 5;
2948 *dst = '\0';
2949
2950 return dst;
2951}
2952
Willy Tarreaucb1949b2017-07-19 19:05:29 +02002953/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
2954 * It is meant as a portable replacement for timegm() for use with valid inputs.
2955 * Returns undefined results for invalid dates (eg: months out of range 0..11).
2956 */
2957time_t my_timegm(const struct tm *tm)
2958{
2959 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
2960 * is thus (current month - 1)*28 + cumulated_N[month] to count the
2961 * sum of the extra N days for elapsed months. The sum of all these N
2962 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
2963 * in a 5-bit word. This means that with 60 bits we can represent a
2964 * matrix of all these values at once, which is fast and efficient to
2965 * access. The extra February day for leap years is not counted here.
2966 *
2967 * Jan : none = 0 (0)
2968 * Feb : Jan = 3 (3)
2969 * Mar : Jan..Feb = 3 (3 + 0)
2970 * Apr : Jan..Mar = 6 (3 + 0 + 3)
2971 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
2972 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
2973 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
2974 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
2975 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
2976 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
2977 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
2978 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
2979 */
2980 uint64_t extra =
2981 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
2982 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
2983 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
2984 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
2985
2986 unsigned int y = tm->tm_year + 1900;
2987 unsigned int m = tm->tm_mon;
2988 unsigned long days = 0;
2989
2990 /* days since 1/1/1970 for full years */
2991 days += days_since_zero(y) - days_since_zero(1970);
2992
2993 /* days for full months in the current year */
2994 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
2995
2996 /* count + 1 after March for leap years. A leap year is a year multiple
2997 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
2998 * is leap, 1900 isn't, 1904 is.
2999 */
3000 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3001 days++;
3002
3003 days += tm->tm_mday - 1;
3004 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3005}
3006
Thierry Fournier93127942016-01-20 18:49:45 +01003007/* This function check a char. It returns true and updates
3008 * <date> and <len> pointer to the new position if the
3009 * character is found.
3010 */
3011static inline int parse_expect_char(const char **date, int *len, char c)
3012{
3013 if (*len < 1 || **date != c)
3014 return 0;
3015 (*len)--;
3016 (*date)++;
3017 return 1;
3018}
3019
3020/* This function expects a string <str> of len <l>. It return true and updates.
3021 * <date> and <len> if the string matches, otherwise, it returns false.
3022 */
3023static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3024{
3025 if (*len < l || strncmp(*date, str, l) != 0)
3026 return 0;
3027 (*len) -= l;
3028 (*date) += l;
3029 return 1;
3030}
3031
3032/* This macro converts 3 chars name in integer. */
3033#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3034
3035/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3036 * / %x54.75.65 ; "Tue", case-sensitive
3037 * / %x57.65.64 ; "Wed", case-sensitive
3038 * / %x54.68.75 ; "Thu", case-sensitive
3039 * / %x46.72.69 ; "Fri", case-sensitive
3040 * / %x53.61.74 ; "Sat", case-sensitive
3041 * / %x53.75.6E ; "Sun", case-sensitive
3042 *
3043 * This array must be alphabetically sorted
3044 */
3045static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3046{
3047 if (*len < 3)
3048 return 0;
3049 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3050 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3051 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3052 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3053 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3054 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3055 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3056 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3057 default: return 0;
3058 }
3059 *len -= 3;
3060 *date += 3;
3061 return 1;
3062}
3063
3064/* month = %x4A.61.6E ; "Jan", case-sensitive
3065 * / %x46.65.62 ; "Feb", case-sensitive
3066 * / %x4D.61.72 ; "Mar", case-sensitive
3067 * / %x41.70.72 ; "Apr", case-sensitive
3068 * / %x4D.61.79 ; "May", case-sensitive
3069 * / %x4A.75.6E ; "Jun", case-sensitive
3070 * / %x4A.75.6C ; "Jul", case-sensitive
3071 * / %x41.75.67 ; "Aug", case-sensitive
3072 * / %x53.65.70 ; "Sep", case-sensitive
3073 * / %x4F.63.74 ; "Oct", case-sensitive
3074 * / %x4E.6F.76 ; "Nov", case-sensitive
3075 * / %x44.65.63 ; "Dec", case-sensitive
3076 *
3077 * This array must be alphabetically sorted
3078 */
3079static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3080{
3081 if (*len < 3)
3082 return 0;
3083 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3084 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3085 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3086 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3087 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3088 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3089 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3090 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3091 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3092 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3093 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3094 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3095 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3096 default: return 0;
3097 }
3098 *len -= 3;
3099 *date += 3;
3100 return 1;
3101}
3102
3103/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3104 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3105 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3106 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3107 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3108 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3109 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3110 *
3111 * This array must be alphabetically sorted
3112 */
3113static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3114{
3115 if (*len < 6) /* Minimum length. */
3116 return 0;
3117 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3118 case STR2I3('M','o','n'):
3119 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3120 tm->tm_wday = 1;
3121 return 1;
3122 case STR2I3('T','u','e'):
3123 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3124 tm->tm_wday = 2;
3125 return 1;
3126 case STR2I3('W','e','d'):
3127 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3128 tm->tm_wday = 3;
3129 return 1;
3130 case STR2I3('T','h','u'):
3131 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3132 tm->tm_wday = 4;
3133 return 1;
3134 case STR2I3('F','r','i'):
3135 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3136 tm->tm_wday = 5;
3137 return 1;
3138 case STR2I3('S','a','t'):
3139 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3140 tm->tm_wday = 6;
3141 return 1;
3142 case STR2I3('S','u','n'):
3143 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3144 tm->tm_wday = 7;
3145 return 1;
3146 }
3147 return 0;
3148}
3149
3150/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3151static inline int parse_digit(const char **date, int *len, int *digit)
3152{
3153 if (*len < 1 || **date < '0' || **date > '9')
3154 return 0;
3155 *digit = (**date - '0');
3156 (*date)++;
3157 (*len)--;
3158 return 1;
3159}
3160
3161/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3162static inline int parse_2digit(const char **date, int *len, int *digit)
3163{
3164 int value;
3165
3166 RET0_UNLESS(parse_digit(date, len, &value));
3167 (*digit) = value * 10;
3168 RET0_UNLESS(parse_digit(date, len, &value));
3169 (*digit) += value;
3170
3171 return 1;
3172}
3173
3174/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3175static inline int parse_4digit(const char **date, int *len, int *digit)
3176{
3177 int value;
3178
3179 RET0_UNLESS(parse_digit(date, len, &value));
3180 (*digit) = value * 1000;
3181
3182 RET0_UNLESS(parse_digit(date, len, &value));
3183 (*digit) += value * 100;
3184
3185 RET0_UNLESS(parse_digit(date, len, &value));
3186 (*digit) += value * 10;
3187
3188 RET0_UNLESS(parse_digit(date, len, &value));
3189 (*digit) += value;
3190
3191 return 1;
3192}
3193
3194/* time-of-day = hour ":" minute ":" second
3195 * ; 00:00:00 - 23:59:60 (leap second)
3196 *
3197 * hour = 2DIGIT
3198 * minute = 2DIGIT
3199 * second = 2DIGIT
3200 */
3201static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3202{
3203 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3204 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3205 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3206 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3207 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3208 return 1;
3209}
3210
3211/* From RFC7231
3212 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3213 *
3214 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3215 * ; fixed length/zone/capitalization subset of the format
3216 * ; see Section 3.3 of [RFC5322]
3217 *
3218 *
3219 * date1 = day SP month SP year
3220 * ; e.g., 02 Jun 1982
3221 *
3222 * day = 2DIGIT
3223 * year = 4DIGIT
3224 *
3225 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3226 *
3227 * time-of-day = hour ":" minute ":" second
3228 * ; 00:00:00 - 23:59:60 (leap second)
3229 *
3230 * hour = 2DIGIT
3231 * minute = 2DIGIT
3232 * second = 2DIGIT
3233 *
3234 * DIGIT = decimal 0-9
3235 */
3236int parse_imf_date(const char *date, int len, struct tm *tm)
3237{
David Carlier327298c2016-11-20 10:42:38 +00003238 /* tm_gmtoff, if present, ought to be zero'ed */
3239 memset(tm, 0, sizeof(*tm));
3240
Thierry Fournier93127942016-01-20 18:49:45 +01003241 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3242 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3243 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3244 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3245 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3246 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3247 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3248 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3249 tm->tm_year -= 1900;
3250 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3251 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3252 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3253 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3254 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003255 return 1;
3256}
3257
3258/* From RFC7231
3259 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3260 *
3261 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3262 * date2 = day "-" month "-" 2DIGIT
3263 * ; e.g., 02-Jun-82
3264 *
3265 * day = 2DIGIT
3266 */
3267int parse_rfc850_date(const char *date, int len, struct tm *tm)
3268{
3269 int year;
3270
David Carlier327298c2016-11-20 10:42:38 +00003271 /* tm_gmtoff, if present, ought to be zero'ed */
3272 memset(tm, 0, sizeof(*tm));
3273
Thierry Fournier93127942016-01-20 18:49:45 +01003274 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3275 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3276 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3277 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3278 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3279 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3280 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3281
3282 /* year = 2DIGIT
3283 *
3284 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3285 * two-digit year, MUST interpret a timestamp that appears to be more
3286 * than 50 years in the future as representing the most recent year in
3287 * the past that had the same last two digits.
3288 */
3289 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3290
3291 /* expect SP */
3292 if (!parse_expect_char(&date, &len, ' ')) {
3293 /* Maybe we have the date with 4 digits. */
3294 RET0_UNLESS(parse_2digit(&date, &len, &year));
3295 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3296 /* expect SP */
3297 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3298 } else {
3299 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3300 * tm_year is the number of year since 1900, so for +1900, we
3301 * do nothing, and for +2000, we add 100.
3302 */
3303 if (tm->tm_year <= 60)
3304 tm->tm_year += 100;
3305 }
3306
3307 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3308 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3309 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3310 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003311
3312 return 1;
3313}
3314
3315/* From RFC7231
3316 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3317 *
3318 * asctime-date = day-name SP date3 SP time-of-day SP year
3319 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3320 * ; e.g., Jun 2
3321 *
3322 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3323 * whitespace in an HTTP-date beyond that specifically included as SP in
3324 * the grammar.
3325 */
3326int parse_asctime_date(const char *date, int len, struct tm *tm)
3327{
David Carlier327298c2016-11-20 10:42:38 +00003328 /* tm_gmtoff, if present, ought to be zero'ed */
3329 memset(tm, 0, sizeof(*tm));
3330
Thierry Fournier93127942016-01-20 18:49:45 +01003331 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3332 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3333 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3334 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3335
3336 /* expect SP and 1DIGIT or 2DIGIT */
3337 if (parse_expect_char(&date, &len, ' '))
3338 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3339 else
3340 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3341
3342 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3343 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3344 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3345 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3346 tm->tm_year -= 1900;
3347 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003348 return 1;
3349}
3350
3351/* From RFC7231
3352 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3353 *
3354 * HTTP-date = IMF-fixdate / obs-date
3355 * obs-date = rfc850-date / asctime-date
3356 *
3357 * parses an HTTP date in the RFC format and is accepted
3358 * alternatives. <date> is the strinf containing the date,
3359 * len is the len of the string. <tm> is filled with the
3360 * parsed time. We must considers this time as GMT.
3361 */
3362int parse_http_date(const char *date, int len, struct tm *tm)
3363{
3364 if (parse_imf_date(date, len, tm))
3365 return 1;
3366
3367 if (parse_rfc850_date(date, len, tm))
3368 return 1;
3369
3370 if (parse_asctime_date(date, len, tm))
3371 return 1;
3372
3373 return 0;
3374}
3375
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003376/* Dynamically allocates a string of the proper length to hold the formatted
3377 * output. NULL is returned on error. The caller is responsible for freeing the
3378 * memory area using free(). The resulting string is returned in <out> if the
3379 * pointer is not NULL. A previous version of <out> might be used to build the
3380 * new string, and it will be freed before returning if it is not NULL, which
3381 * makes it possible to build complex strings from iterative calls without
3382 * having to care about freeing intermediate values, as in the example below :
3383 *
3384 * memprintf(&err, "invalid argument: '%s'", arg);
3385 * ...
3386 * memprintf(&err, "parser said : <%s>\n", *err);
3387 * ...
3388 * free(*err);
3389 *
3390 * This means that <err> must be initialized to NULL before first invocation.
3391 * The return value also holds the allocated string, which eases error checking
3392 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003393 * passed instead and it will be ignored. The returned message will then also
3394 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003395 *
3396 * It is also convenient to use it without any free except the last one :
3397 * err = NULL;
3398 * if (!fct1(err)) report(*err);
3399 * if (!fct2(err)) report(*err);
3400 * if (!fct3(err)) report(*err);
3401 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003402 *
3403 * memprintf relies on memvprintf. This last version can be called from any
3404 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003405 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003406char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003407{
3408 va_list args;
3409 char *ret = NULL;
3410 int allocated = 0;
3411 int needed = 0;
3412
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003413 if (!out)
3414 return NULL;
3415
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003416 do {
3417 /* vsnprintf() will return the required length even when the
3418 * target buffer is NULL. We do this in a loop just in case
3419 * intermediate evaluations get wrong.
3420 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003421 va_copy(args, orig_args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003422 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003423 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003424 if (needed < allocated) {
3425 /* Note: on Solaris 8, the first iteration always
3426 * returns -1 if allocated is zero, so we force a
3427 * retry.
3428 */
3429 if (!allocated)
3430 needed = 0;
3431 else
3432 break;
3433 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003434
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003435 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003436 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003437 } while (ret);
3438
3439 if (needed < 0) {
3440 /* an error was encountered */
3441 free(ret);
3442 ret = NULL;
3443 }
3444
3445 if (out) {
3446 free(*out);
3447 *out = ret;
3448 }
3449
3450 return ret;
3451}
William Lallemand421f5b52012-02-06 18:15:57 +01003452
Christopher Faulet93a518f2017-10-24 11:25:33 +02003453char *memprintf(char **out, const char *format, ...)
3454{
3455 va_list args;
3456 char *ret = NULL;
3457
3458 va_start(args, format);
3459 ret = memvprintf(out, format, args);
3460 va_end(args);
3461
3462 return ret;
3463}
3464
Willy Tarreau21c705b2012-09-14 11:40:36 +02003465/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3466 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003467 * freed by the caller. It also supports being passed a NULL which results in the same
3468 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003469 * Example of use :
3470 * parse(cmd, &err); (callee: memprintf(&err, ...))
3471 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3472 * free(err);
3473 */
3474char *indent_msg(char **out, int level)
3475{
3476 char *ret, *in, *p;
3477 int needed = 0;
3478 int lf = 0;
3479 int lastlf = 0;
3480 int len;
3481
Willy Tarreau70eec382012-10-10 08:56:47 +02003482 if (!out || !*out)
3483 return NULL;
3484
Willy Tarreau21c705b2012-09-14 11:40:36 +02003485 in = *out - 1;
3486 while ((in = strchr(in + 1, '\n')) != NULL) {
3487 lastlf = in - *out;
3488 lf++;
3489 }
3490
3491 if (!lf) /* single line, no LF, return it as-is */
3492 return *out;
3493
3494 len = strlen(*out);
3495
3496 if (lf == 1 && lastlf == len - 1) {
3497 /* single line, LF at end, strip it and return as-is */
3498 (*out)[lastlf] = 0;
3499 return *out;
3500 }
3501
3502 /* OK now we have at least one LF, we need to process the whole string
3503 * as a multi-line string. What we'll do :
3504 * - prefix with an LF if there is none
3505 * - add <level> spaces before each line
3506 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3507 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3508 */
3509
3510 needed = 1 + level * (lf + 1) + len + 1;
3511 p = ret = malloc(needed);
3512 in = *out;
3513
3514 /* skip initial LFs */
3515 while (*in == '\n')
3516 in++;
3517
3518 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3519 while (*in) {
3520 *p++ = '\n';
3521 memset(p, ' ', level);
3522 p += level;
3523 do {
3524 *p++ = *in++;
3525 } while (*in && *in != '\n');
3526 if (*in)
3527 in++;
3528 }
3529 *p = 0;
3530
3531 free(*out);
3532 *out = ret;
3533
3534 return ret;
3535}
3536
Willy Tarreaudad36a32013-03-11 01:20:04 +01003537/* Convert occurrences of environment variables in the input string to their
3538 * corresponding value. A variable is identified as a series of alphanumeric
3539 * characters or underscores following a '$' sign. The <in> string must be
3540 * free()able. NULL returns NULL. The resulting string might be reallocated if
3541 * some expansion is made. Variable names may also be enclosed into braces if
3542 * needed (eg: to concatenate alphanum characters).
3543 */
3544char *env_expand(char *in)
3545{
3546 char *txt_beg;
3547 char *out;
3548 char *txt_end;
3549 char *var_beg;
3550 char *var_end;
3551 char *value;
3552 char *next;
3553 int out_len;
3554 int val_len;
3555
3556 if (!in)
3557 return in;
3558
3559 value = out = NULL;
3560 out_len = 0;
3561
3562 txt_beg = in;
3563 do {
3564 /* look for next '$' sign in <in> */
3565 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3566
3567 if (!*txt_end && !out) /* end and no expansion performed */
3568 return in;
3569
3570 val_len = 0;
3571 next = txt_end;
3572 if (*txt_end == '$') {
3573 char save;
3574
3575 var_beg = txt_end + 1;
3576 if (*var_beg == '{')
3577 var_beg++;
3578
3579 var_end = var_beg;
3580 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3581 var_end++;
3582 }
3583
3584 next = var_end;
3585 if (*var_end == '}' && (var_beg > txt_end + 1))
3586 next++;
3587
3588 /* get value of the variable name at this location */
3589 save = *var_end;
3590 *var_end = '\0';
3591 value = getenv(var_beg);
3592 *var_end = save;
3593 val_len = value ? strlen(value) : 0;
3594 }
3595
Hubert Verstraete831962e2016-06-28 22:44:26 +02003596 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003597 if (txt_end > txt_beg) {
3598 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3599 out_len += txt_end - txt_beg;
3600 }
3601 if (val_len) {
3602 memcpy(out + out_len, value, val_len);
3603 out_len += val_len;
3604 }
3605 out[out_len] = 0;
3606 txt_beg = next;
3607 } while (*txt_beg);
3608
3609 /* here we know that <out> was allocated and that we don't need <in> anymore */
3610 free(in);
3611 return out;
3612}
3613
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003614
3615/* same as strstr() but case-insensitive and with limit length */
3616const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3617{
3618 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003619 unsigned int slen, plen;
3620 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003621
3622 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3623 return NULL;
3624
3625 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3626 return str1;
3627
3628 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3629 return NULL;
3630
3631 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3632 while (toupper(*start) != toupper(*str2)) {
3633 start++;
3634 slen--;
3635 tmp1++;
3636
3637 if (tmp1 >= len_str1)
3638 return NULL;
3639
3640 /* if pattern longer than string */
3641 if (slen < plen)
3642 return NULL;
3643 }
3644
3645 sptr = start;
3646 pptr = (char *)str2;
3647
3648 tmp2 = 0;
3649 while (toupper(*sptr) == toupper(*pptr)) {
3650 sptr++;
3651 pptr++;
3652 tmp2++;
3653
3654 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3655 return start;
3656 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3657 return NULL;
3658 }
3659 }
3660 return NULL;
3661}
3662
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003663/* This function read the next valid utf8 char.
3664 * <s> is the byte srray to be decode, <len> is its length.
3665 * The function returns decoded char encoded like this:
3666 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3667 * are the length read. The decoded character is stored in <c>.
3668 */
3669unsigned char utf8_next(const char *s, int len, unsigned int *c)
3670{
3671 const unsigned char *p = (unsigned char *)s;
3672 int dec;
3673 unsigned char code = UTF8_CODE_OK;
3674
3675 if (len < 1)
3676 return UTF8_CODE_OK;
3677
3678 /* Check the type of UTF8 sequence
3679 *
3680 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3681 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3682 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3683 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3684 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3685 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3686 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3687 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3688 */
3689 switch (*p) {
3690 case 0x00 ... 0x7f:
3691 *c = *p;
3692 return UTF8_CODE_OK | 1;
3693
3694 case 0x80 ... 0xbf:
3695 *c = *p;
3696 return UTF8_CODE_BADSEQ | 1;
3697
3698 case 0xc0 ... 0xdf:
3699 if (len < 2) {
3700 *c = *p;
3701 return UTF8_CODE_BADSEQ | 1;
3702 }
3703 *c = *p & 0x1f;
3704 dec = 1;
3705 break;
3706
3707 case 0xe0 ... 0xef:
3708 if (len < 3) {
3709 *c = *p;
3710 return UTF8_CODE_BADSEQ | 1;
3711 }
3712 *c = *p & 0x0f;
3713 dec = 2;
3714 break;
3715
3716 case 0xf0 ... 0xf7:
3717 if (len < 4) {
3718 *c = *p;
3719 return UTF8_CODE_BADSEQ | 1;
3720 }
3721 *c = *p & 0x07;
3722 dec = 3;
3723 break;
3724
3725 case 0xf8 ... 0xfb:
3726 if (len < 5) {
3727 *c = *p;
3728 return UTF8_CODE_BADSEQ | 1;
3729 }
3730 *c = *p & 0x03;
3731 dec = 4;
3732 break;
3733
3734 case 0xfc ... 0xfd:
3735 if (len < 6) {
3736 *c = *p;
3737 return UTF8_CODE_BADSEQ | 1;
3738 }
3739 *c = *p & 0x01;
3740 dec = 5;
3741 break;
3742
3743 case 0xfe ... 0xff:
3744 default:
3745 *c = *p;
3746 return UTF8_CODE_BADSEQ | 1;
3747 }
3748
3749 p++;
3750
3751 while (dec > 0) {
3752
3753 /* need 0x10 for the 2 first bits */
3754 if ( ( *p & 0xc0 ) != 0x80 )
3755 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3756
3757 /* add data at char */
3758 *c = ( *c << 6 ) | ( *p & 0x3f );
3759
3760 dec--;
3761 p++;
3762 }
3763
3764 /* Check ovelong encoding.
3765 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3766 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3767 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3768 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003769 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003770 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3771 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3772 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3773 code |= UTF8_CODE_OVERLONG;
3774
3775 /* Check invalid UTF8 range. */
3776 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3777 (*c >= 0xfffe && *c <= 0xffff))
3778 code |= UTF8_CODE_INVRANGE;
3779
3780 return code | ((p-(unsigned char *)s)&0x0f);
3781}
3782
Maxime de Roucydc887852016-05-13 23:52:54 +02003783/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3784 * On failure : return 0 and <err> filled with an error message.
3785 * The caller is responsible for freeing the <err> and <str> copy
3786 * memory area using free()
3787 */
3788int list_append_word(struct list *li, const char *str, char **err)
3789{
3790 struct wordlist *wl;
3791
3792 wl = calloc(1, sizeof(*wl));
3793 if (!wl) {
3794 memprintf(err, "out of memory");
3795 goto fail_wl;
3796 }
3797
3798 wl->s = strdup(str);
3799 if (!wl->s) {
3800 memprintf(err, "out of memory");
3801 goto fail_wl_s;
3802 }
3803
3804 LIST_ADDQ(li, &wl->list);
3805
3806 return 1;
3807
3808fail_wl_s:
3809 free(wl->s);
3810fail_wl:
3811 free(wl);
3812 return 0;
3813}
3814
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003815/* print a string of text buffer to <out>. The format is :
3816 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3817 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3818 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3819 */
3820int dump_text(struct chunk *out, const char *buf, int bsize)
3821{
3822 unsigned char c;
3823 int ptr = 0;
3824
3825 while (buf[ptr] && ptr < bsize) {
3826 c = buf[ptr];
3827 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
3828 if (out->len > out->size - 1)
3829 break;
3830 out->str[out->len++] = c;
3831 }
3832 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
3833 if (out->len > out->size - 2)
3834 break;
3835 out->str[out->len++] = '\\';
3836 switch (c) {
3837 case ' ': c = ' '; break;
3838 case '\t': c = 't'; break;
3839 case '\n': c = 'n'; break;
3840 case '\r': c = 'r'; break;
3841 case '\e': c = 'e'; break;
3842 case '\\': c = '\\'; break;
3843 case '=': c = '='; break;
3844 }
3845 out->str[out->len++] = c;
3846 }
3847 else {
3848 if (out->len > out->size - 4)
3849 break;
3850 out->str[out->len++] = '\\';
3851 out->str[out->len++] = 'x';
3852 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3853 out->str[out->len++] = hextab[c & 0xF];
3854 }
3855 ptr++;
3856 }
3857
3858 return ptr;
3859}
3860
3861/* print a buffer in hexa.
3862 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3863 */
3864int dump_binary(struct chunk *out, const char *buf, int bsize)
3865{
3866 unsigned char c;
3867 int ptr = 0;
3868
3869 while (ptr < bsize) {
3870 c = buf[ptr];
3871
3872 if (out->len > out->size - 2)
3873 break;
3874 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3875 out->str[out->len++] = hextab[c & 0xF];
3876
3877 ptr++;
3878 }
3879 return ptr;
3880}
3881
3882/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3883 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3884 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3885 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3886 * lines are respected within the limit of 70 output chars. Lines that are
3887 * continuation of a previous truncated line begin with "+" instead of " "
3888 * after the offset. The new pointer is returned.
3889 */
3890int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3891 int *line, int ptr)
3892{
3893 int end;
3894 unsigned char c;
3895
3896 end = out->len + 80;
3897 if (end > out->size)
3898 return ptr;
3899
3900 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3901
3902 while (ptr < len && ptr < bsize) {
3903 c = buf[ptr];
3904 if (isprint(c) && isascii(c) && c != '\\') {
3905 if (out->len > end - 2)
3906 break;
3907 out->str[out->len++] = c;
3908 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3909 if (out->len > end - 3)
3910 break;
3911 out->str[out->len++] = '\\';
3912 switch (c) {
3913 case '\t': c = 't'; break;
3914 case '\n': c = 'n'; break;
3915 case '\r': c = 'r'; break;
3916 case '\e': c = 'e'; break;
3917 case '\\': c = '\\'; break;
3918 }
3919 out->str[out->len++] = c;
3920 } else {
3921 if (out->len > end - 5)
3922 break;
3923 out->str[out->len++] = '\\';
3924 out->str[out->len++] = 'x';
3925 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3926 out->str[out->len++] = hextab[c & 0xF];
3927 }
3928 if (buf[ptr++] == '\n') {
3929 /* we had a line break, let's return now */
3930 out->str[out->len++] = '\n';
3931 *line = ptr;
3932 return ptr;
3933 }
3934 }
3935 /* we have an incomplete line, we return it as-is */
3936 out->str[out->len++] = '\n';
3937 return ptr;
3938}
3939
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003940/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02003941 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
3942 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003943 */
Willy Tarreaued936c52017-04-27 18:03:20 +02003944void debug_hexdump(FILE *out, const char *pfx, const char *buf,
3945 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003946{
Willy Tarreau73459792017-04-11 07:58:08 +02003947 unsigned int i;
3948 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003949
3950 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3951 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02003952 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003953 for (j = 0; j < 8; j++) {
3954 if (b + j >= 0 && b + j < len)
3955 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3956 else
3957 fprintf(out, " ");
3958 }
3959
3960 if (b + j >= 0 && b + j < len)
3961 fputc('-', out);
3962 else
3963 fputc(' ', out);
3964
3965 for (j = 8; j < 16; j++) {
3966 if (b + j >= 0 && b + j < len)
3967 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3968 else
3969 fprintf(out, " ");
3970 }
3971
3972 fprintf(out, " ");
3973 for (j = 0; j < 16; j++) {
3974 if (b + j >= 0 && b + j < len) {
3975 if (isprint((unsigned char)buf[b + j]))
3976 fputc((unsigned char)buf[b + j], out);
3977 else
3978 fputc('.', out);
3979 }
3980 else
3981 fputc(' ', out);
3982 }
3983 fputc('\n', out);
3984 }
3985}
3986
Willy Tarreau12963822017-10-24 10:54:08 +02003987/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
3988__attribute__((weak,format(printf, 1, 2)))
3989void trace(char *msg, ...)
3990{
3991}
3992
Willy Tarreaubaaee002006-06-26 02:48:02 +02003993/*
3994 * Local variables:
3995 * c-indent-level: 8
3996 * c-basic-offset: 8
3997 * End:
3998 */