blob: 495bae571c1b7e605e907f677fedcf29d8fe1cd3 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010013#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020014#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020015#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020016#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020017#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020018#include <stdlib.h>
19#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010020#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020021#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010022#include <sys/socket.h>
23#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <netinet/in.h>
25#include <arpa/inet.h>
26
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010027#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020028#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020029#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010030#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010031#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020032#include <proto/dns.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010033#include <eb32tree.h>
Willy Tarreaued3cda02017-11-15 15:04:05 +010034#include <eb32sctree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035
Thierry Fournier93127942016-01-20 18:49:45 +010036/* This macro returns false if the test __x is false. Many
37 * of the following parsing function must be abort the processing
38 * if it returns 0, so this macro is useful for writing light code.
39 */
40#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
41
Willy Tarreau56adcf22012-12-23 18:00:29 +010042/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020043 * 2^64-1 = 18446744073709551615 or
44 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020045 *
46 * The HTML version needs room for adding the 25 characters
47 * '<span class="rls"></span>' around digits at positions 3N+1 in order
48 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020049 */
Christopher Faulet99bca652017-11-14 16:47:26 +010050THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
51THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020052
Willy Tarreau588297f2014-06-16 15:16:40 +020053/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
54 * to quote strings larger than a max configuration line.
55 */
Christopher Faulet99bca652017-11-14 16:47:26 +010056THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
57THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020058
Willy Tarreaubaaee002006-06-26 02:48:02 +020059/*
William Lallemande7340ec2012-01-24 11:15:39 +010060 * unsigned long long ASCII representation
61 *
62 * return the last char '\0' or NULL if no enough
63 * space in dst
64 */
65char *ulltoa(unsigned long long n, char *dst, size_t size)
66{
67 int i = 0;
68 char *res;
69
70 switch(n) {
71 case 1ULL ... 9ULL:
72 i = 0;
73 break;
74
75 case 10ULL ... 99ULL:
76 i = 1;
77 break;
78
79 case 100ULL ... 999ULL:
80 i = 2;
81 break;
82
83 case 1000ULL ... 9999ULL:
84 i = 3;
85 break;
86
87 case 10000ULL ... 99999ULL:
88 i = 4;
89 break;
90
91 case 100000ULL ... 999999ULL:
92 i = 5;
93 break;
94
95 case 1000000ULL ... 9999999ULL:
96 i = 6;
97 break;
98
99 case 10000000ULL ... 99999999ULL:
100 i = 7;
101 break;
102
103 case 100000000ULL ... 999999999ULL:
104 i = 8;
105 break;
106
107 case 1000000000ULL ... 9999999999ULL:
108 i = 9;
109 break;
110
111 case 10000000000ULL ... 99999999999ULL:
112 i = 10;
113 break;
114
115 case 100000000000ULL ... 999999999999ULL:
116 i = 11;
117 break;
118
119 case 1000000000000ULL ... 9999999999999ULL:
120 i = 12;
121 break;
122
123 case 10000000000000ULL ... 99999999999999ULL:
124 i = 13;
125 break;
126
127 case 100000000000000ULL ... 999999999999999ULL:
128 i = 14;
129 break;
130
131 case 1000000000000000ULL ... 9999999999999999ULL:
132 i = 15;
133 break;
134
135 case 10000000000000000ULL ... 99999999999999999ULL:
136 i = 16;
137 break;
138
139 case 100000000000000000ULL ... 999999999999999999ULL:
140 i = 17;
141 break;
142
143 case 1000000000000000000ULL ... 9999999999999999999ULL:
144 i = 18;
145 break;
146
147 case 10000000000000000000ULL ... ULLONG_MAX:
148 i = 19;
149 break;
150 }
151 if (i + 2 > size) // (i + 1) + '\0'
152 return NULL; // too long
153 res = dst + i + 1;
154 *res = '\0';
155 for (; i >= 0; i--) {
156 dst[i] = n % 10ULL + '0';
157 n /= 10ULL;
158 }
159 return res;
160}
161
162/*
163 * unsigned long ASCII representation
164 *
165 * return the last char '\0' or NULL if no enough
166 * space in dst
167 */
168char *ultoa_o(unsigned long n, char *dst, size_t size)
169{
170 int i = 0;
171 char *res;
172
173 switch (n) {
174 case 0U ... 9UL:
175 i = 0;
176 break;
177
178 case 10U ... 99UL:
179 i = 1;
180 break;
181
182 case 100U ... 999UL:
183 i = 2;
184 break;
185
186 case 1000U ... 9999UL:
187 i = 3;
188 break;
189
190 case 10000U ... 99999UL:
191 i = 4;
192 break;
193
194 case 100000U ... 999999UL:
195 i = 5;
196 break;
197
198 case 1000000U ... 9999999UL:
199 i = 6;
200 break;
201
202 case 10000000U ... 99999999UL:
203 i = 7;
204 break;
205
206 case 100000000U ... 999999999UL:
207 i = 8;
208 break;
209#if __WORDSIZE == 32
210
211 case 1000000000ULL ... ULONG_MAX:
212 i = 9;
213 break;
214
215#elif __WORDSIZE == 64
216
217 case 1000000000ULL ... 9999999999UL:
218 i = 9;
219 break;
220
221 case 10000000000ULL ... 99999999999UL:
222 i = 10;
223 break;
224
225 case 100000000000ULL ... 999999999999UL:
226 i = 11;
227 break;
228
229 case 1000000000000ULL ... 9999999999999UL:
230 i = 12;
231 break;
232
233 case 10000000000000ULL ... 99999999999999UL:
234 i = 13;
235 break;
236
237 case 100000000000000ULL ... 999999999999999UL:
238 i = 14;
239 break;
240
241 case 1000000000000000ULL ... 9999999999999999UL:
242 i = 15;
243 break;
244
245 case 10000000000000000ULL ... 99999999999999999UL:
246 i = 16;
247 break;
248
249 case 100000000000000000ULL ... 999999999999999999UL:
250 i = 17;
251 break;
252
253 case 1000000000000000000ULL ... 9999999999999999999UL:
254 i = 18;
255 break;
256
257 case 10000000000000000000ULL ... ULONG_MAX:
258 i = 19;
259 break;
260
261#endif
262 }
263 if (i + 2 > size) // (i + 1) + '\0'
264 return NULL; // too long
265 res = dst + i + 1;
266 *res = '\0';
267 for (; i >= 0; i--) {
268 dst[i] = n % 10U + '0';
269 n /= 10U;
270 }
271 return res;
272}
273
274/*
275 * signed long ASCII representation
276 *
277 * return the last char '\0' or NULL if no enough
278 * space in dst
279 */
280char *ltoa_o(long int n, char *dst, size_t size)
281{
282 char *pos = dst;
283
284 if (n < 0) {
285 if (size < 3)
286 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
287 *pos = '-';
288 pos++;
289 dst = ultoa_o(-n, pos, size - 1);
290 } else {
291 dst = ultoa_o(n, dst, size);
292 }
293 return dst;
294}
295
296/*
297 * signed long long ASCII representation
298 *
299 * return the last char '\0' or NULL if no enough
300 * space in dst
301 */
302char *lltoa(long long n, char *dst, size_t size)
303{
304 char *pos = dst;
305
306 if (n < 0) {
307 if (size < 3)
308 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
309 *pos = '-';
310 pos++;
311 dst = ulltoa(-n, pos, size - 1);
312 } else {
313 dst = ulltoa(n, dst, size);
314 }
315 return dst;
316}
317
318/*
319 * write a ascii representation of a unsigned into dst,
320 * return a pointer to the last character
321 * Pad the ascii representation with '0', using size.
322 */
323char *utoa_pad(unsigned int n, char *dst, size_t size)
324{
325 int i = 0;
326 char *ret;
327
328 switch(n) {
329 case 0U ... 9U:
330 i = 0;
331 break;
332
333 case 10U ... 99U:
334 i = 1;
335 break;
336
337 case 100U ... 999U:
338 i = 2;
339 break;
340
341 case 1000U ... 9999U:
342 i = 3;
343 break;
344
345 case 10000U ... 99999U:
346 i = 4;
347 break;
348
349 case 100000U ... 999999U:
350 i = 5;
351 break;
352
353 case 1000000U ... 9999999U:
354 i = 6;
355 break;
356
357 case 10000000U ... 99999999U:
358 i = 7;
359 break;
360
361 case 100000000U ... 999999999U:
362 i = 8;
363 break;
364
365 case 1000000000U ... 4294967295U:
366 i = 9;
367 break;
368 }
369 if (i + 2 > size) // (i + 1) + '\0'
370 return NULL; // too long
371 if (i < size)
372 i = size - 2; // padding - '\0'
373
374 ret = dst + i + 1;
375 *ret = '\0';
376 for (; i >= 0; i--) {
377 dst[i] = n % 10U + '0';
378 n /= 10U;
379 }
380 return ret;
381}
382
383/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200384 * copies at most <size-1> chars from <src> to <dst>. Last char is always
385 * set to 0, unless <size> is 0. The number of chars copied is returned
386 * (excluding the terminating zero).
387 * This code has been optimized for size and speed : on x86, it's 45 bytes
388 * long, uses only registers, and consumes only 4 cycles per char.
389 */
390int strlcpy2(char *dst, const char *src, int size)
391{
392 char *orig = dst;
393 if (size) {
394 while (--size && (*dst = *src)) {
395 src++; dst++;
396 }
397 *dst = 0;
398 }
399 return dst - orig;
400}
401
402/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200403 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404 * the ascii representation for number 'n' in decimal.
405 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100406char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200407{
408 char *pos;
409
Willy Tarreau72d759c2007-10-25 12:14:10 +0200410 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200411 *pos-- = '\0';
412
413 do {
414 *pos-- = '0' + n % 10;
415 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200416 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200417 return pos + 1;
418}
419
Willy Tarreau91092e52007-10-25 16:58:42 +0200420/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200421 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200422 * the ascii representation for number 'n' in decimal.
423 */
424char *lltoa_r(long long int in, char *buffer, int size)
425{
426 char *pos;
427 int neg = 0;
428 unsigned long long int n;
429
430 pos = buffer + size - 1;
431 *pos-- = '\0';
432
433 if (in < 0) {
434 neg = 1;
435 n = -in;
436 }
437 else
438 n = in;
439
440 do {
441 *pos-- = '0' + n % 10;
442 n /= 10;
443 } while (n && pos >= buffer);
444 if (neg && pos > buffer)
445 *pos-- = '-';
446 return pos + 1;
447}
448
449/*
450 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200451 * the ascii representation for signed number 'n' in decimal.
452 */
453char *sltoa_r(long n, char *buffer, int size)
454{
455 char *pos;
456
457 if (n >= 0)
458 return ultoa_r(n, buffer, size);
459
460 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
461 *pos = '-';
462 return pos;
463}
464
465/*
466 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200467 * the ascii representation for number 'n' in decimal, formatted for
468 * HTML output with tags to create visual grouping by 3 digits. The
469 * output needs to support at least 171 characters.
470 */
471const char *ulltoh_r(unsigned long long n, char *buffer, int size)
472{
473 char *start;
474 int digit = 0;
475
476 start = buffer + size;
477 *--start = '\0';
478
479 do {
480 if (digit == 3 && start >= buffer + 7)
481 memcpy(start -= 7, "</span>", 7);
482
483 if (start >= buffer + 1) {
484 *--start = '0' + n % 10;
485 n /= 10;
486 }
487
488 if (digit == 3 && start >= buffer + 18)
489 memcpy(start -= 18, "<span class=\"rls\">", 18);
490
491 if (digit++ == 3)
492 digit = 1;
493 } while (n && start > buffer);
494 return start;
495}
496
497/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200498 * This function simply returns a locally allocated string containing the ascii
499 * representation for number 'n' in decimal, unless n is 0 in which case it
500 * returns the alternate string (or an empty string if the alternate string is
501 * NULL). It use is intended for limits reported in reports, where it's
502 * desirable not to display anything if there is no limit. Warning! it shares
503 * the same vector as ultoa_r().
504 */
505const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
506{
507 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
508}
509
Willy Tarreau588297f2014-06-16 15:16:40 +0200510/* returns a locally allocated string containing the quoted encoding of the
511 * input string. The output may be truncated to QSTR_SIZE chars, but it is
512 * guaranteed that the string will always be properly terminated. Quotes are
513 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
514 * always be at least 4 chars.
515 */
516const char *qstr(const char *str)
517{
518 char *ret = quoted_str[quoted_idx];
519 char *p, *end;
520
521 if (++quoted_idx >= NB_QSTR)
522 quoted_idx = 0;
523
524 p = ret;
525 end = ret + QSTR_SIZE;
526
527 *p++ = '"';
528
529 /* always keep 3 chars to support passing "" and the ending " */
530 while (*str && p < end - 3) {
531 if (*str == '"') {
532 *p++ = '"';
533 *p++ = '"';
534 }
535 else
536 *p++ = *str;
537 str++;
538 }
539 *p++ = '"';
540 return ret;
541}
542
Robert Tsai81ae1952007-12-05 10:47:29 +0100543/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200544 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
545 *
546 * It looks like this one would be a good candidate for inlining, but this is
547 * not interesting because it around 35 bytes long and often called multiple
548 * times within the same function.
549 */
550int ishex(char s)
551{
552 s -= '0';
553 if ((unsigned char)s <= 9)
554 return 1;
555 s -= 'A' - '0';
556 if ((unsigned char)s <= 5)
557 return 1;
558 s -= 'a' - 'A';
559 if ((unsigned char)s <= 5)
560 return 1;
561 return 0;
562}
563
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100564/* rounds <i> down to the closest value having max 2 digits */
565unsigned int round_2dig(unsigned int i)
566{
567 unsigned int mul = 1;
568
569 while (i >= 100) {
570 i /= 10;
571 mul *= 10;
572 }
573 return i * mul;
574}
575
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100576/*
577 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
578 * invalid character is found, a pointer to it is returned. If everything is
579 * fine, NULL is returned.
580 */
581const char *invalid_char(const char *name)
582{
583 if (!*name)
584 return name;
585
586 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100587 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100588 *name != '_' && *name != '-')
589 return name;
590 name++;
591 }
592 return NULL;
593}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200594
595/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200596 * Checks <name> for invalid characters. Valid chars are [_.-] and those
597 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200598 * If an invalid character is found, a pointer to it is returned.
599 * If everything is fine, NULL is returned.
600 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200601static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200602
603 if (!*name)
604 return name;
605
606 while (*name) {
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200607 if (!f((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200608 *name != '_' && *name != '-')
609 return name;
610
611 name++;
612 }
613
614 return NULL;
615}
616
617/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200618 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
619 * If an invalid character is found, a pointer to it is returned.
620 * If everything is fine, NULL is returned.
621 */
622const char *invalid_domainchar(const char *name) {
623 return __invalid_char(name, isalnum);
624}
625
626/*
627 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
628 * If an invalid character is found, a pointer to it is returned.
629 * If everything is fine, NULL is returned.
630 */
631const char *invalid_prefix_char(const char *name) {
632 return __invalid_char(name, isalpha);
633}
634
635/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100636 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100637 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
638 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
639 * the function tries to guess the address family from the syntax. If the
640 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100641 * string is assumed to contain only an address, no port. The address can be a
642 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
643 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
644 * The return address will only have the address family and the address set,
645 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100646 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
647 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100648 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200649 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100650struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200651{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100652 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100653 /* max IPv6 length, including brackets and terminating NULL */
654 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100655 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100656
657 /* check IPv6 with square brackets */
658 if (str[0] == '[') {
659 size_t iplength = strlen(str);
660
661 if (iplength < 4) {
662 /* minimal size is 4 when using brackets "[::]" */
663 goto fail;
664 }
665 else if (iplength >= sizeof(tmpip)) {
666 /* IPv6 literal can not be larger than tmpip */
667 goto fail;
668 }
669 else {
670 if (str[iplength - 1] != ']') {
671 /* if address started with bracket, it should end with bracket */
672 goto fail;
673 }
674 else {
675 memcpy(tmpip, str + 1, iplength - 2);
676 tmpip[iplength - 2] = '\0';
677 str = tmpip;
678 }
679 }
680 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100681
Willy Tarreaufab5a432011-03-04 15:31:53 +0100682 /* Any IPv6 address */
683 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100684 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
685 sa->ss_family = AF_INET6;
686 else if (sa->ss_family != AF_INET6)
687 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100688 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100689 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100690 }
691
Willy Tarreau24709282013-03-10 21:32:12 +0100692 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100693 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100694 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
695 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100696 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100697 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100698 }
699
700 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100701 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
702 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100703 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100704 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100705 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100706 }
707
708 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100709 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
710 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100711 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100712 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100713 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100714 }
715
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100716 if (!resolve)
717 return NULL;
718
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200719 if (!dns_hostname_validation(str, NULL))
720 return NULL;
721
David du Colombierd5f43282011-03-17 10:40:16 +0100722#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200723 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100724 struct addrinfo hints, *result;
725
726 memset(&result, 0, sizeof(result));
727 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100728 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100729 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200730 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100731 hints.ai_protocol = 0;
732
733 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100734 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
735 sa->ss_family = result->ai_family;
736 else if (sa->ss_family != result->ai_family)
737 goto fail;
738
David du Colombierd5f43282011-03-17 10:40:16 +0100739 switch (result->ai_family) {
740 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100741 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100742 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100743 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100744 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100745 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100746 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100747 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100748 }
749 }
750
Sean Carey58ea0392013-02-15 23:39:18 +0100751 if (result)
752 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100753 }
David du Colombierd5f43282011-03-17 10:40:16 +0100754#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200755 /* try to resolve an IPv4/IPv6 hostname */
756 he = gethostbyname(str);
757 if (he) {
758 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
759 sa->ss_family = he->h_addrtype;
760 else if (sa->ss_family != he->h_addrtype)
761 goto fail;
762
763 switch (sa->ss_family) {
764 case AF_INET:
765 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100766 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200767 return sa;
768 case AF_INET6:
769 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100770 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200771 return sa;
772 }
773 }
774
David du Colombierd5f43282011-03-17 10:40:16 +0100775 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100776 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100777 return NULL;
778}
779
780/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100781 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
782 * range or offset consisting in two integers that the caller will have to
783 * check to find the relevant input format. The following format are supported :
784 *
785 * String format | address | port | low | high
786 * addr | <addr> | 0 | 0 | 0
787 * addr: | <addr> | 0 | 0 | 0
788 * addr:port | <addr> | <port> | <port> | <port>
789 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
790 * addr:+port | <addr> | <port> | 0 | <port>
791 * addr:-port | <addr> |-<port> | <port> | 0
792 *
793 * The detection of a port range or increment by the caller is made by
794 * comparing <low> and <high>. If both are equal, then port 0 means no port
795 * was specified. The caller may pass NULL for <low> and <high> if it is not
796 * interested in retrieving port ranges.
797 *
798 * Note that <addr> above may also be :
799 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
800 * - "*" => family will be AF_INET and address will be INADDR_ANY
801 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
802 * - a host name => family and address will depend on host name resolving.
803 *
Willy Tarreau24709282013-03-10 21:32:12 +0100804 * A prefix may be passed in before the address above to force the family :
805 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
806 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
807 * - "unix@" => force address to be a path to a UNIX socket even if the
808 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200809 * - 'abns@' -> force address to belong to the abstract namespace (Linux
810 * only). These sockets are just like Unix sockets but without
811 * the need for an underlying file system. The address is a
812 * string. Technically it's like a Unix socket with a zero in
813 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100814 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100815 *
mildisff5d5102015-10-26 18:50:08 +0100816 * IPv6 addresses can be declared with or without square brackets. When using
817 * square brackets for IPv6 addresses, the port separator (colon) is optional.
818 * If not using square brackets, and in order to avoid any ambiguity with
819 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
820 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
821 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100822 *
823 * If <pfx> is non-null, it is used as a string prefix before any path-based
824 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100825 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200826 * if <fqdn> is non-null, it will be filled with :
827 * - a pointer to the FQDN of the server name to resolve if there's one, and
828 * that the caller will have to free(),
829 * - NULL if there was an explicit address that doesn't require resolution.
830 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100831 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
832 * is null, <fqdn> is still honnored so it is possible for the caller to know
833 * whether a resolution failed by setting <resolve> to null and checking if
834 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200835 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100836 * When a file descriptor is passed, its value is put into the s_addr part of
837 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100838 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100839struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100840{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100841 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100842 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100843 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100844 char *port1, *port2;
845 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200846 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100847
848 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200849 if (fqdn)
850 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200851
Willy Tarreaudad36a32013-03-11 01:20:04 +0100852 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100853 if (str2 == NULL) {
854 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100855 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100856 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200857
Willy Tarreau9f69f462015-09-08 16:01:25 +0200858 if (!*str2) {
859 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
860 goto out;
861 }
862
Willy Tarreau24709282013-03-10 21:32:12 +0100863 memset(&ss, 0, sizeof(ss));
864
865 if (strncmp(str2, "unix@", 5) == 0) {
866 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200867 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100868 ss.ss_family = AF_UNIX;
869 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200870 else if (strncmp(str2, "abns@", 5) == 0) {
871 str2 += 5;
872 abstract = 1;
873 ss.ss_family = AF_UNIX;
874 }
Willy Tarreau24709282013-03-10 21:32:12 +0100875 else if (strncmp(str2, "ipv4@", 5) == 0) {
876 str2 += 5;
877 ss.ss_family = AF_INET;
878 }
879 else if (strncmp(str2, "ipv6@", 5) == 0) {
880 str2 += 5;
881 ss.ss_family = AF_INET6;
882 }
883 else if (*str2 == '/') {
884 ss.ss_family = AF_UNIX;
885 }
886 else
887 ss.ss_family = AF_UNSPEC;
888
Willy Tarreau40aa0702013-03-10 23:51:38 +0100889 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
890 char *endptr;
891
892 str2 += 3;
893 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
894
895 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100896 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100897 goto out;
898 }
899
900 /* we return AF_UNSPEC if we use a file descriptor number */
901 ss.ss_family = AF_UNSPEC;
902 }
903 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100904 int prefix_path_len;
905 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200906 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100907
908 /* complete unix socket path name during startup or soft-restart is
909 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
910 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200911 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100912 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
913 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
914
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200915 adr_len = strlen(str2);
916 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100917 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
918 goto out;
919 }
920
Willy Tarreauccfccef2014-05-10 01:49:15 +0200921 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
922 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200923 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100924 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200925 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100926 }
Willy Tarreau24709282013-03-10 21:32:12 +0100927 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100928 char *end = str2 + strlen(str2);
929 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200930
mildisff5d5102015-10-26 18:50:08 +0100931 /* search for : or ] whatever comes first */
932 for (chr = end-1; chr > str2; chr--) {
933 if (*chr == ']' || *chr == ':')
934 break;
935 }
936
937 if (*chr == ':') {
938 /* Found a colon before a closing-bracket, must be a port separator.
939 * This guarantee backward compatibility.
940 */
941 *chr++ = '\0';
942 port1 = chr;
943 }
944 else {
945 /* Either no colon and no closing-bracket
946 * or directly ending with a closing-bracket.
947 * However, no port.
948 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100949 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100950 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200951
Willy Tarreaua39d1992013-04-01 20:37:42 +0200952 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100953 port2 = strchr(port1, '-');
954 if (port2)
955 *port2++ = '\0';
956 else
957 port2 = port1;
958 portl = atoi(port1);
959 porth = atoi(port2);
960 porta = portl;
961 }
962 else if (*port1 == '-') { /* negative offset */
963 portl = atoi(port1 + 1);
964 porta = -portl;
965 }
966 else if (*port1 == '+') { /* positive offset */
967 porth = atoi(port1 + 1);
968 porta = porth;
969 }
970 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100971 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100972 goto out;
973 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100974
975 /* first try to parse the IP without resolving. If it fails, it
976 * tells us we need to keep a copy of the FQDN to resolve later
977 * and to enable DNS. In this case we can proceed if <fqdn> is
978 * set or if resolve is set, otherwise it's an error.
979 */
980 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +0100981 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +0100982 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
983 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
984 goto out;
985 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200986
Willy Tarreauceccdd72016-11-02 22:27:10 +0100987 if (fqdn) {
988 if (str2 != back)
989 memmove(back, str2, strlen(str2) + 1);
990 *fqdn = back;
991 back = NULL;
992 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200993 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100994 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100995 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100996
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100997 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100998 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100999 if (port)
1000 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001001 if (low)
1002 *low = portl;
1003 if (high)
1004 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001005 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001006 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001007}
1008
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001009/* converts <str> to a struct in_addr containing a network mask. It can be
1010 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001011 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001012 */
1013int str2mask(const char *str, struct in_addr *mask)
1014{
1015 if (strchr(str, '.') != NULL) { /* dotted notation */
1016 if (!inet_pton(AF_INET, str, mask))
1017 return 0;
1018 }
1019 else { /* mask length */
1020 char *err;
1021 unsigned long len = strtol(str, &err, 10);
1022
1023 if (!*str || (err && *err) || (unsigned)len > 32)
1024 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001025
1026 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001027 }
1028 return 1;
1029}
1030
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001031/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1032 * succeeds otherwise zero.
1033 */
1034int cidr2dotted(int cidr, struct in_addr *mask) {
1035
1036 if (cidr < 0 || cidr > 32)
1037 return 0;
1038
1039 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1040 return 1;
1041}
1042
Thierry Fournier70473a52016-02-17 17:12:14 +01001043/* Convert mask from bit length form to in_addr form.
1044 * This function never fails.
1045 */
1046void len2mask4(int len, struct in_addr *addr)
1047{
1048 if (len >= 32) {
1049 addr->s_addr = 0xffffffff;
1050 return;
1051 }
1052 if (len <= 0) {
1053 addr->s_addr = 0x00000000;
1054 return;
1055 }
1056 addr->s_addr = 0xffffffff << (32 - len);
1057 addr->s_addr = htonl(addr->s_addr);
1058}
1059
1060/* Convert mask from bit length form to in6_addr form.
1061 * This function never fails.
1062 */
1063void len2mask6(int len, struct in6_addr *addr)
1064{
1065 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1066 len -= 32;
1067 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1068 len -= 32;
1069 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1070 len -= 32;
1071 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1072}
1073
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001074/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001075 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001076 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1077 * is optionnal and either in the dotted or CIDR notation.
1078 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1079 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001080int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001081{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001082 __label__ out_free, out_err;
1083 char *c, *s;
1084 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001085
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001086 s = strdup(str);
1087 if (!s)
1088 return 0;
1089
Willy Tarreaubaaee002006-06-26 02:48:02 +02001090 memset(mask, 0, sizeof(*mask));
1091 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001092
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001093 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001094 *c++ = '\0';
1095 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001096 if (!str2mask(c, mask))
1097 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001098 }
1099 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001100 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001101 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001102 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001103 struct hostent *he;
1104
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001105 if (!resolve)
1106 goto out_err;
1107
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001108 if ((he = gethostbyname(s)) == NULL) {
1109 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001110 }
1111 else
1112 *addr = *(struct in_addr *) *(he->h_addr_list);
1113 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001114
1115 ret_val = 1;
1116 out_free:
1117 free(s);
1118 return ret_val;
1119 out_err:
1120 ret_val = 0;
1121 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001122}
1123
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001124
1125/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001126 * converts <str> to two struct in6_addr* which must be pre-allocated.
1127 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1128 * is an optionnal number of bits (128 being the default).
1129 * Returns 1 if OK, 0 if error.
1130 */
1131int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1132{
1133 char *c, *s;
1134 int ret_val = 0;
1135 char *err;
1136 unsigned long len = 128;
1137
1138 s = strdup(str);
1139 if (!s)
1140 return 0;
1141
1142 memset(mask, 0, sizeof(*mask));
1143 memset(addr, 0, sizeof(*addr));
1144
1145 if ((c = strrchr(s, '/')) != NULL) {
1146 *c++ = '\0'; /* c points to the mask */
1147 if (!*c)
1148 goto out_free;
1149
1150 len = strtoul(c, &err, 10);
1151 if ((err && *err) || (unsigned)len > 128)
1152 goto out_free;
1153 }
1154 *mask = len; /* OK we have a valid mask in <len> */
1155
1156 if (!inet_pton(AF_INET6, s, addr))
1157 goto out_free;
1158
1159 ret_val = 1;
1160 out_free:
1161 free(s);
1162 return ret_val;
1163}
1164
1165
1166/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001167 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001168 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001169int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001170{
1171 int saw_digit, octets, ch;
1172 u_char tmp[4], *tp;
1173 const char *cp = addr;
1174
1175 saw_digit = 0;
1176 octets = 0;
1177 *(tp = tmp) = 0;
1178
1179 while (*addr) {
1180 unsigned char digit = (ch = *addr++) - '0';
1181 if (digit > 9 && ch != '.')
1182 break;
1183 if (digit <= 9) {
1184 u_int new = *tp * 10 + digit;
1185 if (new > 255)
1186 return 0;
1187 *tp = new;
1188 if (!saw_digit) {
1189 if (++octets > 4)
1190 return 0;
1191 saw_digit = 1;
1192 }
1193 } else if (ch == '.' && saw_digit) {
1194 if (octets == 4)
1195 return 0;
1196 *++tp = 0;
1197 saw_digit = 0;
1198 } else
1199 return 0;
1200 }
1201
1202 if (octets < 4)
1203 return 0;
1204
1205 memcpy(&dst->s_addr, tmp, 4);
1206 return addr-cp-1;
1207}
1208
1209/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001210 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1211 * <out> contain the code of the dectected scheme, the start and length of
1212 * the hostname. Actually only http and https are supported. <out> can be NULL.
1213 * This function returns the consumed length. It is useful if you parse complete
1214 * url like http://host:port/path, because the consumed length corresponds to
1215 * the first character of the path. If the conversion fails, it returns -1.
1216 *
1217 * This function tries to resolve the DNS name if haproxy is in starting mode.
1218 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001219 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001220int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001221{
1222 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001223 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001224 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001225 unsigned long long int http_code = 0;
1226 int default_port;
1227 struct hostent *he;
1228 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001229
1230 /* Firstly, try to find :// pattern */
1231 while (curr < url+ulen && url_code != 0x3a2f2f) {
1232 url_code = ((url_code & 0xffff) << 8);
1233 url_code += (unsigned char)*curr++;
1234 }
1235
1236 /* Secondly, if :// pattern is found, verify parsed stuff
1237 * before pattern is matching our http pattern.
1238 * If so parse ip address and port in uri.
1239 *
1240 * WARNING: Current code doesn't support dynamic async dns resolver.
1241 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001242 if (url_code != 0x3a2f2f)
1243 return -1;
1244
1245 /* Copy scheme, and utrn to lower case. */
1246 while (cp < curr - 3)
1247 http_code = (http_code << 8) + *cp++;
1248 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001249
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001250 /* HTTP or HTTPS url matching */
1251 if (http_code == 0x2020202068747470ULL) {
1252 default_port = 80;
1253 if (out)
1254 out->scheme = SCH_HTTP;
1255 }
1256 else if (http_code == 0x2020206874747073ULL) {
1257 default_port = 443;
1258 if (out)
1259 out->scheme = SCH_HTTPS;
1260 }
1261 else
1262 return -1;
1263
1264 /* If the next char is '[', the host address is IPv6. */
1265 if (*curr == '[') {
1266 curr++;
1267
1268 /* Check trash size */
1269 if (trash.size < ulen)
1270 return -1;
1271
1272 /* Look for ']' and copy the address in a trash buffer. */
1273 p = trash.str;
1274 for (end = curr;
1275 end < url + ulen && *end != ']';
1276 end++, p++)
1277 *p = *end;
1278 if (*end != ']')
1279 return -1;
1280 *p = '\0';
1281
1282 /* Update out. */
1283 if (out) {
1284 out->host = curr;
1285 out->host_len = end - curr;
1286 }
1287
1288 /* Try IPv6 decoding. */
1289 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1290 return -1;
1291 end++;
1292
1293 /* Decode port. */
1294 if (*end == ':') {
1295 end++;
1296 default_port = read_uint(&end, url + ulen);
1297 }
1298 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1299 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1300 return end - url;
1301 }
1302 else {
1303 /* We are looking for IP address. If you want to parse and
1304 * resolve hostname found in url, you can use str2sa_range(), but
1305 * be warned this can slow down global daemon performances
1306 * while handling lagging dns responses.
1307 */
1308 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1309 if (ret) {
1310 /* Update out. */
1311 if (out) {
1312 out->host = curr;
1313 out->host_len = ret;
1314 }
1315
1316 curr += ret;
1317
1318 /* Decode port. */
1319 if (*curr == ':') {
1320 curr++;
1321 default_port = read_uint(&curr, url + ulen);
1322 }
1323 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1324
1325 /* Set family. */
1326 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1327 return curr - url;
1328 }
1329 else if (global.mode & MODE_STARTING) {
1330 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1331 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001332 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001333
1334 /* look for : or / or end */
1335 for (end = curr;
1336 end < url + ulen && *end != '/' && *end != ':';
1337 end++);
1338 memcpy(trash.str, curr, end - curr);
1339 trash.str[end - curr] = '\0';
1340
1341 /* try to resolve an IPv4/IPv6 hostname */
1342 he = gethostbyname(trash.str);
1343 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001344 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001345
1346 /* Update out. */
1347 if (out) {
1348 out->host = curr;
1349 out->host_len = end - curr;
1350 }
1351
1352 /* Decode port. */
1353 if (*end == ':') {
1354 end++;
1355 default_port = read_uint(&end, url + ulen);
1356 }
1357
1358 /* Copy IP address, set port and family. */
1359 switch (he->h_addrtype) {
1360 case AF_INET:
1361 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1362 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1363 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1364 return end - url;
1365
1366 case AF_INET6:
1367 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1368 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1369 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1370 return end - url;
1371 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001372 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001373 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001374 return -1;
1375}
1376
Willy Tarreau631f01c2011-09-05 00:36:48 +02001377/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1378 * address family is returned so that it's easy for the caller to adapt to the
1379 * output format. Zero is returned if the address family is not supported. -1
1380 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1381 * supported.
1382 */
1383int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1384{
1385
1386 void *ptr;
1387
1388 if (size < 5)
1389 return 0;
1390 *str = '\0';
1391
1392 switch (addr->ss_family) {
1393 case AF_INET:
1394 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1395 break;
1396 case AF_INET6:
1397 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1398 break;
1399 case AF_UNIX:
1400 memcpy(str, "unix", 5);
1401 return addr->ss_family;
1402 default:
1403 return 0;
1404 }
1405
1406 if (inet_ntop(addr->ss_family, ptr, str, size))
1407 return addr->ss_family;
1408
1409 /* failed */
1410 return -1;
1411}
1412
Simon Horman75ab8bd2014-06-16 09:39:41 +09001413/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1414 * address family is returned so that it's easy for the caller to adapt to the
1415 * output format. Zero is returned if the address family is not supported. -1
1416 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1417 * supported.
1418 */
1419int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1420{
1421
1422 uint16_t port;
1423
1424
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001425 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001426 return 0;
1427 *str = '\0';
1428
1429 switch (addr->ss_family) {
1430 case AF_INET:
1431 port = ((struct sockaddr_in *)addr)->sin_port;
1432 break;
1433 case AF_INET6:
1434 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1435 break;
1436 case AF_UNIX:
1437 memcpy(str, "unix", 5);
1438 return addr->ss_family;
1439 default:
1440 return 0;
1441 }
1442
1443 snprintf(str, size, "%u", ntohs(port));
1444 return addr->ss_family;
1445}
1446
Willy Tarreau16e01562016-08-09 16:46:18 +02001447/* check if the given address is local to the system or not. It will return
1448 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1449 * it is. We don't want to iterate over all interfaces for this (and it is not
1450 * portable). So instead we try to bind in UDP to this address on a free non
1451 * privileged port and to connect to the same address, port 0 (connect doesn't
1452 * care). If it succeeds, we own the address. Note that non-inet addresses are
1453 * considered local since they're most likely AF_UNIX.
1454 */
1455int addr_is_local(const struct netns_entry *ns,
1456 const struct sockaddr_storage *orig)
1457{
1458 struct sockaddr_storage addr;
1459 int result;
1460 int fd;
1461
1462 if (!is_inet_addr(orig))
1463 return 1;
1464
1465 memcpy(&addr, orig, sizeof(addr));
1466 set_host_port(&addr, 0);
1467
1468 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1469 if (fd < 0)
1470 return -1;
1471
1472 result = -1;
1473 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1474 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1475 result = 0; // fail, non-local address
1476 else
1477 result = 1; // success, local address
1478 }
1479 else {
1480 if (errno == EADDRNOTAVAIL)
1481 result = 0; // definitely not local :-)
1482 }
1483 close(fd);
1484
1485 return result;
1486}
1487
Willy Tarreaubaaee002006-06-26 02:48:02 +02001488/* will try to encode the string <string> replacing all characters tagged in
1489 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1490 * prefixed by <escape>, and will store the result between <start> (included)
1491 * and <stop> (excluded), and will always terminate the string with a '\0'
1492 * before <stop>. The position of the '\0' is returned if the conversion
1493 * completes. If bytes are missing between <start> and <stop>, then the
1494 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1495 * cannot even be stored so we return <start> without writing the 0.
1496 * The input string must also be zero-terminated.
1497 */
1498const char hextab[16] = "0123456789ABCDEF";
1499char *encode_string(char *start, char *stop,
1500 const char escape, const fd_set *map,
1501 const char *string)
1502{
1503 if (start < stop) {
1504 stop--; /* reserve one byte for the final '\0' */
1505 while (start < stop && *string != '\0') {
1506 if (!FD_ISSET((unsigned char)(*string), map))
1507 *start++ = *string;
1508 else {
1509 if (start + 3 >= stop)
1510 break;
1511 *start++ = escape;
1512 *start++ = hextab[(*string >> 4) & 15];
1513 *start++ = hextab[*string & 15];
1514 }
1515 string++;
1516 }
1517 *start = '\0';
1518 }
1519 return start;
1520}
1521
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001522/*
1523 * Same behavior as encode_string() above, except that it encodes chunk
1524 * <chunk> instead of a string.
1525 */
1526char *encode_chunk(char *start, char *stop,
1527 const char escape, const fd_set *map,
1528 const struct chunk *chunk)
1529{
1530 char *str = chunk->str;
1531 char *end = chunk->str + chunk->len;
1532
1533 if (start < stop) {
1534 stop--; /* reserve one byte for the final '\0' */
1535 while (start < stop && str < end) {
1536 if (!FD_ISSET((unsigned char)(*str), map))
1537 *start++ = *str;
1538 else {
1539 if (start + 3 >= stop)
1540 break;
1541 *start++ = escape;
1542 *start++ = hextab[(*str >> 4) & 15];
1543 *start++ = hextab[*str & 15];
1544 }
1545 str++;
1546 }
1547 *start = '\0';
1548 }
1549 return start;
1550}
1551
Dragan Dosen0edd1092016-02-12 13:23:02 +01001552/*
1553 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001554 * character. The input <string> must be zero-terminated. The result will
1555 * be stored between <start> (included) and <stop> (excluded). This
1556 * function will always try to terminate the resulting string with a '\0'
1557 * before <stop>, and will return its position if the conversion
1558 * completes.
1559 */
1560char *escape_string(char *start, char *stop,
1561 const char escape, const fd_set *map,
1562 const char *string)
1563{
1564 if (start < stop) {
1565 stop--; /* reserve one byte for the final '\0' */
1566 while (start < stop && *string != '\0') {
1567 if (!FD_ISSET((unsigned char)(*string), map))
1568 *start++ = *string;
1569 else {
1570 if (start + 2 >= stop)
1571 break;
1572 *start++ = escape;
1573 *start++ = *string;
1574 }
1575 string++;
1576 }
1577 *start = '\0';
1578 }
1579 return start;
1580}
1581
1582/*
1583 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001584 * character. <chunk> contains the input to be escaped. The result will be
1585 * stored between <start> (included) and <stop> (excluded). The function
1586 * will always try to terminate the resulting string with a '\0' before
1587 * <stop>, and will return its position if the conversion completes.
1588 */
1589char *escape_chunk(char *start, char *stop,
1590 const char escape, const fd_set *map,
1591 const struct chunk *chunk)
1592{
1593 char *str = chunk->str;
1594 char *end = chunk->str + chunk->len;
1595
1596 if (start < stop) {
1597 stop--; /* reserve one byte for the final '\0' */
1598 while (start < stop && str < end) {
1599 if (!FD_ISSET((unsigned char)(*str), map))
1600 *start++ = *str;
1601 else {
1602 if (start + 2 >= stop)
1603 break;
1604 *start++ = escape;
1605 *start++ = *str;
1606 }
1607 str++;
1608 }
1609 *start = '\0';
1610 }
1611 return start;
1612}
1613
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001614/* Check a string for using it in a CSV output format. If the string contains
1615 * one of the following four char <">, <,>, CR or LF, the string is
1616 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1617 * <str> is the input string to be escaped. The function assumes that
1618 * the input string is null-terminated.
1619 *
1620 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001621 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001622 * format.
1623 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001624 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001625 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001626 * If <quote> is 1, the converter puts the quotes only if any reserved character
1627 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001628 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001629 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001630 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001631 * The function returns the converted string on its output. If an error
1632 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001633 * for using the function directly as printf() argument.
1634 *
1635 * If the output buffer is too short to contain the input string, the result
1636 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001637 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001638 * This function appends the encoding to the existing output chunk, and it
1639 * guarantees that it starts immediately at the first available character of
1640 * the chunk. Please use csv_enc() instead if you want to replace the output
1641 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001642 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001643const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001644{
1645 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001646 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001647 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001648
Willy Tarreaub631c292016-01-08 10:04:08 +01001649 if (quote == 1) {
1650 /* automatic quoting: first verify if we'll have to quote the string */
1651 if (!strpbrk(str, "\n\r,\""))
1652 quote = 0;
1653 }
1654
1655 if (quote)
1656 *ptr++ = '"';
1657
Willy Tarreau898529b2016-01-06 18:07:04 +01001658 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1659 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001660 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001661 ptr++;
1662 if (ptr >= end - 2) {
1663 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001664 break;
1665 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001666 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001667 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001668 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001669 str++;
1670 }
1671
Willy Tarreaub631c292016-01-08 10:04:08 +01001672 if (quote)
1673 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001674
Willy Tarreau898529b2016-01-06 18:07:04 +01001675 *ptr = '\0';
1676 output->len = ptr - output->str;
1677 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001678}
1679
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001680/* Decode an URL-encoded string in-place. The resulting string might
1681 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001682 * aborted, the string is truncated before the issue and a negative value is
1683 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001684 */
1685int url_decode(char *string)
1686{
1687 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001688 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001689
1690 in = string;
1691 out = string;
1692 while (*in) {
1693 switch (*in) {
1694 case '+' :
1695 *out++ = ' ';
1696 break;
1697 case '%' :
1698 if (!ishex(in[1]) || !ishex(in[2]))
1699 goto end;
1700 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1701 in += 2;
1702 break;
1703 default:
1704 *out++ = *in;
1705 break;
1706 }
1707 in++;
1708 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001709 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001710 end:
1711 *out = 0;
1712 return ret;
1713}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001714
Willy Tarreau6911fa42007-03-04 18:06:08 +01001715unsigned int str2ui(const char *s)
1716{
1717 return __str2ui(s);
1718}
1719
1720unsigned int str2uic(const char *s)
1721{
1722 return __str2uic(s);
1723}
1724
1725unsigned int strl2ui(const char *s, int len)
1726{
1727 return __strl2ui(s, len);
1728}
1729
1730unsigned int strl2uic(const char *s, int len)
1731{
1732 return __strl2uic(s, len);
1733}
1734
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001735unsigned int read_uint(const char **s, const char *end)
1736{
1737 return __read_uint(s, end);
1738}
1739
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001740/* This function reads an unsigned integer from the string pointed to by <s> and
1741 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1742 * function automatically stops at <end>. If the number overflows, the 2^64-1
1743 * value is returned.
1744 */
1745unsigned long long int read_uint64(const char **s, const char *end)
1746{
1747 const char *ptr = *s;
1748 unsigned long long int i = 0, tmp;
1749 unsigned int j;
1750
1751 while (ptr < end) {
1752
1753 /* read next char */
1754 j = *ptr - '0';
1755 if (j > 9)
1756 goto read_uint64_end;
1757
1758 /* add char to the number and check overflow. */
1759 tmp = i * 10;
1760 if (tmp / 10 != i) {
1761 i = ULLONG_MAX;
1762 goto read_uint64_eat;
1763 }
1764 if (ULLONG_MAX - tmp < j) {
1765 i = ULLONG_MAX;
1766 goto read_uint64_eat;
1767 }
1768 i = tmp + j;
1769 ptr++;
1770 }
1771read_uint64_eat:
1772 /* eat each numeric char */
1773 while (ptr < end) {
1774 if ((unsigned int)(*ptr - '0') > 9)
1775 break;
1776 ptr++;
1777 }
1778read_uint64_end:
1779 *s = ptr;
1780 return i;
1781}
1782
1783/* This function reads an integer from the string pointed to by <s> and returns
1784 * it. The <s> pointer is adjusted to point to the first unread char. The function
1785 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1786 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1787 * returned.
1788 */
1789long long int read_int64(const char **s, const char *end)
1790{
1791 unsigned long long int i = 0;
1792 int neg = 0;
1793
1794 /* Look for minus char. */
1795 if (**s == '-') {
1796 neg = 1;
1797 (*s)++;
1798 }
1799 else if (**s == '+')
1800 (*s)++;
1801
1802 /* convert as positive number. */
1803 i = read_uint64(s, end);
1804
1805 if (neg) {
1806 if (i > 0x8000000000000000ULL)
1807 return LLONG_MIN;
1808 return -i;
1809 }
1810 if (i > 0x7fffffffffffffffULL)
1811 return LLONG_MAX;
1812 return i;
1813}
1814
Willy Tarreau6911fa42007-03-04 18:06:08 +01001815/* This one is 7 times faster than strtol() on athlon with checks.
1816 * It returns the value of the number composed of all valid digits read,
1817 * and can process negative numbers too.
1818 */
1819int strl2ic(const char *s, int len)
1820{
1821 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001822 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001823
1824 if (len > 0) {
1825 if (*s != '-') {
1826 /* positive number */
1827 while (len-- > 0) {
1828 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001829 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001830 if (j > 9)
1831 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001832 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001833 }
1834 } else {
1835 /* negative number */
1836 s++;
1837 while (--len > 0) {
1838 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001839 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001840 if (j > 9)
1841 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001842 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001843 }
1844 }
1845 }
1846 return i;
1847}
1848
1849
1850/* This function reads exactly <len> chars from <s> and converts them to a
1851 * signed integer which it stores into <ret>. It accurately detects any error
1852 * (truncated string, invalid chars, overflows). It is meant to be used in
1853 * applications designed for hostile environments. It returns zero when the
1854 * number has successfully been converted, non-zero otherwise. When an error
1855 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1856 * faster than strtol().
1857 */
1858int strl2irc(const char *s, int len, int *ret)
1859{
1860 int i = 0;
1861 int j;
1862
1863 if (!len)
1864 return 1;
1865
1866 if (*s != '-') {
1867 /* positive number */
1868 while (len-- > 0) {
1869 j = (*s++) - '0';
1870 if (j > 9) return 1; /* invalid char */
1871 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1872 i = i * 10;
1873 if (i + j < i) return 1; /* check for addition overflow */
1874 i = i + j;
1875 }
1876 } else {
1877 /* negative number */
1878 s++;
1879 while (--len > 0) {
1880 j = (*s++) - '0';
1881 if (j > 9) return 1; /* invalid char */
1882 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1883 i = i * 10;
1884 if (i - j > i) return 1; /* check for subtract overflow */
1885 i = i - j;
1886 }
1887 }
1888 *ret = i;
1889 return 0;
1890}
1891
1892
1893/* This function reads exactly <len> chars from <s> and converts them to a
1894 * signed integer which it stores into <ret>. It accurately detects any error
1895 * (truncated string, invalid chars, overflows). It is meant to be used in
1896 * applications designed for hostile environments. It returns zero when the
1897 * number has successfully been converted, non-zero otherwise. When an error
1898 * is returned, the <ret> value is left untouched. It is about 3 times slower
1899 * than str2irc().
1900 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001901
1902int strl2llrc(const char *s, int len, long long *ret)
1903{
1904 long long i = 0;
1905 int j;
1906
1907 if (!len)
1908 return 1;
1909
1910 if (*s != '-') {
1911 /* positive number */
1912 while (len-- > 0) {
1913 j = (*s++) - '0';
1914 if (j > 9) return 1; /* invalid char */
1915 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1916 i = i * 10LL;
1917 if (i + j < i) return 1; /* check for addition overflow */
1918 i = i + j;
1919 }
1920 } else {
1921 /* negative number */
1922 s++;
1923 while (--len > 0) {
1924 j = (*s++) - '0';
1925 if (j > 9) return 1; /* invalid char */
1926 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1927 i = i * 10LL;
1928 if (i - j > i) return 1; /* check for subtract overflow */
1929 i = i - j;
1930 }
1931 }
1932 *ret = i;
1933 return 0;
1934}
1935
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001936/* This function is used with pat_parse_dotted_ver(). It converts a string
1937 * composed by two number separated by a dot. Each part must contain in 16 bits
1938 * because internally they will be represented as a 32-bit quantity stored in
1939 * a 64-bit integer. It returns zero when the number has successfully been
1940 * converted, non-zero otherwise. When an error is returned, the <ret> value
1941 * is left untouched.
1942 *
1943 * "1.3" -> 0x0000000000010003
1944 * "65535.65535" -> 0x00000000ffffffff
1945 */
1946int strl2llrc_dotted(const char *text, int len, long long *ret)
1947{
1948 const char *end = &text[len];
1949 const char *p;
1950 long long major, minor;
1951
1952 /* Look for dot. */
1953 for (p = text; p < end; p++)
1954 if (*p == '.')
1955 break;
1956
1957 /* Convert major. */
1958 if (strl2llrc(text, p - text, &major) != 0)
1959 return 1;
1960
1961 /* Check major. */
1962 if (major >= 65536)
1963 return 1;
1964
1965 /* Convert minor. */
1966 minor = 0;
1967 if (p < end)
1968 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1969 return 1;
1970
1971 /* Check minor. */
1972 if (minor >= 65536)
1973 return 1;
1974
1975 /* Compose value. */
1976 *ret = (major << 16) | (minor & 0xffff);
1977 return 0;
1978}
1979
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001980/* This function parses a time value optionally followed by a unit suffix among
1981 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1982 * expected by the caller. The computation does its best to avoid overflows.
1983 * The value is returned in <ret> if everything is fine, and a NULL is returned
1984 * by the function. In case of error, a pointer to the error is returned and
1985 * <ret> is left untouched. Values are automatically rounded up when needed.
1986 */
1987const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1988{
1989 unsigned imult, idiv;
1990 unsigned omult, odiv;
1991 unsigned value;
1992
1993 omult = odiv = 1;
1994
1995 switch (unit_flags & TIME_UNIT_MASK) {
1996 case TIME_UNIT_US: omult = 1000000; break;
1997 case TIME_UNIT_MS: omult = 1000; break;
1998 case TIME_UNIT_S: break;
1999 case TIME_UNIT_MIN: odiv = 60; break;
2000 case TIME_UNIT_HOUR: odiv = 3600; break;
2001 case TIME_UNIT_DAY: odiv = 86400; break;
2002 default: break;
2003 }
2004
2005 value = 0;
2006
2007 while (1) {
2008 unsigned int j;
2009
2010 j = *text - '0';
2011 if (j > 9)
2012 break;
2013 text++;
2014 value *= 10;
2015 value += j;
2016 }
2017
2018 imult = idiv = 1;
2019 switch (*text) {
2020 case '\0': /* no unit = default unit */
2021 imult = omult = idiv = odiv = 1;
2022 break;
2023 case 's': /* second = unscaled unit */
2024 break;
2025 case 'u': /* microsecond : "us" */
2026 if (text[1] == 's') {
2027 idiv = 1000000;
2028 text++;
2029 }
2030 break;
2031 case 'm': /* millisecond : "ms" or minute: "m" */
2032 if (text[1] == 's') {
2033 idiv = 1000;
2034 text++;
2035 } else
2036 imult = 60;
2037 break;
2038 case 'h': /* hour : "h" */
2039 imult = 3600;
2040 break;
2041 case 'd': /* day : "d" */
2042 imult = 86400;
2043 break;
2044 default:
2045 return text;
2046 break;
2047 }
2048
2049 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2050 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2051 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2052 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2053
2054 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2055 *ret = value;
2056 return NULL;
2057}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002058
Emeric Brun39132b22010-01-04 14:57:24 +01002059/* this function converts the string starting at <text> to an unsigned int
2060 * stored in <ret>. If an error is detected, the pointer to the unexpected
2061 * character is returned. If the conversio is succesful, NULL is returned.
2062 */
2063const char *parse_size_err(const char *text, unsigned *ret) {
2064 unsigned value = 0;
2065
2066 while (1) {
2067 unsigned int j;
2068
2069 j = *text - '0';
2070 if (j > 9)
2071 break;
2072 if (value > ~0U / 10)
2073 return text;
2074 value *= 10;
2075 if (value > (value + j))
2076 return text;
2077 value += j;
2078 text++;
2079 }
2080
2081 switch (*text) {
2082 case '\0':
2083 break;
2084 case 'K':
2085 case 'k':
2086 if (value > ~0U >> 10)
2087 return text;
2088 value = value << 10;
2089 break;
2090 case 'M':
2091 case 'm':
2092 if (value > ~0U >> 20)
2093 return text;
2094 value = value << 20;
2095 break;
2096 case 'G':
2097 case 'g':
2098 if (value > ~0U >> 30)
2099 return text;
2100 value = value << 30;
2101 break;
2102 default:
2103 return text;
2104 }
2105
Godbach58048a22015-01-28 17:36:16 +08002106 if (*text != '\0' && *++text != '\0')
2107 return text;
2108
Emeric Brun39132b22010-01-04 14:57:24 +01002109 *ret = value;
2110 return NULL;
2111}
2112
Willy Tarreau126d4062013-12-03 17:50:47 +01002113/*
2114 * Parse binary string written in hexadecimal (source) and store the decoded
2115 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2116 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002117 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002118 */
2119int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2120{
2121 int len;
2122 const char *p = source;
2123 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002124 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002125
2126 len = strlen(source);
2127 if (len % 2) {
2128 memprintf(err, "an even number of hex digit is expected");
2129 return 0;
2130 }
2131
2132 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002133
Willy Tarreau126d4062013-12-03 17:50:47 +01002134 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002135 *binstr = calloc(len, sizeof(char));
2136 if (!*binstr) {
2137 memprintf(err, "out of memory while loading string pattern");
2138 return 0;
2139 }
2140 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002141 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002142 else {
2143 if (*binstrlen < len) {
2144 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2145 len, *binstrlen);
2146 return 0;
2147 }
2148 alloc = 0;
2149 }
2150 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002151
2152 i = j = 0;
2153 while (j < len) {
2154 if (!ishex(p[i++]))
2155 goto bad_input;
2156 if (!ishex(p[i++]))
2157 goto bad_input;
2158 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2159 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002160 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002161
2162bad_input:
2163 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002164 if (alloc) {
2165 free(*binstr);
2166 *binstr = NULL;
2167 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002168 return 0;
2169}
2170
Willy Tarreau946ba592009-05-10 15:41:18 +02002171/* copies at most <n> characters from <src> and always terminates with '\0' */
2172char *my_strndup(const char *src, int n)
2173{
2174 int len = 0;
2175 char *ret;
2176
2177 while (len < n && src[len])
2178 len++;
2179
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002180 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002181 if (!ret)
2182 return ret;
2183 memcpy(ret, src, len);
2184 ret[len] = '\0';
2185 return ret;
2186}
2187
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002188/*
2189 * search needle in haystack
2190 * returns the pointer if found, returns NULL otherwise
2191 */
2192const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2193{
2194 const void *c = NULL;
2195 unsigned char f;
2196
2197 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2198 return NULL;
2199
2200 f = *(char *)needle;
2201 c = haystack;
2202 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2203 if ((haystacklen - (c - haystack)) < needlelen)
2204 return NULL;
2205
2206 if (memcmp(c, needle, needlelen) == 0)
2207 return c;
2208 ++c;
2209 }
2210 return NULL;
2211}
2212
Willy Tarreau482b00d2009-10-04 22:48:42 +02002213/* This function returns the first unused key greater than or equal to <key> in
2214 * ID tree <root>. Zero is returned if no place is found.
2215 */
2216unsigned int get_next_id(struct eb_root *root, unsigned int key)
2217{
2218 struct eb32_node *used;
2219
2220 do {
2221 used = eb32_lookup_ge(root, key);
2222 if (!used || used->key > key)
2223 return key; /* key is available */
2224 key++;
2225 } while (key);
2226 return key;
2227}
2228
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002229/* dump the full tree to <file> in DOT format for debugging purposes. Will
2230 * optionally highlight node <subj> if found, depending on operation <op> :
2231 * 0 : nothing
2232 * >0 : insertion, node/leaf are surrounded in red
2233 * <0 : removal, node/leaf are dashed with no background
2234 * Will optionally add "desc" as a label on the graph if set and non-null.
2235 */
2236void 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 +01002237{
2238 struct eb32sc_node *node;
2239 unsigned long scope = -1;
2240
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002241 fprintf(file, "digraph ebtree {\n");
2242
2243 if (desc && *desc) {
2244 fprintf(file,
2245 " fontname=\"fixed\";\n"
2246 " fontsize=8;\n"
2247 " label=\"%s\";\n", desc);
2248 }
2249
Willy Tarreaued3cda02017-11-15 15:04:05 +01002250 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002251 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2252 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002253 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2254 );
2255
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002256 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002257 (long)eb_root_to_node(root),
2258 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002259 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2260
2261 node = eb32sc_first(root, scope);
2262 while (node) {
2263 if (node->node.node_p) {
2264 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002265 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2266 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2267 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002268
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002269 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002270 (long)node,
2271 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002272 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002273
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002274 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002275 (long)node,
2276 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002277 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2278
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002279 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002280 (long)node,
2281 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002282 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2283 }
2284
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002285 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2286 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2287 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002288
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002289 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002290 (long)node,
2291 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002292 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002293 node = eb32sc_next(node, scope);
2294 }
2295 fprintf(file, "}\n");
2296}
2297
Willy Tarreau348238b2010-01-18 15:05:57 +01002298/* This function compares a sample word possibly followed by blanks to another
2299 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2300 * otherwise zero. This intends to be used when checking HTTP headers for some
2301 * values. Note that it validates a word followed only by blanks but does not
2302 * validate a word followed by blanks then other chars.
2303 */
2304int word_match(const char *sample, int slen, const char *word, int wlen)
2305{
2306 if (slen < wlen)
2307 return 0;
2308
2309 while (wlen) {
2310 char c = *sample ^ *word;
2311 if (c && c != ('A' ^ 'a'))
2312 return 0;
2313 sample++;
2314 word++;
2315 slen--;
2316 wlen--;
2317 }
2318
2319 while (slen) {
2320 if (*sample != ' ' && *sample != '\t')
2321 return 0;
2322 sample++;
2323 slen--;
2324 }
2325 return 1;
2326}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002327
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002328/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2329 * is particularly fast because it avoids expensive operations such as
2330 * multiplies, which are optimized away at the end. It requires a properly
2331 * formated address though (3 points).
2332 */
2333unsigned int inetaddr_host(const char *text)
2334{
2335 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2336 register unsigned int dig100, dig10, dig1;
2337 int s;
2338 const char *p, *d;
2339
2340 dig1 = dig10 = dig100 = ascii_zero;
2341 s = 24;
2342
2343 p = text;
2344 while (1) {
2345 if (((unsigned)(*p - '0')) <= 9) {
2346 p++;
2347 continue;
2348 }
2349
2350 /* here, we have a complete byte between <text> and <p> (exclusive) */
2351 if (p == text)
2352 goto end;
2353
2354 d = p - 1;
2355 dig1 |= (unsigned int)(*d << s);
2356 if (d == text)
2357 goto end;
2358
2359 d--;
2360 dig10 |= (unsigned int)(*d << s);
2361 if (d == text)
2362 goto end;
2363
2364 d--;
2365 dig100 |= (unsigned int)(*d << s);
2366 end:
2367 if (!s || *p != '.')
2368 break;
2369
2370 s -= 8;
2371 text = ++p;
2372 }
2373
2374 dig100 -= ascii_zero;
2375 dig10 -= ascii_zero;
2376 dig1 -= ascii_zero;
2377 return ((dig100 * 10) + dig10) * 10 + dig1;
2378}
2379
2380/*
2381 * Idem except the first unparsed character has to be passed in <stop>.
2382 */
2383unsigned int inetaddr_host_lim(const char *text, const char *stop)
2384{
2385 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2386 register unsigned int dig100, dig10, dig1;
2387 int s;
2388 const char *p, *d;
2389
2390 dig1 = dig10 = dig100 = ascii_zero;
2391 s = 24;
2392
2393 p = text;
2394 while (1) {
2395 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2396 p++;
2397 continue;
2398 }
2399
2400 /* here, we have a complete byte between <text> and <p> (exclusive) */
2401 if (p == text)
2402 goto end;
2403
2404 d = p - 1;
2405 dig1 |= (unsigned int)(*d << s);
2406 if (d == text)
2407 goto end;
2408
2409 d--;
2410 dig10 |= (unsigned int)(*d << s);
2411 if (d == text)
2412 goto end;
2413
2414 d--;
2415 dig100 |= (unsigned int)(*d << s);
2416 end:
2417 if (!s || p == stop || *p != '.')
2418 break;
2419
2420 s -= 8;
2421 text = ++p;
2422 }
2423
2424 dig100 -= ascii_zero;
2425 dig10 -= ascii_zero;
2426 dig1 -= ascii_zero;
2427 return ((dig100 * 10) + dig10) * 10 + dig1;
2428}
2429
2430/*
2431 * Idem except the pointer to first unparsed byte is returned into <ret> which
2432 * must not be NULL.
2433 */
Willy Tarreau74172752010-10-15 23:21:42 +02002434unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002435{
2436 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2437 register unsigned int dig100, dig10, dig1;
2438 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002439 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002440
2441 dig1 = dig10 = dig100 = ascii_zero;
2442 s = 24;
2443
2444 p = text;
2445 while (1) {
2446 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2447 p++;
2448 continue;
2449 }
2450
2451 /* here, we have a complete byte between <text> and <p> (exclusive) */
2452 if (p == text)
2453 goto end;
2454
2455 d = p - 1;
2456 dig1 |= (unsigned int)(*d << s);
2457 if (d == text)
2458 goto end;
2459
2460 d--;
2461 dig10 |= (unsigned int)(*d << s);
2462 if (d == text)
2463 goto end;
2464
2465 d--;
2466 dig100 |= (unsigned int)(*d << s);
2467 end:
2468 if (!s || p == stop || *p != '.')
2469 break;
2470
2471 s -= 8;
2472 text = ++p;
2473 }
2474
2475 *ret = p;
2476 dig100 -= ascii_zero;
2477 dig10 -= ascii_zero;
2478 dig1 -= ascii_zero;
2479 return ((dig100 * 10) + dig10) * 10 + dig1;
2480}
2481
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002482/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2483 * or the number of chars read in case of success. Maybe this could be replaced
2484 * by one of the functions above. Also, apparently this function does not support
2485 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002486 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002487 */
2488int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2489{
2490 const char *addr;
2491 int saw_digit, octets, ch;
2492 u_char tmp[4], *tp;
2493 const char *cp = buf;
2494
2495 saw_digit = 0;
2496 octets = 0;
2497 *(tp = tmp) = 0;
2498
2499 for (addr = buf; addr - buf < len; addr++) {
2500 unsigned char digit = (ch = *addr) - '0';
2501
2502 if (digit > 9 && ch != '.')
2503 break;
2504
2505 if (digit <= 9) {
2506 u_int new = *tp * 10 + digit;
2507
2508 if (new > 255)
2509 return 0;
2510
2511 *tp = new;
2512
2513 if (!saw_digit) {
2514 if (++octets > 4)
2515 return 0;
2516 saw_digit = 1;
2517 }
2518 } else if (ch == '.' && saw_digit) {
2519 if (octets == 4)
2520 return 0;
2521
2522 *++tp = 0;
2523 saw_digit = 0;
2524 } else
2525 return 0;
2526 }
2527
2528 if (octets < 4)
2529 return 0;
2530
2531 memcpy(&dst->s_addr, tmp, 4);
2532 return addr - cp;
2533}
2534
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002535/* This function converts the string in <buf> of the len <len> to
2536 * struct in6_addr <dst> which must be allocated by the caller.
2537 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002538 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002539 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002540int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2541{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002542 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002543 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002544
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002545 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002546 return 0;
2547
2548 memcpy(null_term_ip6, buf, len);
2549 null_term_ip6[len] = '\0';
2550
Willy Tarreau075415a2013-12-12 11:29:39 +01002551 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002552 return 0;
2553
Willy Tarreau075415a2013-12-12 11:29:39 +01002554 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002555 return 1;
2556}
2557
Willy Tarreauacf95772010-06-14 19:09:21 +02002558/* To be used to quote config arg positions. Returns the short string at <ptr>
2559 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2560 * if ptr is NULL or empty. The string is locally allocated.
2561 */
2562const char *quote_arg(const char *ptr)
2563{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002564 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002565 int i;
2566
2567 if (!ptr || !*ptr)
2568 return "end of line";
2569 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002570 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002571 val[i] = *ptr++;
2572 val[i++] = '\'';
2573 val[i] = '\0';
2574 return val;
2575}
2576
Willy Tarreau5b180202010-07-18 10:40:48 +02002577/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2578int get_std_op(const char *str)
2579{
2580 int ret = -1;
2581
2582 if (*str == 'e' && str[1] == 'q')
2583 ret = STD_OP_EQ;
2584 else if (*str == 'n' && str[1] == 'e')
2585 ret = STD_OP_NE;
2586 else if (*str == 'l') {
2587 if (str[1] == 'e') ret = STD_OP_LE;
2588 else if (str[1] == 't') ret = STD_OP_LT;
2589 }
2590 else if (*str == 'g') {
2591 if (str[1] == 'e') ret = STD_OP_GE;
2592 else if (str[1] == 't') ret = STD_OP_GT;
2593 }
2594
2595 if (ret == -1 || str[2] != '\0')
2596 return -1;
2597 return ret;
2598}
2599
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002600/* hash a 32-bit integer to another 32-bit integer */
2601unsigned int full_hash(unsigned int a)
2602{
2603 return __full_hash(a);
2604}
2605
David du Colombier4f92d322011-03-24 11:09:31 +01002606/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002607 * otherwise zero. Note that <addr> may not necessarily be aligned
2608 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002609 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002610int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002611{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002612 struct in_addr addr_copy;
2613
2614 memcpy(&addr_copy, addr, sizeof(addr_copy));
2615 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002616}
2617
2618/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002619 * otherwise zero. Note that <addr> may not necessarily be aligned
2620 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002621 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002622int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002623{
2624 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002625 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002626
Willy Tarreaueec1d382016-07-13 11:59:39 +02002627 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002628 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002629 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002630 (((int *)net)[i] & ((int *)mask)[i]))
2631 return 0;
2632 return 1;
2633}
2634
2635/* RFC 4291 prefix */
2636const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2637 0x00, 0x00, 0x00, 0x00,
2638 0x00, 0x00, 0xFF, 0xFF };
2639
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002640/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2641 * Input and output may overlap.
2642 */
David du Colombier4f92d322011-03-24 11:09:31 +01002643void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2644{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002645 struct in_addr tmp_addr;
2646
2647 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002648 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002649 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002650}
2651
2652/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2653 * Return true if conversion is possible and false otherwise.
2654 */
2655int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2656{
2657 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2658 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2659 sizeof(struct in_addr));
2660 return 1;
2661 }
2662
2663 return 0;
2664}
2665
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002666/* compare two struct sockaddr_storage and return:
2667 * 0 (true) if the addr is the same in both
2668 * 1 (false) if the addr is not the same in both
2669 * -1 (unable) if one of the addr is not AF_INET*
2670 */
2671int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2672{
2673 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2674 return -1;
2675
2676 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2677 return -1;
2678
2679 if (ss1->ss_family != ss2->ss_family)
2680 return 1;
2681
2682 switch (ss1->ss_family) {
2683 case AF_INET:
2684 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2685 &((struct sockaddr_in *)ss2)->sin_addr,
2686 sizeof(struct in_addr)) != 0;
2687 case AF_INET6:
2688 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2689 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2690 sizeof(struct in6_addr)) != 0;
2691 }
2692
2693 return 1;
2694}
2695
Baptiste Assmann08396c82016-01-31 00:27:17 +01002696/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002697 * The caller must allocate and clear <dest> before calling.
2698 * The source must be in either AF_INET or AF_INET6 family, or the destination
2699 * address will be undefined. If the destination address used to hold a port,
2700 * it is preserved, so that this function can be used to switch to another
2701 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002702 */
2703struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2704{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002705 int prev_port;
2706
2707 prev_port = get_net_port(dest);
2708 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002709 dest->ss_family = source->ss_family;
2710
2711 /* copy new addr and apply it */
2712 switch (source->ss_family) {
2713 case AF_INET:
2714 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002715 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002716 break;
2717 case AF_INET6:
2718 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 +01002719 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002720 break;
2721 }
2722
2723 return dest;
2724}
2725
William Lallemand421f5b52012-02-06 18:15:57 +01002726char *human_time(int t, short hz_div) {
2727 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2728 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002729 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002730 int cnt=2; // print two numbers
2731
2732 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002733 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002734 return rv;
2735 }
2736
2737 if (unlikely(hz_div > 1))
2738 t /= hz_div;
2739
2740 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002741 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002742 cnt--;
2743 }
2744
2745 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002746 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002747 cnt--;
2748 }
2749
2750 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002751 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002752 cnt--;
2753 }
2754
2755 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002756 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002757
2758 return rv;
2759}
2760
2761const char *monthname[12] = {
2762 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2763 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2764};
2765
2766/* date2str_log: write a date in the format :
2767 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2768 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2769 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2770 *
2771 * without using sprintf. return a pointer to the last char written (\0) or
2772 * NULL if there isn't enough space.
2773 */
2774char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2775{
2776
2777 if (size < 25) /* the size is fixed: 24 chars + \0 */
2778 return NULL;
2779
2780 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2781 *dst++ = '/';
2782 memcpy(dst, monthname[tm->tm_mon], 3); // month
2783 dst += 3;
2784 *dst++ = '/';
2785 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2786 *dst++ = ':';
2787 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2788 *dst++ = ':';
2789 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2790 *dst++ = ':';
2791 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2792 *dst++ = '.';
2793 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2794 dst += 3; // only the 3 first digits
2795 *dst = '\0';
2796
2797 return dst;
2798}
2799
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002800/* Base year used to compute leap years */
2801#define TM_YEAR_BASE 1900
2802
2803/* Return the difference in seconds between two times (leap seconds are ignored).
2804 * Retrieved from glibc 2.18 source code.
2805 */
2806static int my_tm_diff(const struct tm *a, const struct tm *b)
2807{
2808 /* Compute intervening leap days correctly even if year is negative.
2809 * Take care to avoid int overflow in leap day calculations,
2810 * but it's OK to assume that A and B are close to each other.
2811 */
2812 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2813 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2814 int a100 = a4 / 25 - (a4 % 25 < 0);
2815 int b100 = b4 / 25 - (b4 % 25 < 0);
2816 int a400 = a100 >> 2;
2817 int b400 = b100 >> 2;
2818 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2819 int years = a->tm_year - b->tm_year;
2820 int days = (365 * years + intervening_leap_days
2821 + (a->tm_yday - b->tm_yday));
2822 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2823 + (a->tm_min - b->tm_min))
2824 + (a->tm_sec - b->tm_sec));
2825}
2826
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002827/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002828 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002829 * The string returned has the same format as returned by strftime(... "%z", tm).
2830 * Offsets are kept in an internal cache for better performances.
2831 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002832const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002833{
2834 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002835 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002836
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002837 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002838 struct tm tm_gmt;
2839 int diff;
2840 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002841
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002842 /* Pretend DST not active if its status is unknown */
2843 if (isdst < 0)
2844 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002845
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002846 /* Fetch the offset and initialize it if needed */
2847 gmt_offset = gmt_offsets[isdst & 0x01];
2848 if (unlikely(!*gmt_offset)) {
2849 get_gmtime(t, &tm_gmt);
2850 diff = my_tm_diff(tm, &tm_gmt);
2851 if (diff < 0) {
2852 diff = -diff;
2853 *gmt_offset = '-';
2854 } else {
2855 *gmt_offset = '+';
2856 }
2857 diff /= 60; /* Convert to minutes */
2858 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2859 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002860
2861 return gmt_offset;
2862}
2863
William Lallemand421f5b52012-02-06 18:15:57 +01002864/* gmt2str_log: write a date in the format :
2865 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2866 * return a pointer to the last char written (\0) or
2867 * NULL if there isn't enough space.
2868 */
2869char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2870{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002871 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002872 return NULL;
2873
2874 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2875 *dst++ = '/';
2876 memcpy(dst, monthname[tm->tm_mon], 3); // month
2877 dst += 3;
2878 *dst++ = '/';
2879 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2880 *dst++ = ':';
2881 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2882 *dst++ = ':';
2883 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2884 *dst++ = ':';
2885 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2886 *dst++ = ' ';
2887 *dst++ = '+';
2888 *dst++ = '0';
2889 *dst++ = '0';
2890 *dst++ = '0';
2891 *dst++ = '0';
2892 *dst = '\0';
2893
2894 return dst;
2895}
2896
Yuxans Yao4e25b012012-10-19 10:36:09 +08002897/* localdate2str_log: write a date in the format :
2898 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002899 * Both t and tm must represent the same time.
2900 * return a pointer to the last char written (\0) or
2901 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002902 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002903char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002904{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002905 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002906 if (size < 27) /* the size is fixed: 26 chars + \0 */
2907 return NULL;
2908
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002909 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002910
Yuxans Yao4e25b012012-10-19 10:36:09 +08002911 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2912 *dst++ = '/';
2913 memcpy(dst, monthname[tm->tm_mon], 3); // month
2914 dst += 3;
2915 *dst++ = '/';
2916 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2917 *dst++ = ':';
2918 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2919 *dst++ = ':';
2920 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2921 *dst++ = ':';
2922 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2923 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002924 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002925 dst += 5;
2926 *dst = '\0';
2927
2928 return dst;
2929}
2930
Willy Tarreaucb1949b2017-07-19 19:05:29 +02002931/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
2932 * It is meant as a portable replacement for timegm() for use with valid inputs.
2933 * Returns undefined results for invalid dates (eg: months out of range 0..11).
2934 */
2935time_t my_timegm(const struct tm *tm)
2936{
2937 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
2938 * is thus (current month - 1)*28 + cumulated_N[month] to count the
2939 * sum of the extra N days for elapsed months. The sum of all these N
2940 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
2941 * in a 5-bit word. This means that with 60 bits we can represent a
2942 * matrix of all these values at once, which is fast and efficient to
2943 * access. The extra February day for leap years is not counted here.
2944 *
2945 * Jan : none = 0 (0)
2946 * Feb : Jan = 3 (3)
2947 * Mar : Jan..Feb = 3 (3 + 0)
2948 * Apr : Jan..Mar = 6 (3 + 0 + 3)
2949 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
2950 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
2951 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
2952 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
2953 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
2954 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
2955 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
2956 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
2957 */
2958 uint64_t extra =
2959 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
2960 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
2961 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
2962 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
2963
2964 unsigned int y = tm->tm_year + 1900;
2965 unsigned int m = tm->tm_mon;
2966 unsigned long days = 0;
2967
2968 /* days since 1/1/1970 for full years */
2969 days += days_since_zero(y) - days_since_zero(1970);
2970
2971 /* days for full months in the current year */
2972 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
2973
2974 /* count + 1 after March for leap years. A leap year is a year multiple
2975 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
2976 * is leap, 1900 isn't, 1904 is.
2977 */
2978 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
2979 days++;
2980
2981 days += tm->tm_mday - 1;
2982 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
2983}
2984
Thierry Fournier93127942016-01-20 18:49:45 +01002985/* This function check a char. It returns true and updates
2986 * <date> and <len> pointer to the new position if the
2987 * character is found.
2988 */
2989static inline int parse_expect_char(const char **date, int *len, char c)
2990{
2991 if (*len < 1 || **date != c)
2992 return 0;
2993 (*len)--;
2994 (*date)++;
2995 return 1;
2996}
2997
2998/* This function expects a string <str> of len <l>. It return true and updates.
2999 * <date> and <len> if the string matches, otherwise, it returns false.
3000 */
3001static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3002{
3003 if (*len < l || strncmp(*date, str, l) != 0)
3004 return 0;
3005 (*len) -= l;
3006 (*date) += l;
3007 return 1;
3008}
3009
3010/* This macro converts 3 chars name in integer. */
3011#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3012
3013/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3014 * / %x54.75.65 ; "Tue", case-sensitive
3015 * / %x57.65.64 ; "Wed", case-sensitive
3016 * / %x54.68.75 ; "Thu", case-sensitive
3017 * / %x46.72.69 ; "Fri", case-sensitive
3018 * / %x53.61.74 ; "Sat", case-sensitive
3019 * / %x53.75.6E ; "Sun", case-sensitive
3020 *
3021 * This array must be alphabetically sorted
3022 */
3023static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3024{
3025 if (*len < 3)
3026 return 0;
3027 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3028 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3029 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3030 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3031 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3032 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3033 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3034 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3035 default: return 0;
3036 }
3037 *len -= 3;
3038 *date += 3;
3039 return 1;
3040}
3041
3042/* month = %x4A.61.6E ; "Jan", case-sensitive
3043 * / %x46.65.62 ; "Feb", case-sensitive
3044 * / %x4D.61.72 ; "Mar", case-sensitive
3045 * / %x41.70.72 ; "Apr", case-sensitive
3046 * / %x4D.61.79 ; "May", case-sensitive
3047 * / %x4A.75.6E ; "Jun", case-sensitive
3048 * / %x4A.75.6C ; "Jul", case-sensitive
3049 * / %x41.75.67 ; "Aug", case-sensitive
3050 * / %x53.65.70 ; "Sep", case-sensitive
3051 * / %x4F.63.74 ; "Oct", case-sensitive
3052 * / %x4E.6F.76 ; "Nov", case-sensitive
3053 * / %x44.65.63 ; "Dec", case-sensitive
3054 *
3055 * This array must be alphabetically sorted
3056 */
3057static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3058{
3059 if (*len < 3)
3060 return 0;
3061 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3062 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3063 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3064 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3065 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3066 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3067 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3068 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3069 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3070 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3071 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3072 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3073 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3074 default: return 0;
3075 }
3076 *len -= 3;
3077 *date += 3;
3078 return 1;
3079}
3080
3081/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3082 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3083 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3084 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3085 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3086 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3087 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3088 *
3089 * This array must be alphabetically sorted
3090 */
3091static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3092{
3093 if (*len < 6) /* Minimum length. */
3094 return 0;
3095 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3096 case STR2I3('M','o','n'):
3097 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3098 tm->tm_wday = 1;
3099 return 1;
3100 case STR2I3('T','u','e'):
3101 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3102 tm->tm_wday = 2;
3103 return 1;
3104 case STR2I3('W','e','d'):
3105 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3106 tm->tm_wday = 3;
3107 return 1;
3108 case STR2I3('T','h','u'):
3109 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3110 tm->tm_wday = 4;
3111 return 1;
3112 case STR2I3('F','r','i'):
3113 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3114 tm->tm_wday = 5;
3115 return 1;
3116 case STR2I3('S','a','t'):
3117 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3118 tm->tm_wday = 6;
3119 return 1;
3120 case STR2I3('S','u','n'):
3121 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3122 tm->tm_wday = 7;
3123 return 1;
3124 }
3125 return 0;
3126}
3127
3128/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3129static inline int parse_digit(const char **date, int *len, int *digit)
3130{
3131 if (*len < 1 || **date < '0' || **date > '9')
3132 return 0;
3133 *digit = (**date - '0');
3134 (*date)++;
3135 (*len)--;
3136 return 1;
3137}
3138
3139/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3140static inline int parse_2digit(const char **date, int *len, int *digit)
3141{
3142 int value;
3143
3144 RET0_UNLESS(parse_digit(date, len, &value));
3145 (*digit) = value * 10;
3146 RET0_UNLESS(parse_digit(date, len, &value));
3147 (*digit) += value;
3148
3149 return 1;
3150}
3151
3152/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3153static inline int parse_4digit(const char **date, int *len, int *digit)
3154{
3155 int value;
3156
3157 RET0_UNLESS(parse_digit(date, len, &value));
3158 (*digit) = value * 1000;
3159
3160 RET0_UNLESS(parse_digit(date, len, &value));
3161 (*digit) += value * 100;
3162
3163 RET0_UNLESS(parse_digit(date, len, &value));
3164 (*digit) += value * 10;
3165
3166 RET0_UNLESS(parse_digit(date, len, &value));
3167 (*digit) += value;
3168
3169 return 1;
3170}
3171
3172/* time-of-day = hour ":" minute ":" second
3173 * ; 00:00:00 - 23:59:60 (leap second)
3174 *
3175 * hour = 2DIGIT
3176 * minute = 2DIGIT
3177 * second = 2DIGIT
3178 */
3179static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3180{
3181 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3182 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3183 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3184 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3185 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3186 return 1;
3187}
3188
3189/* From RFC7231
3190 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3191 *
3192 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3193 * ; fixed length/zone/capitalization subset of the format
3194 * ; see Section 3.3 of [RFC5322]
3195 *
3196 *
3197 * date1 = day SP month SP year
3198 * ; e.g., 02 Jun 1982
3199 *
3200 * day = 2DIGIT
3201 * year = 4DIGIT
3202 *
3203 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3204 *
3205 * time-of-day = hour ":" minute ":" second
3206 * ; 00:00:00 - 23:59:60 (leap second)
3207 *
3208 * hour = 2DIGIT
3209 * minute = 2DIGIT
3210 * second = 2DIGIT
3211 *
3212 * DIGIT = decimal 0-9
3213 */
3214int parse_imf_date(const char *date, int len, struct tm *tm)
3215{
David Carlier327298c2016-11-20 10:42:38 +00003216 /* tm_gmtoff, if present, ought to be zero'ed */
3217 memset(tm, 0, sizeof(*tm));
3218
Thierry Fournier93127942016-01-20 18:49:45 +01003219 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3220 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3221 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3222 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3223 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3224 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3225 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3226 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3227 tm->tm_year -= 1900;
3228 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3229 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3230 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3231 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3232 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003233 return 1;
3234}
3235
3236/* From RFC7231
3237 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3238 *
3239 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3240 * date2 = day "-" month "-" 2DIGIT
3241 * ; e.g., 02-Jun-82
3242 *
3243 * day = 2DIGIT
3244 */
3245int parse_rfc850_date(const char *date, int len, struct tm *tm)
3246{
3247 int year;
3248
David Carlier327298c2016-11-20 10:42:38 +00003249 /* tm_gmtoff, if present, ought to be zero'ed */
3250 memset(tm, 0, sizeof(*tm));
3251
Thierry Fournier93127942016-01-20 18:49:45 +01003252 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3253 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3254 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3255 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3256 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3257 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3258 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3259
3260 /* year = 2DIGIT
3261 *
3262 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3263 * two-digit year, MUST interpret a timestamp that appears to be more
3264 * than 50 years in the future as representing the most recent year in
3265 * the past that had the same last two digits.
3266 */
3267 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3268
3269 /* expect SP */
3270 if (!parse_expect_char(&date, &len, ' ')) {
3271 /* Maybe we have the date with 4 digits. */
3272 RET0_UNLESS(parse_2digit(&date, &len, &year));
3273 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3274 /* expect SP */
3275 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3276 } else {
3277 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3278 * tm_year is the number of year since 1900, so for +1900, we
3279 * do nothing, and for +2000, we add 100.
3280 */
3281 if (tm->tm_year <= 60)
3282 tm->tm_year += 100;
3283 }
3284
3285 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3286 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3287 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3288 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003289
3290 return 1;
3291}
3292
3293/* From RFC7231
3294 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3295 *
3296 * asctime-date = day-name SP date3 SP time-of-day SP year
3297 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3298 * ; e.g., Jun 2
3299 *
3300 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3301 * whitespace in an HTTP-date beyond that specifically included as SP in
3302 * the grammar.
3303 */
3304int parse_asctime_date(const char *date, int len, struct tm *tm)
3305{
David Carlier327298c2016-11-20 10:42:38 +00003306 /* tm_gmtoff, if present, ought to be zero'ed */
3307 memset(tm, 0, sizeof(*tm));
3308
Thierry Fournier93127942016-01-20 18:49:45 +01003309 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3310 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3311 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3312 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3313
3314 /* expect SP and 1DIGIT or 2DIGIT */
3315 if (parse_expect_char(&date, &len, ' '))
3316 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3317 else
3318 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3319
3320 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3321 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3322 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3323 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3324 tm->tm_year -= 1900;
3325 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003326 return 1;
3327}
3328
3329/* From RFC7231
3330 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3331 *
3332 * HTTP-date = IMF-fixdate / obs-date
3333 * obs-date = rfc850-date / asctime-date
3334 *
3335 * parses an HTTP date in the RFC format and is accepted
3336 * alternatives. <date> is the strinf containing the date,
3337 * len is the len of the string. <tm> is filled with the
3338 * parsed time. We must considers this time as GMT.
3339 */
3340int parse_http_date(const char *date, int len, struct tm *tm)
3341{
3342 if (parse_imf_date(date, len, tm))
3343 return 1;
3344
3345 if (parse_rfc850_date(date, len, tm))
3346 return 1;
3347
3348 if (parse_asctime_date(date, len, tm))
3349 return 1;
3350
3351 return 0;
3352}
3353
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003354/* Dynamically allocates a string of the proper length to hold the formatted
3355 * output. NULL is returned on error. The caller is responsible for freeing the
3356 * memory area using free(). The resulting string is returned in <out> if the
3357 * pointer is not NULL. A previous version of <out> might be used to build the
3358 * new string, and it will be freed before returning if it is not NULL, which
3359 * makes it possible to build complex strings from iterative calls without
3360 * having to care about freeing intermediate values, as in the example below :
3361 *
3362 * memprintf(&err, "invalid argument: '%s'", arg);
3363 * ...
3364 * memprintf(&err, "parser said : <%s>\n", *err);
3365 * ...
3366 * free(*err);
3367 *
3368 * This means that <err> must be initialized to NULL before first invocation.
3369 * The return value also holds the allocated string, which eases error checking
3370 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003371 * passed instead and it will be ignored. The returned message will then also
3372 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003373 *
3374 * It is also convenient to use it without any free except the last one :
3375 * err = NULL;
3376 * if (!fct1(err)) report(*err);
3377 * if (!fct2(err)) report(*err);
3378 * if (!fct3(err)) report(*err);
3379 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003380 *
3381 * memprintf relies on memvprintf. This last version can be called from any
3382 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003383 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003384char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003385{
3386 va_list args;
3387 char *ret = NULL;
3388 int allocated = 0;
3389 int needed = 0;
3390
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003391 if (!out)
3392 return NULL;
3393
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003394 do {
3395 /* vsnprintf() will return the required length even when the
3396 * target buffer is NULL. We do this in a loop just in case
3397 * intermediate evaluations get wrong.
3398 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003399 va_copy(args, orig_args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003400 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003401 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003402 if (needed < allocated) {
3403 /* Note: on Solaris 8, the first iteration always
3404 * returns -1 if allocated is zero, so we force a
3405 * retry.
3406 */
3407 if (!allocated)
3408 needed = 0;
3409 else
3410 break;
3411 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003412
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003413 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003414 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003415 } while (ret);
3416
3417 if (needed < 0) {
3418 /* an error was encountered */
3419 free(ret);
3420 ret = NULL;
3421 }
3422
3423 if (out) {
3424 free(*out);
3425 *out = ret;
3426 }
3427
3428 return ret;
3429}
William Lallemand421f5b52012-02-06 18:15:57 +01003430
Christopher Faulet93a518f2017-10-24 11:25:33 +02003431char *memprintf(char **out, const char *format, ...)
3432{
3433 va_list args;
3434 char *ret = NULL;
3435
3436 va_start(args, format);
3437 ret = memvprintf(out, format, args);
3438 va_end(args);
3439
3440 return ret;
3441}
3442
Willy Tarreau21c705b2012-09-14 11:40:36 +02003443/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3444 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003445 * freed by the caller. It also supports being passed a NULL which results in the same
3446 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003447 * Example of use :
3448 * parse(cmd, &err); (callee: memprintf(&err, ...))
3449 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3450 * free(err);
3451 */
3452char *indent_msg(char **out, int level)
3453{
3454 char *ret, *in, *p;
3455 int needed = 0;
3456 int lf = 0;
3457 int lastlf = 0;
3458 int len;
3459
Willy Tarreau70eec382012-10-10 08:56:47 +02003460 if (!out || !*out)
3461 return NULL;
3462
Willy Tarreau21c705b2012-09-14 11:40:36 +02003463 in = *out - 1;
3464 while ((in = strchr(in + 1, '\n')) != NULL) {
3465 lastlf = in - *out;
3466 lf++;
3467 }
3468
3469 if (!lf) /* single line, no LF, return it as-is */
3470 return *out;
3471
3472 len = strlen(*out);
3473
3474 if (lf == 1 && lastlf == len - 1) {
3475 /* single line, LF at end, strip it and return as-is */
3476 (*out)[lastlf] = 0;
3477 return *out;
3478 }
3479
3480 /* OK now we have at least one LF, we need to process the whole string
3481 * as a multi-line string. What we'll do :
3482 * - prefix with an LF if there is none
3483 * - add <level> spaces before each line
3484 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3485 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3486 */
3487
3488 needed = 1 + level * (lf + 1) + len + 1;
3489 p = ret = malloc(needed);
3490 in = *out;
3491
3492 /* skip initial LFs */
3493 while (*in == '\n')
3494 in++;
3495
3496 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3497 while (*in) {
3498 *p++ = '\n';
3499 memset(p, ' ', level);
3500 p += level;
3501 do {
3502 *p++ = *in++;
3503 } while (*in && *in != '\n');
3504 if (*in)
3505 in++;
3506 }
3507 *p = 0;
3508
3509 free(*out);
3510 *out = ret;
3511
3512 return ret;
3513}
3514
Willy Tarreaudad36a32013-03-11 01:20:04 +01003515/* Convert occurrences of environment variables in the input string to their
3516 * corresponding value. A variable is identified as a series of alphanumeric
3517 * characters or underscores following a '$' sign. The <in> string must be
3518 * free()able. NULL returns NULL. The resulting string might be reallocated if
3519 * some expansion is made. Variable names may also be enclosed into braces if
3520 * needed (eg: to concatenate alphanum characters).
3521 */
3522char *env_expand(char *in)
3523{
3524 char *txt_beg;
3525 char *out;
3526 char *txt_end;
3527 char *var_beg;
3528 char *var_end;
3529 char *value;
3530 char *next;
3531 int out_len;
3532 int val_len;
3533
3534 if (!in)
3535 return in;
3536
3537 value = out = NULL;
3538 out_len = 0;
3539
3540 txt_beg = in;
3541 do {
3542 /* look for next '$' sign in <in> */
3543 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3544
3545 if (!*txt_end && !out) /* end and no expansion performed */
3546 return in;
3547
3548 val_len = 0;
3549 next = txt_end;
3550 if (*txt_end == '$') {
3551 char save;
3552
3553 var_beg = txt_end + 1;
3554 if (*var_beg == '{')
3555 var_beg++;
3556
3557 var_end = var_beg;
3558 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3559 var_end++;
3560 }
3561
3562 next = var_end;
3563 if (*var_end == '}' && (var_beg > txt_end + 1))
3564 next++;
3565
3566 /* get value of the variable name at this location */
3567 save = *var_end;
3568 *var_end = '\0';
3569 value = getenv(var_beg);
3570 *var_end = save;
3571 val_len = value ? strlen(value) : 0;
3572 }
3573
Hubert Verstraete831962e2016-06-28 22:44:26 +02003574 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003575 if (txt_end > txt_beg) {
3576 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3577 out_len += txt_end - txt_beg;
3578 }
3579 if (val_len) {
3580 memcpy(out + out_len, value, val_len);
3581 out_len += val_len;
3582 }
3583 out[out_len] = 0;
3584 txt_beg = next;
3585 } while (*txt_beg);
3586
3587 /* here we know that <out> was allocated and that we don't need <in> anymore */
3588 free(in);
3589 return out;
3590}
3591
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003592
3593/* same as strstr() but case-insensitive and with limit length */
3594const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3595{
3596 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003597 unsigned int slen, plen;
3598 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003599
3600 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3601 return NULL;
3602
3603 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3604 return str1;
3605
3606 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3607 return NULL;
3608
3609 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3610 while (toupper(*start) != toupper(*str2)) {
3611 start++;
3612 slen--;
3613 tmp1++;
3614
3615 if (tmp1 >= len_str1)
3616 return NULL;
3617
3618 /* if pattern longer than string */
3619 if (slen < plen)
3620 return NULL;
3621 }
3622
3623 sptr = start;
3624 pptr = (char *)str2;
3625
3626 tmp2 = 0;
3627 while (toupper(*sptr) == toupper(*pptr)) {
3628 sptr++;
3629 pptr++;
3630 tmp2++;
3631
3632 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3633 return start;
3634 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3635 return NULL;
3636 }
3637 }
3638 return NULL;
3639}
3640
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003641/* This function read the next valid utf8 char.
3642 * <s> is the byte srray to be decode, <len> is its length.
3643 * The function returns decoded char encoded like this:
3644 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3645 * are the length read. The decoded character is stored in <c>.
3646 */
3647unsigned char utf8_next(const char *s, int len, unsigned int *c)
3648{
3649 const unsigned char *p = (unsigned char *)s;
3650 int dec;
3651 unsigned char code = UTF8_CODE_OK;
3652
3653 if (len < 1)
3654 return UTF8_CODE_OK;
3655
3656 /* Check the type of UTF8 sequence
3657 *
3658 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3659 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3660 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3661 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3662 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3663 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3664 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3665 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3666 */
3667 switch (*p) {
3668 case 0x00 ... 0x7f:
3669 *c = *p;
3670 return UTF8_CODE_OK | 1;
3671
3672 case 0x80 ... 0xbf:
3673 *c = *p;
3674 return UTF8_CODE_BADSEQ | 1;
3675
3676 case 0xc0 ... 0xdf:
3677 if (len < 2) {
3678 *c = *p;
3679 return UTF8_CODE_BADSEQ | 1;
3680 }
3681 *c = *p & 0x1f;
3682 dec = 1;
3683 break;
3684
3685 case 0xe0 ... 0xef:
3686 if (len < 3) {
3687 *c = *p;
3688 return UTF8_CODE_BADSEQ | 1;
3689 }
3690 *c = *p & 0x0f;
3691 dec = 2;
3692 break;
3693
3694 case 0xf0 ... 0xf7:
3695 if (len < 4) {
3696 *c = *p;
3697 return UTF8_CODE_BADSEQ | 1;
3698 }
3699 *c = *p & 0x07;
3700 dec = 3;
3701 break;
3702
3703 case 0xf8 ... 0xfb:
3704 if (len < 5) {
3705 *c = *p;
3706 return UTF8_CODE_BADSEQ | 1;
3707 }
3708 *c = *p & 0x03;
3709 dec = 4;
3710 break;
3711
3712 case 0xfc ... 0xfd:
3713 if (len < 6) {
3714 *c = *p;
3715 return UTF8_CODE_BADSEQ | 1;
3716 }
3717 *c = *p & 0x01;
3718 dec = 5;
3719 break;
3720
3721 case 0xfe ... 0xff:
3722 default:
3723 *c = *p;
3724 return UTF8_CODE_BADSEQ | 1;
3725 }
3726
3727 p++;
3728
3729 while (dec > 0) {
3730
3731 /* need 0x10 for the 2 first bits */
3732 if ( ( *p & 0xc0 ) != 0x80 )
3733 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3734
3735 /* add data at char */
3736 *c = ( *c << 6 ) | ( *p & 0x3f );
3737
3738 dec--;
3739 p++;
3740 }
3741
3742 /* Check ovelong encoding.
3743 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3744 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3745 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3746 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003747 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003748 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3749 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3750 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3751 code |= UTF8_CODE_OVERLONG;
3752
3753 /* Check invalid UTF8 range. */
3754 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3755 (*c >= 0xfffe && *c <= 0xffff))
3756 code |= UTF8_CODE_INVRANGE;
3757
3758 return code | ((p-(unsigned char *)s)&0x0f);
3759}
3760
Maxime de Roucydc887852016-05-13 23:52:54 +02003761/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3762 * On failure : return 0 and <err> filled with an error message.
3763 * The caller is responsible for freeing the <err> and <str> copy
3764 * memory area using free()
3765 */
3766int list_append_word(struct list *li, const char *str, char **err)
3767{
3768 struct wordlist *wl;
3769
3770 wl = calloc(1, sizeof(*wl));
3771 if (!wl) {
3772 memprintf(err, "out of memory");
3773 goto fail_wl;
3774 }
3775
3776 wl->s = strdup(str);
3777 if (!wl->s) {
3778 memprintf(err, "out of memory");
3779 goto fail_wl_s;
3780 }
3781
3782 LIST_ADDQ(li, &wl->list);
3783
3784 return 1;
3785
3786fail_wl_s:
3787 free(wl->s);
3788fail_wl:
3789 free(wl);
3790 return 0;
3791}
3792
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003793/* print a string of text buffer to <out>. The format is :
3794 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3795 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3796 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3797 */
3798int dump_text(struct chunk *out, const char *buf, int bsize)
3799{
3800 unsigned char c;
3801 int ptr = 0;
3802
3803 while (buf[ptr] && ptr < bsize) {
3804 c = buf[ptr];
3805 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
3806 if (out->len > out->size - 1)
3807 break;
3808 out->str[out->len++] = c;
3809 }
3810 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
3811 if (out->len > out->size - 2)
3812 break;
3813 out->str[out->len++] = '\\';
3814 switch (c) {
3815 case ' ': c = ' '; break;
3816 case '\t': c = 't'; break;
3817 case '\n': c = 'n'; break;
3818 case '\r': c = 'r'; break;
3819 case '\e': c = 'e'; break;
3820 case '\\': c = '\\'; break;
3821 case '=': c = '='; break;
3822 }
3823 out->str[out->len++] = c;
3824 }
3825 else {
3826 if (out->len > out->size - 4)
3827 break;
3828 out->str[out->len++] = '\\';
3829 out->str[out->len++] = 'x';
3830 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3831 out->str[out->len++] = hextab[c & 0xF];
3832 }
3833 ptr++;
3834 }
3835
3836 return ptr;
3837}
3838
3839/* print a buffer in hexa.
3840 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3841 */
3842int dump_binary(struct chunk *out, const char *buf, int bsize)
3843{
3844 unsigned char c;
3845 int ptr = 0;
3846
3847 while (ptr < bsize) {
3848 c = buf[ptr];
3849
3850 if (out->len > out->size - 2)
3851 break;
3852 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3853 out->str[out->len++] = hextab[c & 0xF];
3854
3855 ptr++;
3856 }
3857 return ptr;
3858}
3859
3860/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3861 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3862 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3863 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3864 * lines are respected within the limit of 70 output chars. Lines that are
3865 * continuation of a previous truncated line begin with "+" instead of " "
3866 * after the offset. The new pointer is returned.
3867 */
3868int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3869 int *line, int ptr)
3870{
3871 int end;
3872 unsigned char c;
3873
3874 end = out->len + 80;
3875 if (end > out->size)
3876 return ptr;
3877
3878 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3879
3880 while (ptr < len && ptr < bsize) {
3881 c = buf[ptr];
3882 if (isprint(c) && isascii(c) && c != '\\') {
3883 if (out->len > end - 2)
3884 break;
3885 out->str[out->len++] = c;
3886 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3887 if (out->len > end - 3)
3888 break;
3889 out->str[out->len++] = '\\';
3890 switch (c) {
3891 case '\t': c = 't'; break;
3892 case '\n': c = 'n'; break;
3893 case '\r': c = 'r'; break;
3894 case '\e': c = 'e'; break;
3895 case '\\': c = '\\'; break;
3896 }
3897 out->str[out->len++] = c;
3898 } else {
3899 if (out->len > end - 5)
3900 break;
3901 out->str[out->len++] = '\\';
3902 out->str[out->len++] = 'x';
3903 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3904 out->str[out->len++] = hextab[c & 0xF];
3905 }
3906 if (buf[ptr++] == '\n') {
3907 /* we had a line break, let's return now */
3908 out->str[out->len++] = '\n';
3909 *line = ptr;
3910 return ptr;
3911 }
3912 }
3913 /* we have an incomplete line, we return it as-is */
3914 out->str[out->len++] = '\n';
3915 return ptr;
3916}
3917
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003918/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02003919 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
3920 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003921 */
Willy Tarreaued936c52017-04-27 18:03:20 +02003922void debug_hexdump(FILE *out, const char *pfx, const char *buf,
3923 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003924{
Willy Tarreau73459792017-04-11 07:58:08 +02003925 unsigned int i;
3926 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003927
3928 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3929 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02003930 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003931 for (j = 0; j < 8; j++) {
3932 if (b + j >= 0 && b + j < len)
3933 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3934 else
3935 fprintf(out, " ");
3936 }
3937
3938 if (b + j >= 0 && b + j < len)
3939 fputc('-', out);
3940 else
3941 fputc(' ', out);
3942
3943 for (j = 8; j < 16; j++) {
3944 if (b + j >= 0 && b + j < len)
3945 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3946 else
3947 fprintf(out, " ");
3948 }
3949
3950 fprintf(out, " ");
3951 for (j = 0; j < 16; j++) {
3952 if (b + j >= 0 && b + j < len) {
3953 if (isprint((unsigned char)buf[b + j]))
3954 fputc((unsigned char)buf[b + j], out);
3955 else
3956 fputc('.', out);
3957 }
3958 else
3959 fputc(' ', out);
3960 }
3961 fputc('\n', out);
3962 }
3963}
3964
Willy Tarreau12963822017-10-24 10:54:08 +02003965/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
3966__attribute__((weak,format(printf, 1, 2)))
3967void trace(char *msg, ...)
3968{
3969}
3970
Willy Tarreaubaaee002006-06-26 02:48:02 +02003971/*
3972 * Local variables:
3973 * c-indent-level: 8
3974 * c-basic-offset: 8
3975 * End:
3976 */