blob: acd136c27c384c256fde7dc7d15a2607d4cd1b56 [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;
1025 if (len)
1026 mask->s_addr = htonl(~0UL << (32 - len));
1027 else
1028 mask->s_addr = 0;
1029 }
1030 return 1;
1031}
1032
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001033/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1034 * succeeds otherwise zero.
1035 */
1036int cidr2dotted(int cidr, struct in_addr *mask) {
1037
1038 if (cidr < 0 || cidr > 32)
1039 return 0;
1040
1041 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1042 return 1;
1043}
1044
Thierry Fournier70473a52016-02-17 17:12:14 +01001045/* Convert mask from bit length form to in_addr form.
1046 * This function never fails.
1047 */
1048void len2mask4(int len, struct in_addr *addr)
1049{
1050 if (len >= 32) {
1051 addr->s_addr = 0xffffffff;
1052 return;
1053 }
1054 if (len <= 0) {
1055 addr->s_addr = 0x00000000;
1056 return;
1057 }
1058 addr->s_addr = 0xffffffff << (32 - len);
1059 addr->s_addr = htonl(addr->s_addr);
1060}
1061
1062/* Convert mask from bit length form to in6_addr form.
1063 * This function never fails.
1064 */
1065void len2mask6(int len, struct in6_addr *addr)
1066{
1067 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1068 len -= 32;
1069 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1070 len -= 32;
1071 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1072 len -= 32;
1073 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1074}
1075
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001076/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001077 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001078 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1079 * is optionnal and either in the dotted or CIDR notation.
1080 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1081 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001082int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001083{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001084 __label__ out_free, out_err;
1085 char *c, *s;
1086 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001087
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001088 s = strdup(str);
1089 if (!s)
1090 return 0;
1091
Willy Tarreaubaaee002006-06-26 02:48:02 +02001092 memset(mask, 0, sizeof(*mask));
1093 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001094
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001095 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001096 *c++ = '\0';
1097 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001098 if (!str2mask(c, mask))
1099 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001100 }
1101 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001102 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001103 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001104 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001105 struct hostent *he;
1106
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001107 if (!resolve)
1108 goto out_err;
1109
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001110 if ((he = gethostbyname(s)) == NULL) {
1111 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001112 }
1113 else
1114 *addr = *(struct in_addr *) *(he->h_addr_list);
1115 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001116
1117 ret_val = 1;
1118 out_free:
1119 free(s);
1120 return ret_val;
1121 out_err:
1122 ret_val = 0;
1123 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001124}
1125
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001126
1127/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001128 * converts <str> to two struct in6_addr* which must be pre-allocated.
1129 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1130 * is an optionnal number of bits (128 being the default).
1131 * Returns 1 if OK, 0 if error.
1132 */
1133int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1134{
1135 char *c, *s;
1136 int ret_val = 0;
1137 char *err;
1138 unsigned long len = 128;
1139
1140 s = strdup(str);
1141 if (!s)
1142 return 0;
1143
1144 memset(mask, 0, sizeof(*mask));
1145 memset(addr, 0, sizeof(*addr));
1146
1147 if ((c = strrchr(s, '/')) != NULL) {
1148 *c++ = '\0'; /* c points to the mask */
1149 if (!*c)
1150 goto out_free;
1151
1152 len = strtoul(c, &err, 10);
1153 if ((err && *err) || (unsigned)len > 128)
1154 goto out_free;
1155 }
1156 *mask = len; /* OK we have a valid mask in <len> */
1157
1158 if (!inet_pton(AF_INET6, s, addr))
1159 goto out_free;
1160
1161 ret_val = 1;
1162 out_free:
1163 free(s);
1164 return ret_val;
1165}
1166
1167
1168/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001169 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001170 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001171int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001172{
1173 int saw_digit, octets, ch;
1174 u_char tmp[4], *tp;
1175 const char *cp = addr;
1176
1177 saw_digit = 0;
1178 octets = 0;
1179 *(tp = tmp) = 0;
1180
1181 while (*addr) {
1182 unsigned char digit = (ch = *addr++) - '0';
1183 if (digit > 9 && ch != '.')
1184 break;
1185 if (digit <= 9) {
1186 u_int new = *tp * 10 + digit;
1187 if (new > 255)
1188 return 0;
1189 *tp = new;
1190 if (!saw_digit) {
1191 if (++octets > 4)
1192 return 0;
1193 saw_digit = 1;
1194 }
1195 } else if (ch == '.' && saw_digit) {
1196 if (octets == 4)
1197 return 0;
1198 *++tp = 0;
1199 saw_digit = 0;
1200 } else
1201 return 0;
1202 }
1203
1204 if (octets < 4)
1205 return 0;
1206
1207 memcpy(&dst->s_addr, tmp, 4);
1208 return addr-cp-1;
1209}
1210
1211/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001212 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1213 * <out> contain the code of the dectected scheme, the start and length of
1214 * the hostname. Actually only http and https are supported. <out> can be NULL.
1215 * This function returns the consumed length. It is useful if you parse complete
1216 * url like http://host:port/path, because the consumed length corresponds to
1217 * the first character of the path. If the conversion fails, it returns -1.
1218 *
1219 * This function tries to resolve the DNS name if haproxy is in starting mode.
1220 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001221 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001222int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001223{
1224 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001225 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001226 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001227 unsigned long long int http_code = 0;
1228 int default_port;
1229 struct hostent *he;
1230 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001231
1232 /* Firstly, try to find :// pattern */
1233 while (curr < url+ulen && url_code != 0x3a2f2f) {
1234 url_code = ((url_code & 0xffff) << 8);
1235 url_code += (unsigned char)*curr++;
1236 }
1237
1238 /* Secondly, if :// pattern is found, verify parsed stuff
1239 * before pattern is matching our http pattern.
1240 * If so parse ip address and port in uri.
1241 *
1242 * WARNING: Current code doesn't support dynamic async dns resolver.
1243 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001244 if (url_code != 0x3a2f2f)
1245 return -1;
1246
1247 /* Copy scheme, and utrn to lower case. */
1248 while (cp < curr - 3)
1249 http_code = (http_code << 8) + *cp++;
1250 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001251
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001252 /* HTTP or HTTPS url matching */
1253 if (http_code == 0x2020202068747470ULL) {
1254 default_port = 80;
1255 if (out)
1256 out->scheme = SCH_HTTP;
1257 }
1258 else if (http_code == 0x2020206874747073ULL) {
1259 default_port = 443;
1260 if (out)
1261 out->scheme = SCH_HTTPS;
1262 }
1263 else
1264 return -1;
1265
1266 /* If the next char is '[', the host address is IPv6. */
1267 if (*curr == '[') {
1268 curr++;
1269
1270 /* Check trash size */
1271 if (trash.size < ulen)
1272 return -1;
1273
1274 /* Look for ']' and copy the address in a trash buffer. */
1275 p = trash.str;
1276 for (end = curr;
1277 end < url + ulen && *end != ']';
1278 end++, p++)
1279 *p = *end;
1280 if (*end != ']')
1281 return -1;
1282 *p = '\0';
1283
1284 /* Update out. */
1285 if (out) {
1286 out->host = curr;
1287 out->host_len = end - curr;
1288 }
1289
1290 /* Try IPv6 decoding. */
1291 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1292 return -1;
1293 end++;
1294
1295 /* Decode port. */
1296 if (*end == ':') {
1297 end++;
1298 default_port = read_uint(&end, url + ulen);
1299 }
1300 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1301 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1302 return end - url;
1303 }
1304 else {
1305 /* We are looking for IP address. If you want to parse and
1306 * resolve hostname found in url, you can use str2sa_range(), but
1307 * be warned this can slow down global daemon performances
1308 * while handling lagging dns responses.
1309 */
1310 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1311 if (ret) {
1312 /* Update out. */
1313 if (out) {
1314 out->host = curr;
1315 out->host_len = ret;
1316 }
1317
1318 curr += ret;
1319
1320 /* Decode port. */
1321 if (*curr == ':') {
1322 curr++;
1323 default_port = read_uint(&curr, url + ulen);
1324 }
1325 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1326
1327 /* Set family. */
1328 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1329 return curr - url;
1330 }
1331 else if (global.mode & MODE_STARTING) {
1332 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1333 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001334 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001335
1336 /* look for : or / or end */
1337 for (end = curr;
1338 end < url + ulen && *end != '/' && *end != ':';
1339 end++);
1340 memcpy(trash.str, curr, end - curr);
1341 trash.str[end - curr] = '\0';
1342
1343 /* try to resolve an IPv4/IPv6 hostname */
1344 he = gethostbyname(trash.str);
1345 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001346 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001347
1348 /* Update out. */
1349 if (out) {
1350 out->host = curr;
1351 out->host_len = end - curr;
1352 }
1353
1354 /* Decode port. */
1355 if (*end == ':') {
1356 end++;
1357 default_port = read_uint(&end, url + ulen);
1358 }
1359
1360 /* Copy IP address, set port and family. */
1361 switch (he->h_addrtype) {
1362 case AF_INET:
1363 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1364 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1365 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1366 return end - url;
1367
1368 case AF_INET6:
1369 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1370 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1371 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1372 return end - url;
1373 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001374 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001375 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001376 return -1;
1377}
1378
Willy Tarreau631f01c2011-09-05 00:36:48 +02001379/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1380 * address family is returned so that it's easy for the caller to adapt to the
1381 * output format. Zero is returned if the address family is not supported. -1
1382 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1383 * supported.
1384 */
1385int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1386{
1387
1388 void *ptr;
1389
1390 if (size < 5)
1391 return 0;
1392 *str = '\0';
1393
1394 switch (addr->ss_family) {
1395 case AF_INET:
1396 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1397 break;
1398 case AF_INET6:
1399 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1400 break;
1401 case AF_UNIX:
1402 memcpy(str, "unix", 5);
1403 return addr->ss_family;
1404 default:
1405 return 0;
1406 }
1407
1408 if (inet_ntop(addr->ss_family, ptr, str, size))
1409 return addr->ss_family;
1410
1411 /* failed */
1412 return -1;
1413}
1414
Simon Horman75ab8bd2014-06-16 09:39:41 +09001415/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1416 * address family is returned so that it's easy for the caller to adapt to the
1417 * output format. Zero is returned if the address family is not supported. -1
1418 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1419 * supported.
1420 */
1421int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1422{
1423
1424 uint16_t port;
1425
1426
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001427 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001428 return 0;
1429 *str = '\0';
1430
1431 switch (addr->ss_family) {
1432 case AF_INET:
1433 port = ((struct sockaddr_in *)addr)->sin_port;
1434 break;
1435 case AF_INET6:
1436 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1437 break;
1438 case AF_UNIX:
1439 memcpy(str, "unix", 5);
1440 return addr->ss_family;
1441 default:
1442 return 0;
1443 }
1444
1445 snprintf(str, size, "%u", ntohs(port));
1446 return addr->ss_family;
1447}
1448
Willy Tarreau16e01562016-08-09 16:46:18 +02001449/* check if the given address is local to the system or not. It will return
1450 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1451 * it is. We don't want to iterate over all interfaces for this (and it is not
1452 * portable). So instead we try to bind in UDP to this address on a free non
1453 * privileged port and to connect to the same address, port 0 (connect doesn't
1454 * care). If it succeeds, we own the address. Note that non-inet addresses are
1455 * considered local since they're most likely AF_UNIX.
1456 */
1457int addr_is_local(const struct netns_entry *ns,
1458 const struct sockaddr_storage *orig)
1459{
1460 struct sockaddr_storage addr;
1461 int result;
1462 int fd;
1463
1464 if (!is_inet_addr(orig))
1465 return 1;
1466
1467 memcpy(&addr, orig, sizeof(addr));
1468 set_host_port(&addr, 0);
1469
1470 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1471 if (fd < 0)
1472 return -1;
1473
1474 result = -1;
1475 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1476 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1477 result = 0; // fail, non-local address
1478 else
1479 result = 1; // success, local address
1480 }
1481 else {
1482 if (errno == EADDRNOTAVAIL)
1483 result = 0; // definitely not local :-)
1484 }
1485 close(fd);
1486
1487 return result;
1488}
1489
Willy Tarreaubaaee002006-06-26 02:48:02 +02001490/* will try to encode the string <string> replacing all characters tagged in
1491 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1492 * prefixed by <escape>, and will store the result between <start> (included)
1493 * and <stop> (excluded), and will always terminate the string with a '\0'
1494 * before <stop>. The position of the '\0' is returned if the conversion
1495 * completes. If bytes are missing between <start> and <stop>, then the
1496 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1497 * cannot even be stored so we return <start> without writing the 0.
1498 * The input string must also be zero-terminated.
1499 */
1500const char hextab[16] = "0123456789ABCDEF";
1501char *encode_string(char *start, char *stop,
1502 const char escape, const fd_set *map,
1503 const char *string)
1504{
1505 if (start < stop) {
1506 stop--; /* reserve one byte for the final '\0' */
1507 while (start < stop && *string != '\0') {
1508 if (!FD_ISSET((unsigned char)(*string), map))
1509 *start++ = *string;
1510 else {
1511 if (start + 3 >= stop)
1512 break;
1513 *start++ = escape;
1514 *start++ = hextab[(*string >> 4) & 15];
1515 *start++ = hextab[*string & 15];
1516 }
1517 string++;
1518 }
1519 *start = '\0';
1520 }
1521 return start;
1522}
1523
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001524/*
1525 * Same behavior as encode_string() above, except that it encodes chunk
1526 * <chunk> instead of a string.
1527 */
1528char *encode_chunk(char *start, char *stop,
1529 const char escape, const fd_set *map,
1530 const struct chunk *chunk)
1531{
1532 char *str = chunk->str;
1533 char *end = chunk->str + chunk->len;
1534
1535 if (start < stop) {
1536 stop--; /* reserve one byte for the final '\0' */
1537 while (start < stop && str < end) {
1538 if (!FD_ISSET((unsigned char)(*str), map))
1539 *start++ = *str;
1540 else {
1541 if (start + 3 >= stop)
1542 break;
1543 *start++ = escape;
1544 *start++ = hextab[(*str >> 4) & 15];
1545 *start++ = hextab[*str & 15];
1546 }
1547 str++;
1548 }
1549 *start = '\0';
1550 }
1551 return start;
1552}
1553
Dragan Dosen0edd1092016-02-12 13:23:02 +01001554/*
1555 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001556 * character. The input <string> must be zero-terminated. The result will
1557 * be stored between <start> (included) and <stop> (excluded). This
1558 * function will always try to terminate the resulting string with a '\0'
1559 * before <stop>, and will return its position if the conversion
1560 * completes.
1561 */
1562char *escape_string(char *start, char *stop,
1563 const char escape, const fd_set *map,
1564 const char *string)
1565{
1566 if (start < stop) {
1567 stop--; /* reserve one byte for the final '\0' */
1568 while (start < stop && *string != '\0') {
1569 if (!FD_ISSET((unsigned char)(*string), map))
1570 *start++ = *string;
1571 else {
1572 if (start + 2 >= stop)
1573 break;
1574 *start++ = escape;
1575 *start++ = *string;
1576 }
1577 string++;
1578 }
1579 *start = '\0';
1580 }
1581 return start;
1582}
1583
1584/*
1585 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001586 * character. <chunk> contains the input to be escaped. The result will be
1587 * stored between <start> (included) and <stop> (excluded). The function
1588 * will always try to terminate the resulting string with a '\0' before
1589 * <stop>, and will return its position if the conversion completes.
1590 */
1591char *escape_chunk(char *start, char *stop,
1592 const char escape, const fd_set *map,
1593 const struct chunk *chunk)
1594{
1595 char *str = chunk->str;
1596 char *end = chunk->str + chunk->len;
1597
1598 if (start < stop) {
1599 stop--; /* reserve one byte for the final '\0' */
1600 while (start < stop && str < end) {
1601 if (!FD_ISSET((unsigned char)(*str), map))
1602 *start++ = *str;
1603 else {
1604 if (start + 2 >= stop)
1605 break;
1606 *start++ = escape;
1607 *start++ = *str;
1608 }
1609 str++;
1610 }
1611 *start = '\0';
1612 }
1613 return start;
1614}
1615
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001616/* Check a string for using it in a CSV output format. If the string contains
1617 * one of the following four char <">, <,>, CR or LF, the string is
1618 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1619 * <str> is the input string to be escaped. The function assumes that
1620 * the input string is null-terminated.
1621 *
1622 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001623 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001624 * format.
1625 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001626 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001627 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001628 * If <quote> is 1, the converter puts the quotes only if any reserved character
1629 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001630 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001631 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001632 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001633 * The function returns the converted string on its output. If an error
1634 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001635 * for using the function directly as printf() argument.
1636 *
1637 * If the output buffer is too short to contain the input string, the result
1638 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001639 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001640 * This function appends the encoding to the existing output chunk, and it
1641 * guarantees that it starts immediately at the first available character of
1642 * the chunk. Please use csv_enc() instead if you want to replace the output
1643 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001644 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001645const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001646{
1647 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001648 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001649 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001650
Willy Tarreaub631c292016-01-08 10:04:08 +01001651 if (quote == 1) {
1652 /* automatic quoting: first verify if we'll have to quote the string */
1653 if (!strpbrk(str, "\n\r,\""))
1654 quote = 0;
1655 }
1656
1657 if (quote)
1658 *ptr++ = '"';
1659
Willy Tarreau898529b2016-01-06 18:07:04 +01001660 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1661 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001662 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001663 ptr++;
1664 if (ptr >= end - 2) {
1665 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001666 break;
1667 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001668 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001669 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001670 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001671 str++;
1672 }
1673
Willy Tarreaub631c292016-01-08 10:04:08 +01001674 if (quote)
1675 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001676
Willy Tarreau898529b2016-01-06 18:07:04 +01001677 *ptr = '\0';
1678 output->len = ptr - output->str;
1679 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001680}
1681
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001682/* Decode an URL-encoded string in-place. The resulting string might
1683 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001684 * aborted, the string is truncated before the issue and a negative value is
1685 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001686 */
1687int url_decode(char *string)
1688{
1689 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001690 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001691
1692 in = string;
1693 out = string;
1694 while (*in) {
1695 switch (*in) {
1696 case '+' :
1697 *out++ = ' ';
1698 break;
1699 case '%' :
1700 if (!ishex(in[1]) || !ishex(in[2]))
1701 goto end;
1702 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1703 in += 2;
1704 break;
1705 default:
1706 *out++ = *in;
1707 break;
1708 }
1709 in++;
1710 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001711 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001712 end:
1713 *out = 0;
1714 return ret;
1715}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001716
Willy Tarreau6911fa42007-03-04 18:06:08 +01001717unsigned int str2ui(const char *s)
1718{
1719 return __str2ui(s);
1720}
1721
1722unsigned int str2uic(const char *s)
1723{
1724 return __str2uic(s);
1725}
1726
1727unsigned int strl2ui(const char *s, int len)
1728{
1729 return __strl2ui(s, len);
1730}
1731
1732unsigned int strl2uic(const char *s, int len)
1733{
1734 return __strl2uic(s, len);
1735}
1736
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001737unsigned int read_uint(const char **s, const char *end)
1738{
1739 return __read_uint(s, end);
1740}
1741
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001742/* This function reads an unsigned integer from the string pointed to by <s> and
1743 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1744 * function automatically stops at <end>. If the number overflows, the 2^64-1
1745 * value is returned.
1746 */
1747unsigned long long int read_uint64(const char **s, const char *end)
1748{
1749 const char *ptr = *s;
1750 unsigned long long int i = 0, tmp;
1751 unsigned int j;
1752
1753 while (ptr < end) {
1754
1755 /* read next char */
1756 j = *ptr - '0';
1757 if (j > 9)
1758 goto read_uint64_end;
1759
1760 /* add char to the number and check overflow. */
1761 tmp = i * 10;
1762 if (tmp / 10 != i) {
1763 i = ULLONG_MAX;
1764 goto read_uint64_eat;
1765 }
1766 if (ULLONG_MAX - tmp < j) {
1767 i = ULLONG_MAX;
1768 goto read_uint64_eat;
1769 }
1770 i = tmp + j;
1771 ptr++;
1772 }
1773read_uint64_eat:
1774 /* eat each numeric char */
1775 while (ptr < end) {
1776 if ((unsigned int)(*ptr - '0') > 9)
1777 break;
1778 ptr++;
1779 }
1780read_uint64_end:
1781 *s = ptr;
1782 return i;
1783}
1784
1785/* This function reads an integer from the string pointed to by <s> and returns
1786 * it. The <s> pointer is adjusted to point to the first unread char. The function
1787 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1788 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1789 * returned.
1790 */
1791long long int read_int64(const char **s, const char *end)
1792{
1793 unsigned long long int i = 0;
1794 int neg = 0;
1795
1796 /* Look for minus char. */
1797 if (**s == '-') {
1798 neg = 1;
1799 (*s)++;
1800 }
1801 else if (**s == '+')
1802 (*s)++;
1803
1804 /* convert as positive number. */
1805 i = read_uint64(s, end);
1806
1807 if (neg) {
1808 if (i > 0x8000000000000000ULL)
1809 return LLONG_MIN;
1810 return -i;
1811 }
1812 if (i > 0x7fffffffffffffffULL)
1813 return LLONG_MAX;
1814 return i;
1815}
1816
Willy Tarreau6911fa42007-03-04 18:06:08 +01001817/* This one is 7 times faster than strtol() on athlon with checks.
1818 * It returns the value of the number composed of all valid digits read,
1819 * and can process negative numbers too.
1820 */
1821int strl2ic(const char *s, int len)
1822{
1823 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001824 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001825
1826 if (len > 0) {
1827 if (*s != '-') {
1828 /* positive number */
1829 while (len-- > 0) {
1830 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001831 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001832 if (j > 9)
1833 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001834 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001835 }
1836 } else {
1837 /* negative number */
1838 s++;
1839 while (--len > 0) {
1840 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001841 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001842 if (j > 9)
1843 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001844 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001845 }
1846 }
1847 }
1848 return i;
1849}
1850
1851
1852/* This function reads exactly <len> chars from <s> and converts them to a
1853 * signed integer which it stores into <ret>. It accurately detects any error
1854 * (truncated string, invalid chars, overflows). It is meant to be used in
1855 * applications designed for hostile environments. It returns zero when the
1856 * number has successfully been converted, non-zero otherwise. When an error
1857 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1858 * faster than strtol().
1859 */
1860int strl2irc(const char *s, int len, int *ret)
1861{
1862 int i = 0;
1863 int j;
1864
1865 if (!len)
1866 return 1;
1867
1868 if (*s != '-') {
1869 /* positive number */
1870 while (len-- > 0) {
1871 j = (*s++) - '0';
1872 if (j > 9) return 1; /* invalid char */
1873 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1874 i = i * 10;
1875 if (i + j < i) return 1; /* check for addition overflow */
1876 i = i + j;
1877 }
1878 } else {
1879 /* negative number */
1880 s++;
1881 while (--len > 0) {
1882 j = (*s++) - '0';
1883 if (j > 9) return 1; /* invalid char */
1884 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1885 i = i * 10;
1886 if (i - j > i) return 1; /* check for subtract overflow */
1887 i = i - j;
1888 }
1889 }
1890 *ret = i;
1891 return 0;
1892}
1893
1894
1895/* This function reads exactly <len> chars from <s> and converts them to a
1896 * signed integer which it stores into <ret>. It accurately detects any error
1897 * (truncated string, invalid chars, overflows). It is meant to be used in
1898 * applications designed for hostile environments. It returns zero when the
1899 * number has successfully been converted, non-zero otherwise. When an error
1900 * is returned, the <ret> value is left untouched. It is about 3 times slower
1901 * than str2irc().
1902 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001903
1904int strl2llrc(const char *s, int len, long long *ret)
1905{
1906 long long i = 0;
1907 int j;
1908
1909 if (!len)
1910 return 1;
1911
1912 if (*s != '-') {
1913 /* positive number */
1914 while (len-- > 0) {
1915 j = (*s++) - '0';
1916 if (j > 9) return 1; /* invalid char */
1917 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1918 i = i * 10LL;
1919 if (i + j < i) return 1; /* check for addition overflow */
1920 i = i + j;
1921 }
1922 } else {
1923 /* negative number */
1924 s++;
1925 while (--len > 0) {
1926 j = (*s++) - '0';
1927 if (j > 9) return 1; /* invalid char */
1928 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1929 i = i * 10LL;
1930 if (i - j > i) return 1; /* check for subtract overflow */
1931 i = i - j;
1932 }
1933 }
1934 *ret = i;
1935 return 0;
1936}
1937
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001938/* This function is used with pat_parse_dotted_ver(). It converts a string
1939 * composed by two number separated by a dot. Each part must contain in 16 bits
1940 * because internally they will be represented as a 32-bit quantity stored in
1941 * a 64-bit integer. It returns zero when the number has successfully been
1942 * converted, non-zero otherwise. When an error is returned, the <ret> value
1943 * is left untouched.
1944 *
1945 * "1.3" -> 0x0000000000010003
1946 * "65535.65535" -> 0x00000000ffffffff
1947 */
1948int strl2llrc_dotted(const char *text, int len, long long *ret)
1949{
1950 const char *end = &text[len];
1951 const char *p;
1952 long long major, minor;
1953
1954 /* Look for dot. */
1955 for (p = text; p < end; p++)
1956 if (*p == '.')
1957 break;
1958
1959 /* Convert major. */
1960 if (strl2llrc(text, p - text, &major) != 0)
1961 return 1;
1962
1963 /* Check major. */
1964 if (major >= 65536)
1965 return 1;
1966
1967 /* Convert minor. */
1968 minor = 0;
1969 if (p < end)
1970 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1971 return 1;
1972
1973 /* Check minor. */
1974 if (minor >= 65536)
1975 return 1;
1976
1977 /* Compose value. */
1978 *ret = (major << 16) | (minor & 0xffff);
1979 return 0;
1980}
1981
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001982/* This function parses a time value optionally followed by a unit suffix among
1983 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1984 * expected by the caller. The computation does its best to avoid overflows.
1985 * The value is returned in <ret> if everything is fine, and a NULL is returned
1986 * by the function. In case of error, a pointer to the error is returned and
1987 * <ret> is left untouched. Values are automatically rounded up when needed.
1988 */
1989const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1990{
1991 unsigned imult, idiv;
1992 unsigned omult, odiv;
1993 unsigned value;
1994
1995 omult = odiv = 1;
1996
1997 switch (unit_flags & TIME_UNIT_MASK) {
1998 case TIME_UNIT_US: omult = 1000000; break;
1999 case TIME_UNIT_MS: omult = 1000; break;
2000 case TIME_UNIT_S: break;
2001 case TIME_UNIT_MIN: odiv = 60; break;
2002 case TIME_UNIT_HOUR: odiv = 3600; break;
2003 case TIME_UNIT_DAY: odiv = 86400; break;
2004 default: break;
2005 }
2006
2007 value = 0;
2008
2009 while (1) {
2010 unsigned int j;
2011
2012 j = *text - '0';
2013 if (j > 9)
2014 break;
2015 text++;
2016 value *= 10;
2017 value += j;
2018 }
2019
2020 imult = idiv = 1;
2021 switch (*text) {
2022 case '\0': /* no unit = default unit */
2023 imult = omult = idiv = odiv = 1;
2024 break;
2025 case 's': /* second = unscaled unit */
2026 break;
2027 case 'u': /* microsecond : "us" */
2028 if (text[1] == 's') {
2029 idiv = 1000000;
2030 text++;
2031 }
2032 break;
2033 case 'm': /* millisecond : "ms" or minute: "m" */
2034 if (text[1] == 's') {
2035 idiv = 1000;
2036 text++;
2037 } else
2038 imult = 60;
2039 break;
2040 case 'h': /* hour : "h" */
2041 imult = 3600;
2042 break;
2043 case 'd': /* day : "d" */
2044 imult = 86400;
2045 break;
2046 default:
2047 return text;
2048 break;
2049 }
2050
2051 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2052 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2053 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2054 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2055
2056 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2057 *ret = value;
2058 return NULL;
2059}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002060
Emeric Brun39132b22010-01-04 14:57:24 +01002061/* this function converts the string starting at <text> to an unsigned int
2062 * stored in <ret>. If an error is detected, the pointer to the unexpected
2063 * character is returned. If the conversio is succesful, NULL is returned.
2064 */
2065const char *parse_size_err(const char *text, unsigned *ret) {
2066 unsigned value = 0;
2067
2068 while (1) {
2069 unsigned int j;
2070
2071 j = *text - '0';
2072 if (j > 9)
2073 break;
2074 if (value > ~0U / 10)
2075 return text;
2076 value *= 10;
2077 if (value > (value + j))
2078 return text;
2079 value += j;
2080 text++;
2081 }
2082
2083 switch (*text) {
2084 case '\0':
2085 break;
2086 case 'K':
2087 case 'k':
2088 if (value > ~0U >> 10)
2089 return text;
2090 value = value << 10;
2091 break;
2092 case 'M':
2093 case 'm':
2094 if (value > ~0U >> 20)
2095 return text;
2096 value = value << 20;
2097 break;
2098 case 'G':
2099 case 'g':
2100 if (value > ~0U >> 30)
2101 return text;
2102 value = value << 30;
2103 break;
2104 default:
2105 return text;
2106 }
2107
Godbach58048a22015-01-28 17:36:16 +08002108 if (*text != '\0' && *++text != '\0')
2109 return text;
2110
Emeric Brun39132b22010-01-04 14:57:24 +01002111 *ret = value;
2112 return NULL;
2113}
2114
Willy Tarreau126d4062013-12-03 17:50:47 +01002115/*
2116 * Parse binary string written in hexadecimal (source) and store the decoded
2117 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2118 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002119 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002120 */
2121int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2122{
2123 int len;
2124 const char *p = source;
2125 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002126 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002127
2128 len = strlen(source);
2129 if (len % 2) {
2130 memprintf(err, "an even number of hex digit is expected");
2131 return 0;
2132 }
2133
2134 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002135
Willy Tarreau126d4062013-12-03 17:50:47 +01002136 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002137 *binstr = calloc(len, sizeof(char));
2138 if (!*binstr) {
2139 memprintf(err, "out of memory while loading string pattern");
2140 return 0;
2141 }
2142 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002143 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002144 else {
2145 if (*binstrlen < len) {
2146 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2147 len, *binstrlen);
2148 return 0;
2149 }
2150 alloc = 0;
2151 }
2152 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002153
2154 i = j = 0;
2155 while (j < len) {
2156 if (!ishex(p[i++]))
2157 goto bad_input;
2158 if (!ishex(p[i++]))
2159 goto bad_input;
2160 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2161 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002162 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002163
2164bad_input:
2165 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002166 if (alloc) {
2167 free(*binstr);
2168 *binstr = NULL;
2169 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002170 return 0;
2171}
2172
Willy Tarreau946ba592009-05-10 15:41:18 +02002173/* copies at most <n> characters from <src> and always terminates with '\0' */
2174char *my_strndup(const char *src, int n)
2175{
2176 int len = 0;
2177 char *ret;
2178
2179 while (len < n && src[len])
2180 len++;
2181
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002182 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002183 if (!ret)
2184 return ret;
2185 memcpy(ret, src, len);
2186 ret[len] = '\0';
2187 return ret;
2188}
2189
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002190/*
2191 * search needle in haystack
2192 * returns the pointer if found, returns NULL otherwise
2193 */
2194const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2195{
2196 const void *c = NULL;
2197 unsigned char f;
2198
2199 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2200 return NULL;
2201
2202 f = *(char *)needle;
2203 c = haystack;
2204 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2205 if ((haystacklen - (c - haystack)) < needlelen)
2206 return NULL;
2207
2208 if (memcmp(c, needle, needlelen) == 0)
2209 return c;
2210 ++c;
2211 }
2212 return NULL;
2213}
2214
Willy Tarreau482b00d2009-10-04 22:48:42 +02002215/* This function returns the first unused key greater than or equal to <key> in
2216 * ID tree <root>. Zero is returned if no place is found.
2217 */
2218unsigned int get_next_id(struct eb_root *root, unsigned int key)
2219{
2220 struct eb32_node *used;
2221
2222 do {
2223 used = eb32_lookup_ge(root, key);
2224 if (!used || used->key > key)
2225 return key; /* key is available */
2226 key++;
2227 } while (key);
2228 return key;
2229}
2230
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002231/* dump the full tree to <file> in DOT format for debugging purposes. Will
2232 * optionally highlight node <subj> if found, depending on operation <op> :
2233 * 0 : nothing
2234 * >0 : insertion, node/leaf are surrounded in red
2235 * <0 : removal, node/leaf are dashed with no background
2236 * Will optionally add "desc" as a label on the graph if set and non-null.
2237 */
2238void 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 +01002239{
2240 struct eb32sc_node *node;
2241 unsigned long scope = -1;
2242
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002243 fprintf(file, "digraph ebtree {\n");
2244
2245 if (desc && *desc) {
2246 fprintf(file,
2247 " fontname=\"fixed\";\n"
2248 " fontsize=8;\n"
2249 " label=\"%s\";\n", desc);
2250 }
2251
Willy Tarreaued3cda02017-11-15 15:04:05 +01002252 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002253 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2254 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002255 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2256 );
2257
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002258 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002259 (long)eb_root_to_node(root),
2260 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002261 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2262
2263 node = eb32sc_first(root, scope);
2264 while (node) {
2265 if (node->node.node_p) {
2266 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002267 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2268 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2269 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002270
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002271 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002272 (long)node,
2273 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002274 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002275
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002276 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002277 (long)node,
2278 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002279 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2280
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002281 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002282 (long)node,
2283 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002284 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2285 }
2286
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002287 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2288 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
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_l\" -> \"%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.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002294 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002295 node = eb32sc_next(node, scope);
2296 }
2297 fprintf(file, "}\n");
2298}
2299
Willy Tarreau348238b2010-01-18 15:05:57 +01002300/* This function compares a sample word possibly followed by blanks to another
2301 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2302 * otherwise zero. This intends to be used when checking HTTP headers for some
2303 * values. Note that it validates a word followed only by blanks but does not
2304 * validate a word followed by blanks then other chars.
2305 */
2306int word_match(const char *sample, int slen, const char *word, int wlen)
2307{
2308 if (slen < wlen)
2309 return 0;
2310
2311 while (wlen) {
2312 char c = *sample ^ *word;
2313 if (c && c != ('A' ^ 'a'))
2314 return 0;
2315 sample++;
2316 word++;
2317 slen--;
2318 wlen--;
2319 }
2320
2321 while (slen) {
2322 if (*sample != ' ' && *sample != '\t')
2323 return 0;
2324 sample++;
2325 slen--;
2326 }
2327 return 1;
2328}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002329
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002330/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2331 * is particularly fast because it avoids expensive operations such as
2332 * multiplies, which are optimized away at the end. It requires a properly
2333 * formated address though (3 points).
2334 */
2335unsigned int inetaddr_host(const char *text)
2336{
2337 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2338 register unsigned int dig100, dig10, dig1;
2339 int s;
2340 const char *p, *d;
2341
2342 dig1 = dig10 = dig100 = ascii_zero;
2343 s = 24;
2344
2345 p = text;
2346 while (1) {
2347 if (((unsigned)(*p - '0')) <= 9) {
2348 p++;
2349 continue;
2350 }
2351
2352 /* here, we have a complete byte between <text> and <p> (exclusive) */
2353 if (p == text)
2354 goto end;
2355
2356 d = p - 1;
2357 dig1 |= (unsigned int)(*d << s);
2358 if (d == text)
2359 goto end;
2360
2361 d--;
2362 dig10 |= (unsigned int)(*d << s);
2363 if (d == text)
2364 goto end;
2365
2366 d--;
2367 dig100 |= (unsigned int)(*d << s);
2368 end:
2369 if (!s || *p != '.')
2370 break;
2371
2372 s -= 8;
2373 text = ++p;
2374 }
2375
2376 dig100 -= ascii_zero;
2377 dig10 -= ascii_zero;
2378 dig1 -= ascii_zero;
2379 return ((dig100 * 10) + dig10) * 10 + dig1;
2380}
2381
2382/*
2383 * Idem except the first unparsed character has to be passed in <stop>.
2384 */
2385unsigned int inetaddr_host_lim(const char *text, const char *stop)
2386{
2387 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2388 register unsigned int dig100, dig10, dig1;
2389 int s;
2390 const char *p, *d;
2391
2392 dig1 = dig10 = dig100 = ascii_zero;
2393 s = 24;
2394
2395 p = text;
2396 while (1) {
2397 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2398 p++;
2399 continue;
2400 }
2401
2402 /* here, we have a complete byte between <text> and <p> (exclusive) */
2403 if (p == text)
2404 goto end;
2405
2406 d = p - 1;
2407 dig1 |= (unsigned int)(*d << s);
2408 if (d == text)
2409 goto end;
2410
2411 d--;
2412 dig10 |= (unsigned int)(*d << s);
2413 if (d == text)
2414 goto end;
2415
2416 d--;
2417 dig100 |= (unsigned int)(*d << s);
2418 end:
2419 if (!s || p == stop || *p != '.')
2420 break;
2421
2422 s -= 8;
2423 text = ++p;
2424 }
2425
2426 dig100 -= ascii_zero;
2427 dig10 -= ascii_zero;
2428 dig1 -= ascii_zero;
2429 return ((dig100 * 10) + dig10) * 10 + dig1;
2430}
2431
2432/*
2433 * Idem except the pointer to first unparsed byte is returned into <ret> which
2434 * must not be NULL.
2435 */
Willy Tarreau74172752010-10-15 23:21:42 +02002436unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002437{
2438 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2439 register unsigned int dig100, dig10, dig1;
2440 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002441 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002442
2443 dig1 = dig10 = dig100 = ascii_zero;
2444 s = 24;
2445
2446 p = text;
2447 while (1) {
2448 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2449 p++;
2450 continue;
2451 }
2452
2453 /* here, we have a complete byte between <text> and <p> (exclusive) */
2454 if (p == text)
2455 goto end;
2456
2457 d = p - 1;
2458 dig1 |= (unsigned int)(*d << s);
2459 if (d == text)
2460 goto end;
2461
2462 d--;
2463 dig10 |= (unsigned int)(*d << s);
2464 if (d == text)
2465 goto end;
2466
2467 d--;
2468 dig100 |= (unsigned int)(*d << s);
2469 end:
2470 if (!s || p == stop || *p != '.')
2471 break;
2472
2473 s -= 8;
2474 text = ++p;
2475 }
2476
2477 *ret = p;
2478 dig100 -= ascii_zero;
2479 dig10 -= ascii_zero;
2480 dig1 -= ascii_zero;
2481 return ((dig100 * 10) + dig10) * 10 + dig1;
2482}
2483
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002484/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2485 * or the number of chars read in case of success. Maybe this could be replaced
2486 * by one of the functions above. Also, apparently this function does not support
2487 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002488 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002489 */
2490int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2491{
2492 const char *addr;
2493 int saw_digit, octets, ch;
2494 u_char tmp[4], *tp;
2495 const char *cp = buf;
2496
2497 saw_digit = 0;
2498 octets = 0;
2499 *(tp = tmp) = 0;
2500
2501 for (addr = buf; addr - buf < len; addr++) {
2502 unsigned char digit = (ch = *addr) - '0';
2503
2504 if (digit > 9 && ch != '.')
2505 break;
2506
2507 if (digit <= 9) {
2508 u_int new = *tp * 10 + digit;
2509
2510 if (new > 255)
2511 return 0;
2512
2513 *tp = new;
2514
2515 if (!saw_digit) {
2516 if (++octets > 4)
2517 return 0;
2518 saw_digit = 1;
2519 }
2520 } else if (ch == '.' && saw_digit) {
2521 if (octets == 4)
2522 return 0;
2523
2524 *++tp = 0;
2525 saw_digit = 0;
2526 } else
2527 return 0;
2528 }
2529
2530 if (octets < 4)
2531 return 0;
2532
2533 memcpy(&dst->s_addr, tmp, 4);
2534 return addr - cp;
2535}
2536
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002537/* This function converts the string in <buf> of the len <len> to
2538 * struct in6_addr <dst> which must be allocated by the caller.
2539 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002540 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002541 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002542int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2543{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002544 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002545 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002546
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002547 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002548 return 0;
2549
2550 memcpy(null_term_ip6, buf, len);
2551 null_term_ip6[len] = '\0';
2552
Willy Tarreau075415a2013-12-12 11:29:39 +01002553 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002554 return 0;
2555
Willy Tarreau075415a2013-12-12 11:29:39 +01002556 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002557 return 1;
2558}
2559
Willy Tarreauacf95772010-06-14 19:09:21 +02002560/* To be used to quote config arg positions. Returns the short string at <ptr>
2561 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2562 * if ptr is NULL or empty. The string is locally allocated.
2563 */
2564const char *quote_arg(const char *ptr)
2565{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002566 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002567 int i;
2568
2569 if (!ptr || !*ptr)
2570 return "end of line";
2571 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002572 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002573 val[i] = *ptr++;
2574 val[i++] = '\'';
2575 val[i] = '\0';
2576 return val;
2577}
2578
Willy Tarreau5b180202010-07-18 10:40:48 +02002579/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2580int get_std_op(const char *str)
2581{
2582 int ret = -1;
2583
2584 if (*str == 'e' && str[1] == 'q')
2585 ret = STD_OP_EQ;
2586 else if (*str == 'n' && str[1] == 'e')
2587 ret = STD_OP_NE;
2588 else if (*str == 'l') {
2589 if (str[1] == 'e') ret = STD_OP_LE;
2590 else if (str[1] == 't') ret = STD_OP_LT;
2591 }
2592 else if (*str == 'g') {
2593 if (str[1] == 'e') ret = STD_OP_GE;
2594 else if (str[1] == 't') ret = STD_OP_GT;
2595 }
2596
2597 if (ret == -1 || str[2] != '\0')
2598 return -1;
2599 return ret;
2600}
2601
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002602/* hash a 32-bit integer to another 32-bit integer */
2603unsigned int full_hash(unsigned int a)
2604{
2605 return __full_hash(a);
2606}
2607
David du Colombier4f92d322011-03-24 11:09:31 +01002608/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002609 * otherwise zero. Note that <addr> may not necessarily be aligned
2610 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002611 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002612int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002613{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002614 struct in_addr addr_copy;
2615
2616 memcpy(&addr_copy, addr, sizeof(addr_copy));
2617 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002618}
2619
2620/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002621 * otherwise zero. Note that <addr> may not necessarily be aligned
2622 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002623 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002624int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002625{
2626 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002627 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002628
Willy Tarreaueec1d382016-07-13 11:59:39 +02002629 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002630 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002631 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002632 (((int *)net)[i] & ((int *)mask)[i]))
2633 return 0;
2634 return 1;
2635}
2636
2637/* RFC 4291 prefix */
2638const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2639 0x00, 0x00, 0x00, 0x00,
2640 0x00, 0x00, 0xFF, 0xFF };
2641
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002642/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2643 * Input and output may overlap.
2644 */
David du Colombier4f92d322011-03-24 11:09:31 +01002645void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2646{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002647 struct in_addr tmp_addr;
2648
2649 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002650 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002651 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002652}
2653
2654/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2655 * Return true if conversion is possible and false otherwise.
2656 */
2657int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2658{
2659 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2660 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2661 sizeof(struct in_addr));
2662 return 1;
2663 }
2664
2665 return 0;
2666}
2667
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002668/* compare two struct sockaddr_storage and return:
2669 * 0 (true) if the addr is the same in both
2670 * 1 (false) if the addr is not the same in both
2671 * -1 (unable) if one of the addr is not AF_INET*
2672 */
2673int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2674{
2675 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2676 return -1;
2677
2678 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2679 return -1;
2680
2681 if (ss1->ss_family != ss2->ss_family)
2682 return 1;
2683
2684 switch (ss1->ss_family) {
2685 case AF_INET:
2686 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2687 &((struct sockaddr_in *)ss2)->sin_addr,
2688 sizeof(struct in_addr)) != 0;
2689 case AF_INET6:
2690 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2691 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2692 sizeof(struct in6_addr)) != 0;
2693 }
2694
2695 return 1;
2696}
2697
Baptiste Assmann08396c82016-01-31 00:27:17 +01002698/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002699 * The caller must allocate and clear <dest> before calling.
2700 * The source must be in either AF_INET or AF_INET6 family, or the destination
2701 * address will be undefined. If the destination address used to hold a port,
2702 * it is preserved, so that this function can be used to switch to another
2703 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002704 */
2705struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2706{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002707 int prev_port;
2708
2709 prev_port = get_net_port(dest);
2710 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002711 dest->ss_family = source->ss_family;
2712
2713 /* copy new addr and apply it */
2714 switch (source->ss_family) {
2715 case AF_INET:
2716 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002717 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002718 break;
2719 case AF_INET6:
2720 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 +01002721 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002722 break;
2723 }
2724
2725 return dest;
2726}
2727
William Lallemand421f5b52012-02-06 18:15:57 +01002728char *human_time(int t, short hz_div) {
2729 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2730 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002731 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002732 int cnt=2; // print two numbers
2733
2734 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002735 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002736 return rv;
2737 }
2738
2739 if (unlikely(hz_div > 1))
2740 t /= hz_div;
2741
2742 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002743 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002744 cnt--;
2745 }
2746
2747 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002748 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002749 cnt--;
2750 }
2751
2752 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002753 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002754 cnt--;
2755 }
2756
2757 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002758 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002759
2760 return rv;
2761}
2762
2763const char *monthname[12] = {
2764 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2765 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2766};
2767
2768/* date2str_log: write a date in the format :
2769 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2770 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2771 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2772 *
2773 * without using sprintf. return a pointer to the last char written (\0) or
2774 * NULL if there isn't enough space.
2775 */
2776char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2777{
2778
2779 if (size < 25) /* the size is fixed: 24 chars + \0 */
2780 return NULL;
2781
2782 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2783 *dst++ = '/';
2784 memcpy(dst, monthname[tm->tm_mon], 3); // month
2785 dst += 3;
2786 *dst++ = '/';
2787 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2788 *dst++ = ':';
2789 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2790 *dst++ = ':';
2791 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2792 *dst++ = ':';
2793 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2794 *dst++ = '.';
2795 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2796 dst += 3; // only the 3 first digits
2797 *dst = '\0';
2798
2799 return dst;
2800}
2801
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002802/* Base year used to compute leap years */
2803#define TM_YEAR_BASE 1900
2804
2805/* Return the difference in seconds between two times (leap seconds are ignored).
2806 * Retrieved from glibc 2.18 source code.
2807 */
2808static int my_tm_diff(const struct tm *a, const struct tm *b)
2809{
2810 /* Compute intervening leap days correctly even if year is negative.
2811 * Take care to avoid int overflow in leap day calculations,
2812 * but it's OK to assume that A and B are close to each other.
2813 */
2814 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2815 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2816 int a100 = a4 / 25 - (a4 % 25 < 0);
2817 int b100 = b4 / 25 - (b4 % 25 < 0);
2818 int a400 = a100 >> 2;
2819 int b400 = b100 >> 2;
2820 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2821 int years = a->tm_year - b->tm_year;
2822 int days = (365 * years + intervening_leap_days
2823 + (a->tm_yday - b->tm_yday));
2824 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2825 + (a->tm_min - b->tm_min))
2826 + (a->tm_sec - b->tm_sec));
2827}
2828
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002829/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002830 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002831 * The string returned has the same format as returned by strftime(... "%z", tm).
2832 * Offsets are kept in an internal cache for better performances.
2833 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002834const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002835{
2836 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002837 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002838
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002839 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002840 struct tm tm_gmt;
2841 int diff;
2842 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002843
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002844 /* Pretend DST not active if its status is unknown */
2845 if (isdst < 0)
2846 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002847
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002848 /* Fetch the offset and initialize it if needed */
2849 gmt_offset = gmt_offsets[isdst & 0x01];
2850 if (unlikely(!*gmt_offset)) {
2851 get_gmtime(t, &tm_gmt);
2852 diff = my_tm_diff(tm, &tm_gmt);
2853 if (diff < 0) {
2854 diff = -diff;
2855 *gmt_offset = '-';
2856 } else {
2857 *gmt_offset = '+';
2858 }
2859 diff /= 60; /* Convert to minutes */
2860 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2861 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002862
2863 return gmt_offset;
2864}
2865
William Lallemand421f5b52012-02-06 18:15:57 +01002866/* gmt2str_log: write a date in the format :
2867 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2868 * return a pointer to the last char written (\0) or
2869 * NULL if there isn't enough space.
2870 */
2871char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2872{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002873 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002874 return NULL;
2875
2876 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2877 *dst++ = '/';
2878 memcpy(dst, monthname[tm->tm_mon], 3); // month
2879 dst += 3;
2880 *dst++ = '/';
2881 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2882 *dst++ = ':';
2883 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2884 *dst++ = ':';
2885 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2886 *dst++ = ':';
2887 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2888 *dst++ = ' ';
2889 *dst++ = '+';
2890 *dst++ = '0';
2891 *dst++ = '0';
2892 *dst++ = '0';
2893 *dst++ = '0';
2894 *dst = '\0';
2895
2896 return dst;
2897}
2898
Yuxans Yao4e25b012012-10-19 10:36:09 +08002899/* localdate2str_log: write a date in the format :
2900 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002901 * Both t and tm must represent the same time.
2902 * return a pointer to the last char written (\0) or
2903 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002904 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002905char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002906{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002907 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002908 if (size < 27) /* the size is fixed: 26 chars + \0 */
2909 return NULL;
2910
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002911 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002912
Yuxans Yao4e25b012012-10-19 10:36:09 +08002913 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2914 *dst++ = '/';
2915 memcpy(dst, monthname[tm->tm_mon], 3); // month
2916 dst += 3;
2917 *dst++ = '/';
2918 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2919 *dst++ = ':';
2920 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2921 *dst++ = ':';
2922 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2923 *dst++ = ':';
2924 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2925 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002926 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002927 dst += 5;
2928 *dst = '\0';
2929
2930 return dst;
2931}
2932
Willy Tarreaucb1949b2017-07-19 19:05:29 +02002933/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
2934 * It is meant as a portable replacement for timegm() for use with valid inputs.
2935 * Returns undefined results for invalid dates (eg: months out of range 0..11).
2936 */
2937time_t my_timegm(const struct tm *tm)
2938{
2939 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
2940 * is thus (current month - 1)*28 + cumulated_N[month] to count the
2941 * sum of the extra N days for elapsed months. The sum of all these N
2942 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
2943 * in a 5-bit word. This means that with 60 bits we can represent a
2944 * matrix of all these values at once, which is fast and efficient to
2945 * access. The extra February day for leap years is not counted here.
2946 *
2947 * Jan : none = 0 (0)
2948 * Feb : Jan = 3 (3)
2949 * Mar : Jan..Feb = 3 (3 + 0)
2950 * Apr : Jan..Mar = 6 (3 + 0 + 3)
2951 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
2952 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
2953 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
2954 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
2955 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
2956 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
2957 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
2958 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
2959 */
2960 uint64_t extra =
2961 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
2962 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
2963 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
2964 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
2965
2966 unsigned int y = tm->tm_year + 1900;
2967 unsigned int m = tm->tm_mon;
2968 unsigned long days = 0;
2969
2970 /* days since 1/1/1970 for full years */
2971 days += days_since_zero(y) - days_since_zero(1970);
2972
2973 /* days for full months in the current year */
2974 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
2975
2976 /* count + 1 after March for leap years. A leap year is a year multiple
2977 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
2978 * is leap, 1900 isn't, 1904 is.
2979 */
2980 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
2981 days++;
2982
2983 days += tm->tm_mday - 1;
2984 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
2985}
2986
Thierry Fournier93127942016-01-20 18:49:45 +01002987/* This function check a char. It returns true and updates
2988 * <date> and <len> pointer to the new position if the
2989 * character is found.
2990 */
2991static inline int parse_expect_char(const char **date, int *len, char c)
2992{
2993 if (*len < 1 || **date != c)
2994 return 0;
2995 (*len)--;
2996 (*date)++;
2997 return 1;
2998}
2999
3000/* This function expects a string <str> of len <l>. It return true and updates.
3001 * <date> and <len> if the string matches, otherwise, it returns false.
3002 */
3003static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3004{
3005 if (*len < l || strncmp(*date, str, l) != 0)
3006 return 0;
3007 (*len) -= l;
3008 (*date) += l;
3009 return 1;
3010}
3011
3012/* This macro converts 3 chars name in integer. */
3013#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3014
3015/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3016 * / %x54.75.65 ; "Tue", case-sensitive
3017 * / %x57.65.64 ; "Wed", case-sensitive
3018 * / %x54.68.75 ; "Thu", case-sensitive
3019 * / %x46.72.69 ; "Fri", case-sensitive
3020 * / %x53.61.74 ; "Sat", case-sensitive
3021 * / %x53.75.6E ; "Sun", case-sensitive
3022 *
3023 * This array must be alphabetically sorted
3024 */
3025static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3026{
3027 if (*len < 3)
3028 return 0;
3029 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3030 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3031 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3032 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3033 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3034 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3035 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3036 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3037 default: return 0;
3038 }
3039 *len -= 3;
3040 *date += 3;
3041 return 1;
3042}
3043
3044/* month = %x4A.61.6E ; "Jan", case-sensitive
3045 * / %x46.65.62 ; "Feb", case-sensitive
3046 * / %x4D.61.72 ; "Mar", case-sensitive
3047 * / %x41.70.72 ; "Apr", case-sensitive
3048 * / %x4D.61.79 ; "May", case-sensitive
3049 * / %x4A.75.6E ; "Jun", case-sensitive
3050 * / %x4A.75.6C ; "Jul", case-sensitive
3051 * / %x41.75.67 ; "Aug", case-sensitive
3052 * / %x53.65.70 ; "Sep", case-sensitive
3053 * / %x4F.63.74 ; "Oct", case-sensitive
3054 * / %x4E.6F.76 ; "Nov", case-sensitive
3055 * / %x44.65.63 ; "Dec", case-sensitive
3056 *
3057 * This array must be alphabetically sorted
3058 */
3059static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3060{
3061 if (*len < 3)
3062 return 0;
3063 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3064 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3065 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3066 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3067 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3068 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3069 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3070 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3071 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3072 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3073 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3074 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3075 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3076 default: return 0;
3077 }
3078 *len -= 3;
3079 *date += 3;
3080 return 1;
3081}
3082
3083/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3084 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3085 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3086 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3087 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3088 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3089 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3090 *
3091 * This array must be alphabetically sorted
3092 */
3093static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3094{
3095 if (*len < 6) /* Minimum length. */
3096 return 0;
3097 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3098 case STR2I3('M','o','n'):
3099 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3100 tm->tm_wday = 1;
3101 return 1;
3102 case STR2I3('T','u','e'):
3103 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3104 tm->tm_wday = 2;
3105 return 1;
3106 case STR2I3('W','e','d'):
3107 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3108 tm->tm_wday = 3;
3109 return 1;
3110 case STR2I3('T','h','u'):
3111 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3112 tm->tm_wday = 4;
3113 return 1;
3114 case STR2I3('F','r','i'):
3115 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3116 tm->tm_wday = 5;
3117 return 1;
3118 case STR2I3('S','a','t'):
3119 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3120 tm->tm_wday = 6;
3121 return 1;
3122 case STR2I3('S','u','n'):
3123 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3124 tm->tm_wday = 7;
3125 return 1;
3126 }
3127 return 0;
3128}
3129
3130/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3131static inline int parse_digit(const char **date, int *len, int *digit)
3132{
3133 if (*len < 1 || **date < '0' || **date > '9')
3134 return 0;
3135 *digit = (**date - '0');
3136 (*date)++;
3137 (*len)--;
3138 return 1;
3139}
3140
3141/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3142static inline int parse_2digit(const char **date, int *len, int *digit)
3143{
3144 int value;
3145
3146 RET0_UNLESS(parse_digit(date, len, &value));
3147 (*digit) = value * 10;
3148 RET0_UNLESS(parse_digit(date, len, &value));
3149 (*digit) += value;
3150
3151 return 1;
3152}
3153
3154/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3155static inline int parse_4digit(const char **date, int *len, int *digit)
3156{
3157 int value;
3158
3159 RET0_UNLESS(parse_digit(date, len, &value));
3160 (*digit) = value * 1000;
3161
3162 RET0_UNLESS(parse_digit(date, len, &value));
3163 (*digit) += value * 100;
3164
3165 RET0_UNLESS(parse_digit(date, len, &value));
3166 (*digit) += value * 10;
3167
3168 RET0_UNLESS(parse_digit(date, len, &value));
3169 (*digit) += value;
3170
3171 return 1;
3172}
3173
3174/* time-of-day = hour ":" minute ":" second
3175 * ; 00:00:00 - 23:59:60 (leap second)
3176 *
3177 * hour = 2DIGIT
3178 * minute = 2DIGIT
3179 * second = 2DIGIT
3180 */
3181static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3182{
3183 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3184 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3185 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3186 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3187 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3188 return 1;
3189}
3190
3191/* From RFC7231
3192 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3193 *
3194 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3195 * ; fixed length/zone/capitalization subset of the format
3196 * ; see Section 3.3 of [RFC5322]
3197 *
3198 *
3199 * date1 = day SP month SP year
3200 * ; e.g., 02 Jun 1982
3201 *
3202 * day = 2DIGIT
3203 * year = 4DIGIT
3204 *
3205 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3206 *
3207 * time-of-day = hour ":" minute ":" second
3208 * ; 00:00:00 - 23:59:60 (leap second)
3209 *
3210 * hour = 2DIGIT
3211 * minute = 2DIGIT
3212 * second = 2DIGIT
3213 *
3214 * DIGIT = decimal 0-9
3215 */
3216int parse_imf_date(const char *date, int len, struct tm *tm)
3217{
David Carlier327298c2016-11-20 10:42:38 +00003218 /* tm_gmtoff, if present, ought to be zero'ed */
3219 memset(tm, 0, sizeof(*tm));
3220
Thierry Fournier93127942016-01-20 18:49:45 +01003221 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3222 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3223 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3224 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3225 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3226 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3227 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3228 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3229 tm->tm_year -= 1900;
3230 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3231 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3232 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3233 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3234 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003235 return 1;
3236}
3237
3238/* From RFC7231
3239 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3240 *
3241 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3242 * date2 = day "-" month "-" 2DIGIT
3243 * ; e.g., 02-Jun-82
3244 *
3245 * day = 2DIGIT
3246 */
3247int parse_rfc850_date(const char *date, int len, struct tm *tm)
3248{
3249 int year;
3250
David Carlier327298c2016-11-20 10:42:38 +00003251 /* tm_gmtoff, if present, ought to be zero'ed */
3252 memset(tm, 0, sizeof(*tm));
3253
Thierry Fournier93127942016-01-20 18:49:45 +01003254 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3255 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3256 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3257 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3258 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3259 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3260 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3261
3262 /* year = 2DIGIT
3263 *
3264 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3265 * two-digit year, MUST interpret a timestamp that appears to be more
3266 * than 50 years in the future as representing the most recent year in
3267 * the past that had the same last two digits.
3268 */
3269 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3270
3271 /* expect SP */
3272 if (!parse_expect_char(&date, &len, ' ')) {
3273 /* Maybe we have the date with 4 digits. */
3274 RET0_UNLESS(parse_2digit(&date, &len, &year));
3275 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3276 /* expect SP */
3277 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3278 } else {
3279 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3280 * tm_year is the number of year since 1900, so for +1900, we
3281 * do nothing, and for +2000, we add 100.
3282 */
3283 if (tm->tm_year <= 60)
3284 tm->tm_year += 100;
3285 }
3286
3287 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3288 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3289 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3290 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003291
3292 return 1;
3293}
3294
3295/* From RFC7231
3296 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3297 *
3298 * asctime-date = day-name SP date3 SP time-of-day SP year
3299 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3300 * ; e.g., Jun 2
3301 *
3302 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3303 * whitespace in an HTTP-date beyond that specifically included as SP in
3304 * the grammar.
3305 */
3306int parse_asctime_date(const char *date, int len, struct tm *tm)
3307{
David Carlier327298c2016-11-20 10:42:38 +00003308 /* tm_gmtoff, if present, ought to be zero'ed */
3309 memset(tm, 0, sizeof(*tm));
3310
Thierry Fournier93127942016-01-20 18:49:45 +01003311 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3312 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3313 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3314 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3315
3316 /* expect SP and 1DIGIT or 2DIGIT */
3317 if (parse_expect_char(&date, &len, ' '))
3318 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3319 else
3320 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3321
3322 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3323 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3324 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3325 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3326 tm->tm_year -= 1900;
3327 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003328 return 1;
3329}
3330
3331/* From RFC7231
3332 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3333 *
3334 * HTTP-date = IMF-fixdate / obs-date
3335 * obs-date = rfc850-date / asctime-date
3336 *
3337 * parses an HTTP date in the RFC format and is accepted
3338 * alternatives. <date> is the strinf containing the date,
3339 * len is the len of the string. <tm> is filled with the
3340 * parsed time. We must considers this time as GMT.
3341 */
3342int parse_http_date(const char *date, int len, struct tm *tm)
3343{
3344 if (parse_imf_date(date, len, tm))
3345 return 1;
3346
3347 if (parse_rfc850_date(date, len, tm))
3348 return 1;
3349
3350 if (parse_asctime_date(date, len, tm))
3351 return 1;
3352
3353 return 0;
3354}
3355
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003356/* Dynamically allocates a string of the proper length to hold the formatted
3357 * output. NULL is returned on error. The caller is responsible for freeing the
3358 * memory area using free(). The resulting string is returned in <out> if the
3359 * pointer is not NULL. A previous version of <out> might be used to build the
3360 * new string, and it will be freed before returning if it is not NULL, which
3361 * makes it possible to build complex strings from iterative calls without
3362 * having to care about freeing intermediate values, as in the example below :
3363 *
3364 * memprintf(&err, "invalid argument: '%s'", arg);
3365 * ...
3366 * memprintf(&err, "parser said : <%s>\n", *err);
3367 * ...
3368 * free(*err);
3369 *
3370 * This means that <err> must be initialized to NULL before first invocation.
3371 * The return value also holds the allocated string, which eases error checking
3372 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003373 * passed instead and it will be ignored. The returned message will then also
3374 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003375 *
3376 * It is also convenient to use it without any free except the last one :
3377 * err = NULL;
3378 * if (!fct1(err)) report(*err);
3379 * if (!fct2(err)) report(*err);
3380 * if (!fct3(err)) report(*err);
3381 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003382 *
3383 * memprintf relies on memvprintf. This last version can be called from any
3384 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003385 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003386char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003387{
3388 va_list args;
3389 char *ret = NULL;
3390 int allocated = 0;
3391 int needed = 0;
3392
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003393 if (!out)
3394 return NULL;
3395
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003396 do {
3397 /* vsnprintf() will return the required length even when the
3398 * target buffer is NULL. We do this in a loop just in case
3399 * intermediate evaluations get wrong.
3400 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003401 va_copy(args, orig_args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003402 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003403 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003404 if (needed < allocated) {
3405 /* Note: on Solaris 8, the first iteration always
3406 * returns -1 if allocated is zero, so we force a
3407 * retry.
3408 */
3409 if (!allocated)
3410 needed = 0;
3411 else
3412 break;
3413 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003414
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003415 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003416 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003417 } while (ret);
3418
3419 if (needed < 0) {
3420 /* an error was encountered */
3421 free(ret);
3422 ret = NULL;
3423 }
3424
3425 if (out) {
3426 free(*out);
3427 *out = ret;
3428 }
3429
3430 return ret;
3431}
William Lallemand421f5b52012-02-06 18:15:57 +01003432
Christopher Faulet93a518f2017-10-24 11:25:33 +02003433char *memprintf(char **out, const char *format, ...)
3434{
3435 va_list args;
3436 char *ret = NULL;
3437
3438 va_start(args, format);
3439 ret = memvprintf(out, format, args);
3440 va_end(args);
3441
3442 return ret;
3443}
3444
Willy Tarreau21c705b2012-09-14 11:40:36 +02003445/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3446 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003447 * freed by the caller. It also supports being passed a NULL which results in the same
3448 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003449 * Example of use :
3450 * parse(cmd, &err); (callee: memprintf(&err, ...))
3451 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3452 * free(err);
3453 */
3454char *indent_msg(char **out, int level)
3455{
3456 char *ret, *in, *p;
3457 int needed = 0;
3458 int lf = 0;
3459 int lastlf = 0;
3460 int len;
3461
Willy Tarreau70eec382012-10-10 08:56:47 +02003462 if (!out || !*out)
3463 return NULL;
3464
Willy Tarreau21c705b2012-09-14 11:40:36 +02003465 in = *out - 1;
3466 while ((in = strchr(in + 1, '\n')) != NULL) {
3467 lastlf = in - *out;
3468 lf++;
3469 }
3470
3471 if (!lf) /* single line, no LF, return it as-is */
3472 return *out;
3473
3474 len = strlen(*out);
3475
3476 if (lf == 1 && lastlf == len - 1) {
3477 /* single line, LF at end, strip it and return as-is */
3478 (*out)[lastlf] = 0;
3479 return *out;
3480 }
3481
3482 /* OK now we have at least one LF, we need to process the whole string
3483 * as a multi-line string. What we'll do :
3484 * - prefix with an LF if there is none
3485 * - add <level> spaces before each line
3486 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3487 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3488 */
3489
3490 needed = 1 + level * (lf + 1) + len + 1;
3491 p = ret = malloc(needed);
3492 in = *out;
3493
3494 /* skip initial LFs */
3495 while (*in == '\n')
3496 in++;
3497
3498 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3499 while (*in) {
3500 *p++ = '\n';
3501 memset(p, ' ', level);
3502 p += level;
3503 do {
3504 *p++ = *in++;
3505 } while (*in && *in != '\n');
3506 if (*in)
3507 in++;
3508 }
3509 *p = 0;
3510
3511 free(*out);
3512 *out = ret;
3513
3514 return ret;
3515}
3516
Willy Tarreaudad36a32013-03-11 01:20:04 +01003517/* Convert occurrences of environment variables in the input string to their
3518 * corresponding value. A variable is identified as a series of alphanumeric
3519 * characters or underscores following a '$' sign. The <in> string must be
3520 * free()able. NULL returns NULL. The resulting string might be reallocated if
3521 * some expansion is made. Variable names may also be enclosed into braces if
3522 * needed (eg: to concatenate alphanum characters).
3523 */
3524char *env_expand(char *in)
3525{
3526 char *txt_beg;
3527 char *out;
3528 char *txt_end;
3529 char *var_beg;
3530 char *var_end;
3531 char *value;
3532 char *next;
3533 int out_len;
3534 int val_len;
3535
3536 if (!in)
3537 return in;
3538
3539 value = out = NULL;
3540 out_len = 0;
3541
3542 txt_beg = in;
3543 do {
3544 /* look for next '$' sign in <in> */
3545 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3546
3547 if (!*txt_end && !out) /* end and no expansion performed */
3548 return in;
3549
3550 val_len = 0;
3551 next = txt_end;
3552 if (*txt_end == '$') {
3553 char save;
3554
3555 var_beg = txt_end + 1;
3556 if (*var_beg == '{')
3557 var_beg++;
3558
3559 var_end = var_beg;
3560 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3561 var_end++;
3562 }
3563
3564 next = var_end;
3565 if (*var_end == '}' && (var_beg > txt_end + 1))
3566 next++;
3567
3568 /* get value of the variable name at this location */
3569 save = *var_end;
3570 *var_end = '\0';
3571 value = getenv(var_beg);
3572 *var_end = save;
3573 val_len = value ? strlen(value) : 0;
3574 }
3575
Hubert Verstraete831962e2016-06-28 22:44:26 +02003576 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003577 if (txt_end > txt_beg) {
3578 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3579 out_len += txt_end - txt_beg;
3580 }
3581 if (val_len) {
3582 memcpy(out + out_len, value, val_len);
3583 out_len += val_len;
3584 }
3585 out[out_len] = 0;
3586 txt_beg = next;
3587 } while (*txt_beg);
3588
3589 /* here we know that <out> was allocated and that we don't need <in> anymore */
3590 free(in);
3591 return out;
3592}
3593
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003594
3595/* same as strstr() but case-insensitive and with limit length */
3596const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3597{
3598 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003599 unsigned int slen, plen;
3600 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003601
3602 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3603 return NULL;
3604
3605 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3606 return str1;
3607
3608 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3609 return NULL;
3610
3611 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3612 while (toupper(*start) != toupper(*str2)) {
3613 start++;
3614 slen--;
3615 tmp1++;
3616
3617 if (tmp1 >= len_str1)
3618 return NULL;
3619
3620 /* if pattern longer than string */
3621 if (slen < plen)
3622 return NULL;
3623 }
3624
3625 sptr = start;
3626 pptr = (char *)str2;
3627
3628 tmp2 = 0;
3629 while (toupper(*sptr) == toupper(*pptr)) {
3630 sptr++;
3631 pptr++;
3632 tmp2++;
3633
3634 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3635 return start;
3636 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3637 return NULL;
3638 }
3639 }
3640 return NULL;
3641}
3642
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003643/* This function read the next valid utf8 char.
3644 * <s> is the byte srray to be decode, <len> is its length.
3645 * The function returns decoded char encoded like this:
3646 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3647 * are the length read. The decoded character is stored in <c>.
3648 */
3649unsigned char utf8_next(const char *s, int len, unsigned int *c)
3650{
3651 const unsigned char *p = (unsigned char *)s;
3652 int dec;
3653 unsigned char code = UTF8_CODE_OK;
3654
3655 if (len < 1)
3656 return UTF8_CODE_OK;
3657
3658 /* Check the type of UTF8 sequence
3659 *
3660 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3661 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3662 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3663 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3664 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3665 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3666 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3667 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3668 */
3669 switch (*p) {
3670 case 0x00 ... 0x7f:
3671 *c = *p;
3672 return UTF8_CODE_OK | 1;
3673
3674 case 0x80 ... 0xbf:
3675 *c = *p;
3676 return UTF8_CODE_BADSEQ | 1;
3677
3678 case 0xc0 ... 0xdf:
3679 if (len < 2) {
3680 *c = *p;
3681 return UTF8_CODE_BADSEQ | 1;
3682 }
3683 *c = *p & 0x1f;
3684 dec = 1;
3685 break;
3686
3687 case 0xe0 ... 0xef:
3688 if (len < 3) {
3689 *c = *p;
3690 return UTF8_CODE_BADSEQ | 1;
3691 }
3692 *c = *p & 0x0f;
3693 dec = 2;
3694 break;
3695
3696 case 0xf0 ... 0xf7:
3697 if (len < 4) {
3698 *c = *p;
3699 return UTF8_CODE_BADSEQ | 1;
3700 }
3701 *c = *p & 0x07;
3702 dec = 3;
3703 break;
3704
3705 case 0xf8 ... 0xfb:
3706 if (len < 5) {
3707 *c = *p;
3708 return UTF8_CODE_BADSEQ | 1;
3709 }
3710 *c = *p & 0x03;
3711 dec = 4;
3712 break;
3713
3714 case 0xfc ... 0xfd:
3715 if (len < 6) {
3716 *c = *p;
3717 return UTF8_CODE_BADSEQ | 1;
3718 }
3719 *c = *p & 0x01;
3720 dec = 5;
3721 break;
3722
3723 case 0xfe ... 0xff:
3724 default:
3725 *c = *p;
3726 return UTF8_CODE_BADSEQ | 1;
3727 }
3728
3729 p++;
3730
3731 while (dec > 0) {
3732
3733 /* need 0x10 for the 2 first bits */
3734 if ( ( *p & 0xc0 ) != 0x80 )
3735 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3736
3737 /* add data at char */
3738 *c = ( *c << 6 ) | ( *p & 0x3f );
3739
3740 dec--;
3741 p++;
3742 }
3743
3744 /* Check ovelong encoding.
3745 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3746 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3747 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3748 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003749 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003750 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3751 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3752 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3753 code |= UTF8_CODE_OVERLONG;
3754
3755 /* Check invalid UTF8 range. */
3756 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3757 (*c >= 0xfffe && *c <= 0xffff))
3758 code |= UTF8_CODE_INVRANGE;
3759
3760 return code | ((p-(unsigned char *)s)&0x0f);
3761}
3762
Maxime de Roucydc887852016-05-13 23:52:54 +02003763/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3764 * On failure : return 0 and <err> filled with an error message.
3765 * The caller is responsible for freeing the <err> and <str> copy
3766 * memory area using free()
3767 */
3768int list_append_word(struct list *li, const char *str, char **err)
3769{
3770 struct wordlist *wl;
3771
3772 wl = calloc(1, sizeof(*wl));
3773 if (!wl) {
3774 memprintf(err, "out of memory");
3775 goto fail_wl;
3776 }
3777
3778 wl->s = strdup(str);
3779 if (!wl->s) {
3780 memprintf(err, "out of memory");
3781 goto fail_wl_s;
3782 }
3783
3784 LIST_ADDQ(li, &wl->list);
3785
3786 return 1;
3787
3788fail_wl_s:
3789 free(wl->s);
3790fail_wl:
3791 free(wl);
3792 return 0;
3793}
3794
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003795/* print a string of text buffer to <out>. The format is :
3796 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3797 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3798 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3799 */
3800int dump_text(struct chunk *out, const char *buf, int bsize)
3801{
3802 unsigned char c;
3803 int ptr = 0;
3804
3805 while (buf[ptr] && ptr < bsize) {
3806 c = buf[ptr];
3807 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
3808 if (out->len > out->size - 1)
3809 break;
3810 out->str[out->len++] = c;
3811 }
3812 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
3813 if (out->len > out->size - 2)
3814 break;
3815 out->str[out->len++] = '\\';
3816 switch (c) {
3817 case ' ': c = ' '; break;
3818 case '\t': c = 't'; break;
3819 case '\n': c = 'n'; break;
3820 case '\r': c = 'r'; break;
3821 case '\e': c = 'e'; break;
3822 case '\\': c = '\\'; break;
3823 case '=': c = '='; break;
3824 }
3825 out->str[out->len++] = c;
3826 }
3827 else {
3828 if (out->len > out->size - 4)
3829 break;
3830 out->str[out->len++] = '\\';
3831 out->str[out->len++] = 'x';
3832 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3833 out->str[out->len++] = hextab[c & 0xF];
3834 }
3835 ptr++;
3836 }
3837
3838 return ptr;
3839}
3840
3841/* print a buffer in hexa.
3842 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3843 */
3844int dump_binary(struct chunk *out, const char *buf, int bsize)
3845{
3846 unsigned char c;
3847 int ptr = 0;
3848
3849 while (ptr < bsize) {
3850 c = buf[ptr];
3851
3852 if (out->len > out->size - 2)
3853 break;
3854 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3855 out->str[out->len++] = hextab[c & 0xF];
3856
3857 ptr++;
3858 }
3859 return ptr;
3860}
3861
3862/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3863 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3864 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3865 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3866 * lines are respected within the limit of 70 output chars. Lines that are
3867 * continuation of a previous truncated line begin with "+" instead of " "
3868 * after the offset. The new pointer is returned.
3869 */
3870int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3871 int *line, int ptr)
3872{
3873 int end;
3874 unsigned char c;
3875
3876 end = out->len + 80;
3877 if (end > out->size)
3878 return ptr;
3879
3880 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3881
3882 while (ptr < len && ptr < bsize) {
3883 c = buf[ptr];
3884 if (isprint(c) && isascii(c) && c != '\\') {
3885 if (out->len > end - 2)
3886 break;
3887 out->str[out->len++] = c;
3888 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3889 if (out->len > end - 3)
3890 break;
3891 out->str[out->len++] = '\\';
3892 switch (c) {
3893 case '\t': c = 't'; break;
3894 case '\n': c = 'n'; break;
3895 case '\r': c = 'r'; break;
3896 case '\e': c = 'e'; break;
3897 case '\\': c = '\\'; break;
3898 }
3899 out->str[out->len++] = c;
3900 } else {
3901 if (out->len > end - 5)
3902 break;
3903 out->str[out->len++] = '\\';
3904 out->str[out->len++] = 'x';
3905 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3906 out->str[out->len++] = hextab[c & 0xF];
3907 }
3908 if (buf[ptr++] == '\n') {
3909 /* we had a line break, let's return now */
3910 out->str[out->len++] = '\n';
3911 *line = ptr;
3912 return ptr;
3913 }
3914 }
3915 /* we have an incomplete line, we return it as-is */
3916 out->str[out->len++] = '\n';
3917 return ptr;
3918}
3919
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003920/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02003921 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
3922 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003923 */
Willy Tarreaued936c52017-04-27 18:03:20 +02003924void debug_hexdump(FILE *out, const char *pfx, const char *buf,
3925 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003926{
Willy Tarreau73459792017-04-11 07:58:08 +02003927 unsigned int i;
3928 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003929
3930 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3931 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02003932 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003933 for (j = 0; j < 8; j++) {
3934 if (b + j >= 0 && b + j < len)
3935 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3936 else
3937 fprintf(out, " ");
3938 }
3939
3940 if (b + j >= 0 && b + j < len)
3941 fputc('-', out);
3942 else
3943 fputc(' ', out);
3944
3945 for (j = 8; j < 16; j++) {
3946 if (b + j >= 0 && b + j < len)
3947 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3948 else
3949 fprintf(out, " ");
3950 }
3951
3952 fprintf(out, " ");
3953 for (j = 0; j < 16; j++) {
3954 if (b + j >= 0 && b + j < len) {
3955 if (isprint((unsigned char)buf[b + j]))
3956 fputc((unsigned char)buf[b + j], out);
3957 else
3958 fputc('.', out);
3959 }
3960 else
3961 fputc(' ', out);
3962 }
3963 fputc('\n', out);
3964 }
3965}
3966
Willy Tarreau12963822017-10-24 10:54:08 +02003967/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
3968__attribute__((weak,format(printf, 1, 2)))
3969void trace(char *msg, ...)
3970{
3971}
3972
Willy Tarreaubaaee002006-06-26 02:48:02 +02003973/*
3974 * Local variables:
3975 * c-indent-level: 8
3976 * c-basic-offset: 8
3977 * End:
3978 */