blob: d87e09cc1010484ce42bdc62216592e1b614bc71 [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;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100725 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100726
727 memset(&result, 0, sizeof(result));
728 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100729 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100730 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200731 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100732 hints.ai_protocol = 0;
733
734 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100735 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
736 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100737 else if (sa->ss_family != result->ai_family) {
738 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100739 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100740 }
Willy Tarreau24709282013-03-10 21:32:12 +0100741
David du Colombierd5f43282011-03-17 10:40:16 +0100742 switch (result->ai_family) {
743 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100744 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100745 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100746 success = 1;
747 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100748 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100749 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100750 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100751 success = 1;
752 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100753 }
754 }
755
Sean Carey58ea0392013-02-15 23:39:18 +0100756 if (result)
757 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100758
759 if (success)
760 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100761 }
David du Colombierd5f43282011-03-17 10:40:16 +0100762#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200763 /* try to resolve an IPv4/IPv6 hostname */
764 he = gethostbyname(str);
765 if (he) {
766 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
767 sa->ss_family = he->h_addrtype;
768 else if (sa->ss_family != he->h_addrtype)
769 goto fail;
770
771 switch (sa->ss_family) {
772 case AF_INET:
773 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100774 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200775 return sa;
776 case AF_INET6:
777 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100778 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200779 return sa;
780 }
781 }
782
David du Colombierd5f43282011-03-17 10:40:16 +0100783 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100784 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100785 return NULL;
786}
787
788/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100789 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
790 * range or offset consisting in two integers that the caller will have to
791 * check to find the relevant input format. The following format are supported :
792 *
793 * String format | address | port | low | high
794 * addr | <addr> | 0 | 0 | 0
795 * addr: | <addr> | 0 | 0 | 0
796 * addr:port | <addr> | <port> | <port> | <port>
797 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
798 * addr:+port | <addr> | <port> | 0 | <port>
799 * addr:-port | <addr> |-<port> | <port> | 0
800 *
801 * The detection of a port range or increment by the caller is made by
802 * comparing <low> and <high>. If both are equal, then port 0 means no port
803 * was specified. The caller may pass NULL for <low> and <high> if it is not
804 * interested in retrieving port ranges.
805 *
806 * Note that <addr> above may also be :
807 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
808 * - "*" => family will be AF_INET and address will be INADDR_ANY
809 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
810 * - a host name => family and address will depend on host name resolving.
811 *
Willy Tarreau24709282013-03-10 21:32:12 +0100812 * A prefix may be passed in before the address above to force the family :
813 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
814 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
815 * - "unix@" => force address to be a path to a UNIX socket even if the
816 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200817 * - 'abns@' -> force address to belong to the abstract namespace (Linux
818 * only). These sockets are just like Unix sockets but without
819 * the need for an underlying file system. The address is a
820 * string. Technically it's like a Unix socket with a zero in
821 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100822 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100823 *
mildisff5d5102015-10-26 18:50:08 +0100824 * IPv6 addresses can be declared with or without square brackets. When using
825 * square brackets for IPv6 addresses, the port separator (colon) is optional.
826 * If not using square brackets, and in order to avoid any ambiguity with
827 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
828 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
829 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100830 *
831 * If <pfx> is non-null, it is used as a string prefix before any path-based
832 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100833 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200834 * if <fqdn> is non-null, it will be filled with :
835 * - a pointer to the FQDN of the server name to resolve if there's one, and
836 * that the caller will have to free(),
837 * - NULL if there was an explicit address that doesn't require resolution.
838 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100839 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
840 * is null, <fqdn> is still honnored so it is possible for the caller to know
841 * whether a resolution failed by setting <resolve> to null and checking if
842 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200843 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100844 * When a file descriptor is passed, its value is put into the s_addr part of
845 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100846 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100847struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100848{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100849 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100850 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100851 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100852 char *port1, *port2;
853 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200854 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100855
856 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200857 if (fqdn)
858 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200859
Willy Tarreaudad36a32013-03-11 01:20:04 +0100860 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100861 if (str2 == NULL) {
862 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100863 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100864 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200865
Willy Tarreau9f69f462015-09-08 16:01:25 +0200866 if (!*str2) {
867 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
868 goto out;
869 }
870
Willy Tarreau24709282013-03-10 21:32:12 +0100871 memset(&ss, 0, sizeof(ss));
872
873 if (strncmp(str2, "unix@", 5) == 0) {
874 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200875 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100876 ss.ss_family = AF_UNIX;
877 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200878 else if (strncmp(str2, "abns@", 5) == 0) {
879 str2 += 5;
880 abstract = 1;
881 ss.ss_family = AF_UNIX;
882 }
Willy Tarreau24709282013-03-10 21:32:12 +0100883 else if (strncmp(str2, "ipv4@", 5) == 0) {
884 str2 += 5;
885 ss.ss_family = AF_INET;
886 }
887 else if (strncmp(str2, "ipv6@", 5) == 0) {
888 str2 += 5;
889 ss.ss_family = AF_INET6;
890 }
891 else if (*str2 == '/') {
892 ss.ss_family = AF_UNIX;
893 }
894 else
895 ss.ss_family = AF_UNSPEC;
896
Willy Tarreau40aa0702013-03-10 23:51:38 +0100897 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
898 char *endptr;
899
900 str2 += 3;
901 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
902
903 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100904 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100905 goto out;
906 }
907
908 /* we return AF_UNSPEC if we use a file descriptor number */
909 ss.ss_family = AF_UNSPEC;
910 }
911 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100912 int prefix_path_len;
913 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200914 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100915
916 /* complete unix socket path name during startup or soft-restart is
917 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
918 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200919 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100920 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
921 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
922
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200923 adr_len = strlen(str2);
924 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100925 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
926 goto out;
927 }
928
Willy Tarreauccfccef2014-05-10 01:49:15 +0200929 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
930 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200931 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100932 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200933 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100934 }
Willy Tarreau24709282013-03-10 21:32:12 +0100935 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100936 char *end = str2 + strlen(str2);
937 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200938
mildisff5d5102015-10-26 18:50:08 +0100939 /* search for : or ] whatever comes first */
940 for (chr = end-1; chr > str2; chr--) {
941 if (*chr == ']' || *chr == ':')
942 break;
943 }
944
945 if (*chr == ':') {
946 /* Found a colon before a closing-bracket, must be a port separator.
947 * This guarantee backward compatibility.
948 */
949 *chr++ = '\0';
950 port1 = chr;
951 }
952 else {
953 /* Either no colon and no closing-bracket
954 * or directly ending with a closing-bracket.
955 * However, no port.
956 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100957 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100958 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200959
Willy Tarreaua39d1992013-04-01 20:37:42 +0200960 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100961 port2 = strchr(port1, '-');
962 if (port2)
963 *port2++ = '\0';
964 else
965 port2 = port1;
966 portl = atoi(port1);
967 porth = atoi(port2);
968 porta = portl;
969 }
970 else if (*port1 == '-') { /* negative offset */
971 portl = atoi(port1 + 1);
972 porta = -portl;
973 }
974 else if (*port1 == '+') { /* positive offset */
975 porth = atoi(port1 + 1);
976 porta = porth;
977 }
978 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100979 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100980 goto out;
981 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100982
983 /* first try to parse the IP without resolving. If it fails, it
984 * tells us we need to keep a copy of the FQDN to resolve later
985 * and to enable DNS. In this case we can proceed if <fqdn> is
986 * set or if resolve is set, otherwise it's an error.
987 */
988 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +0100989 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +0100990 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
991 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
992 goto out;
993 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200994
Willy Tarreauceccdd72016-11-02 22:27:10 +0100995 if (fqdn) {
996 if (str2 != back)
997 memmove(back, str2, strlen(str2) + 1);
998 *fqdn = back;
999 back = NULL;
1000 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001001 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001002 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001003 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001004
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001005 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001006 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001007 if (port)
1008 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001009 if (low)
1010 *low = portl;
1011 if (high)
1012 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001013 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001014 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001015}
1016
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001017/* converts <str> to a struct in_addr containing a network mask. It can be
1018 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001019 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001020 */
1021int str2mask(const char *str, struct in_addr *mask)
1022{
1023 if (strchr(str, '.') != NULL) { /* dotted notation */
1024 if (!inet_pton(AF_INET, str, mask))
1025 return 0;
1026 }
1027 else { /* mask length */
1028 char *err;
1029 unsigned long len = strtol(str, &err, 10);
1030
1031 if (!*str || (err && *err) || (unsigned)len > 32)
1032 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001033
1034 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001035 }
1036 return 1;
1037}
1038
Tim Duesterhus47185172018-01-25 16:24:49 +01001039/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001040 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001041 * if the conversion succeeds otherwise zero.
1042 */
1043int str2mask6(const char *str, struct in6_addr *mask)
1044{
1045 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1046 if (!inet_pton(AF_INET6, str, mask))
1047 return 0;
1048 }
1049 else { /* mask length */
1050 char *err;
1051 unsigned long len = strtol(str, &err, 10);
1052
1053 if (!*str || (err && *err) || (unsigned)len > 128)
1054 return 0;
1055
1056 len2mask6(len, mask);
1057 }
1058 return 1;
1059}
1060
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001061/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1062 * succeeds otherwise zero.
1063 */
1064int cidr2dotted(int cidr, struct in_addr *mask) {
1065
1066 if (cidr < 0 || cidr > 32)
1067 return 0;
1068
1069 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1070 return 1;
1071}
1072
Thierry Fournier70473a52016-02-17 17:12:14 +01001073/* Convert mask from bit length form to in_addr form.
1074 * This function never fails.
1075 */
1076void len2mask4(int len, struct in_addr *addr)
1077{
1078 if (len >= 32) {
1079 addr->s_addr = 0xffffffff;
1080 return;
1081 }
1082 if (len <= 0) {
1083 addr->s_addr = 0x00000000;
1084 return;
1085 }
1086 addr->s_addr = 0xffffffff << (32 - len);
1087 addr->s_addr = htonl(addr->s_addr);
1088}
1089
1090/* Convert mask from bit length form to in6_addr form.
1091 * This function never fails.
1092 */
1093void len2mask6(int len, struct in6_addr *addr)
1094{
1095 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1096 len -= 32;
1097 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1098 len -= 32;
1099 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1100 len -= 32;
1101 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1102}
1103
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001104/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001105 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001106 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1107 * is optionnal and either in the dotted or CIDR notation.
1108 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1109 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001110int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001111{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001112 __label__ out_free, out_err;
1113 char *c, *s;
1114 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001115
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001116 s = strdup(str);
1117 if (!s)
1118 return 0;
1119
Willy Tarreaubaaee002006-06-26 02:48:02 +02001120 memset(mask, 0, sizeof(*mask));
1121 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001122
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001123 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001124 *c++ = '\0';
1125 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001126 if (!str2mask(c, mask))
1127 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001128 }
1129 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001130 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001131 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001132 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001133 struct hostent *he;
1134
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001135 if (!resolve)
1136 goto out_err;
1137
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001138 if ((he = gethostbyname(s)) == NULL) {
1139 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001140 }
1141 else
1142 *addr = *(struct in_addr *) *(he->h_addr_list);
1143 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001144
1145 ret_val = 1;
1146 out_free:
1147 free(s);
1148 return ret_val;
1149 out_err:
1150 ret_val = 0;
1151 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001152}
1153
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001154
1155/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001156 * converts <str> to two struct in6_addr* which must be pre-allocated.
1157 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1158 * is an optionnal number of bits (128 being the default).
1159 * Returns 1 if OK, 0 if error.
1160 */
1161int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1162{
1163 char *c, *s;
1164 int ret_val = 0;
1165 char *err;
1166 unsigned long len = 128;
1167
1168 s = strdup(str);
1169 if (!s)
1170 return 0;
1171
1172 memset(mask, 0, sizeof(*mask));
1173 memset(addr, 0, sizeof(*addr));
1174
1175 if ((c = strrchr(s, '/')) != NULL) {
1176 *c++ = '\0'; /* c points to the mask */
1177 if (!*c)
1178 goto out_free;
1179
1180 len = strtoul(c, &err, 10);
1181 if ((err && *err) || (unsigned)len > 128)
1182 goto out_free;
1183 }
1184 *mask = len; /* OK we have a valid mask in <len> */
1185
1186 if (!inet_pton(AF_INET6, s, addr))
1187 goto out_free;
1188
1189 ret_val = 1;
1190 out_free:
1191 free(s);
1192 return ret_val;
1193}
1194
1195
1196/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001197 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001198 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001199int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001200{
1201 int saw_digit, octets, ch;
1202 u_char tmp[4], *tp;
1203 const char *cp = addr;
1204
1205 saw_digit = 0;
1206 octets = 0;
1207 *(tp = tmp) = 0;
1208
1209 while (*addr) {
1210 unsigned char digit = (ch = *addr++) - '0';
1211 if (digit > 9 && ch != '.')
1212 break;
1213 if (digit <= 9) {
1214 u_int new = *tp * 10 + digit;
1215 if (new > 255)
1216 return 0;
1217 *tp = new;
1218 if (!saw_digit) {
1219 if (++octets > 4)
1220 return 0;
1221 saw_digit = 1;
1222 }
1223 } else if (ch == '.' && saw_digit) {
1224 if (octets == 4)
1225 return 0;
1226 *++tp = 0;
1227 saw_digit = 0;
1228 } else
1229 return 0;
1230 }
1231
1232 if (octets < 4)
1233 return 0;
1234
1235 memcpy(&dst->s_addr, tmp, 4);
1236 return addr-cp-1;
1237}
1238
1239/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001240 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1241 * <out> contain the code of the dectected scheme, the start and length of
1242 * the hostname. Actually only http and https are supported. <out> can be NULL.
1243 * This function returns the consumed length. It is useful if you parse complete
1244 * url like http://host:port/path, because the consumed length corresponds to
1245 * the first character of the path. If the conversion fails, it returns -1.
1246 *
1247 * This function tries to resolve the DNS name if haproxy is in starting mode.
1248 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001249 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001250int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001251{
1252 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001253 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001254 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001255 unsigned long long int http_code = 0;
1256 int default_port;
1257 struct hostent *he;
1258 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001259
1260 /* Firstly, try to find :// pattern */
1261 while (curr < url+ulen && url_code != 0x3a2f2f) {
1262 url_code = ((url_code & 0xffff) << 8);
1263 url_code += (unsigned char)*curr++;
1264 }
1265
1266 /* Secondly, if :// pattern is found, verify parsed stuff
1267 * before pattern is matching our http pattern.
1268 * If so parse ip address and port in uri.
1269 *
1270 * WARNING: Current code doesn't support dynamic async dns resolver.
1271 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001272 if (url_code != 0x3a2f2f)
1273 return -1;
1274
1275 /* Copy scheme, and utrn to lower case. */
1276 while (cp < curr - 3)
1277 http_code = (http_code << 8) + *cp++;
1278 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001279
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001280 /* HTTP or HTTPS url matching */
1281 if (http_code == 0x2020202068747470ULL) {
1282 default_port = 80;
1283 if (out)
1284 out->scheme = SCH_HTTP;
1285 }
1286 else if (http_code == 0x2020206874747073ULL) {
1287 default_port = 443;
1288 if (out)
1289 out->scheme = SCH_HTTPS;
1290 }
1291 else
1292 return -1;
1293
1294 /* If the next char is '[', the host address is IPv6. */
1295 if (*curr == '[') {
1296 curr++;
1297
1298 /* Check trash size */
1299 if (trash.size < ulen)
1300 return -1;
1301
1302 /* Look for ']' and copy the address in a trash buffer. */
1303 p = trash.str;
1304 for (end = curr;
1305 end < url + ulen && *end != ']';
1306 end++, p++)
1307 *p = *end;
1308 if (*end != ']')
1309 return -1;
1310 *p = '\0';
1311
1312 /* Update out. */
1313 if (out) {
1314 out->host = curr;
1315 out->host_len = end - curr;
1316 }
1317
1318 /* Try IPv6 decoding. */
1319 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1320 return -1;
1321 end++;
1322
1323 /* Decode port. */
1324 if (*end == ':') {
1325 end++;
1326 default_port = read_uint(&end, url + ulen);
1327 }
1328 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1329 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1330 return end - url;
1331 }
1332 else {
1333 /* We are looking for IP address. If you want to parse and
1334 * resolve hostname found in url, you can use str2sa_range(), but
1335 * be warned this can slow down global daemon performances
1336 * while handling lagging dns responses.
1337 */
1338 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1339 if (ret) {
1340 /* Update out. */
1341 if (out) {
1342 out->host = curr;
1343 out->host_len = ret;
1344 }
1345
1346 curr += ret;
1347
1348 /* Decode port. */
1349 if (*curr == ':') {
1350 curr++;
1351 default_port = read_uint(&curr, url + ulen);
1352 }
1353 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1354
1355 /* Set family. */
1356 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1357 return curr - url;
1358 }
1359 else if (global.mode & MODE_STARTING) {
1360 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1361 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001362 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001363
1364 /* look for : or / or end */
1365 for (end = curr;
1366 end < url + ulen && *end != '/' && *end != ':';
1367 end++);
1368 memcpy(trash.str, curr, end - curr);
1369 trash.str[end - curr] = '\0';
1370
1371 /* try to resolve an IPv4/IPv6 hostname */
1372 he = gethostbyname(trash.str);
1373 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001374 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001375
1376 /* Update out. */
1377 if (out) {
1378 out->host = curr;
1379 out->host_len = end - curr;
1380 }
1381
1382 /* Decode port. */
1383 if (*end == ':') {
1384 end++;
1385 default_port = read_uint(&end, url + ulen);
1386 }
1387
1388 /* Copy IP address, set port and family. */
1389 switch (he->h_addrtype) {
1390 case AF_INET:
1391 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1392 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1393 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1394 return end - url;
1395
1396 case AF_INET6:
1397 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1398 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1399 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1400 return end - url;
1401 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001402 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001403 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001404 return -1;
1405}
1406
Willy Tarreau631f01c2011-09-05 00:36:48 +02001407/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1408 * address family is returned so that it's easy for the caller to adapt to the
1409 * output format. Zero is returned if the address family is not supported. -1
1410 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1411 * supported.
1412 */
1413int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1414{
1415
1416 void *ptr;
1417
1418 if (size < 5)
1419 return 0;
1420 *str = '\0';
1421
1422 switch (addr->ss_family) {
1423 case AF_INET:
1424 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1425 break;
1426 case AF_INET6:
1427 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1428 break;
1429 case AF_UNIX:
1430 memcpy(str, "unix", 5);
1431 return addr->ss_family;
1432 default:
1433 return 0;
1434 }
1435
1436 if (inet_ntop(addr->ss_family, ptr, str, size))
1437 return addr->ss_family;
1438
1439 /* failed */
1440 return -1;
1441}
1442
Simon Horman75ab8bd2014-06-16 09:39:41 +09001443/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1444 * address family is returned so that it's easy for the caller to adapt to the
1445 * output format. Zero is returned if the address family is not supported. -1
1446 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1447 * supported.
1448 */
1449int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1450{
1451
1452 uint16_t port;
1453
1454
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001455 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001456 return 0;
1457 *str = '\0';
1458
1459 switch (addr->ss_family) {
1460 case AF_INET:
1461 port = ((struct sockaddr_in *)addr)->sin_port;
1462 break;
1463 case AF_INET6:
1464 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1465 break;
1466 case AF_UNIX:
1467 memcpy(str, "unix", 5);
1468 return addr->ss_family;
1469 default:
1470 return 0;
1471 }
1472
1473 snprintf(str, size, "%u", ntohs(port));
1474 return addr->ss_family;
1475}
1476
Willy Tarreau16e01562016-08-09 16:46:18 +02001477/* check if the given address is local to the system or not. It will return
1478 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1479 * it is. We don't want to iterate over all interfaces for this (and it is not
1480 * portable). So instead we try to bind in UDP to this address on a free non
1481 * privileged port and to connect to the same address, port 0 (connect doesn't
1482 * care). If it succeeds, we own the address. Note that non-inet addresses are
1483 * considered local since they're most likely AF_UNIX.
1484 */
1485int addr_is_local(const struct netns_entry *ns,
1486 const struct sockaddr_storage *orig)
1487{
1488 struct sockaddr_storage addr;
1489 int result;
1490 int fd;
1491
1492 if (!is_inet_addr(orig))
1493 return 1;
1494
1495 memcpy(&addr, orig, sizeof(addr));
1496 set_host_port(&addr, 0);
1497
1498 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1499 if (fd < 0)
1500 return -1;
1501
1502 result = -1;
1503 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1504 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1505 result = 0; // fail, non-local address
1506 else
1507 result = 1; // success, local address
1508 }
1509 else {
1510 if (errno == EADDRNOTAVAIL)
1511 result = 0; // definitely not local :-)
1512 }
1513 close(fd);
1514
1515 return result;
1516}
1517
Willy Tarreaubaaee002006-06-26 02:48:02 +02001518/* will try to encode the string <string> replacing all characters tagged in
1519 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1520 * prefixed by <escape>, and will store the result between <start> (included)
1521 * and <stop> (excluded), and will always terminate the string with a '\0'
1522 * before <stop>. The position of the '\0' is returned if the conversion
1523 * completes. If bytes are missing between <start> and <stop>, then the
1524 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1525 * cannot even be stored so we return <start> without writing the 0.
1526 * The input string must also be zero-terminated.
1527 */
1528const char hextab[16] = "0123456789ABCDEF";
1529char *encode_string(char *start, char *stop,
1530 const char escape, const fd_set *map,
1531 const char *string)
1532{
1533 if (start < stop) {
1534 stop--; /* reserve one byte for the final '\0' */
1535 while (start < stop && *string != '\0') {
1536 if (!FD_ISSET((unsigned char)(*string), map))
1537 *start++ = *string;
1538 else {
1539 if (start + 3 >= stop)
1540 break;
1541 *start++ = escape;
1542 *start++ = hextab[(*string >> 4) & 15];
1543 *start++ = hextab[*string & 15];
1544 }
1545 string++;
1546 }
1547 *start = '\0';
1548 }
1549 return start;
1550}
1551
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001552/*
1553 * Same behavior as encode_string() above, except that it encodes chunk
1554 * <chunk> instead of a string.
1555 */
1556char *encode_chunk(char *start, char *stop,
1557 const char escape, const fd_set *map,
1558 const struct chunk *chunk)
1559{
1560 char *str = chunk->str;
1561 char *end = chunk->str + chunk->len;
1562
1563 if (start < stop) {
1564 stop--; /* reserve one byte for the final '\0' */
1565 while (start < stop && str < end) {
1566 if (!FD_ISSET((unsigned char)(*str), map))
1567 *start++ = *str;
1568 else {
1569 if (start + 3 >= stop)
1570 break;
1571 *start++ = escape;
1572 *start++ = hextab[(*str >> 4) & 15];
1573 *start++ = hextab[*str & 15];
1574 }
1575 str++;
1576 }
1577 *start = '\0';
1578 }
1579 return start;
1580}
1581
Dragan Dosen0edd1092016-02-12 13:23:02 +01001582/*
1583 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001584 * character. The input <string> must be zero-terminated. The result will
1585 * be stored between <start> (included) and <stop> (excluded). This
1586 * function will always try to terminate the resulting string with a '\0'
1587 * before <stop>, and will return its position if the conversion
1588 * completes.
1589 */
1590char *escape_string(char *start, char *stop,
1591 const char escape, const fd_set *map,
1592 const char *string)
1593{
1594 if (start < stop) {
1595 stop--; /* reserve one byte for the final '\0' */
1596 while (start < stop && *string != '\0') {
1597 if (!FD_ISSET((unsigned char)(*string), map))
1598 *start++ = *string;
1599 else {
1600 if (start + 2 >= stop)
1601 break;
1602 *start++ = escape;
1603 *start++ = *string;
1604 }
1605 string++;
1606 }
1607 *start = '\0';
1608 }
1609 return start;
1610}
1611
1612/*
1613 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001614 * character. <chunk> contains the input to be escaped. The result will be
1615 * stored between <start> (included) and <stop> (excluded). The function
1616 * will always try to terminate the resulting string with a '\0' before
1617 * <stop>, and will return its position if the conversion completes.
1618 */
1619char *escape_chunk(char *start, char *stop,
1620 const char escape, const fd_set *map,
1621 const struct chunk *chunk)
1622{
1623 char *str = chunk->str;
1624 char *end = chunk->str + chunk->len;
1625
1626 if (start < stop) {
1627 stop--; /* reserve one byte for the final '\0' */
1628 while (start < stop && str < end) {
1629 if (!FD_ISSET((unsigned char)(*str), map))
1630 *start++ = *str;
1631 else {
1632 if (start + 2 >= stop)
1633 break;
1634 *start++ = escape;
1635 *start++ = *str;
1636 }
1637 str++;
1638 }
1639 *start = '\0';
1640 }
1641 return start;
1642}
1643
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001644/* Check a string for using it in a CSV output format. If the string contains
1645 * one of the following four char <">, <,>, CR or LF, the string is
1646 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1647 * <str> is the input string to be escaped. The function assumes that
1648 * the input string is null-terminated.
1649 *
1650 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001651 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001652 * format.
1653 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001654 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001655 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001656 * If <quote> is 1, the converter puts the quotes only if any reserved character
1657 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001658 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001659 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001660 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001661 * The function returns the converted string on its output. If an error
1662 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001663 * for using the function directly as printf() argument.
1664 *
1665 * If the output buffer is too short to contain the input string, the result
1666 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001667 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001668 * This function appends the encoding to the existing output chunk, and it
1669 * guarantees that it starts immediately at the first available character of
1670 * the chunk. Please use csv_enc() instead if you want to replace the output
1671 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001672 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001673const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001674{
1675 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001676 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001677 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001678
Willy Tarreaub631c292016-01-08 10:04:08 +01001679 if (quote == 1) {
1680 /* automatic quoting: first verify if we'll have to quote the string */
1681 if (!strpbrk(str, "\n\r,\""))
1682 quote = 0;
1683 }
1684
1685 if (quote)
1686 *ptr++ = '"';
1687
Willy Tarreau898529b2016-01-06 18:07:04 +01001688 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1689 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001690 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001691 ptr++;
1692 if (ptr >= end - 2) {
1693 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001694 break;
1695 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001696 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001697 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001698 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001699 str++;
1700 }
1701
Willy Tarreaub631c292016-01-08 10:04:08 +01001702 if (quote)
1703 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001704
Willy Tarreau898529b2016-01-06 18:07:04 +01001705 *ptr = '\0';
1706 output->len = ptr - output->str;
1707 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001708}
1709
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001710/* Decode an URL-encoded string in-place. The resulting string might
1711 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001712 * aborted, the string is truncated before the issue and a negative value is
1713 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001714 */
1715int url_decode(char *string)
1716{
1717 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001718 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001719
1720 in = string;
1721 out = string;
1722 while (*in) {
1723 switch (*in) {
1724 case '+' :
1725 *out++ = ' ';
1726 break;
1727 case '%' :
1728 if (!ishex(in[1]) || !ishex(in[2]))
1729 goto end;
1730 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1731 in += 2;
1732 break;
1733 default:
1734 *out++ = *in;
1735 break;
1736 }
1737 in++;
1738 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001739 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001740 end:
1741 *out = 0;
1742 return ret;
1743}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001744
Willy Tarreau6911fa42007-03-04 18:06:08 +01001745unsigned int str2ui(const char *s)
1746{
1747 return __str2ui(s);
1748}
1749
1750unsigned int str2uic(const char *s)
1751{
1752 return __str2uic(s);
1753}
1754
1755unsigned int strl2ui(const char *s, int len)
1756{
1757 return __strl2ui(s, len);
1758}
1759
1760unsigned int strl2uic(const char *s, int len)
1761{
1762 return __strl2uic(s, len);
1763}
1764
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001765unsigned int read_uint(const char **s, const char *end)
1766{
1767 return __read_uint(s, end);
1768}
1769
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001770/* This function reads an unsigned integer from the string pointed to by <s> and
1771 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1772 * function automatically stops at <end>. If the number overflows, the 2^64-1
1773 * value is returned.
1774 */
1775unsigned long long int read_uint64(const char **s, const char *end)
1776{
1777 const char *ptr = *s;
1778 unsigned long long int i = 0, tmp;
1779 unsigned int j;
1780
1781 while (ptr < end) {
1782
1783 /* read next char */
1784 j = *ptr - '0';
1785 if (j > 9)
1786 goto read_uint64_end;
1787
1788 /* add char to the number and check overflow. */
1789 tmp = i * 10;
1790 if (tmp / 10 != i) {
1791 i = ULLONG_MAX;
1792 goto read_uint64_eat;
1793 }
1794 if (ULLONG_MAX - tmp < j) {
1795 i = ULLONG_MAX;
1796 goto read_uint64_eat;
1797 }
1798 i = tmp + j;
1799 ptr++;
1800 }
1801read_uint64_eat:
1802 /* eat each numeric char */
1803 while (ptr < end) {
1804 if ((unsigned int)(*ptr - '0') > 9)
1805 break;
1806 ptr++;
1807 }
1808read_uint64_end:
1809 *s = ptr;
1810 return i;
1811}
1812
1813/* This function reads an integer from the string pointed to by <s> and returns
1814 * it. The <s> pointer is adjusted to point to the first unread char. The function
1815 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1816 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1817 * returned.
1818 */
1819long long int read_int64(const char **s, const char *end)
1820{
1821 unsigned long long int i = 0;
1822 int neg = 0;
1823
1824 /* Look for minus char. */
1825 if (**s == '-') {
1826 neg = 1;
1827 (*s)++;
1828 }
1829 else if (**s == '+')
1830 (*s)++;
1831
1832 /* convert as positive number. */
1833 i = read_uint64(s, end);
1834
1835 if (neg) {
1836 if (i > 0x8000000000000000ULL)
1837 return LLONG_MIN;
1838 return -i;
1839 }
1840 if (i > 0x7fffffffffffffffULL)
1841 return LLONG_MAX;
1842 return i;
1843}
1844
Willy Tarreau6911fa42007-03-04 18:06:08 +01001845/* This one is 7 times faster than strtol() on athlon with checks.
1846 * It returns the value of the number composed of all valid digits read,
1847 * and can process negative numbers too.
1848 */
1849int strl2ic(const char *s, int len)
1850{
1851 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001852 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001853
1854 if (len > 0) {
1855 if (*s != '-') {
1856 /* positive number */
1857 while (len-- > 0) {
1858 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001859 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001860 if (j > 9)
1861 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001862 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001863 }
1864 } else {
1865 /* negative number */
1866 s++;
1867 while (--len > 0) {
1868 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001869 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001870 if (j > 9)
1871 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001872 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001873 }
1874 }
1875 }
1876 return i;
1877}
1878
1879
1880/* This function reads exactly <len> chars from <s> and converts them to a
1881 * signed integer which it stores into <ret>. It accurately detects any error
1882 * (truncated string, invalid chars, overflows). It is meant to be used in
1883 * applications designed for hostile environments. It returns zero when the
1884 * number has successfully been converted, non-zero otherwise. When an error
1885 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1886 * faster than strtol().
1887 */
1888int strl2irc(const char *s, int len, int *ret)
1889{
1890 int i = 0;
1891 int j;
1892
1893 if (!len)
1894 return 1;
1895
1896 if (*s != '-') {
1897 /* positive number */
1898 while (len-- > 0) {
1899 j = (*s++) - '0';
1900 if (j > 9) return 1; /* invalid char */
1901 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1902 i = i * 10;
1903 if (i + j < i) return 1; /* check for addition overflow */
1904 i = i + j;
1905 }
1906 } else {
1907 /* negative number */
1908 s++;
1909 while (--len > 0) {
1910 j = (*s++) - '0';
1911 if (j > 9) return 1; /* invalid char */
1912 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1913 i = i * 10;
1914 if (i - j > i) return 1; /* check for subtract overflow */
1915 i = i - j;
1916 }
1917 }
1918 *ret = i;
1919 return 0;
1920}
1921
1922
1923/* This function reads exactly <len> chars from <s> and converts them to a
1924 * signed integer which it stores into <ret>. It accurately detects any error
1925 * (truncated string, invalid chars, overflows). It is meant to be used in
1926 * applications designed for hostile environments. It returns zero when the
1927 * number has successfully been converted, non-zero otherwise. When an error
1928 * is returned, the <ret> value is left untouched. It is about 3 times slower
1929 * than str2irc().
1930 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001931
1932int strl2llrc(const char *s, int len, long long *ret)
1933{
1934 long long i = 0;
1935 int j;
1936
1937 if (!len)
1938 return 1;
1939
1940 if (*s != '-') {
1941 /* positive number */
1942 while (len-- > 0) {
1943 j = (*s++) - '0';
1944 if (j > 9) return 1; /* invalid char */
1945 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1946 i = i * 10LL;
1947 if (i + j < i) return 1; /* check for addition overflow */
1948 i = i + j;
1949 }
1950 } else {
1951 /* negative number */
1952 s++;
1953 while (--len > 0) {
1954 j = (*s++) - '0';
1955 if (j > 9) return 1; /* invalid char */
1956 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1957 i = i * 10LL;
1958 if (i - j > i) return 1; /* check for subtract overflow */
1959 i = i - j;
1960 }
1961 }
1962 *ret = i;
1963 return 0;
1964}
1965
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001966/* This function is used with pat_parse_dotted_ver(). It converts a string
1967 * composed by two number separated by a dot. Each part must contain in 16 bits
1968 * because internally they will be represented as a 32-bit quantity stored in
1969 * a 64-bit integer. It returns zero when the number has successfully been
1970 * converted, non-zero otherwise. When an error is returned, the <ret> value
1971 * is left untouched.
1972 *
1973 * "1.3" -> 0x0000000000010003
1974 * "65535.65535" -> 0x00000000ffffffff
1975 */
1976int strl2llrc_dotted(const char *text, int len, long long *ret)
1977{
1978 const char *end = &text[len];
1979 const char *p;
1980 long long major, minor;
1981
1982 /* Look for dot. */
1983 for (p = text; p < end; p++)
1984 if (*p == '.')
1985 break;
1986
1987 /* Convert major. */
1988 if (strl2llrc(text, p - text, &major) != 0)
1989 return 1;
1990
1991 /* Check major. */
1992 if (major >= 65536)
1993 return 1;
1994
1995 /* Convert minor. */
1996 minor = 0;
1997 if (p < end)
1998 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1999 return 1;
2000
2001 /* Check minor. */
2002 if (minor >= 65536)
2003 return 1;
2004
2005 /* Compose value. */
2006 *ret = (major << 16) | (minor & 0xffff);
2007 return 0;
2008}
2009
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002010/* This function parses a time value optionally followed by a unit suffix among
2011 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2012 * expected by the caller. The computation does its best to avoid overflows.
2013 * The value is returned in <ret> if everything is fine, and a NULL is returned
2014 * by the function. In case of error, a pointer to the error is returned and
2015 * <ret> is left untouched. Values are automatically rounded up when needed.
2016 */
2017const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2018{
2019 unsigned imult, idiv;
2020 unsigned omult, odiv;
2021 unsigned value;
2022
2023 omult = odiv = 1;
2024
2025 switch (unit_flags & TIME_UNIT_MASK) {
2026 case TIME_UNIT_US: omult = 1000000; break;
2027 case TIME_UNIT_MS: omult = 1000; break;
2028 case TIME_UNIT_S: break;
2029 case TIME_UNIT_MIN: odiv = 60; break;
2030 case TIME_UNIT_HOUR: odiv = 3600; break;
2031 case TIME_UNIT_DAY: odiv = 86400; break;
2032 default: break;
2033 }
2034
2035 value = 0;
2036
2037 while (1) {
2038 unsigned int j;
2039
2040 j = *text - '0';
2041 if (j > 9)
2042 break;
2043 text++;
2044 value *= 10;
2045 value += j;
2046 }
2047
2048 imult = idiv = 1;
2049 switch (*text) {
2050 case '\0': /* no unit = default unit */
2051 imult = omult = idiv = odiv = 1;
2052 break;
2053 case 's': /* second = unscaled unit */
2054 break;
2055 case 'u': /* microsecond : "us" */
2056 if (text[1] == 's') {
2057 idiv = 1000000;
2058 text++;
2059 }
2060 break;
2061 case 'm': /* millisecond : "ms" or minute: "m" */
2062 if (text[1] == 's') {
2063 idiv = 1000;
2064 text++;
2065 } else
2066 imult = 60;
2067 break;
2068 case 'h': /* hour : "h" */
2069 imult = 3600;
2070 break;
2071 case 'd': /* day : "d" */
2072 imult = 86400;
2073 break;
2074 default:
2075 return text;
2076 break;
2077 }
2078
2079 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2080 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2081 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2082 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2083
2084 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2085 *ret = value;
2086 return NULL;
2087}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002088
Emeric Brun39132b22010-01-04 14:57:24 +01002089/* this function converts the string starting at <text> to an unsigned int
2090 * stored in <ret>. If an error is detected, the pointer to the unexpected
2091 * character is returned. If the conversio is succesful, NULL is returned.
2092 */
2093const char *parse_size_err(const char *text, unsigned *ret) {
2094 unsigned value = 0;
2095
2096 while (1) {
2097 unsigned int j;
2098
2099 j = *text - '0';
2100 if (j > 9)
2101 break;
2102 if (value > ~0U / 10)
2103 return text;
2104 value *= 10;
2105 if (value > (value + j))
2106 return text;
2107 value += j;
2108 text++;
2109 }
2110
2111 switch (*text) {
2112 case '\0':
2113 break;
2114 case 'K':
2115 case 'k':
2116 if (value > ~0U >> 10)
2117 return text;
2118 value = value << 10;
2119 break;
2120 case 'M':
2121 case 'm':
2122 if (value > ~0U >> 20)
2123 return text;
2124 value = value << 20;
2125 break;
2126 case 'G':
2127 case 'g':
2128 if (value > ~0U >> 30)
2129 return text;
2130 value = value << 30;
2131 break;
2132 default:
2133 return text;
2134 }
2135
Godbach58048a22015-01-28 17:36:16 +08002136 if (*text != '\0' && *++text != '\0')
2137 return text;
2138
Emeric Brun39132b22010-01-04 14:57:24 +01002139 *ret = value;
2140 return NULL;
2141}
2142
Willy Tarreau126d4062013-12-03 17:50:47 +01002143/*
2144 * Parse binary string written in hexadecimal (source) and store the decoded
2145 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2146 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002147 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002148 */
2149int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2150{
2151 int len;
2152 const char *p = source;
2153 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002154 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002155
2156 len = strlen(source);
2157 if (len % 2) {
2158 memprintf(err, "an even number of hex digit is expected");
2159 return 0;
2160 }
2161
2162 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002163
Willy Tarreau126d4062013-12-03 17:50:47 +01002164 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002165 *binstr = calloc(len, sizeof(char));
2166 if (!*binstr) {
2167 memprintf(err, "out of memory while loading string pattern");
2168 return 0;
2169 }
2170 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002171 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002172 else {
2173 if (*binstrlen < len) {
2174 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2175 len, *binstrlen);
2176 return 0;
2177 }
2178 alloc = 0;
2179 }
2180 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002181
2182 i = j = 0;
2183 while (j < len) {
2184 if (!ishex(p[i++]))
2185 goto bad_input;
2186 if (!ishex(p[i++]))
2187 goto bad_input;
2188 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2189 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002190 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002191
2192bad_input:
2193 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002194 if (alloc) {
2195 free(*binstr);
2196 *binstr = NULL;
2197 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002198 return 0;
2199}
2200
Willy Tarreau946ba592009-05-10 15:41:18 +02002201/* copies at most <n> characters from <src> and always terminates with '\0' */
2202char *my_strndup(const char *src, int n)
2203{
2204 int len = 0;
2205 char *ret;
2206
2207 while (len < n && src[len])
2208 len++;
2209
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002210 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002211 if (!ret)
2212 return ret;
2213 memcpy(ret, src, len);
2214 ret[len] = '\0';
2215 return ret;
2216}
2217
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002218/*
2219 * search needle in haystack
2220 * returns the pointer if found, returns NULL otherwise
2221 */
2222const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2223{
2224 const void *c = NULL;
2225 unsigned char f;
2226
2227 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2228 return NULL;
2229
2230 f = *(char *)needle;
2231 c = haystack;
2232 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2233 if ((haystacklen - (c - haystack)) < needlelen)
2234 return NULL;
2235
2236 if (memcmp(c, needle, needlelen) == 0)
2237 return c;
2238 ++c;
2239 }
2240 return NULL;
2241}
2242
Willy Tarreau482b00d2009-10-04 22:48:42 +02002243/* This function returns the first unused key greater than or equal to <key> in
2244 * ID tree <root>. Zero is returned if no place is found.
2245 */
2246unsigned int get_next_id(struct eb_root *root, unsigned int key)
2247{
2248 struct eb32_node *used;
2249
2250 do {
2251 used = eb32_lookup_ge(root, key);
2252 if (!used || used->key > key)
2253 return key; /* key is available */
2254 key++;
2255 } while (key);
2256 return key;
2257}
2258
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002259/* dump the full tree to <file> in DOT format for debugging purposes. Will
2260 * optionally highlight node <subj> if found, depending on operation <op> :
2261 * 0 : nothing
2262 * >0 : insertion, node/leaf are surrounded in red
2263 * <0 : removal, node/leaf are dashed with no background
2264 * Will optionally add "desc" as a label on the graph if set and non-null.
2265 */
2266void 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 +01002267{
2268 struct eb32sc_node *node;
2269 unsigned long scope = -1;
2270
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002271 fprintf(file, "digraph ebtree {\n");
2272
2273 if (desc && *desc) {
2274 fprintf(file,
2275 " fontname=\"fixed\";\n"
2276 " fontsize=8;\n"
2277 " label=\"%s\";\n", desc);
2278 }
2279
Willy Tarreaued3cda02017-11-15 15:04:05 +01002280 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002281 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2282 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002283 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2284 );
2285
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002286 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002287 (long)eb_root_to_node(root),
2288 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002289 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2290
2291 node = eb32sc_first(root, scope);
2292 while (node) {
2293 if (node->node.node_p) {
2294 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002295 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2296 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2297 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002298
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002299 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002300 (long)node,
2301 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002302 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002303
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002304 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002305 (long)node,
2306 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002307 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2308
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002309 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002310 (long)node,
2311 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002312 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2313 }
2314
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002315 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2316 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2317 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002318
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002319 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002320 (long)node,
2321 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002322 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002323 node = eb32sc_next(node, scope);
2324 }
2325 fprintf(file, "}\n");
2326}
2327
Willy Tarreau348238b2010-01-18 15:05:57 +01002328/* This function compares a sample word possibly followed by blanks to another
2329 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2330 * otherwise zero. This intends to be used when checking HTTP headers for some
2331 * values. Note that it validates a word followed only by blanks but does not
2332 * validate a word followed by blanks then other chars.
2333 */
2334int word_match(const char *sample, int slen, const char *word, int wlen)
2335{
2336 if (slen < wlen)
2337 return 0;
2338
2339 while (wlen) {
2340 char c = *sample ^ *word;
2341 if (c && c != ('A' ^ 'a'))
2342 return 0;
2343 sample++;
2344 word++;
2345 slen--;
2346 wlen--;
2347 }
2348
2349 while (slen) {
2350 if (*sample != ' ' && *sample != '\t')
2351 return 0;
2352 sample++;
2353 slen--;
2354 }
2355 return 1;
2356}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002357
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002358/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2359 * is particularly fast because it avoids expensive operations such as
2360 * multiplies, which are optimized away at the end. It requires a properly
2361 * formated address though (3 points).
2362 */
2363unsigned int inetaddr_host(const char *text)
2364{
2365 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2366 register unsigned int dig100, dig10, dig1;
2367 int s;
2368 const char *p, *d;
2369
2370 dig1 = dig10 = dig100 = ascii_zero;
2371 s = 24;
2372
2373 p = text;
2374 while (1) {
2375 if (((unsigned)(*p - '0')) <= 9) {
2376 p++;
2377 continue;
2378 }
2379
2380 /* here, we have a complete byte between <text> and <p> (exclusive) */
2381 if (p == text)
2382 goto end;
2383
2384 d = p - 1;
2385 dig1 |= (unsigned int)(*d << s);
2386 if (d == text)
2387 goto end;
2388
2389 d--;
2390 dig10 |= (unsigned int)(*d << s);
2391 if (d == text)
2392 goto end;
2393
2394 d--;
2395 dig100 |= (unsigned int)(*d << s);
2396 end:
2397 if (!s || *p != '.')
2398 break;
2399
2400 s -= 8;
2401 text = ++p;
2402 }
2403
2404 dig100 -= ascii_zero;
2405 dig10 -= ascii_zero;
2406 dig1 -= ascii_zero;
2407 return ((dig100 * 10) + dig10) * 10 + dig1;
2408}
2409
2410/*
2411 * Idem except the first unparsed character has to be passed in <stop>.
2412 */
2413unsigned int inetaddr_host_lim(const char *text, const char *stop)
2414{
2415 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2416 register unsigned int dig100, dig10, dig1;
2417 int s;
2418 const char *p, *d;
2419
2420 dig1 = dig10 = dig100 = ascii_zero;
2421 s = 24;
2422
2423 p = text;
2424 while (1) {
2425 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2426 p++;
2427 continue;
2428 }
2429
2430 /* here, we have a complete byte between <text> and <p> (exclusive) */
2431 if (p == text)
2432 goto end;
2433
2434 d = p - 1;
2435 dig1 |= (unsigned int)(*d << s);
2436 if (d == text)
2437 goto end;
2438
2439 d--;
2440 dig10 |= (unsigned int)(*d << s);
2441 if (d == text)
2442 goto end;
2443
2444 d--;
2445 dig100 |= (unsigned int)(*d << s);
2446 end:
2447 if (!s || p == stop || *p != '.')
2448 break;
2449
2450 s -= 8;
2451 text = ++p;
2452 }
2453
2454 dig100 -= ascii_zero;
2455 dig10 -= ascii_zero;
2456 dig1 -= ascii_zero;
2457 return ((dig100 * 10) + dig10) * 10 + dig1;
2458}
2459
2460/*
2461 * Idem except the pointer to first unparsed byte is returned into <ret> which
2462 * must not be NULL.
2463 */
Willy Tarreau74172752010-10-15 23:21:42 +02002464unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002465{
2466 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2467 register unsigned int dig100, dig10, dig1;
2468 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002469 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002470
2471 dig1 = dig10 = dig100 = ascii_zero;
2472 s = 24;
2473
2474 p = text;
2475 while (1) {
2476 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2477 p++;
2478 continue;
2479 }
2480
2481 /* here, we have a complete byte between <text> and <p> (exclusive) */
2482 if (p == text)
2483 goto end;
2484
2485 d = p - 1;
2486 dig1 |= (unsigned int)(*d << s);
2487 if (d == text)
2488 goto end;
2489
2490 d--;
2491 dig10 |= (unsigned int)(*d << s);
2492 if (d == text)
2493 goto end;
2494
2495 d--;
2496 dig100 |= (unsigned int)(*d << s);
2497 end:
2498 if (!s || p == stop || *p != '.')
2499 break;
2500
2501 s -= 8;
2502 text = ++p;
2503 }
2504
2505 *ret = p;
2506 dig100 -= ascii_zero;
2507 dig10 -= ascii_zero;
2508 dig1 -= ascii_zero;
2509 return ((dig100 * 10) + dig10) * 10 + dig1;
2510}
2511
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002512/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2513 * or the number of chars read in case of success. Maybe this could be replaced
2514 * by one of the functions above. Also, apparently this function does not support
2515 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002516 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002517 */
2518int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2519{
2520 const char *addr;
2521 int saw_digit, octets, ch;
2522 u_char tmp[4], *tp;
2523 const char *cp = buf;
2524
2525 saw_digit = 0;
2526 octets = 0;
2527 *(tp = tmp) = 0;
2528
2529 for (addr = buf; addr - buf < len; addr++) {
2530 unsigned char digit = (ch = *addr) - '0';
2531
2532 if (digit > 9 && ch != '.')
2533 break;
2534
2535 if (digit <= 9) {
2536 u_int new = *tp * 10 + digit;
2537
2538 if (new > 255)
2539 return 0;
2540
2541 *tp = new;
2542
2543 if (!saw_digit) {
2544 if (++octets > 4)
2545 return 0;
2546 saw_digit = 1;
2547 }
2548 } else if (ch == '.' && saw_digit) {
2549 if (octets == 4)
2550 return 0;
2551
2552 *++tp = 0;
2553 saw_digit = 0;
2554 } else
2555 return 0;
2556 }
2557
2558 if (octets < 4)
2559 return 0;
2560
2561 memcpy(&dst->s_addr, tmp, 4);
2562 return addr - cp;
2563}
2564
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002565/* This function converts the string in <buf> of the len <len> to
2566 * struct in6_addr <dst> which must be allocated by the caller.
2567 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002568 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002569 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002570int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2571{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002572 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002573 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002574
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002575 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002576 return 0;
2577
2578 memcpy(null_term_ip6, buf, len);
2579 null_term_ip6[len] = '\0';
2580
Willy Tarreau075415a2013-12-12 11:29:39 +01002581 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002582 return 0;
2583
Willy Tarreau075415a2013-12-12 11:29:39 +01002584 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002585 return 1;
2586}
2587
Willy Tarreauacf95772010-06-14 19:09:21 +02002588/* To be used to quote config arg positions. Returns the short string at <ptr>
2589 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2590 * if ptr is NULL or empty. The string is locally allocated.
2591 */
2592const char *quote_arg(const char *ptr)
2593{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002594 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002595 int i;
2596
2597 if (!ptr || !*ptr)
2598 return "end of line";
2599 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002600 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002601 val[i] = *ptr++;
2602 val[i++] = '\'';
2603 val[i] = '\0';
2604 return val;
2605}
2606
Willy Tarreau5b180202010-07-18 10:40:48 +02002607/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2608int get_std_op(const char *str)
2609{
2610 int ret = -1;
2611
2612 if (*str == 'e' && str[1] == 'q')
2613 ret = STD_OP_EQ;
2614 else if (*str == 'n' && str[1] == 'e')
2615 ret = STD_OP_NE;
2616 else if (*str == 'l') {
2617 if (str[1] == 'e') ret = STD_OP_LE;
2618 else if (str[1] == 't') ret = STD_OP_LT;
2619 }
2620 else if (*str == 'g') {
2621 if (str[1] == 'e') ret = STD_OP_GE;
2622 else if (str[1] == 't') ret = STD_OP_GT;
2623 }
2624
2625 if (ret == -1 || str[2] != '\0')
2626 return -1;
2627 return ret;
2628}
2629
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002630/* hash a 32-bit integer to another 32-bit integer */
2631unsigned int full_hash(unsigned int a)
2632{
2633 return __full_hash(a);
2634}
2635
David du Colombier4f92d322011-03-24 11:09:31 +01002636/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002637 * otherwise zero. Note that <addr> may not necessarily be aligned
2638 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002639 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002640int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002641{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002642 struct in_addr addr_copy;
2643
2644 memcpy(&addr_copy, addr, sizeof(addr_copy));
2645 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002646}
2647
2648/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002649 * otherwise zero. Note that <addr> may not necessarily be aligned
2650 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002651 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002652int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002653{
2654 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002655 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002656
Willy Tarreaueec1d382016-07-13 11:59:39 +02002657 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002658 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002659 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002660 (((int *)net)[i] & ((int *)mask)[i]))
2661 return 0;
2662 return 1;
2663}
2664
2665/* RFC 4291 prefix */
2666const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2667 0x00, 0x00, 0x00, 0x00,
2668 0x00, 0x00, 0xFF, 0xFF };
2669
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002670/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2671 * Input and output may overlap.
2672 */
David du Colombier4f92d322011-03-24 11:09:31 +01002673void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2674{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002675 struct in_addr tmp_addr;
2676
2677 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002678 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002679 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002680}
2681
2682/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2683 * Return true if conversion is possible and false otherwise.
2684 */
2685int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2686{
2687 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2688 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2689 sizeof(struct in_addr));
2690 return 1;
2691 }
2692
2693 return 0;
2694}
2695
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002696/* compare two struct sockaddr_storage and return:
2697 * 0 (true) if the addr is the same in both
2698 * 1 (false) if the addr is not the same in both
2699 * -1 (unable) if one of the addr is not AF_INET*
2700 */
2701int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2702{
2703 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2704 return -1;
2705
2706 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2707 return -1;
2708
2709 if (ss1->ss_family != ss2->ss_family)
2710 return 1;
2711
2712 switch (ss1->ss_family) {
2713 case AF_INET:
2714 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2715 &((struct sockaddr_in *)ss2)->sin_addr,
2716 sizeof(struct in_addr)) != 0;
2717 case AF_INET6:
2718 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2719 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2720 sizeof(struct in6_addr)) != 0;
2721 }
2722
2723 return 1;
2724}
2725
Baptiste Assmann08396c82016-01-31 00:27:17 +01002726/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002727 * The caller must allocate and clear <dest> before calling.
2728 * The source must be in either AF_INET or AF_INET6 family, or the destination
2729 * address will be undefined. If the destination address used to hold a port,
2730 * it is preserved, so that this function can be used to switch to another
2731 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002732 */
2733struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2734{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002735 int prev_port;
2736
2737 prev_port = get_net_port(dest);
2738 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002739 dest->ss_family = source->ss_family;
2740
2741 /* copy new addr and apply it */
2742 switch (source->ss_family) {
2743 case AF_INET:
2744 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002745 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002746 break;
2747 case AF_INET6:
2748 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 +01002749 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002750 break;
2751 }
2752
2753 return dest;
2754}
2755
William Lallemand421f5b52012-02-06 18:15:57 +01002756char *human_time(int t, short hz_div) {
2757 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2758 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002759 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002760 int cnt=2; // print two numbers
2761
2762 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002763 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002764 return rv;
2765 }
2766
2767 if (unlikely(hz_div > 1))
2768 t /= hz_div;
2769
2770 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002771 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002772 cnt--;
2773 }
2774
2775 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002776 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002777 cnt--;
2778 }
2779
2780 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002781 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002782 cnt--;
2783 }
2784
2785 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002786 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002787
2788 return rv;
2789}
2790
2791const char *monthname[12] = {
2792 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2793 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2794};
2795
2796/* date2str_log: write a date in the format :
2797 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2798 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2799 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2800 *
2801 * without using sprintf. return a pointer to the last char written (\0) or
2802 * NULL if there isn't enough space.
2803 */
2804char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2805{
2806
2807 if (size < 25) /* the size is fixed: 24 chars + \0 */
2808 return NULL;
2809
2810 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2811 *dst++ = '/';
2812 memcpy(dst, monthname[tm->tm_mon], 3); // month
2813 dst += 3;
2814 *dst++ = '/';
2815 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2816 *dst++ = ':';
2817 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2818 *dst++ = ':';
2819 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2820 *dst++ = ':';
2821 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2822 *dst++ = '.';
2823 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2824 dst += 3; // only the 3 first digits
2825 *dst = '\0';
2826
2827 return dst;
2828}
2829
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002830/* Base year used to compute leap years */
2831#define TM_YEAR_BASE 1900
2832
2833/* Return the difference in seconds between two times (leap seconds are ignored).
2834 * Retrieved from glibc 2.18 source code.
2835 */
2836static int my_tm_diff(const struct tm *a, const struct tm *b)
2837{
2838 /* Compute intervening leap days correctly even if year is negative.
2839 * Take care to avoid int overflow in leap day calculations,
2840 * but it's OK to assume that A and B are close to each other.
2841 */
2842 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2843 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2844 int a100 = a4 / 25 - (a4 % 25 < 0);
2845 int b100 = b4 / 25 - (b4 % 25 < 0);
2846 int a400 = a100 >> 2;
2847 int b400 = b100 >> 2;
2848 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2849 int years = a->tm_year - b->tm_year;
2850 int days = (365 * years + intervening_leap_days
2851 + (a->tm_yday - b->tm_yday));
2852 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2853 + (a->tm_min - b->tm_min))
2854 + (a->tm_sec - b->tm_sec));
2855}
2856
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002857/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002858 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002859 * The string returned has the same format as returned by strftime(... "%z", tm).
2860 * Offsets are kept in an internal cache for better performances.
2861 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002862const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002863{
2864 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002865 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002866
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002867 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002868 struct tm tm_gmt;
2869 int diff;
2870 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002871
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002872 /* Pretend DST not active if its status is unknown */
2873 if (isdst < 0)
2874 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002875
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002876 /* Fetch the offset and initialize it if needed */
2877 gmt_offset = gmt_offsets[isdst & 0x01];
2878 if (unlikely(!*gmt_offset)) {
2879 get_gmtime(t, &tm_gmt);
2880 diff = my_tm_diff(tm, &tm_gmt);
2881 if (diff < 0) {
2882 diff = -diff;
2883 *gmt_offset = '-';
2884 } else {
2885 *gmt_offset = '+';
2886 }
2887 diff /= 60; /* Convert to minutes */
2888 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2889 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002890
2891 return gmt_offset;
2892}
2893
William Lallemand421f5b52012-02-06 18:15:57 +01002894/* gmt2str_log: write a date in the format :
2895 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2896 * return a pointer to the last char written (\0) or
2897 * NULL if there isn't enough space.
2898 */
2899char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2900{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002901 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002902 return NULL;
2903
2904 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2905 *dst++ = '/';
2906 memcpy(dst, monthname[tm->tm_mon], 3); // month
2907 dst += 3;
2908 *dst++ = '/';
2909 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2910 *dst++ = ':';
2911 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2912 *dst++ = ':';
2913 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2914 *dst++ = ':';
2915 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2916 *dst++ = ' ';
2917 *dst++ = '+';
2918 *dst++ = '0';
2919 *dst++ = '0';
2920 *dst++ = '0';
2921 *dst++ = '0';
2922 *dst = '\0';
2923
2924 return dst;
2925}
2926
Yuxans Yao4e25b012012-10-19 10:36:09 +08002927/* localdate2str_log: write a date in the format :
2928 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002929 * Both t and tm must represent the same time.
2930 * return a pointer to the last char written (\0) or
2931 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002932 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002933char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002934{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002935 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002936 if (size < 27) /* the size is fixed: 26 chars + \0 */
2937 return NULL;
2938
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002939 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002940
Yuxans Yao4e25b012012-10-19 10:36:09 +08002941 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2942 *dst++ = '/';
2943 memcpy(dst, monthname[tm->tm_mon], 3); // month
2944 dst += 3;
2945 *dst++ = '/';
2946 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2947 *dst++ = ':';
2948 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2949 *dst++ = ':';
2950 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2951 *dst++ = ':';
2952 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2953 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002954 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002955 dst += 5;
2956 *dst = '\0';
2957
2958 return dst;
2959}
2960
Willy Tarreaucb1949b2017-07-19 19:05:29 +02002961/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
2962 * It is meant as a portable replacement for timegm() for use with valid inputs.
2963 * Returns undefined results for invalid dates (eg: months out of range 0..11).
2964 */
2965time_t my_timegm(const struct tm *tm)
2966{
2967 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
2968 * is thus (current month - 1)*28 + cumulated_N[month] to count the
2969 * sum of the extra N days for elapsed months. The sum of all these N
2970 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
2971 * in a 5-bit word. This means that with 60 bits we can represent a
2972 * matrix of all these values at once, which is fast and efficient to
2973 * access. The extra February day for leap years is not counted here.
2974 *
2975 * Jan : none = 0 (0)
2976 * Feb : Jan = 3 (3)
2977 * Mar : Jan..Feb = 3 (3 + 0)
2978 * Apr : Jan..Mar = 6 (3 + 0 + 3)
2979 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
2980 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
2981 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
2982 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
2983 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
2984 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
2985 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
2986 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
2987 */
2988 uint64_t extra =
2989 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
2990 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
2991 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
2992 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
2993
2994 unsigned int y = tm->tm_year + 1900;
2995 unsigned int m = tm->tm_mon;
2996 unsigned long days = 0;
2997
2998 /* days since 1/1/1970 for full years */
2999 days += days_since_zero(y) - days_since_zero(1970);
3000
3001 /* days for full months in the current year */
3002 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3003
3004 /* count + 1 after March for leap years. A leap year is a year multiple
3005 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3006 * is leap, 1900 isn't, 1904 is.
3007 */
3008 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3009 days++;
3010
3011 days += tm->tm_mday - 1;
3012 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3013}
3014
Thierry Fournier93127942016-01-20 18:49:45 +01003015/* This function check a char. It returns true and updates
3016 * <date> and <len> pointer to the new position if the
3017 * character is found.
3018 */
3019static inline int parse_expect_char(const char **date, int *len, char c)
3020{
3021 if (*len < 1 || **date != c)
3022 return 0;
3023 (*len)--;
3024 (*date)++;
3025 return 1;
3026}
3027
3028/* This function expects a string <str> of len <l>. It return true and updates.
3029 * <date> and <len> if the string matches, otherwise, it returns false.
3030 */
3031static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3032{
3033 if (*len < l || strncmp(*date, str, l) != 0)
3034 return 0;
3035 (*len) -= l;
3036 (*date) += l;
3037 return 1;
3038}
3039
3040/* This macro converts 3 chars name in integer. */
3041#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3042
3043/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3044 * / %x54.75.65 ; "Tue", case-sensitive
3045 * / %x57.65.64 ; "Wed", case-sensitive
3046 * / %x54.68.75 ; "Thu", case-sensitive
3047 * / %x46.72.69 ; "Fri", case-sensitive
3048 * / %x53.61.74 ; "Sat", case-sensitive
3049 * / %x53.75.6E ; "Sun", case-sensitive
3050 *
3051 * This array must be alphabetically sorted
3052 */
3053static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3054{
3055 if (*len < 3)
3056 return 0;
3057 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3058 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3059 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3060 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3061 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3062 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3063 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3064 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3065 default: return 0;
3066 }
3067 *len -= 3;
3068 *date += 3;
3069 return 1;
3070}
3071
3072/* month = %x4A.61.6E ; "Jan", case-sensitive
3073 * / %x46.65.62 ; "Feb", case-sensitive
3074 * / %x4D.61.72 ; "Mar", case-sensitive
3075 * / %x41.70.72 ; "Apr", case-sensitive
3076 * / %x4D.61.79 ; "May", case-sensitive
3077 * / %x4A.75.6E ; "Jun", case-sensitive
3078 * / %x4A.75.6C ; "Jul", case-sensitive
3079 * / %x41.75.67 ; "Aug", case-sensitive
3080 * / %x53.65.70 ; "Sep", case-sensitive
3081 * / %x4F.63.74 ; "Oct", case-sensitive
3082 * / %x4E.6F.76 ; "Nov", case-sensitive
3083 * / %x44.65.63 ; "Dec", case-sensitive
3084 *
3085 * This array must be alphabetically sorted
3086 */
3087static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3088{
3089 if (*len < 3)
3090 return 0;
3091 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3092 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3093 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3094 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3095 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3096 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3097 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3098 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3099 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3100 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3101 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3102 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3103 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3104 default: return 0;
3105 }
3106 *len -= 3;
3107 *date += 3;
3108 return 1;
3109}
3110
3111/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3112 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3113 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3114 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3115 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3116 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3117 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3118 *
3119 * This array must be alphabetically sorted
3120 */
3121static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3122{
3123 if (*len < 6) /* Minimum length. */
3124 return 0;
3125 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3126 case STR2I3('M','o','n'):
3127 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3128 tm->tm_wday = 1;
3129 return 1;
3130 case STR2I3('T','u','e'):
3131 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3132 tm->tm_wday = 2;
3133 return 1;
3134 case STR2I3('W','e','d'):
3135 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3136 tm->tm_wday = 3;
3137 return 1;
3138 case STR2I3('T','h','u'):
3139 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3140 tm->tm_wday = 4;
3141 return 1;
3142 case STR2I3('F','r','i'):
3143 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3144 tm->tm_wday = 5;
3145 return 1;
3146 case STR2I3('S','a','t'):
3147 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3148 tm->tm_wday = 6;
3149 return 1;
3150 case STR2I3('S','u','n'):
3151 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3152 tm->tm_wday = 7;
3153 return 1;
3154 }
3155 return 0;
3156}
3157
3158/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3159static inline int parse_digit(const char **date, int *len, int *digit)
3160{
3161 if (*len < 1 || **date < '0' || **date > '9')
3162 return 0;
3163 *digit = (**date - '0');
3164 (*date)++;
3165 (*len)--;
3166 return 1;
3167}
3168
3169/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3170static inline int parse_2digit(const char **date, int *len, int *digit)
3171{
3172 int value;
3173
3174 RET0_UNLESS(parse_digit(date, len, &value));
3175 (*digit) = value * 10;
3176 RET0_UNLESS(parse_digit(date, len, &value));
3177 (*digit) += value;
3178
3179 return 1;
3180}
3181
3182/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3183static inline int parse_4digit(const char **date, int *len, int *digit)
3184{
3185 int value;
3186
3187 RET0_UNLESS(parse_digit(date, len, &value));
3188 (*digit) = value * 1000;
3189
3190 RET0_UNLESS(parse_digit(date, len, &value));
3191 (*digit) += value * 100;
3192
3193 RET0_UNLESS(parse_digit(date, len, &value));
3194 (*digit) += value * 10;
3195
3196 RET0_UNLESS(parse_digit(date, len, &value));
3197 (*digit) += value;
3198
3199 return 1;
3200}
3201
3202/* time-of-day = hour ":" minute ":" second
3203 * ; 00:00:00 - 23:59:60 (leap second)
3204 *
3205 * hour = 2DIGIT
3206 * minute = 2DIGIT
3207 * second = 2DIGIT
3208 */
3209static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3210{
3211 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3212 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3213 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3214 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3215 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3216 return 1;
3217}
3218
3219/* From RFC7231
3220 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3221 *
3222 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3223 * ; fixed length/zone/capitalization subset of the format
3224 * ; see Section 3.3 of [RFC5322]
3225 *
3226 *
3227 * date1 = day SP month SP year
3228 * ; e.g., 02 Jun 1982
3229 *
3230 * day = 2DIGIT
3231 * year = 4DIGIT
3232 *
3233 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3234 *
3235 * time-of-day = hour ":" minute ":" second
3236 * ; 00:00:00 - 23:59:60 (leap second)
3237 *
3238 * hour = 2DIGIT
3239 * minute = 2DIGIT
3240 * second = 2DIGIT
3241 *
3242 * DIGIT = decimal 0-9
3243 */
3244int parse_imf_date(const char *date, int len, struct tm *tm)
3245{
David Carlier327298c2016-11-20 10:42:38 +00003246 /* tm_gmtoff, if present, ought to be zero'ed */
3247 memset(tm, 0, sizeof(*tm));
3248
Thierry Fournier93127942016-01-20 18:49:45 +01003249 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3250 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3251 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3252 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3253 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3254 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3255 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3256 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3257 tm->tm_year -= 1900;
3258 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3259 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3260 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3261 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3262 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003263 return 1;
3264}
3265
3266/* From RFC7231
3267 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3268 *
3269 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3270 * date2 = day "-" month "-" 2DIGIT
3271 * ; e.g., 02-Jun-82
3272 *
3273 * day = 2DIGIT
3274 */
3275int parse_rfc850_date(const char *date, int len, struct tm *tm)
3276{
3277 int year;
3278
David Carlier327298c2016-11-20 10:42:38 +00003279 /* tm_gmtoff, if present, ought to be zero'ed */
3280 memset(tm, 0, sizeof(*tm));
3281
Thierry Fournier93127942016-01-20 18:49:45 +01003282 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3283 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3284 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3285 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3286 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3287 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3288 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3289
3290 /* year = 2DIGIT
3291 *
3292 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3293 * two-digit year, MUST interpret a timestamp that appears to be more
3294 * than 50 years in the future as representing the most recent year in
3295 * the past that had the same last two digits.
3296 */
3297 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3298
3299 /* expect SP */
3300 if (!parse_expect_char(&date, &len, ' ')) {
3301 /* Maybe we have the date with 4 digits. */
3302 RET0_UNLESS(parse_2digit(&date, &len, &year));
3303 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3304 /* expect SP */
3305 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3306 } else {
3307 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3308 * tm_year is the number of year since 1900, so for +1900, we
3309 * do nothing, and for +2000, we add 100.
3310 */
3311 if (tm->tm_year <= 60)
3312 tm->tm_year += 100;
3313 }
3314
3315 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3316 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3317 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3318 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003319
3320 return 1;
3321}
3322
3323/* From RFC7231
3324 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3325 *
3326 * asctime-date = day-name SP date3 SP time-of-day SP year
3327 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3328 * ; e.g., Jun 2
3329 *
3330 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3331 * whitespace in an HTTP-date beyond that specifically included as SP in
3332 * the grammar.
3333 */
3334int parse_asctime_date(const char *date, int len, struct tm *tm)
3335{
David Carlier327298c2016-11-20 10:42:38 +00003336 /* tm_gmtoff, if present, ought to be zero'ed */
3337 memset(tm, 0, sizeof(*tm));
3338
Thierry Fournier93127942016-01-20 18:49:45 +01003339 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3340 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3341 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3342 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3343
3344 /* expect SP and 1DIGIT or 2DIGIT */
3345 if (parse_expect_char(&date, &len, ' '))
3346 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3347 else
3348 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3349
3350 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3351 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3352 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3353 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3354 tm->tm_year -= 1900;
3355 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003356 return 1;
3357}
3358
3359/* From RFC7231
3360 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3361 *
3362 * HTTP-date = IMF-fixdate / obs-date
3363 * obs-date = rfc850-date / asctime-date
3364 *
3365 * parses an HTTP date in the RFC format and is accepted
3366 * alternatives. <date> is the strinf containing the date,
3367 * len is the len of the string. <tm> is filled with the
3368 * parsed time. We must considers this time as GMT.
3369 */
3370int parse_http_date(const char *date, int len, struct tm *tm)
3371{
3372 if (parse_imf_date(date, len, tm))
3373 return 1;
3374
3375 if (parse_rfc850_date(date, len, tm))
3376 return 1;
3377
3378 if (parse_asctime_date(date, len, tm))
3379 return 1;
3380
3381 return 0;
3382}
3383
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003384/* Dynamically allocates a string of the proper length to hold the formatted
3385 * output. NULL is returned on error. The caller is responsible for freeing the
3386 * memory area using free(). The resulting string is returned in <out> if the
3387 * pointer is not NULL. A previous version of <out> might be used to build the
3388 * new string, and it will be freed before returning if it is not NULL, which
3389 * makes it possible to build complex strings from iterative calls without
3390 * having to care about freeing intermediate values, as in the example below :
3391 *
3392 * memprintf(&err, "invalid argument: '%s'", arg);
3393 * ...
3394 * memprintf(&err, "parser said : <%s>\n", *err);
3395 * ...
3396 * free(*err);
3397 *
3398 * This means that <err> must be initialized to NULL before first invocation.
3399 * The return value also holds the allocated string, which eases error checking
3400 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003401 * passed instead and it will be ignored. The returned message will then also
3402 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003403 *
3404 * It is also convenient to use it without any free except the last one :
3405 * err = NULL;
3406 * if (!fct1(err)) report(*err);
3407 * if (!fct2(err)) report(*err);
3408 * if (!fct3(err)) report(*err);
3409 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003410 *
3411 * memprintf relies on memvprintf. This last version can be called from any
3412 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003413 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003414char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003415{
3416 va_list args;
3417 char *ret = NULL;
3418 int allocated = 0;
3419 int needed = 0;
3420
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003421 if (!out)
3422 return NULL;
3423
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003424 do {
3425 /* vsnprintf() will return the required length even when the
3426 * target buffer is NULL. We do this in a loop just in case
3427 * intermediate evaluations get wrong.
3428 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003429 va_copy(args, orig_args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003430 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003431 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003432 if (needed < allocated) {
3433 /* Note: on Solaris 8, the first iteration always
3434 * returns -1 if allocated is zero, so we force a
3435 * retry.
3436 */
3437 if (!allocated)
3438 needed = 0;
3439 else
3440 break;
3441 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003442
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003443 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003444 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003445 } while (ret);
3446
3447 if (needed < 0) {
3448 /* an error was encountered */
3449 free(ret);
3450 ret = NULL;
3451 }
3452
3453 if (out) {
3454 free(*out);
3455 *out = ret;
3456 }
3457
3458 return ret;
3459}
William Lallemand421f5b52012-02-06 18:15:57 +01003460
Christopher Faulet93a518f2017-10-24 11:25:33 +02003461char *memprintf(char **out, const char *format, ...)
3462{
3463 va_list args;
3464 char *ret = NULL;
3465
3466 va_start(args, format);
3467 ret = memvprintf(out, format, args);
3468 va_end(args);
3469
3470 return ret;
3471}
3472
Willy Tarreau21c705b2012-09-14 11:40:36 +02003473/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3474 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003475 * freed by the caller. It also supports being passed a NULL which results in the same
3476 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003477 * Example of use :
3478 * parse(cmd, &err); (callee: memprintf(&err, ...))
3479 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3480 * free(err);
3481 */
3482char *indent_msg(char **out, int level)
3483{
3484 char *ret, *in, *p;
3485 int needed = 0;
3486 int lf = 0;
3487 int lastlf = 0;
3488 int len;
3489
Willy Tarreau70eec382012-10-10 08:56:47 +02003490 if (!out || !*out)
3491 return NULL;
3492
Willy Tarreau21c705b2012-09-14 11:40:36 +02003493 in = *out - 1;
3494 while ((in = strchr(in + 1, '\n')) != NULL) {
3495 lastlf = in - *out;
3496 lf++;
3497 }
3498
3499 if (!lf) /* single line, no LF, return it as-is */
3500 return *out;
3501
3502 len = strlen(*out);
3503
3504 if (lf == 1 && lastlf == len - 1) {
3505 /* single line, LF at end, strip it and return as-is */
3506 (*out)[lastlf] = 0;
3507 return *out;
3508 }
3509
3510 /* OK now we have at least one LF, we need to process the whole string
3511 * as a multi-line string. What we'll do :
3512 * - prefix with an LF if there is none
3513 * - add <level> spaces before each line
3514 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3515 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3516 */
3517
3518 needed = 1 + level * (lf + 1) + len + 1;
3519 p = ret = malloc(needed);
3520 in = *out;
3521
3522 /* skip initial LFs */
3523 while (*in == '\n')
3524 in++;
3525
3526 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3527 while (*in) {
3528 *p++ = '\n';
3529 memset(p, ' ', level);
3530 p += level;
3531 do {
3532 *p++ = *in++;
3533 } while (*in && *in != '\n');
3534 if (*in)
3535 in++;
3536 }
3537 *p = 0;
3538
3539 free(*out);
3540 *out = ret;
3541
3542 return ret;
3543}
3544
Willy Tarreaudad36a32013-03-11 01:20:04 +01003545/* Convert occurrences of environment variables in the input string to their
3546 * corresponding value. A variable is identified as a series of alphanumeric
3547 * characters or underscores following a '$' sign. The <in> string must be
3548 * free()able. NULL returns NULL. The resulting string might be reallocated if
3549 * some expansion is made. Variable names may also be enclosed into braces if
3550 * needed (eg: to concatenate alphanum characters).
3551 */
3552char *env_expand(char *in)
3553{
3554 char *txt_beg;
3555 char *out;
3556 char *txt_end;
3557 char *var_beg;
3558 char *var_end;
3559 char *value;
3560 char *next;
3561 int out_len;
3562 int val_len;
3563
3564 if (!in)
3565 return in;
3566
3567 value = out = NULL;
3568 out_len = 0;
3569
3570 txt_beg = in;
3571 do {
3572 /* look for next '$' sign in <in> */
3573 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3574
3575 if (!*txt_end && !out) /* end and no expansion performed */
3576 return in;
3577
3578 val_len = 0;
3579 next = txt_end;
3580 if (*txt_end == '$') {
3581 char save;
3582
3583 var_beg = txt_end + 1;
3584 if (*var_beg == '{')
3585 var_beg++;
3586
3587 var_end = var_beg;
3588 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3589 var_end++;
3590 }
3591
3592 next = var_end;
3593 if (*var_end == '}' && (var_beg > txt_end + 1))
3594 next++;
3595
3596 /* get value of the variable name at this location */
3597 save = *var_end;
3598 *var_end = '\0';
3599 value = getenv(var_beg);
3600 *var_end = save;
3601 val_len = value ? strlen(value) : 0;
3602 }
3603
Hubert Verstraete831962e2016-06-28 22:44:26 +02003604 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003605 if (txt_end > txt_beg) {
3606 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3607 out_len += txt_end - txt_beg;
3608 }
3609 if (val_len) {
3610 memcpy(out + out_len, value, val_len);
3611 out_len += val_len;
3612 }
3613 out[out_len] = 0;
3614 txt_beg = next;
3615 } while (*txt_beg);
3616
3617 /* here we know that <out> was allocated and that we don't need <in> anymore */
3618 free(in);
3619 return out;
3620}
3621
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003622
3623/* same as strstr() but case-insensitive and with limit length */
3624const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3625{
3626 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003627 unsigned int slen, plen;
3628 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003629
3630 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3631 return NULL;
3632
3633 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3634 return str1;
3635
3636 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3637 return NULL;
3638
3639 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3640 while (toupper(*start) != toupper(*str2)) {
3641 start++;
3642 slen--;
3643 tmp1++;
3644
3645 if (tmp1 >= len_str1)
3646 return NULL;
3647
3648 /* if pattern longer than string */
3649 if (slen < plen)
3650 return NULL;
3651 }
3652
3653 sptr = start;
3654 pptr = (char *)str2;
3655
3656 tmp2 = 0;
3657 while (toupper(*sptr) == toupper(*pptr)) {
3658 sptr++;
3659 pptr++;
3660 tmp2++;
3661
3662 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3663 return start;
3664 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3665 return NULL;
3666 }
3667 }
3668 return NULL;
3669}
3670
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003671/* This function read the next valid utf8 char.
3672 * <s> is the byte srray to be decode, <len> is its length.
3673 * The function returns decoded char encoded like this:
3674 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3675 * are the length read. The decoded character is stored in <c>.
3676 */
3677unsigned char utf8_next(const char *s, int len, unsigned int *c)
3678{
3679 const unsigned char *p = (unsigned char *)s;
3680 int dec;
3681 unsigned char code = UTF8_CODE_OK;
3682
3683 if (len < 1)
3684 return UTF8_CODE_OK;
3685
3686 /* Check the type of UTF8 sequence
3687 *
3688 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3689 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3690 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3691 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3692 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3693 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3694 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3695 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3696 */
3697 switch (*p) {
3698 case 0x00 ... 0x7f:
3699 *c = *p;
3700 return UTF8_CODE_OK | 1;
3701
3702 case 0x80 ... 0xbf:
3703 *c = *p;
3704 return UTF8_CODE_BADSEQ | 1;
3705
3706 case 0xc0 ... 0xdf:
3707 if (len < 2) {
3708 *c = *p;
3709 return UTF8_CODE_BADSEQ | 1;
3710 }
3711 *c = *p & 0x1f;
3712 dec = 1;
3713 break;
3714
3715 case 0xe0 ... 0xef:
3716 if (len < 3) {
3717 *c = *p;
3718 return UTF8_CODE_BADSEQ | 1;
3719 }
3720 *c = *p & 0x0f;
3721 dec = 2;
3722 break;
3723
3724 case 0xf0 ... 0xf7:
3725 if (len < 4) {
3726 *c = *p;
3727 return UTF8_CODE_BADSEQ | 1;
3728 }
3729 *c = *p & 0x07;
3730 dec = 3;
3731 break;
3732
3733 case 0xf8 ... 0xfb:
3734 if (len < 5) {
3735 *c = *p;
3736 return UTF8_CODE_BADSEQ | 1;
3737 }
3738 *c = *p & 0x03;
3739 dec = 4;
3740 break;
3741
3742 case 0xfc ... 0xfd:
3743 if (len < 6) {
3744 *c = *p;
3745 return UTF8_CODE_BADSEQ | 1;
3746 }
3747 *c = *p & 0x01;
3748 dec = 5;
3749 break;
3750
3751 case 0xfe ... 0xff:
3752 default:
3753 *c = *p;
3754 return UTF8_CODE_BADSEQ | 1;
3755 }
3756
3757 p++;
3758
3759 while (dec > 0) {
3760
3761 /* need 0x10 for the 2 first bits */
3762 if ( ( *p & 0xc0 ) != 0x80 )
3763 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3764
3765 /* add data at char */
3766 *c = ( *c << 6 ) | ( *p & 0x3f );
3767
3768 dec--;
3769 p++;
3770 }
3771
3772 /* Check ovelong encoding.
3773 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3774 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3775 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3776 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003777 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003778 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3779 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3780 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3781 code |= UTF8_CODE_OVERLONG;
3782
3783 /* Check invalid UTF8 range. */
3784 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3785 (*c >= 0xfffe && *c <= 0xffff))
3786 code |= UTF8_CODE_INVRANGE;
3787
3788 return code | ((p-(unsigned char *)s)&0x0f);
3789}
3790
Maxime de Roucydc887852016-05-13 23:52:54 +02003791/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3792 * On failure : return 0 and <err> filled with an error message.
3793 * The caller is responsible for freeing the <err> and <str> copy
3794 * memory area using free()
3795 */
3796int list_append_word(struct list *li, const char *str, char **err)
3797{
3798 struct wordlist *wl;
3799
3800 wl = calloc(1, sizeof(*wl));
3801 if (!wl) {
3802 memprintf(err, "out of memory");
3803 goto fail_wl;
3804 }
3805
3806 wl->s = strdup(str);
3807 if (!wl->s) {
3808 memprintf(err, "out of memory");
3809 goto fail_wl_s;
3810 }
3811
3812 LIST_ADDQ(li, &wl->list);
3813
3814 return 1;
3815
3816fail_wl_s:
3817 free(wl->s);
3818fail_wl:
3819 free(wl);
3820 return 0;
3821}
3822
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003823/* print a string of text buffer to <out>. The format is :
3824 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3825 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3826 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3827 */
3828int dump_text(struct chunk *out, const char *buf, int bsize)
3829{
3830 unsigned char c;
3831 int ptr = 0;
3832
3833 while (buf[ptr] && ptr < bsize) {
3834 c = buf[ptr];
3835 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
3836 if (out->len > out->size - 1)
3837 break;
3838 out->str[out->len++] = c;
3839 }
3840 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
3841 if (out->len > out->size - 2)
3842 break;
3843 out->str[out->len++] = '\\';
3844 switch (c) {
3845 case ' ': c = ' '; break;
3846 case '\t': c = 't'; break;
3847 case '\n': c = 'n'; break;
3848 case '\r': c = 'r'; break;
3849 case '\e': c = 'e'; break;
3850 case '\\': c = '\\'; break;
3851 case '=': c = '='; break;
3852 }
3853 out->str[out->len++] = c;
3854 }
3855 else {
3856 if (out->len > out->size - 4)
3857 break;
3858 out->str[out->len++] = '\\';
3859 out->str[out->len++] = 'x';
3860 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3861 out->str[out->len++] = hextab[c & 0xF];
3862 }
3863 ptr++;
3864 }
3865
3866 return ptr;
3867}
3868
3869/* print a buffer in hexa.
3870 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3871 */
3872int dump_binary(struct chunk *out, const char *buf, int bsize)
3873{
3874 unsigned char c;
3875 int ptr = 0;
3876
3877 while (ptr < bsize) {
3878 c = buf[ptr];
3879
3880 if (out->len > out->size - 2)
3881 break;
3882 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3883 out->str[out->len++] = hextab[c & 0xF];
3884
3885 ptr++;
3886 }
3887 return ptr;
3888}
3889
3890/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3891 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3892 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3893 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3894 * lines are respected within the limit of 70 output chars. Lines that are
3895 * continuation of a previous truncated line begin with "+" instead of " "
3896 * after the offset. The new pointer is returned.
3897 */
3898int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3899 int *line, int ptr)
3900{
3901 int end;
3902 unsigned char c;
3903
3904 end = out->len + 80;
3905 if (end > out->size)
3906 return ptr;
3907
3908 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3909
3910 while (ptr < len && ptr < bsize) {
3911 c = buf[ptr];
3912 if (isprint(c) && isascii(c) && c != '\\') {
3913 if (out->len > end - 2)
3914 break;
3915 out->str[out->len++] = c;
3916 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3917 if (out->len > end - 3)
3918 break;
3919 out->str[out->len++] = '\\';
3920 switch (c) {
3921 case '\t': c = 't'; break;
3922 case '\n': c = 'n'; break;
3923 case '\r': c = 'r'; break;
3924 case '\e': c = 'e'; break;
3925 case '\\': c = '\\'; break;
3926 }
3927 out->str[out->len++] = c;
3928 } else {
3929 if (out->len > end - 5)
3930 break;
3931 out->str[out->len++] = '\\';
3932 out->str[out->len++] = 'x';
3933 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3934 out->str[out->len++] = hextab[c & 0xF];
3935 }
3936 if (buf[ptr++] == '\n') {
3937 /* we had a line break, let's return now */
3938 out->str[out->len++] = '\n';
3939 *line = ptr;
3940 return ptr;
3941 }
3942 }
3943 /* we have an incomplete line, we return it as-is */
3944 out->str[out->len++] = '\n';
3945 return ptr;
3946}
3947
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003948/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02003949 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
3950 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003951 */
Willy Tarreaued936c52017-04-27 18:03:20 +02003952void debug_hexdump(FILE *out, const char *pfx, const char *buf,
3953 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003954{
Willy Tarreau73459792017-04-11 07:58:08 +02003955 unsigned int i;
3956 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003957
3958 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3959 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02003960 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003961 for (j = 0; j < 8; j++) {
3962 if (b + j >= 0 && b + j < len)
3963 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3964 else
3965 fprintf(out, " ");
3966 }
3967
3968 if (b + j >= 0 && b + j < len)
3969 fputc('-', out);
3970 else
3971 fputc(' ', out);
3972
3973 for (j = 8; j < 16; j++) {
3974 if (b + j >= 0 && b + j < len)
3975 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3976 else
3977 fprintf(out, " ");
3978 }
3979
3980 fprintf(out, " ");
3981 for (j = 0; j < 16; j++) {
3982 if (b + j >= 0 && b + j < len) {
3983 if (isprint((unsigned char)buf[b + j]))
3984 fputc((unsigned char)buf[b + j], out);
3985 else
3986 fputc('.', out);
3987 }
3988 else
3989 fputc(' ', out);
3990 }
3991 fputc('\n', out);
3992 }
3993}
3994
Willy Tarreau12963822017-10-24 10:54:08 +02003995/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
3996__attribute__((weak,format(printf, 1, 2)))
3997void trace(char *msg, ...)
3998{
3999}
4000
Willy Tarreaubaaee002006-06-26 02:48:02 +02004001/*
4002 * Local variables:
4003 * c-indent-level: 8
4004 * c-basic-offset: 8
4005 * End:
4006 */