blob: efa41710e14e3723a795658f20b80be1852eea4d [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010013#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020014#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020015#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020016#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020017#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020018#include <stdlib.h>
19#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010020#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020021#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010022#include <sys/socket.h>
23#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <netinet/in.h>
25#include <arpa/inet.h>
26
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010027#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020028#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020029#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010030#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010031#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020032#include <proto/dns.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010033#include <eb32tree.h>
Willy Tarreaued3cda02017-11-15 15:04:05 +010034#include <eb32sctree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020035
Thierry Fournier93127942016-01-20 18:49:45 +010036/* This macro returns false if the test __x is false. Many
37 * of the following parsing function must be abort the processing
38 * if it returns 0, so this macro is useful for writing light code.
39 */
40#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
41
Willy Tarreau56adcf22012-12-23 18:00:29 +010042/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020043 * 2^64-1 = 18446744073709551615 or
44 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020045 *
46 * The HTML version needs room for adding the 25 characters
47 * '<span class="rls"></span>' around digits at positions 3N+1 in order
48 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020049 */
Christopher Faulet99bca652017-11-14 16:47:26 +010050THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
51THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020052
Willy Tarreau588297f2014-06-16 15:16:40 +020053/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
54 * to quote strings larger than a max configuration line.
55 */
Christopher Faulet99bca652017-11-14 16:47:26 +010056THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
57THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020058
Willy Tarreaubaaee002006-06-26 02:48:02 +020059/*
William Lallemande7340ec2012-01-24 11:15:39 +010060 * unsigned long long ASCII representation
61 *
62 * return the last char '\0' or NULL if no enough
63 * space in dst
64 */
65char *ulltoa(unsigned long long n, char *dst, size_t size)
66{
67 int i = 0;
68 char *res;
69
70 switch(n) {
71 case 1ULL ... 9ULL:
72 i = 0;
73 break;
74
75 case 10ULL ... 99ULL:
76 i = 1;
77 break;
78
79 case 100ULL ... 999ULL:
80 i = 2;
81 break;
82
83 case 1000ULL ... 9999ULL:
84 i = 3;
85 break;
86
87 case 10000ULL ... 99999ULL:
88 i = 4;
89 break;
90
91 case 100000ULL ... 999999ULL:
92 i = 5;
93 break;
94
95 case 1000000ULL ... 9999999ULL:
96 i = 6;
97 break;
98
99 case 10000000ULL ... 99999999ULL:
100 i = 7;
101 break;
102
103 case 100000000ULL ... 999999999ULL:
104 i = 8;
105 break;
106
107 case 1000000000ULL ... 9999999999ULL:
108 i = 9;
109 break;
110
111 case 10000000000ULL ... 99999999999ULL:
112 i = 10;
113 break;
114
115 case 100000000000ULL ... 999999999999ULL:
116 i = 11;
117 break;
118
119 case 1000000000000ULL ... 9999999999999ULL:
120 i = 12;
121 break;
122
123 case 10000000000000ULL ... 99999999999999ULL:
124 i = 13;
125 break;
126
127 case 100000000000000ULL ... 999999999999999ULL:
128 i = 14;
129 break;
130
131 case 1000000000000000ULL ... 9999999999999999ULL:
132 i = 15;
133 break;
134
135 case 10000000000000000ULL ... 99999999999999999ULL:
136 i = 16;
137 break;
138
139 case 100000000000000000ULL ... 999999999999999999ULL:
140 i = 17;
141 break;
142
143 case 1000000000000000000ULL ... 9999999999999999999ULL:
144 i = 18;
145 break;
146
147 case 10000000000000000000ULL ... ULLONG_MAX:
148 i = 19;
149 break;
150 }
151 if (i + 2 > size) // (i + 1) + '\0'
152 return NULL; // too long
153 res = dst + i + 1;
154 *res = '\0';
155 for (; i >= 0; i--) {
156 dst[i] = n % 10ULL + '0';
157 n /= 10ULL;
158 }
159 return res;
160}
161
162/*
163 * unsigned long ASCII representation
164 *
165 * return the last char '\0' or NULL if no enough
166 * space in dst
167 */
168char *ultoa_o(unsigned long n, char *dst, size_t size)
169{
170 int i = 0;
171 char *res;
172
173 switch (n) {
174 case 0U ... 9UL:
175 i = 0;
176 break;
177
178 case 10U ... 99UL:
179 i = 1;
180 break;
181
182 case 100U ... 999UL:
183 i = 2;
184 break;
185
186 case 1000U ... 9999UL:
187 i = 3;
188 break;
189
190 case 10000U ... 99999UL:
191 i = 4;
192 break;
193
194 case 100000U ... 999999UL:
195 i = 5;
196 break;
197
198 case 1000000U ... 9999999UL:
199 i = 6;
200 break;
201
202 case 10000000U ... 99999999UL:
203 i = 7;
204 break;
205
206 case 100000000U ... 999999999UL:
207 i = 8;
208 break;
209#if __WORDSIZE == 32
210
211 case 1000000000ULL ... ULONG_MAX:
212 i = 9;
213 break;
214
215#elif __WORDSIZE == 64
216
217 case 1000000000ULL ... 9999999999UL:
218 i = 9;
219 break;
220
221 case 10000000000ULL ... 99999999999UL:
222 i = 10;
223 break;
224
225 case 100000000000ULL ... 999999999999UL:
226 i = 11;
227 break;
228
229 case 1000000000000ULL ... 9999999999999UL:
230 i = 12;
231 break;
232
233 case 10000000000000ULL ... 99999999999999UL:
234 i = 13;
235 break;
236
237 case 100000000000000ULL ... 999999999999999UL:
238 i = 14;
239 break;
240
241 case 1000000000000000ULL ... 9999999999999999UL:
242 i = 15;
243 break;
244
245 case 10000000000000000ULL ... 99999999999999999UL:
246 i = 16;
247 break;
248
249 case 100000000000000000ULL ... 999999999999999999UL:
250 i = 17;
251 break;
252
253 case 1000000000000000000ULL ... 9999999999999999999UL:
254 i = 18;
255 break;
256
257 case 10000000000000000000ULL ... ULONG_MAX:
258 i = 19;
259 break;
260
261#endif
262 }
263 if (i + 2 > size) // (i + 1) + '\0'
264 return NULL; // too long
265 res = dst + i + 1;
266 *res = '\0';
267 for (; i >= 0; i--) {
268 dst[i] = n % 10U + '0';
269 n /= 10U;
270 }
271 return res;
272}
273
274/*
275 * signed long ASCII representation
276 *
277 * return the last char '\0' or NULL if no enough
278 * space in dst
279 */
280char *ltoa_o(long int n, char *dst, size_t size)
281{
282 char *pos = dst;
283
284 if (n < 0) {
285 if (size < 3)
286 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
287 *pos = '-';
288 pos++;
289 dst = ultoa_o(-n, pos, size - 1);
290 } else {
291 dst = ultoa_o(n, dst, size);
292 }
293 return dst;
294}
295
296/*
297 * signed long long ASCII representation
298 *
299 * return the last char '\0' or NULL if no enough
300 * space in dst
301 */
302char *lltoa(long long n, char *dst, size_t size)
303{
304 char *pos = dst;
305
306 if (n < 0) {
307 if (size < 3)
308 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
309 *pos = '-';
310 pos++;
311 dst = ulltoa(-n, pos, size - 1);
312 } else {
313 dst = ulltoa(n, dst, size);
314 }
315 return dst;
316}
317
318/*
319 * write a ascii representation of a unsigned into dst,
320 * return a pointer to the last character
321 * Pad the ascii representation with '0', using size.
322 */
323char *utoa_pad(unsigned int n, char *dst, size_t size)
324{
325 int i = 0;
326 char *ret;
327
328 switch(n) {
329 case 0U ... 9U:
330 i = 0;
331 break;
332
333 case 10U ... 99U:
334 i = 1;
335 break;
336
337 case 100U ... 999U:
338 i = 2;
339 break;
340
341 case 1000U ... 9999U:
342 i = 3;
343 break;
344
345 case 10000U ... 99999U:
346 i = 4;
347 break;
348
349 case 100000U ... 999999U:
350 i = 5;
351 break;
352
353 case 1000000U ... 9999999U:
354 i = 6;
355 break;
356
357 case 10000000U ... 99999999U:
358 i = 7;
359 break;
360
361 case 100000000U ... 999999999U:
362 i = 8;
363 break;
364
365 case 1000000000U ... 4294967295U:
366 i = 9;
367 break;
368 }
369 if (i + 2 > size) // (i + 1) + '\0'
370 return NULL; // too long
371 if (i < size)
372 i = size - 2; // padding - '\0'
373
374 ret = dst + i + 1;
375 *ret = '\0';
376 for (; i >= 0; i--) {
377 dst[i] = n % 10U + '0';
378 n /= 10U;
379 }
380 return ret;
381}
382
383/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200384 * copies at most <size-1> chars from <src> to <dst>. Last char is always
385 * set to 0, unless <size> is 0. The number of chars copied is returned
386 * (excluding the terminating zero).
387 * This code has been optimized for size and speed : on x86, it's 45 bytes
388 * long, uses only registers, and consumes only 4 cycles per char.
389 */
390int strlcpy2(char *dst, const char *src, int size)
391{
392 char *orig = dst;
393 if (size) {
394 while (--size && (*dst = *src)) {
395 src++; dst++;
396 }
397 *dst = 0;
398 }
399 return dst - orig;
400}
401
402/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200403 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404 * the ascii representation for number 'n' in decimal.
405 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100406char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200407{
408 char *pos;
409
Willy Tarreau72d759c2007-10-25 12:14:10 +0200410 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200411 *pos-- = '\0';
412
413 do {
414 *pos-- = '0' + n % 10;
415 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200416 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200417 return pos + 1;
418}
419
Willy Tarreau91092e52007-10-25 16:58:42 +0200420/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200421 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200422 * the ascii representation for number 'n' in decimal.
423 */
424char *lltoa_r(long long int in, char *buffer, int size)
425{
426 char *pos;
427 int neg = 0;
428 unsigned long long int n;
429
430 pos = buffer + size - 1;
431 *pos-- = '\0';
432
433 if (in < 0) {
434 neg = 1;
435 n = -in;
436 }
437 else
438 n = in;
439
440 do {
441 *pos-- = '0' + n % 10;
442 n /= 10;
443 } while (n && pos >= buffer);
444 if (neg && pos > buffer)
445 *pos-- = '-';
446 return pos + 1;
447}
448
449/*
450 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200451 * the ascii representation for signed number 'n' in decimal.
452 */
453char *sltoa_r(long n, char *buffer, int size)
454{
455 char *pos;
456
457 if (n >= 0)
458 return ultoa_r(n, buffer, size);
459
460 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
461 *pos = '-';
462 return pos;
463}
464
465/*
466 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200467 * the ascii representation for number 'n' in decimal, formatted for
468 * HTML output with tags to create visual grouping by 3 digits. The
469 * output needs to support at least 171 characters.
470 */
471const char *ulltoh_r(unsigned long long n, char *buffer, int size)
472{
473 char *start;
474 int digit = 0;
475
476 start = buffer + size;
477 *--start = '\0';
478
479 do {
480 if (digit == 3 && start >= buffer + 7)
481 memcpy(start -= 7, "</span>", 7);
482
483 if (start >= buffer + 1) {
484 *--start = '0' + n % 10;
485 n /= 10;
486 }
487
488 if (digit == 3 && start >= buffer + 18)
489 memcpy(start -= 18, "<span class=\"rls\">", 18);
490
491 if (digit++ == 3)
492 digit = 1;
493 } while (n && start > buffer);
494 return start;
495}
496
497/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200498 * This function simply returns a locally allocated string containing the ascii
499 * representation for number 'n' in decimal, unless n is 0 in which case it
500 * returns the alternate string (or an empty string if the alternate string is
501 * NULL). It use is intended for limits reported in reports, where it's
502 * desirable not to display anything if there is no limit. Warning! it shares
503 * the same vector as ultoa_r().
504 */
505const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
506{
507 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
508}
509
Willy Tarreau588297f2014-06-16 15:16:40 +0200510/* returns a locally allocated string containing the quoted encoding of the
511 * input string. The output may be truncated to QSTR_SIZE chars, but it is
512 * guaranteed that the string will always be properly terminated. Quotes are
513 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
514 * always be at least 4 chars.
515 */
516const char *qstr(const char *str)
517{
518 char *ret = quoted_str[quoted_idx];
519 char *p, *end;
520
521 if (++quoted_idx >= NB_QSTR)
522 quoted_idx = 0;
523
524 p = ret;
525 end = ret + QSTR_SIZE;
526
527 *p++ = '"';
528
529 /* always keep 3 chars to support passing "" and the ending " */
530 while (*str && p < end - 3) {
531 if (*str == '"') {
532 *p++ = '"';
533 *p++ = '"';
534 }
535 else
536 *p++ = *str;
537 str++;
538 }
539 *p++ = '"';
540 return ret;
541}
542
Robert Tsai81ae1952007-12-05 10:47:29 +0100543/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200544 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
545 *
546 * It looks like this one would be a good candidate for inlining, but this is
547 * not interesting because it around 35 bytes long and often called multiple
548 * times within the same function.
549 */
550int ishex(char s)
551{
552 s -= '0';
553 if ((unsigned char)s <= 9)
554 return 1;
555 s -= 'A' - '0';
556 if ((unsigned char)s <= 5)
557 return 1;
558 s -= 'a' - 'A';
559 if ((unsigned char)s <= 5)
560 return 1;
561 return 0;
562}
563
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100564/* rounds <i> down to the closest value having max 2 digits */
565unsigned int round_2dig(unsigned int i)
566{
567 unsigned int mul = 1;
568
569 while (i >= 100) {
570 i /= 10;
571 mul *= 10;
572 }
573 return i * mul;
574}
575
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100576/*
577 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
578 * invalid character is found, a pointer to it is returned. If everything is
579 * fine, NULL is returned.
580 */
581const char *invalid_char(const char *name)
582{
583 if (!*name)
584 return name;
585
586 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100587 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100588 *name != '_' && *name != '-')
589 return name;
590 name++;
591 }
592 return NULL;
593}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200594
595/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200596 * Checks <name> for invalid characters. Valid chars are [_.-] and those
597 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200598 * If an invalid character is found, a pointer to it is returned.
599 * If everything is fine, NULL is returned.
600 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200601static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200602
603 if (!*name)
604 return name;
605
606 while (*name) {
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200607 if (!f((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200608 *name != '_' && *name != '-')
609 return name;
610
611 name++;
612 }
613
614 return NULL;
615}
616
617/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200618 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
619 * If an invalid character is found, a pointer to it is returned.
620 * If everything is fine, NULL is returned.
621 */
622const char *invalid_domainchar(const char *name) {
623 return __invalid_char(name, isalnum);
624}
625
626/*
627 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
628 * If an invalid character is found, a pointer to it is returned.
629 * If everything is fine, NULL is returned.
630 */
631const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200632 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200633}
634
635/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100636 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100637 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
638 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
639 * the function tries to guess the address family from the syntax. If the
640 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100641 * string is assumed to contain only an address, no port. The address can be a
642 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
643 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
644 * The return address will only have the address family and the address set,
645 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100646 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
647 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100648 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200649 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100650struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200651{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100652 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100653 /* max IPv6 length, including brackets and terminating NULL */
654 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100655 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100656
657 /* check IPv6 with square brackets */
658 if (str[0] == '[') {
659 size_t iplength = strlen(str);
660
661 if (iplength < 4) {
662 /* minimal size is 4 when using brackets "[::]" */
663 goto fail;
664 }
665 else if (iplength >= sizeof(tmpip)) {
666 /* IPv6 literal can not be larger than tmpip */
667 goto fail;
668 }
669 else {
670 if (str[iplength - 1] != ']') {
671 /* if address started with bracket, it should end with bracket */
672 goto fail;
673 }
674 else {
675 memcpy(tmpip, str + 1, iplength - 2);
676 tmpip[iplength - 2] = '\0';
677 str = tmpip;
678 }
679 }
680 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100681
Willy Tarreaufab5a432011-03-04 15:31:53 +0100682 /* Any IPv6 address */
683 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100684 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
685 sa->ss_family = AF_INET6;
686 else if (sa->ss_family != AF_INET6)
687 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100688 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100689 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100690 }
691
Willy Tarreau24709282013-03-10 21:32:12 +0100692 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100693 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100694 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
695 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100696 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100697 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100698 }
699
700 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100701 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
702 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100703 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100704 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100705 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100706 }
707
708 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100709 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
710 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100711 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100712 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100713 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100714 }
715
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100716 if (!resolve)
717 return NULL;
718
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200719 if (!dns_hostname_validation(str, NULL))
720 return NULL;
721
David du Colombierd5f43282011-03-17 10:40:16 +0100722#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200723 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100724 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100725 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100726
727 memset(&result, 0, sizeof(result));
728 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100729 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100730 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200731 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100732 hints.ai_protocol = 0;
733
734 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100735 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
736 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100737 else if (sa->ss_family != result->ai_family) {
738 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100739 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100740 }
Willy Tarreau24709282013-03-10 21:32:12 +0100741
David du Colombierd5f43282011-03-17 10:40:16 +0100742 switch (result->ai_family) {
743 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100744 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100745 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100746 success = 1;
747 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100748 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100749 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100750 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100751 success = 1;
752 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100753 }
754 }
755
Sean Carey58ea0392013-02-15 23:39:18 +0100756 if (result)
757 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100758
759 if (success)
760 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100761 }
David du Colombierd5f43282011-03-17 10:40:16 +0100762#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200763 /* try to resolve an IPv4/IPv6 hostname */
764 he = gethostbyname(str);
765 if (he) {
766 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
767 sa->ss_family = he->h_addrtype;
768 else if (sa->ss_family != he->h_addrtype)
769 goto fail;
770
771 switch (sa->ss_family) {
772 case AF_INET:
773 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100774 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200775 return sa;
776 case AF_INET6:
777 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100778 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200779 return sa;
780 }
781 }
782
David du Colombierd5f43282011-03-17 10:40:16 +0100783 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100784 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100785 return NULL;
786}
787
788/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100789 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
790 * range or offset consisting in two integers that the caller will have to
791 * check to find the relevant input format. The following format are supported :
792 *
793 * String format | address | port | low | high
794 * addr | <addr> | 0 | 0 | 0
795 * addr: | <addr> | 0 | 0 | 0
796 * addr:port | <addr> | <port> | <port> | <port>
797 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
798 * addr:+port | <addr> | <port> | 0 | <port>
799 * addr:-port | <addr> |-<port> | <port> | 0
800 *
801 * The detection of a port range or increment by the caller is made by
802 * comparing <low> and <high>. If both are equal, then port 0 means no port
803 * was specified. The caller may pass NULL for <low> and <high> if it is not
804 * interested in retrieving port ranges.
805 *
806 * Note that <addr> above may also be :
807 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
808 * - "*" => family will be AF_INET and address will be INADDR_ANY
809 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
810 * - a host name => family and address will depend on host name resolving.
811 *
Willy Tarreau24709282013-03-10 21:32:12 +0100812 * A prefix may be passed in before the address above to force the family :
813 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
814 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
815 * - "unix@" => force address to be a path to a UNIX socket even if the
816 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200817 * - 'abns@' -> force address to belong to the abstract namespace (Linux
818 * only). These sockets are just like Unix sockets but without
819 * the need for an underlying file system. The address is a
820 * string. Technically it's like a Unix socket with a zero in
821 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100822 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100823 *
mildisff5d5102015-10-26 18:50:08 +0100824 * IPv6 addresses can be declared with or without square brackets. When using
825 * square brackets for IPv6 addresses, the port separator (colon) is optional.
826 * If not using square brackets, and in order to avoid any ambiguity with
827 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
828 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
829 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100830 *
831 * If <pfx> is non-null, it is used as a string prefix before any path-based
832 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100833 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200834 * if <fqdn> is non-null, it will be filled with :
835 * - a pointer to the FQDN of the server name to resolve if there's one, and
836 * that the caller will have to free(),
837 * - NULL if there was an explicit address that doesn't require resolution.
838 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100839 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
840 * is null, <fqdn> is still honnored so it is possible for the caller to know
841 * whether a resolution failed by setting <resolve> to null and checking if
842 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200843 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100844 * When a file descriptor is passed, its value is put into the s_addr part of
845 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100846 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100847struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, char **err, const char *pfx, char **fqdn, int resolve)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100848{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100849 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100850 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100851 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100852 char *port1, *port2;
853 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200854 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100855
856 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200857 if (fqdn)
858 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200859
Willy Tarreaudad36a32013-03-11 01:20:04 +0100860 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100861 if (str2 == NULL) {
862 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100863 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100864 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200865
Willy Tarreau9f69f462015-09-08 16:01:25 +0200866 if (!*str2) {
867 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
868 goto out;
869 }
870
Willy Tarreau24709282013-03-10 21:32:12 +0100871 memset(&ss, 0, sizeof(ss));
872
873 if (strncmp(str2, "unix@", 5) == 0) {
874 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200875 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100876 ss.ss_family = AF_UNIX;
877 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200878 else if (strncmp(str2, "abns@", 5) == 0) {
879 str2 += 5;
880 abstract = 1;
881 ss.ss_family = AF_UNIX;
882 }
Willy Tarreau24709282013-03-10 21:32:12 +0100883 else if (strncmp(str2, "ipv4@", 5) == 0) {
884 str2 += 5;
885 ss.ss_family = AF_INET;
886 }
887 else if (strncmp(str2, "ipv6@", 5) == 0) {
888 str2 += 5;
889 ss.ss_family = AF_INET6;
890 }
891 else if (*str2 == '/') {
892 ss.ss_family = AF_UNIX;
893 }
894 else
895 ss.ss_family = AF_UNSPEC;
896
William Lallemand2fe7dd02018-09-11 16:51:29 +0200897 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "sockpair@", 9) == 0) {
898 char *endptr;
899
900 str2 += 9;
901
902 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100903 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200904
905 if (!*str2 || *endptr) {
906 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
907 goto out;
908 }
909
910 ss.ss_family = AF_CUST_SOCKPAIR;
911
912 }
913 else if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100914 char *endptr;
915
916 str2 += 3;
917 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
Willy Tarreau0205a4e2018-12-15 15:40:12 +0100918 ((struct sockaddr_in *)&ss)->sin_port = 0;
Willy Tarreau40aa0702013-03-10 23:51:38 +0100919
920 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100921 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100922 goto out;
923 }
924
925 /* we return AF_UNSPEC if we use a file descriptor number */
926 ss.ss_family = AF_UNSPEC;
927 }
928 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100929 int prefix_path_len;
930 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200931 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100932
933 /* complete unix socket path name during startup or soft-restart is
934 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
935 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200936 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100937 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
938 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
939
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200940 adr_len = strlen(str2);
941 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100942 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
943 goto out;
944 }
945
Willy Tarreauccfccef2014-05-10 01:49:15 +0200946 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
947 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200948 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100949 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200950 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100951 }
Willy Tarreau24709282013-03-10 21:32:12 +0100952 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100953 char *end = str2 + strlen(str2);
954 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200955
mildisff5d5102015-10-26 18:50:08 +0100956 /* search for : or ] whatever comes first */
957 for (chr = end-1; chr > str2; chr--) {
958 if (*chr == ']' || *chr == ':')
959 break;
960 }
961
962 if (*chr == ':') {
963 /* Found a colon before a closing-bracket, must be a port separator.
964 * This guarantee backward compatibility.
965 */
966 *chr++ = '\0';
967 port1 = chr;
968 }
969 else {
970 /* Either no colon and no closing-bracket
971 * or directly ending with a closing-bracket.
972 * However, no port.
973 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100974 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100975 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200976
Willy Tarreaua39d1992013-04-01 20:37:42 +0200977 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100978 port2 = strchr(port1, '-');
979 if (port2)
980 *port2++ = '\0';
981 else
982 port2 = port1;
983 portl = atoi(port1);
984 porth = atoi(port2);
985 porta = portl;
986 }
987 else if (*port1 == '-') { /* negative offset */
988 portl = atoi(port1 + 1);
989 porta = -portl;
990 }
991 else if (*port1 == '+') { /* positive offset */
992 porth = atoi(port1 + 1);
993 porta = porth;
994 }
995 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100996 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100997 goto out;
998 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100999
1000 /* first try to parse the IP without resolving. If it fails, it
1001 * tells us we need to keep a copy of the FQDN to resolve later
1002 * and to enable DNS. In this case we can proceed if <fqdn> is
1003 * set or if resolve is set, otherwise it's an error.
1004 */
1005 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +01001006 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +01001007 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
1008 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1009 goto out;
1010 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001011
Willy Tarreauceccdd72016-11-02 22:27:10 +01001012 if (fqdn) {
1013 if (str2 != back)
1014 memmove(back, str2, strlen(str2) + 1);
1015 *fqdn = back;
1016 back = NULL;
1017 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001018 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001019 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001020 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001021
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001022 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001023 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001024 if (port)
1025 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001026 if (low)
1027 *low = portl;
1028 if (high)
1029 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001030 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001031 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001032}
1033
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001034/* converts <str> to a struct in_addr containing a network mask. It can be
1035 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001036 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001037 */
1038int str2mask(const char *str, struct in_addr *mask)
1039{
1040 if (strchr(str, '.') != NULL) { /* dotted notation */
1041 if (!inet_pton(AF_INET, str, mask))
1042 return 0;
1043 }
1044 else { /* mask length */
1045 char *err;
1046 unsigned long len = strtol(str, &err, 10);
1047
1048 if (!*str || (err && *err) || (unsigned)len > 32)
1049 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001050
1051 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001052 }
1053 return 1;
1054}
1055
Tim Duesterhus47185172018-01-25 16:24:49 +01001056/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001057 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001058 * if the conversion succeeds otherwise zero.
1059 */
1060int str2mask6(const char *str, struct in6_addr *mask)
1061{
1062 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1063 if (!inet_pton(AF_INET6, str, mask))
1064 return 0;
1065 }
1066 else { /* mask length */
1067 char *err;
1068 unsigned long len = strtol(str, &err, 10);
1069
1070 if (!*str || (err && *err) || (unsigned)len > 128)
1071 return 0;
1072
1073 len2mask6(len, mask);
1074 }
1075 return 1;
1076}
1077
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001078/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1079 * succeeds otherwise zero.
1080 */
1081int cidr2dotted(int cidr, struct in_addr *mask) {
1082
1083 if (cidr < 0 || cidr > 32)
1084 return 0;
1085
1086 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1087 return 1;
1088}
1089
Thierry Fournier70473a52016-02-17 17:12:14 +01001090/* Convert mask from bit length form to in_addr form.
1091 * This function never fails.
1092 */
1093void len2mask4(int len, struct in_addr *addr)
1094{
1095 if (len >= 32) {
1096 addr->s_addr = 0xffffffff;
1097 return;
1098 }
1099 if (len <= 0) {
1100 addr->s_addr = 0x00000000;
1101 return;
1102 }
1103 addr->s_addr = 0xffffffff << (32 - len);
1104 addr->s_addr = htonl(addr->s_addr);
1105}
1106
1107/* Convert mask from bit length form to in6_addr form.
1108 * This function never fails.
1109 */
1110void len2mask6(int len, struct in6_addr *addr)
1111{
1112 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1113 len -= 32;
1114 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1115 len -= 32;
1116 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1117 len -= 32;
1118 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1119}
1120
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001121/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001122 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001123 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1124 * is optionnal and either in the dotted or CIDR notation.
1125 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1126 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001127int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001128{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001129 __label__ out_free, out_err;
1130 char *c, *s;
1131 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001132
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001133 s = strdup(str);
1134 if (!s)
1135 return 0;
1136
Willy Tarreaubaaee002006-06-26 02:48:02 +02001137 memset(mask, 0, sizeof(*mask));
1138 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001139
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001140 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001141 *c++ = '\0';
1142 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001143 if (!str2mask(c, mask))
1144 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001145 }
1146 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001147 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001148 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001149 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001150 struct hostent *he;
1151
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001152 if (!resolve)
1153 goto out_err;
1154
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001155 if ((he = gethostbyname(s)) == NULL) {
1156 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001157 }
1158 else
1159 *addr = *(struct in_addr *) *(he->h_addr_list);
1160 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001161
1162 ret_val = 1;
1163 out_free:
1164 free(s);
1165 return ret_val;
1166 out_err:
1167 ret_val = 0;
1168 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001169}
1170
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001171
1172/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001173 * converts <str> to two struct in6_addr* which must be pre-allocated.
1174 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1175 * is an optionnal number of bits (128 being the default).
1176 * Returns 1 if OK, 0 if error.
1177 */
1178int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1179{
1180 char *c, *s;
1181 int ret_val = 0;
1182 char *err;
1183 unsigned long len = 128;
1184
1185 s = strdup(str);
1186 if (!s)
1187 return 0;
1188
1189 memset(mask, 0, sizeof(*mask));
1190 memset(addr, 0, sizeof(*addr));
1191
1192 if ((c = strrchr(s, '/')) != NULL) {
1193 *c++ = '\0'; /* c points to the mask */
1194 if (!*c)
1195 goto out_free;
1196
1197 len = strtoul(c, &err, 10);
1198 if ((err && *err) || (unsigned)len > 128)
1199 goto out_free;
1200 }
1201 *mask = len; /* OK we have a valid mask in <len> */
1202
1203 if (!inet_pton(AF_INET6, s, addr))
1204 goto out_free;
1205
1206 ret_val = 1;
1207 out_free:
1208 free(s);
1209 return ret_val;
1210}
1211
1212
1213/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001214 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001215 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001216int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001217{
1218 int saw_digit, octets, ch;
1219 u_char tmp[4], *tp;
1220 const char *cp = addr;
1221
1222 saw_digit = 0;
1223 octets = 0;
1224 *(tp = tmp) = 0;
1225
1226 while (*addr) {
1227 unsigned char digit = (ch = *addr++) - '0';
1228 if (digit > 9 && ch != '.')
1229 break;
1230 if (digit <= 9) {
1231 u_int new = *tp * 10 + digit;
1232 if (new > 255)
1233 return 0;
1234 *tp = new;
1235 if (!saw_digit) {
1236 if (++octets > 4)
1237 return 0;
1238 saw_digit = 1;
1239 }
1240 } else if (ch == '.' && saw_digit) {
1241 if (octets == 4)
1242 return 0;
1243 *++tp = 0;
1244 saw_digit = 0;
1245 } else
1246 return 0;
1247 }
1248
1249 if (octets < 4)
1250 return 0;
1251
1252 memcpy(&dst->s_addr, tmp, 4);
1253 return addr-cp-1;
1254}
1255
1256/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001257 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1258 * <out> contain the code of the dectected scheme, the start and length of
1259 * the hostname. Actually only http and https are supported. <out> can be NULL.
1260 * This function returns the consumed length. It is useful if you parse complete
1261 * url like http://host:port/path, because the consumed length corresponds to
1262 * the first character of the path. If the conversion fails, it returns -1.
1263 *
1264 * This function tries to resolve the DNS name if haproxy is in starting mode.
1265 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001266 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001267int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001268{
1269 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001270 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001271 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001272 unsigned long long int http_code = 0;
1273 int default_port;
1274 struct hostent *he;
1275 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001276
1277 /* Firstly, try to find :// pattern */
1278 while (curr < url+ulen && url_code != 0x3a2f2f) {
1279 url_code = ((url_code & 0xffff) << 8);
1280 url_code += (unsigned char)*curr++;
1281 }
1282
1283 /* Secondly, if :// pattern is found, verify parsed stuff
1284 * before pattern is matching our http pattern.
1285 * If so parse ip address and port in uri.
1286 *
1287 * WARNING: Current code doesn't support dynamic async dns resolver.
1288 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001289 if (url_code != 0x3a2f2f)
1290 return -1;
1291
1292 /* Copy scheme, and utrn to lower case. */
1293 while (cp < curr - 3)
1294 http_code = (http_code << 8) + *cp++;
1295 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001296
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001297 /* HTTP or HTTPS url matching */
1298 if (http_code == 0x2020202068747470ULL) {
1299 default_port = 80;
1300 if (out)
1301 out->scheme = SCH_HTTP;
1302 }
1303 else if (http_code == 0x2020206874747073ULL) {
1304 default_port = 443;
1305 if (out)
1306 out->scheme = SCH_HTTPS;
1307 }
1308 else
1309 return -1;
1310
1311 /* If the next char is '[', the host address is IPv6. */
1312 if (*curr == '[') {
1313 curr++;
1314
1315 /* Check trash size */
1316 if (trash.size < ulen)
1317 return -1;
1318
1319 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001320 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001321 for (end = curr;
1322 end < url + ulen && *end != ']';
1323 end++, p++)
1324 *p = *end;
1325 if (*end != ']')
1326 return -1;
1327 *p = '\0';
1328
1329 /* Update out. */
1330 if (out) {
1331 out->host = curr;
1332 out->host_len = end - curr;
1333 }
1334
1335 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001336 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001337 return -1;
1338 end++;
1339
1340 /* Decode port. */
1341 if (*end == ':') {
1342 end++;
1343 default_port = read_uint(&end, url + ulen);
1344 }
1345 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1346 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1347 return end - url;
1348 }
1349 else {
1350 /* We are looking for IP address. If you want to parse and
1351 * resolve hostname found in url, you can use str2sa_range(), but
1352 * be warned this can slow down global daemon performances
1353 * while handling lagging dns responses.
1354 */
1355 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1356 if (ret) {
1357 /* Update out. */
1358 if (out) {
1359 out->host = curr;
1360 out->host_len = ret;
1361 }
1362
1363 curr += ret;
1364
1365 /* Decode port. */
1366 if (*curr == ':') {
1367 curr++;
1368 default_port = read_uint(&curr, url + ulen);
1369 }
1370 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1371
1372 /* Set family. */
1373 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1374 return curr - url;
1375 }
1376 else if (global.mode & MODE_STARTING) {
1377 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1378 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001379 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001380
1381 /* look for : or / or end */
1382 for (end = curr;
1383 end < url + ulen && *end != '/' && *end != ':';
1384 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001385 memcpy(trash.area, curr, end - curr);
1386 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001387
1388 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001389 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001390 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001391 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001392
1393 /* Update out. */
1394 if (out) {
1395 out->host = curr;
1396 out->host_len = end - curr;
1397 }
1398
1399 /* Decode port. */
1400 if (*end == ':') {
1401 end++;
1402 default_port = read_uint(&end, url + ulen);
1403 }
1404
1405 /* Copy IP address, set port and family. */
1406 switch (he->h_addrtype) {
1407 case AF_INET:
1408 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1409 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1410 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1411 return end - url;
1412
1413 case AF_INET6:
1414 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1415 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1416 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1417 return end - url;
1418 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001419 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001420 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001421 return -1;
1422}
1423
Willy Tarreau631f01c2011-09-05 00:36:48 +02001424/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1425 * address family is returned so that it's easy for the caller to adapt to the
1426 * output format. Zero is returned if the address family is not supported. -1
1427 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1428 * supported.
1429 */
1430int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1431{
1432
1433 void *ptr;
1434
1435 if (size < 5)
1436 return 0;
1437 *str = '\0';
1438
1439 switch (addr->ss_family) {
1440 case AF_INET:
1441 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1442 break;
1443 case AF_INET6:
1444 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1445 break;
1446 case AF_UNIX:
1447 memcpy(str, "unix", 5);
1448 return addr->ss_family;
1449 default:
1450 return 0;
1451 }
1452
1453 if (inet_ntop(addr->ss_family, ptr, str, size))
1454 return addr->ss_family;
1455
1456 /* failed */
1457 return -1;
1458}
1459
Simon Horman75ab8bd2014-06-16 09:39:41 +09001460/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1461 * address family is returned so that it's easy for the caller to adapt to the
1462 * output format. Zero is returned if the address family is not supported. -1
1463 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1464 * supported.
1465 */
1466int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1467{
1468
1469 uint16_t port;
1470
1471
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001472 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001473 return 0;
1474 *str = '\0';
1475
1476 switch (addr->ss_family) {
1477 case AF_INET:
1478 port = ((struct sockaddr_in *)addr)->sin_port;
1479 break;
1480 case AF_INET6:
1481 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1482 break;
1483 case AF_UNIX:
1484 memcpy(str, "unix", 5);
1485 return addr->ss_family;
1486 default:
1487 return 0;
1488 }
1489
1490 snprintf(str, size, "%u", ntohs(port));
1491 return addr->ss_family;
1492}
1493
Willy Tarreau16e01562016-08-09 16:46:18 +02001494/* check if the given address is local to the system or not. It will return
1495 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1496 * it is. We don't want to iterate over all interfaces for this (and it is not
1497 * portable). So instead we try to bind in UDP to this address on a free non
1498 * privileged port and to connect to the same address, port 0 (connect doesn't
1499 * care). If it succeeds, we own the address. Note that non-inet addresses are
1500 * considered local since they're most likely AF_UNIX.
1501 */
1502int addr_is_local(const struct netns_entry *ns,
1503 const struct sockaddr_storage *orig)
1504{
1505 struct sockaddr_storage addr;
1506 int result;
1507 int fd;
1508
1509 if (!is_inet_addr(orig))
1510 return 1;
1511
1512 memcpy(&addr, orig, sizeof(addr));
1513 set_host_port(&addr, 0);
1514
1515 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1516 if (fd < 0)
1517 return -1;
1518
1519 result = -1;
1520 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1521 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1522 result = 0; // fail, non-local address
1523 else
1524 result = 1; // success, local address
1525 }
1526 else {
1527 if (errno == EADDRNOTAVAIL)
1528 result = 0; // definitely not local :-)
1529 }
1530 close(fd);
1531
1532 return result;
1533}
1534
Willy Tarreaubaaee002006-06-26 02:48:02 +02001535/* will try to encode the string <string> replacing all characters tagged in
1536 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1537 * prefixed by <escape>, and will store the result between <start> (included)
1538 * and <stop> (excluded), and will always terminate the string with a '\0'
1539 * before <stop>. The position of the '\0' is returned if the conversion
1540 * completes. If bytes are missing between <start> and <stop>, then the
1541 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1542 * cannot even be stored so we return <start> without writing the 0.
1543 * The input string must also be zero-terminated.
1544 */
1545const char hextab[16] = "0123456789ABCDEF";
1546char *encode_string(char *start, char *stop,
1547 const char escape, const fd_set *map,
1548 const char *string)
1549{
1550 if (start < stop) {
1551 stop--; /* reserve one byte for the final '\0' */
1552 while (start < stop && *string != '\0') {
1553 if (!FD_ISSET((unsigned char)(*string), map))
1554 *start++ = *string;
1555 else {
1556 if (start + 3 >= stop)
1557 break;
1558 *start++ = escape;
1559 *start++ = hextab[(*string >> 4) & 15];
1560 *start++ = hextab[*string & 15];
1561 }
1562 string++;
1563 }
1564 *start = '\0';
1565 }
1566 return start;
1567}
1568
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001569/*
1570 * Same behavior as encode_string() above, except that it encodes chunk
1571 * <chunk> instead of a string.
1572 */
1573char *encode_chunk(char *start, char *stop,
1574 const char escape, const fd_set *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001575 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001576{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001577 char *str = chunk->area;
1578 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001579
1580 if (start < stop) {
1581 stop--; /* reserve one byte for the final '\0' */
1582 while (start < stop && str < end) {
1583 if (!FD_ISSET((unsigned char)(*str), map))
1584 *start++ = *str;
1585 else {
1586 if (start + 3 >= stop)
1587 break;
1588 *start++ = escape;
1589 *start++ = hextab[(*str >> 4) & 15];
1590 *start++ = hextab[*str & 15];
1591 }
1592 str++;
1593 }
1594 *start = '\0';
1595 }
1596 return start;
1597}
1598
Dragan Dosen0edd1092016-02-12 13:23:02 +01001599/*
1600 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001601 * character. The input <string> must be zero-terminated. The result will
1602 * be stored between <start> (included) and <stop> (excluded). This
1603 * function will always try to terminate the resulting string with a '\0'
1604 * before <stop>, and will return its position if the conversion
1605 * completes.
1606 */
1607char *escape_string(char *start, char *stop,
1608 const char escape, const fd_set *map,
1609 const char *string)
1610{
1611 if (start < stop) {
1612 stop--; /* reserve one byte for the final '\0' */
1613 while (start < stop && *string != '\0') {
1614 if (!FD_ISSET((unsigned char)(*string), map))
1615 *start++ = *string;
1616 else {
1617 if (start + 2 >= stop)
1618 break;
1619 *start++ = escape;
1620 *start++ = *string;
1621 }
1622 string++;
1623 }
1624 *start = '\0';
1625 }
1626 return start;
1627}
1628
1629/*
1630 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001631 * character. <chunk> contains the input to be escaped. The result will be
1632 * stored between <start> (included) and <stop> (excluded). The function
1633 * will always try to terminate the resulting string with a '\0' before
1634 * <stop>, and will return its position if the conversion completes.
1635 */
1636char *escape_chunk(char *start, char *stop,
1637 const char escape, const fd_set *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001638 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001639{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001640 char *str = chunk->area;
1641 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001642
1643 if (start < stop) {
1644 stop--; /* reserve one byte for the final '\0' */
1645 while (start < stop && str < end) {
1646 if (!FD_ISSET((unsigned char)(*str), map))
1647 *start++ = *str;
1648 else {
1649 if (start + 2 >= stop)
1650 break;
1651 *start++ = escape;
1652 *start++ = *str;
1653 }
1654 str++;
1655 }
1656 *start = '\0';
1657 }
1658 return start;
1659}
1660
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001661/* Check a string for using it in a CSV output format. If the string contains
1662 * one of the following four char <">, <,>, CR or LF, the string is
1663 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1664 * <str> is the input string to be escaped. The function assumes that
1665 * the input string is null-terminated.
1666 *
1667 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001668 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001669 * format.
1670 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001671 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001672 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001673 * If <quote> is 1, the converter puts the quotes only if any reserved character
1674 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001675 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001676 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001677 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001678 * The function returns the converted string on its output. If an error
1679 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001680 * for using the function directly as printf() argument.
1681 *
1682 * If the output buffer is too short to contain the input string, the result
1683 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001684 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001685 * This function appends the encoding to the existing output chunk, and it
1686 * guarantees that it starts immediately at the first available character of
1687 * the chunk. Please use csv_enc() instead if you want to replace the output
1688 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001689 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001690const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001691{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001692 char *end = output->area + output->size;
1693 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001694 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001695
Willy Tarreaub631c292016-01-08 10:04:08 +01001696 if (quote == 1) {
1697 /* automatic quoting: first verify if we'll have to quote the string */
1698 if (!strpbrk(str, "\n\r,\""))
1699 quote = 0;
1700 }
1701
1702 if (quote)
1703 *ptr++ = '"';
1704
Willy Tarreau898529b2016-01-06 18:07:04 +01001705 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1706 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001707 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001708 ptr++;
1709 if (ptr >= end - 2) {
1710 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001711 break;
1712 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001713 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001714 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001715 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001716 str++;
1717 }
1718
Willy Tarreaub631c292016-01-08 10:04:08 +01001719 if (quote)
1720 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001721
Willy Tarreau898529b2016-01-06 18:07:04 +01001722 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001723 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001724 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001725}
1726
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001727/* Decode an URL-encoded string in-place. The resulting string might
1728 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001729 * aborted, the string is truncated before the issue and a negative value is
1730 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001731 */
1732int url_decode(char *string)
1733{
1734 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001735 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001736
1737 in = string;
1738 out = string;
1739 while (*in) {
1740 switch (*in) {
1741 case '+' :
1742 *out++ = ' ';
1743 break;
1744 case '%' :
1745 if (!ishex(in[1]) || !ishex(in[2]))
1746 goto end;
1747 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1748 in += 2;
1749 break;
1750 default:
1751 *out++ = *in;
1752 break;
1753 }
1754 in++;
1755 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001756 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001757 end:
1758 *out = 0;
1759 return ret;
1760}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001761
Willy Tarreau6911fa42007-03-04 18:06:08 +01001762unsigned int str2ui(const char *s)
1763{
1764 return __str2ui(s);
1765}
1766
1767unsigned int str2uic(const char *s)
1768{
1769 return __str2uic(s);
1770}
1771
1772unsigned int strl2ui(const char *s, int len)
1773{
1774 return __strl2ui(s, len);
1775}
1776
1777unsigned int strl2uic(const char *s, int len)
1778{
1779 return __strl2uic(s, len);
1780}
1781
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001782unsigned int read_uint(const char **s, const char *end)
1783{
1784 return __read_uint(s, end);
1785}
1786
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001787/* This function reads an unsigned integer from the string pointed to by <s> and
1788 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1789 * function automatically stops at <end>. If the number overflows, the 2^64-1
1790 * value is returned.
1791 */
1792unsigned long long int read_uint64(const char **s, const char *end)
1793{
1794 const char *ptr = *s;
1795 unsigned long long int i = 0, tmp;
1796 unsigned int j;
1797
1798 while (ptr < end) {
1799
1800 /* read next char */
1801 j = *ptr - '0';
1802 if (j > 9)
1803 goto read_uint64_end;
1804
1805 /* add char to the number and check overflow. */
1806 tmp = i * 10;
1807 if (tmp / 10 != i) {
1808 i = ULLONG_MAX;
1809 goto read_uint64_eat;
1810 }
1811 if (ULLONG_MAX - tmp < j) {
1812 i = ULLONG_MAX;
1813 goto read_uint64_eat;
1814 }
1815 i = tmp + j;
1816 ptr++;
1817 }
1818read_uint64_eat:
1819 /* eat each numeric char */
1820 while (ptr < end) {
1821 if ((unsigned int)(*ptr - '0') > 9)
1822 break;
1823 ptr++;
1824 }
1825read_uint64_end:
1826 *s = ptr;
1827 return i;
1828}
1829
1830/* This function reads an integer from the string pointed to by <s> and returns
1831 * it. The <s> pointer is adjusted to point to the first unread char. The function
1832 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1833 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1834 * returned.
1835 */
1836long long int read_int64(const char **s, const char *end)
1837{
1838 unsigned long long int i = 0;
1839 int neg = 0;
1840
1841 /* Look for minus char. */
1842 if (**s == '-') {
1843 neg = 1;
1844 (*s)++;
1845 }
1846 else if (**s == '+')
1847 (*s)++;
1848
1849 /* convert as positive number. */
1850 i = read_uint64(s, end);
1851
1852 if (neg) {
1853 if (i > 0x8000000000000000ULL)
1854 return LLONG_MIN;
1855 return -i;
1856 }
1857 if (i > 0x7fffffffffffffffULL)
1858 return LLONG_MAX;
1859 return i;
1860}
1861
Willy Tarreau6911fa42007-03-04 18:06:08 +01001862/* This one is 7 times faster than strtol() on athlon with checks.
1863 * It returns the value of the number composed of all valid digits read,
1864 * and can process negative numbers too.
1865 */
1866int strl2ic(const char *s, int len)
1867{
1868 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001869 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001870
1871 if (len > 0) {
1872 if (*s != '-') {
1873 /* positive number */
1874 while (len-- > 0) {
1875 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001876 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001877 if (j > 9)
1878 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001879 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001880 }
1881 } else {
1882 /* negative number */
1883 s++;
1884 while (--len > 0) {
1885 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001886 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001887 if (j > 9)
1888 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001889 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001890 }
1891 }
1892 }
1893 return i;
1894}
1895
1896
1897/* This function reads exactly <len> chars from <s> and converts them to a
1898 * signed integer which it stores into <ret>. It accurately detects any error
1899 * (truncated string, invalid chars, overflows). It is meant to be used in
1900 * applications designed for hostile environments. It returns zero when the
1901 * number has successfully been converted, non-zero otherwise. When an error
1902 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1903 * faster than strtol().
1904 */
1905int strl2irc(const char *s, int len, int *ret)
1906{
1907 int i = 0;
1908 int j;
1909
1910 if (!len)
1911 return 1;
1912
1913 if (*s != '-') {
1914 /* positive number */
1915 while (len-- > 0) {
1916 j = (*s++) - '0';
1917 if (j > 9) return 1; /* invalid char */
1918 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1919 i = i * 10;
1920 if (i + j < i) return 1; /* check for addition overflow */
1921 i = i + j;
1922 }
1923 } else {
1924 /* negative number */
1925 s++;
1926 while (--len > 0) {
1927 j = (*s++) - '0';
1928 if (j > 9) return 1; /* invalid char */
1929 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1930 i = i * 10;
1931 if (i - j > i) return 1; /* check for subtract overflow */
1932 i = i - j;
1933 }
1934 }
1935 *ret = i;
1936 return 0;
1937}
1938
1939
1940/* This function reads exactly <len> chars from <s> and converts them to a
1941 * signed integer which it stores into <ret>. It accurately detects any error
1942 * (truncated string, invalid chars, overflows). It is meant to be used in
1943 * applications designed for hostile environments. It returns zero when the
1944 * number has successfully been converted, non-zero otherwise. When an error
1945 * is returned, the <ret> value is left untouched. It is about 3 times slower
1946 * than str2irc().
1947 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001948
1949int strl2llrc(const char *s, int len, long long *ret)
1950{
1951 long long i = 0;
1952 int j;
1953
1954 if (!len)
1955 return 1;
1956
1957 if (*s != '-') {
1958 /* positive number */
1959 while (len-- > 0) {
1960 j = (*s++) - '0';
1961 if (j > 9) return 1; /* invalid char */
1962 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1963 i = i * 10LL;
1964 if (i + j < i) return 1; /* check for addition overflow */
1965 i = i + j;
1966 }
1967 } else {
1968 /* negative number */
1969 s++;
1970 while (--len > 0) {
1971 j = (*s++) - '0';
1972 if (j > 9) return 1; /* invalid char */
1973 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1974 i = i * 10LL;
1975 if (i - j > i) return 1; /* check for subtract overflow */
1976 i = i - j;
1977 }
1978 }
1979 *ret = i;
1980 return 0;
1981}
1982
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001983/* This function is used with pat_parse_dotted_ver(). It converts a string
1984 * composed by two number separated by a dot. Each part must contain in 16 bits
1985 * because internally they will be represented as a 32-bit quantity stored in
1986 * a 64-bit integer. It returns zero when the number has successfully been
1987 * converted, non-zero otherwise. When an error is returned, the <ret> value
1988 * is left untouched.
1989 *
1990 * "1.3" -> 0x0000000000010003
1991 * "65535.65535" -> 0x00000000ffffffff
1992 */
1993int strl2llrc_dotted(const char *text, int len, long long *ret)
1994{
1995 const char *end = &text[len];
1996 const char *p;
1997 long long major, minor;
1998
1999 /* Look for dot. */
2000 for (p = text; p < end; p++)
2001 if (*p == '.')
2002 break;
2003
2004 /* Convert major. */
2005 if (strl2llrc(text, p - text, &major) != 0)
2006 return 1;
2007
2008 /* Check major. */
2009 if (major >= 65536)
2010 return 1;
2011
2012 /* Convert minor. */
2013 minor = 0;
2014 if (p < end)
2015 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2016 return 1;
2017
2018 /* Check minor. */
2019 if (minor >= 65536)
2020 return 1;
2021
2022 /* Compose value. */
2023 *ret = (major << 16) | (minor & 0xffff);
2024 return 0;
2025}
2026
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002027/* This function parses a time value optionally followed by a unit suffix among
2028 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2029 * expected by the caller. The computation does its best to avoid overflows.
2030 * The value is returned in <ret> if everything is fine, and a NULL is returned
2031 * by the function. In case of error, a pointer to the error is returned and
2032 * <ret> is left untouched. Values are automatically rounded up when needed.
2033 */
2034const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2035{
2036 unsigned imult, idiv;
2037 unsigned omult, odiv;
2038 unsigned value;
2039
2040 omult = odiv = 1;
2041
2042 switch (unit_flags & TIME_UNIT_MASK) {
2043 case TIME_UNIT_US: omult = 1000000; break;
2044 case TIME_UNIT_MS: omult = 1000; break;
2045 case TIME_UNIT_S: break;
2046 case TIME_UNIT_MIN: odiv = 60; break;
2047 case TIME_UNIT_HOUR: odiv = 3600; break;
2048 case TIME_UNIT_DAY: odiv = 86400; break;
2049 default: break;
2050 }
2051
2052 value = 0;
2053
2054 while (1) {
2055 unsigned int j;
2056
2057 j = *text - '0';
2058 if (j > 9)
2059 break;
2060 text++;
2061 value *= 10;
2062 value += j;
2063 }
2064
2065 imult = idiv = 1;
2066 switch (*text) {
2067 case '\0': /* no unit = default unit */
2068 imult = omult = idiv = odiv = 1;
2069 break;
2070 case 's': /* second = unscaled unit */
2071 break;
2072 case 'u': /* microsecond : "us" */
2073 if (text[1] == 's') {
2074 idiv = 1000000;
2075 text++;
2076 }
2077 break;
2078 case 'm': /* millisecond : "ms" or minute: "m" */
2079 if (text[1] == 's') {
2080 idiv = 1000;
2081 text++;
2082 } else
2083 imult = 60;
2084 break;
2085 case 'h': /* hour : "h" */
2086 imult = 3600;
2087 break;
2088 case 'd': /* day : "d" */
2089 imult = 86400;
2090 break;
2091 default:
2092 return text;
2093 break;
2094 }
2095
2096 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2097 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2098 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2099 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2100
2101 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2102 *ret = value;
2103 return NULL;
2104}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002105
Emeric Brun39132b22010-01-04 14:57:24 +01002106/* this function converts the string starting at <text> to an unsigned int
2107 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002108 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002109 */
2110const char *parse_size_err(const char *text, unsigned *ret) {
2111 unsigned value = 0;
2112
2113 while (1) {
2114 unsigned int j;
2115
2116 j = *text - '0';
2117 if (j > 9)
2118 break;
2119 if (value > ~0U / 10)
2120 return text;
2121 value *= 10;
2122 if (value > (value + j))
2123 return text;
2124 value += j;
2125 text++;
2126 }
2127
2128 switch (*text) {
2129 case '\0':
2130 break;
2131 case 'K':
2132 case 'k':
2133 if (value > ~0U >> 10)
2134 return text;
2135 value = value << 10;
2136 break;
2137 case 'M':
2138 case 'm':
2139 if (value > ~0U >> 20)
2140 return text;
2141 value = value << 20;
2142 break;
2143 case 'G':
2144 case 'g':
2145 if (value > ~0U >> 30)
2146 return text;
2147 value = value << 30;
2148 break;
2149 default:
2150 return text;
2151 }
2152
Godbach58048a22015-01-28 17:36:16 +08002153 if (*text != '\0' && *++text != '\0')
2154 return text;
2155
Emeric Brun39132b22010-01-04 14:57:24 +01002156 *ret = value;
2157 return NULL;
2158}
2159
Willy Tarreau126d4062013-12-03 17:50:47 +01002160/*
2161 * Parse binary string written in hexadecimal (source) and store the decoded
2162 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2163 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002164 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002165 */
2166int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2167{
2168 int len;
2169 const char *p = source;
2170 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002171 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002172
2173 len = strlen(source);
2174 if (len % 2) {
2175 memprintf(err, "an even number of hex digit is expected");
2176 return 0;
2177 }
2178
2179 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002180
Willy Tarreau126d4062013-12-03 17:50:47 +01002181 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002182 *binstr = calloc(len, sizeof(char));
2183 if (!*binstr) {
2184 memprintf(err, "out of memory while loading string pattern");
2185 return 0;
2186 }
2187 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002188 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002189 else {
2190 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002191 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002192 len, *binstrlen);
2193 return 0;
2194 }
2195 alloc = 0;
2196 }
2197 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002198
2199 i = j = 0;
2200 while (j < len) {
2201 if (!ishex(p[i++]))
2202 goto bad_input;
2203 if (!ishex(p[i++]))
2204 goto bad_input;
2205 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2206 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002207 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002208
2209bad_input:
2210 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002211 if (alloc) {
2212 free(*binstr);
2213 *binstr = NULL;
2214 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002215 return 0;
2216}
2217
Willy Tarreau946ba592009-05-10 15:41:18 +02002218/* copies at most <n> characters from <src> and always terminates with '\0' */
2219char *my_strndup(const char *src, int n)
2220{
2221 int len = 0;
2222 char *ret;
2223
2224 while (len < n && src[len])
2225 len++;
2226
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002227 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002228 if (!ret)
2229 return ret;
2230 memcpy(ret, src, len);
2231 ret[len] = '\0';
2232 return ret;
2233}
2234
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002235/*
2236 * search needle in haystack
2237 * returns the pointer if found, returns NULL otherwise
2238 */
2239const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2240{
2241 const void *c = NULL;
2242 unsigned char f;
2243
2244 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2245 return NULL;
2246
2247 f = *(char *)needle;
2248 c = haystack;
2249 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2250 if ((haystacklen - (c - haystack)) < needlelen)
2251 return NULL;
2252
2253 if (memcmp(c, needle, needlelen) == 0)
2254 return c;
2255 ++c;
2256 }
2257 return NULL;
2258}
2259
Willy Tarreau482b00d2009-10-04 22:48:42 +02002260/* This function returns the first unused key greater than or equal to <key> in
2261 * ID tree <root>. Zero is returned if no place is found.
2262 */
2263unsigned int get_next_id(struct eb_root *root, unsigned int key)
2264{
2265 struct eb32_node *used;
2266
2267 do {
2268 used = eb32_lookup_ge(root, key);
2269 if (!used || used->key > key)
2270 return key; /* key is available */
2271 key++;
2272 } while (key);
2273 return key;
2274}
2275
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002276/* dump the full tree to <file> in DOT format for debugging purposes. Will
2277 * optionally highlight node <subj> if found, depending on operation <op> :
2278 * 0 : nothing
2279 * >0 : insertion, node/leaf are surrounded in red
2280 * <0 : removal, node/leaf are dashed with no background
2281 * Will optionally add "desc" as a label on the graph if set and non-null.
2282 */
2283void 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 +01002284{
2285 struct eb32sc_node *node;
2286 unsigned long scope = -1;
2287
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002288 fprintf(file, "digraph ebtree {\n");
2289
2290 if (desc && *desc) {
2291 fprintf(file,
2292 " fontname=\"fixed\";\n"
2293 " fontsize=8;\n"
2294 " label=\"%s\";\n", desc);
2295 }
2296
Willy Tarreaued3cda02017-11-15 15:04:05 +01002297 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002298 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2299 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002300 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2301 );
2302
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002303 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002304 (long)eb_root_to_node(root),
2305 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002306 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2307
2308 node = eb32sc_first(root, scope);
2309 while (node) {
2310 if (node->node.node_p) {
2311 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002312 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2313 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2314 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002315
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002316 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002317 (long)node,
2318 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002319 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002320
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002321 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002322 (long)node,
2323 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002324 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2325
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002326 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002327 (long)node,
2328 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002329 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2330 }
2331
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002332 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2333 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2334 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002335
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002336 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002337 (long)node,
2338 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002339 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002340 node = eb32sc_next(node, scope);
2341 }
2342 fprintf(file, "}\n");
2343}
2344
Willy Tarreau348238b2010-01-18 15:05:57 +01002345/* This function compares a sample word possibly followed by blanks to another
2346 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2347 * otherwise zero. This intends to be used when checking HTTP headers for some
2348 * values. Note that it validates a word followed only by blanks but does not
2349 * validate a word followed by blanks then other chars.
2350 */
2351int word_match(const char *sample, int slen, const char *word, int wlen)
2352{
2353 if (slen < wlen)
2354 return 0;
2355
2356 while (wlen) {
2357 char c = *sample ^ *word;
2358 if (c && c != ('A' ^ 'a'))
2359 return 0;
2360 sample++;
2361 word++;
2362 slen--;
2363 wlen--;
2364 }
2365
2366 while (slen) {
2367 if (*sample != ' ' && *sample != '\t')
2368 return 0;
2369 sample++;
2370 slen--;
2371 }
2372 return 1;
2373}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002374
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002375/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2376 * is particularly fast because it avoids expensive operations such as
2377 * multiplies, which are optimized away at the end. It requires a properly
2378 * formated address though (3 points).
2379 */
2380unsigned int inetaddr_host(const char *text)
2381{
2382 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2383 register unsigned int dig100, dig10, dig1;
2384 int s;
2385 const char *p, *d;
2386
2387 dig1 = dig10 = dig100 = ascii_zero;
2388 s = 24;
2389
2390 p = text;
2391 while (1) {
2392 if (((unsigned)(*p - '0')) <= 9) {
2393 p++;
2394 continue;
2395 }
2396
2397 /* here, we have a complete byte between <text> and <p> (exclusive) */
2398 if (p == text)
2399 goto end;
2400
2401 d = p - 1;
2402 dig1 |= (unsigned int)(*d << s);
2403 if (d == text)
2404 goto end;
2405
2406 d--;
2407 dig10 |= (unsigned int)(*d << s);
2408 if (d == text)
2409 goto end;
2410
2411 d--;
2412 dig100 |= (unsigned int)(*d << s);
2413 end:
2414 if (!s || *p != '.')
2415 break;
2416
2417 s -= 8;
2418 text = ++p;
2419 }
2420
2421 dig100 -= ascii_zero;
2422 dig10 -= ascii_zero;
2423 dig1 -= ascii_zero;
2424 return ((dig100 * 10) + dig10) * 10 + dig1;
2425}
2426
2427/*
2428 * Idem except the first unparsed character has to be passed in <stop>.
2429 */
2430unsigned int inetaddr_host_lim(const char *text, const char *stop)
2431{
2432 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2433 register unsigned int dig100, dig10, dig1;
2434 int s;
2435 const char *p, *d;
2436
2437 dig1 = dig10 = dig100 = ascii_zero;
2438 s = 24;
2439
2440 p = text;
2441 while (1) {
2442 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2443 p++;
2444 continue;
2445 }
2446
2447 /* here, we have a complete byte between <text> and <p> (exclusive) */
2448 if (p == text)
2449 goto end;
2450
2451 d = p - 1;
2452 dig1 |= (unsigned int)(*d << s);
2453 if (d == text)
2454 goto end;
2455
2456 d--;
2457 dig10 |= (unsigned int)(*d << s);
2458 if (d == text)
2459 goto end;
2460
2461 d--;
2462 dig100 |= (unsigned int)(*d << s);
2463 end:
2464 if (!s || p == stop || *p != '.')
2465 break;
2466
2467 s -= 8;
2468 text = ++p;
2469 }
2470
2471 dig100 -= ascii_zero;
2472 dig10 -= ascii_zero;
2473 dig1 -= ascii_zero;
2474 return ((dig100 * 10) + dig10) * 10 + dig1;
2475}
2476
2477/*
2478 * Idem except the pointer to first unparsed byte is returned into <ret> which
2479 * must not be NULL.
2480 */
Willy Tarreau74172752010-10-15 23:21:42 +02002481unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002482{
2483 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2484 register unsigned int dig100, dig10, dig1;
2485 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002486 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002487
2488 dig1 = dig10 = dig100 = ascii_zero;
2489 s = 24;
2490
2491 p = text;
2492 while (1) {
2493 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2494 p++;
2495 continue;
2496 }
2497
2498 /* here, we have a complete byte between <text> and <p> (exclusive) */
2499 if (p == text)
2500 goto end;
2501
2502 d = p - 1;
2503 dig1 |= (unsigned int)(*d << s);
2504 if (d == text)
2505 goto end;
2506
2507 d--;
2508 dig10 |= (unsigned int)(*d << s);
2509 if (d == text)
2510 goto end;
2511
2512 d--;
2513 dig100 |= (unsigned int)(*d << s);
2514 end:
2515 if (!s || p == stop || *p != '.')
2516 break;
2517
2518 s -= 8;
2519 text = ++p;
2520 }
2521
2522 *ret = p;
2523 dig100 -= ascii_zero;
2524 dig10 -= ascii_zero;
2525 dig1 -= ascii_zero;
2526 return ((dig100 * 10) + dig10) * 10 + dig1;
2527}
2528
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002529/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2530 * or the number of chars read in case of success. Maybe this could be replaced
2531 * by one of the functions above. Also, apparently this function does not support
2532 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002533 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002534 */
2535int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2536{
2537 const char *addr;
2538 int saw_digit, octets, ch;
2539 u_char tmp[4], *tp;
2540 const char *cp = buf;
2541
2542 saw_digit = 0;
2543 octets = 0;
2544 *(tp = tmp) = 0;
2545
2546 for (addr = buf; addr - buf < len; addr++) {
2547 unsigned char digit = (ch = *addr) - '0';
2548
2549 if (digit > 9 && ch != '.')
2550 break;
2551
2552 if (digit <= 9) {
2553 u_int new = *tp * 10 + digit;
2554
2555 if (new > 255)
2556 return 0;
2557
2558 *tp = new;
2559
2560 if (!saw_digit) {
2561 if (++octets > 4)
2562 return 0;
2563 saw_digit = 1;
2564 }
2565 } else if (ch == '.' && saw_digit) {
2566 if (octets == 4)
2567 return 0;
2568
2569 *++tp = 0;
2570 saw_digit = 0;
2571 } else
2572 return 0;
2573 }
2574
2575 if (octets < 4)
2576 return 0;
2577
2578 memcpy(&dst->s_addr, tmp, 4);
2579 return addr - cp;
2580}
2581
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002582/* This function converts the string in <buf> of the len <len> to
2583 * struct in6_addr <dst> which must be allocated by the caller.
2584 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002585 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002586 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002587int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2588{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002589 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002590 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002591
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002592 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002593 return 0;
2594
2595 memcpy(null_term_ip6, buf, len);
2596 null_term_ip6[len] = '\0';
2597
Willy Tarreau075415a2013-12-12 11:29:39 +01002598 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002599 return 0;
2600
Willy Tarreau075415a2013-12-12 11:29:39 +01002601 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002602 return 1;
2603}
2604
Willy Tarreauacf95772010-06-14 19:09:21 +02002605/* To be used to quote config arg positions. Returns the short string at <ptr>
2606 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2607 * if ptr is NULL or empty. The string is locally allocated.
2608 */
2609const char *quote_arg(const char *ptr)
2610{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002611 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002612 int i;
2613
2614 if (!ptr || !*ptr)
2615 return "end of line";
2616 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002617 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002618 val[i] = *ptr++;
2619 val[i++] = '\'';
2620 val[i] = '\0';
2621 return val;
2622}
2623
Willy Tarreau5b180202010-07-18 10:40:48 +02002624/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2625int get_std_op(const char *str)
2626{
2627 int ret = -1;
2628
2629 if (*str == 'e' && str[1] == 'q')
2630 ret = STD_OP_EQ;
2631 else if (*str == 'n' && str[1] == 'e')
2632 ret = STD_OP_NE;
2633 else if (*str == 'l') {
2634 if (str[1] == 'e') ret = STD_OP_LE;
2635 else if (str[1] == 't') ret = STD_OP_LT;
2636 }
2637 else if (*str == 'g') {
2638 if (str[1] == 'e') ret = STD_OP_GE;
2639 else if (str[1] == 't') ret = STD_OP_GT;
2640 }
2641
2642 if (ret == -1 || str[2] != '\0')
2643 return -1;
2644 return ret;
2645}
2646
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002647/* hash a 32-bit integer to another 32-bit integer */
2648unsigned int full_hash(unsigned int a)
2649{
2650 return __full_hash(a);
2651}
2652
David du Colombier4f92d322011-03-24 11:09:31 +01002653/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002654 * otherwise zero. Note that <addr> may not necessarily be aligned
2655 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002656 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002657int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002658{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002659 struct in_addr addr_copy;
2660
2661 memcpy(&addr_copy, addr, sizeof(addr_copy));
2662 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002663}
2664
2665/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002666 * otherwise zero. Note that <addr> may not necessarily be aligned
2667 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002668 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002669int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002670{
2671 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002672 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002673
Willy Tarreaueec1d382016-07-13 11:59:39 +02002674 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002675 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002676 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002677 (((int *)net)[i] & ((int *)mask)[i]))
2678 return 0;
2679 return 1;
2680}
2681
2682/* RFC 4291 prefix */
2683const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2684 0x00, 0x00, 0x00, 0x00,
2685 0x00, 0x00, 0xFF, 0xFF };
2686
Joseph Herlant32b83272018-11-15 11:58:28 -08002687/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002688 * Input and output may overlap.
2689 */
David du Colombier4f92d322011-03-24 11:09:31 +01002690void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2691{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002692 struct in_addr tmp_addr;
2693
2694 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002695 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002696 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002697}
2698
Joseph Herlant32b83272018-11-15 11:58:28 -08002699/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01002700 * Return true if conversion is possible and false otherwise.
2701 */
2702int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2703{
2704 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2705 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2706 sizeof(struct in_addr));
2707 return 1;
2708 }
2709
2710 return 0;
2711}
2712
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002713/* compare two struct sockaddr_storage and return:
2714 * 0 (true) if the addr is the same in both
2715 * 1 (false) if the addr is not the same in both
2716 * -1 (unable) if one of the addr is not AF_INET*
2717 */
2718int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2719{
2720 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2721 return -1;
2722
2723 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2724 return -1;
2725
2726 if (ss1->ss_family != ss2->ss_family)
2727 return 1;
2728
2729 switch (ss1->ss_family) {
2730 case AF_INET:
2731 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2732 &((struct sockaddr_in *)ss2)->sin_addr,
2733 sizeof(struct in_addr)) != 0;
2734 case AF_INET6:
2735 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2736 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2737 sizeof(struct in6_addr)) != 0;
2738 }
2739
2740 return 1;
2741}
2742
Baptiste Assmann08396c82016-01-31 00:27:17 +01002743/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002744 * The caller must allocate and clear <dest> before calling.
2745 * The source must be in either AF_INET or AF_INET6 family, or the destination
2746 * address will be undefined. If the destination address used to hold a port,
2747 * it is preserved, so that this function can be used to switch to another
2748 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002749 */
2750struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2751{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002752 int prev_port;
2753
2754 prev_port = get_net_port(dest);
2755 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002756 dest->ss_family = source->ss_family;
2757
2758 /* copy new addr and apply it */
2759 switch (source->ss_family) {
2760 case AF_INET:
2761 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002762 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002763 break;
2764 case AF_INET6:
2765 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 +01002766 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002767 break;
2768 }
2769
2770 return dest;
2771}
2772
William Lallemand421f5b52012-02-06 18:15:57 +01002773char *human_time(int t, short hz_div) {
2774 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2775 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002776 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002777 int cnt=2; // print two numbers
2778
2779 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002780 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002781 return rv;
2782 }
2783
2784 if (unlikely(hz_div > 1))
2785 t /= hz_div;
2786
2787 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002788 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002789 cnt--;
2790 }
2791
2792 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002793 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002794 cnt--;
2795 }
2796
2797 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002798 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002799 cnt--;
2800 }
2801
2802 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002803 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002804
2805 return rv;
2806}
2807
2808const char *monthname[12] = {
2809 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2810 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2811};
2812
2813/* date2str_log: write a date in the format :
2814 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2815 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2816 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2817 *
2818 * without using sprintf. return a pointer to the last char written (\0) or
2819 * NULL if there isn't enough space.
2820 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02002821char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01002822{
2823
2824 if (size < 25) /* the size is fixed: 24 chars + \0 */
2825 return NULL;
2826
2827 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002828 if (!dst)
2829 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002830 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002831
William Lallemand421f5b52012-02-06 18:15:57 +01002832 memcpy(dst, monthname[tm->tm_mon], 3); // month
2833 dst += 3;
2834 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002835
William Lallemand421f5b52012-02-06 18:15:57 +01002836 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002837 if (!dst)
2838 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002839 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002840
William Lallemand421f5b52012-02-06 18:15:57 +01002841 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002842 if (!dst)
2843 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002844 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002845
William Lallemand421f5b52012-02-06 18:15:57 +01002846 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002847 if (!dst)
2848 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002849 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002850
William Lallemand421f5b52012-02-06 18:15:57 +01002851 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002852 if (!dst)
2853 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002854 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002855
William Lallemand421f5b52012-02-06 18:15:57 +01002856 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002857 if (!dst)
2858 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002859 dst += 3; // only the 3 first digits
2860 *dst = '\0';
2861
2862 return dst;
2863}
2864
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002865/* Base year used to compute leap years */
2866#define TM_YEAR_BASE 1900
2867
2868/* Return the difference in seconds between two times (leap seconds are ignored).
2869 * Retrieved from glibc 2.18 source code.
2870 */
2871static int my_tm_diff(const struct tm *a, const struct tm *b)
2872{
2873 /* Compute intervening leap days correctly even if year is negative.
2874 * Take care to avoid int overflow in leap day calculations,
2875 * but it's OK to assume that A and B are close to each other.
2876 */
2877 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2878 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2879 int a100 = a4 / 25 - (a4 % 25 < 0);
2880 int b100 = b4 / 25 - (b4 % 25 < 0);
2881 int a400 = a100 >> 2;
2882 int b400 = b100 >> 2;
2883 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2884 int years = a->tm_year - b->tm_year;
2885 int days = (365 * years + intervening_leap_days
2886 + (a->tm_yday - b->tm_yday));
2887 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2888 + (a->tm_min - b->tm_min))
2889 + (a->tm_sec - b->tm_sec));
2890}
2891
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002892/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002893 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002894 * The string returned has the same format as returned by strftime(... "%z", tm).
2895 * Offsets are kept in an internal cache for better performances.
2896 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002897const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002898{
2899 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002900 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002901
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002902 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002903 struct tm tm_gmt;
2904 int diff;
2905 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002906
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002907 /* Pretend DST not active if its status is unknown */
2908 if (isdst < 0)
2909 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002910
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002911 /* Fetch the offset and initialize it if needed */
2912 gmt_offset = gmt_offsets[isdst & 0x01];
2913 if (unlikely(!*gmt_offset)) {
2914 get_gmtime(t, &tm_gmt);
2915 diff = my_tm_diff(tm, &tm_gmt);
2916 if (diff < 0) {
2917 diff = -diff;
2918 *gmt_offset = '-';
2919 } else {
2920 *gmt_offset = '+';
2921 }
2922 diff /= 60; /* Convert to minutes */
2923 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2924 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002925
2926 return gmt_offset;
2927}
2928
William Lallemand421f5b52012-02-06 18:15:57 +01002929/* gmt2str_log: write a date in the format :
2930 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2931 * return a pointer to the last char written (\0) or
2932 * NULL if there isn't enough space.
2933 */
2934char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2935{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002936 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002937 return NULL;
2938
2939 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002940 if (!dst)
2941 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002942 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002943
William Lallemand421f5b52012-02-06 18:15:57 +01002944 memcpy(dst, monthname[tm->tm_mon], 3); // month
2945 dst += 3;
2946 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002947
William Lallemand421f5b52012-02-06 18:15:57 +01002948 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002949 if (!dst)
2950 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002951 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002952
William Lallemand421f5b52012-02-06 18:15:57 +01002953 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002954 if (!dst)
2955 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002956 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002957
William Lallemand421f5b52012-02-06 18:15:57 +01002958 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002959 if (!dst)
2960 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002961 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002962
William Lallemand421f5b52012-02-06 18:15:57 +01002963 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002964 if (!dst)
2965 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01002966 *dst++ = ' ';
2967 *dst++ = '+';
2968 *dst++ = '0';
2969 *dst++ = '0';
2970 *dst++ = '0';
2971 *dst++ = '0';
2972 *dst = '\0';
2973
2974 return dst;
2975}
2976
Yuxans Yao4e25b012012-10-19 10:36:09 +08002977/* localdate2str_log: write a date in the format :
2978 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002979 * Both t and tm must represent the same time.
2980 * return a pointer to the last char written (\0) or
2981 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002982 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002983char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002984{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002985 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002986 if (size < 27) /* the size is fixed: 26 chars + \0 */
2987 return NULL;
2988
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002989 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002990
Yuxans Yao4e25b012012-10-19 10:36:09 +08002991 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002992 if (!dst)
2993 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002994 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002995
Yuxans Yao4e25b012012-10-19 10:36:09 +08002996 memcpy(dst, monthname[tm->tm_mon], 3); // month
2997 dst += 3;
2998 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01002999
Yuxans Yao4e25b012012-10-19 10:36:09 +08003000 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003001 if (!dst)
3002 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003003 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003004
Yuxans Yao4e25b012012-10-19 10:36:09 +08003005 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003006 if (!dst)
3007 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003008 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003009
Yuxans Yao4e25b012012-10-19 10:36:09 +08003010 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003011 if (!dst)
3012 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003013 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003014
Yuxans Yao4e25b012012-10-19 10:36:09 +08003015 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003016 if (!dst)
3017 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003018 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003019
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003020 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003021 dst += 5;
3022 *dst = '\0';
3023
3024 return dst;
3025}
3026
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003027/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3028 * It is meant as a portable replacement for timegm() for use with valid inputs.
3029 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3030 */
3031time_t my_timegm(const struct tm *tm)
3032{
3033 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3034 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3035 * sum of the extra N days for elapsed months. The sum of all these N
3036 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3037 * in a 5-bit word. This means that with 60 bits we can represent a
3038 * matrix of all these values at once, which is fast and efficient to
3039 * access. The extra February day for leap years is not counted here.
3040 *
3041 * Jan : none = 0 (0)
3042 * Feb : Jan = 3 (3)
3043 * Mar : Jan..Feb = 3 (3 + 0)
3044 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3045 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3046 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3047 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3048 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3049 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3050 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3051 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3052 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3053 */
3054 uint64_t extra =
3055 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3056 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3057 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3058 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3059
3060 unsigned int y = tm->tm_year + 1900;
3061 unsigned int m = tm->tm_mon;
3062 unsigned long days = 0;
3063
3064 /* days since 1/1/1970 for full years */
3065 days += days_since_zero(y) - days_since_zero(1970);
3066
3067 /* days for full months in the current year */
3068 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3069
3070 /* count + 1 after March for leap years. A leap year is a year multiple
3071 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3072 * is leap, 1900 isn't, 1904 is.
3073 */
3074 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3075 days++;
3076
3077 days += tm->tm_mday - 1;
3078 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3079}
3080
Thierry Fournier93127942016-01-20 18:49:45 +01003081/* This function check a char. It returns true and updates
3082 * <date> and <len> pointer to the new position if the
3083 * character is found.
3084 */
3085static inline int parse_expect_char(const char **date, int *len, char c)
3086{
3087 if (*len < 1 || **date != c)
3088 return 0;
3089 (*len)--;
3090 (*date)++;
3091 return 1;
3092}
3093
3094/* This function expects a string <str> of len <l>. It return true and updates.
3095 * <date> and <len> if the string matches, otherwise, it returns false.
3096 */
3097static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3098{
3099 if (*len < l || strncmp(*date, str, l) != 0)
3100 return 0;
3101 (*len) -= l;
3102 (*date) += l;
3103 return 1;
3104}
3105
3106/* This macro converts 3 chars name in integer. */
3107#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3108
3109/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3110 * / %x54.75.65 ; "Tue", case-sensitive
3111 * / %x57.65.64 ; "Wed", case-sensitive
3112 * / %x54.68.75 ; "Thu", case-sensitive
3113 * / %x46.72.69 ; "Fri", case-sensitive
3114 * / %x53.61.74 ; "Sat", case-sensitive
3115 * / %x53.75.6E ; "Sun", case-sensitive
3116 *
3117 * This array must be alphabetically sorted
3118 */
3119static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3120{
3121 if (*len < 3)
3122 return 0;
3123 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3124 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3125 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3126 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3127 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3128 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3129 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3130 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3131 default: return 0;
3132 }
3133 *len -= 3;
3134 *date += 3;
3135 return 1;
3136}
3137
3138/* month = %x4A.61.6E ; "Jan", case-sensitive
3139 * / %x46.65.62 ; "Feb", case-sensitive
3140 * / %x4D.61.72 ; "Mar", case-sensitive
3141 * / %x41.70.72 ; "Apr", case-sensitive
3142 * / %x4D.61.79 ; "May", case-sensitive
3143 * / %x4A.75.6E ; "Jun", case-sensitive
3144 * / %x4A.75.6C ; "Jul", case-sensitive
3145 * / %x41.75.67 ; "Aug", case-sensitive
3146 * / %x53.65.70 ; "Sep", case-sensitive
3147 * / %x4F.63.74 ; "Oct", case-sensitive
3148 * / %x4E.6F.76 ; "Nov", case-sensitive
3149 * / %x44.65.63 ; "Dec", case-sensitive
3150 *
3151 * This array must be alphabetically sorted
3152 */
3153static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3154{
3155 if (*len < 3)
3156 return 0;
3157 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3158 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3159 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3160 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3161 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3162 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3163 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3164 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3165 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3166 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3167 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3168 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3169 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3170 default: return 0;
3171 }
3172 *len -= 3;
3173 *date += 3;
3174 return 1;
3175}
3176
3177/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3178 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3179 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3180 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3181 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3182 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3183 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3184 *
3185 * This array must be alphabetically sorted
3186 */
3187static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3188{
3189 if (*len < 6) /* Minimum length. */
3190 return 0;
3191 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3192 case STR2I3('M','o','n'):
3193 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3194 tm->tm_wday = 1;
3195 return 1;
3196 case STR2I3('T','u','e'):
3197 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3198 tm->tm_wday = 2;
3199 return 1;
3200 case STR2I3('W','e','d'):
3201 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3202 tm->tm_wday = 3;
3203 return 1;
3204 case STR2I3('T','h','u'):
3205 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3206 tm->tm_wday = 4;
3207 return 1;
3208 case STR2I3('F','r','i'):
3209 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3210 tm->tm_wday = 5;
3211 return 1;
3212 case STR2I3('S','a','t'):
3213 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3214 tm->tm_wday = 6;
3215 return 1;
3216 case STR2I3('S','u','n'):
3217 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3218 tm->tm_wday = 7;
3219 return 1;
3220 }
3221 return 0;
3222}
3223
3224/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3225static inline int parse_digit(const char **date, int *len, int *digit)
3226{
3227 if (*len < 1 || **date < '0' || **date > '9')
3228 return 0;
3229 *digit = (**date - '0');
3230 (*date)++;
3231 (*len)--;
3232 return 1;
3233}
3234
3235/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3236static inline int parse_2digit(const char **date, int *len, int *digit)
3237{
3238 int value;
3239
3240 RET0_UNLESS(parse_digit(date, len, &value));
3241 (*digit) = value * 10;
3242 RET0_UNLESS(parse_digit(date, len, &value));
3243 (*digit) += value;
3244
3245 return 1;
3246}
3247
3248/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3249static inline int parse_4digit(const char **date, int *len, int *digit)
3250{
3251 int value;
3252
3253 RET0_UNLESS(parse_digit(date, len, &value));
3254 (*digit) = value * 1000;
3255
3256 RET0_UNLESS(parse_digit(date, len, &value));
3257 (*digit) += value * 100;
3258
3259 RET0_UNLESS(parse_digit(date, len, &value));
3260 (*digit) += value * 10;
3261
3262 RET0_UNLESS(parse_digit(date, len, &value));
3263 (*digit) += value;
3264
3265 return 1;
3266}
3267
3268/* time-of-day = hour ":" minute ":" second
3269 * ; 00:00:00 - 23:59:60 (leap second)
3270 *
3271 * hour = 2DIGIT
3272 * minute = 2DIGIT
3273 * second = 2DIGIT
3274 */
3275static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3276{
3277 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3278 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3279 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3280 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3281 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3282 return 1;
3283}
3284
3285/* From RFC7231
3286 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3287 *
3288 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3289 * ; fixed length/zone/capitalization subset of the format
3290 * ; see Section 3.3 of [RFC5322]
3291 *
3292 *
3293 * date1 = day SP month SP year
3294 * ; e.g., 02 Jun 1982
3295 *
3296 * day = 2DIGIT
3297 * year = 4DIGIT
3298 *
3299 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3300 *
3301 * time-of-day = hour ":" minute ":" second
3302 * ; 00:00:00 - 23:59:60 (leap second)
3303 *
3304 * hour = 2DIGIT
3305 * minute = 2DIGIT
3306 * second = 2DIGIT
3307 *
3308 * DIGIT = decimal 0-9
3309 */
3310int parse_imf_date(const char *date, int len, struct tm *tm)
3311{
David Carlier327298c2016-11-20 10:42:38 +00003312 /* tm_gmtoff, if present, ought to be zero'ed */
3313 memset(tm, 0, sizeof(*tm));
3314
Thierry Fournier93127942016-01-20 18:49:45 +01003315 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3316 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3317 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3318 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3319 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3320 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3321 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3322 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3323 tm->tm_year -= 1900;
3324 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3325 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3326 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3327 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3328 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003329 return 1;
3330}
3331
3332/* From RFC7231
3333 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3334 *
3335 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3336 * date2 = day "-" month "-" 2DIGIT
3337 * ; e.g., 02-Jun-82
3338 *
3339 * day = 2DIGIT
3340 */
3341int parse_rfc850_date(const char *date, int len, struct tm *tm)
3342{
3343 int year;
3344
David Carlier327298c2016-11-20 10:42:38 +00003345 /* tm_gmtoff, if present, ought to be zero'ed */
3346 memset(tm, 0, sizeof(*tm));
3347
Thierry Fournier93127942016-01-20 18:49:45 +01003348 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3349 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3350 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3351 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3352 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3353 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3354 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3355
3356 /* year = 2DIGIT
3357 *
3358 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3359 * two-digit year, MUST interpret a timestamp that appears to be more
3360 * than 50 years in the future as representing the most recent year in
3361 * the past that had the same last two digits.
3362 */
3363 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3364
3365 /* expect SP */
3366 if (!parse_expect_char(&date, &len, ' ')) {
3367 /* Maybe we have the date with 4 digits. */
3368 RET0_UNLESS(parse_2digit(&date, &len, &year));
3369 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3370 /* expect SP */
3371 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3372 } else {
3373 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3374 * tm_year is the number of year since 1900, so for +1900, we
3375 * do nothing, and for +2000, we add 100.
3376 */
3377 if (tm->tm_year <= 60)
3378 tm->tm_year += 100;
3379 }
3380
3381 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3382 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3383 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3384 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003385
3386 return 1;
3387}
3388
3389/* From RFC7231
3390 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3391 *
3392 * asctime-date = day-name SP date3 SP time-of-day SP year
3393 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3394 * ; e.g., Jun 2
3395 *
3396 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3397 * whitespace in an HTTP-date beyond that specifically included as SP in
3398 * the grammar.
3399 */
3400int parse_asctime_date(const char *date, int len, struct tm *tm)
3401{
David Carlier327298c2016-11-20 10:42:38 +00003402 /* tm_gmtoff, if present, ought to be zero'ed */
3403 memset(tm, 0, sizeof(*tm));
3404
Thierry Fournier93127942016-01-20 18:49:45 +01003405 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3406 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3407 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3408 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3409
3410 /* expect SP and 1DIGIT or 2DIGIT */
3411 if (parse_expect_char(&date, &len, ' '))
3412 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3413 else
3414 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3415
3416 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3417 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3418 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3419 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3420 tm->tm_year -= 1900;
3421 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003422 return 1;
3423}
3424
3425/* From RFC7231
3426 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3427 *
3428 * HTTP-date = IMF-fixdate / obs-date
3429 * obs-date = rfc850-date / asctime-date
3430 *
3431 * parses an HTTP date in the RFC format and is accepted
3432 * alternatives. <date> is the strinf containing the date,
3433 * len is the len of the string. <tm> is filled with the
3434 * parsed time. We must considers this time as GMT.
3435 */
3436int parse_http_date(const char *date, int len, struct tm *tm)
3437{
3438 if (parse_imf_date(date, len, tm))
3439 return 1;
3440
3441 if (parse_rfc850_date(date, len, tm))
3442 return 1;
3443
3444 if (parse_asctime_date(date, len, tm))
3445 return 1;
3446
3447 return 0;
3448}
3449
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003450/* Dynamically allocates a string of the proper length to hold the formatted
3451 * output. NULL is returned on error. The caller is responsible for freeing the
3452 * memory area using free(). The resulting string is returned in <out> if the
3453 * pointer is not NULL. A previous version of <out> might be used to build the
3454 * new string, and it will be freed before returning if it is not NULL, which
3455 * makes it possible to build complex strings from iterative calls without
3456 * having to care about freeing intermediate values, as in the example below :
3457 *
3458 * memprintf(&err, "invalid argument: '%s'", arg);
3459 * ...
3460 * memprintf(&err, "parser said : <%s>\n", *err);
3461 * ...
3462 * free(*err);
3463 *
3464 * This means that <err> must be initialized to NULL before first invocation.
3465 * The return value also holds the allocated string, which eases error checking
3466 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003467 * passed instead and it will be ignored. The returned message will then also
3468 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003469 *
3470 * It is also convenient to use it without any free except the last one :
3471 * err = NULL;
3472 * if (!fct1(err)) report(*err);
3473 * if (!fct2(err)) report(*err);
3474 * if (!fct3(err)) report(*err);
3475 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003476 *
3477 * memprintf relies on memvprintf. This last version can be called from any
3478 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003479 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003480char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003481{
3482 va_list args;
3483 char *ret = NULL;
3484 int allocated = 0;
3485 int needed = 0;
3486
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003487 if (!out)
3488 return NULL;
3489
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003490 do {
3491 /* vsnprintf() will return the required length even when the
3492 * target buffer is NULL. We do this in a loop just in case
3493 * intermediate evaluations get wrong.
3494 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003495 va_copy(args, orig_args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003496 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003497 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003498 if (needed < allocated) {
3499 /* Note: on Solaris 8, the first iteration always
3500 * returns -1 if allocated is zero, so we force a
3501 * retry.
3502 */
3503 if (!allocated)
3504 needed = 0;
3505 else
3506 break;
3507 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003508
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003509 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003510 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003511 } while (ret);
3512
3513 if (needed < 0) {
3514 /* an error was encountered */
3515 free(ret);
3516 ret = NULL;
3517 }
3518
3519 if (out) {
3520 free(*out);
3521 *out = ret;
3522 }
3523
3524 return ret;
3525}
William Lallemand421f5b52012-02-06 18:15:57 +01003526
Christopher Faulet93a518f2017-10-24 11:25:33 +02003527char *memprintf(char **out, const char *format, ...)
3528{
3529 va_list args;
3530 char *ret = NULL;
3531
3532 va_start(args, format);
3533 ret = memvprintf(out, format, args);
3534 va_end(args);
3535
3536 return ret;
3537}
3538
Willy Tarreau21c705b2012-09-14 11:40:36 +02003539/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3540 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003541 * freed by the caller. It also supports being passed a NULL which results in the same
3542 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003543 * Example of use :
3544 * parse(cmd, &err); (callee: memprintf(&err, ...))
3545 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3546 * free(err);
3547 */
3548char *indent_msg(char **out, int level)
3549{
3550 char *ret, *in, *p;
3551 int needed = 0;
3552 int lf = 0;
3553 int lastlf = 0;
3554 int len;
3555
Willy Tarreau70eec382012-10-10 08:56:47 +02003556 if (!out || !*out)
3557 return NULL;
3558
Willy Tarreau21c705b2012-09-14 11:40:36 +02003559 in = *out - 1;
3560 while ((in = strchr(in + 1, '\n')) != NULL) {
3561 lastlf = in - *out;
3562 lf++;
3563 }
3564
3565 if (!lf) /* single line, no LF, return it as-is */
3566 return *out;
3567
3568 len = strlen(*out);
3569
3570 if (lf == 1 && lastlf == len - 1) {
3571 /* single line, LF at end, strip it and return as-is */
3572 (*out)[lastlf] = 0;
3573 return *out;
3574 }
3575
3576 /* OK now we have at least one LF, we need to process the whole string
3577 * as a multi-line string. What we'll do :
3578 * - prefix with an LF if there is none
3579 * - add <level> spaces before each line
3580 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3581 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3582 */
3583
3584 needed = 1 + level * (lf + 1) + len + 1;
3585 p = ret = malloc(needed);
3586 in = *out;
3587
3588 /* skip initial LFs */
3589 while (*in == '\n')
3590 in++;
3591
3592 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3593 while (*in) {
3594 *p++ = '\n';
3595 memset(p, ' ', level);
3596 p += level;
3597 do {
3598 *p++ = *in++;
3599 } while (*in && *in != '\n');
3600 if (*in)
3601 in++;
3602 }
3603 *p = 0;
3604
3605 free(*out);
3606 *out = ret;
3607
3608 return ret;
3609}
3610
Willy Tarreaudad36a32013-03-11 01:20:04 +01003611/* Convert occurrences of environment variables in the input string to their
3612 * corresponding value. A variable is identified as a series of alphanumeric
3613 * characters or underscores following a '$' sign. The <in> string must be
3614 * free()able. NULL returns NULL. The resulting string might be reallocated if
3615 * some expansion is made. Variable names may also be enclosed into braces if
3616 * needed (eg: to concatenate alphanum characters).
3617 */
3618char *env_expand(char *in)
3619{
3620 char *txt_beg;
3621 char *out;
3622 char *txt_end;
3623 char *var_beg;
3624 char *var_end;
3625 char *value;
3626 char *next;
3627 int out_len;
3628 int val_len;
3629
3630 if (!in)
3631 return in;
3632
3633 value = out = NULL;
3634 out_len = 0;
3635
3636 txt_beg = in;
3637 do {
3638 /* look for next '$' sign in <in> */
3639 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3640
3641 if (!*txt_end && !out) /* end and no expansion performed */
3642 return in;
3643
3644 val_len = 0;
3645 next = txt_end;
3646 if (*txt_end == '$') {
3647 char save;
3648
3649 var_beg = txt_end + 1;
3650 if (*var_beg == '{')
3651 var_beg++;
3652
3653 var_end = var_beg;
3654 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3655 var_end++;
3656 }
3657
3658 next = var_end;
3659 if (*var_end == '}' && (var_beg > txt_end + 1))
3660 next++;
3661
3662 /* get value of the variable name at this location */
3663 save = *var_end;
3664 *var_end = '\0';
3665 value = getenv(var_beg);
3666 *var_end = save;
3667 val_len = value ? strlen(value) : 0;
3668 }
3669
Hubert Verstraete831962e2016-06-28 22:44:26 +02003670 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003671 if (txt_end > txt_beg) {
3672 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3673 out_len += txt_end - txt_beg;
3674 }
3675 if (val_len) {
3676 memcpy(out + out_len, value, val_len);
3677 out_len += val_len;
3678 }
3679 out[out_len] = 0;
3680 txt_beg = next;
3681 } while (*txt_beg);
3682
3683 /* here we know that <out> was allocated and that we don't need <in> anymore */
3684 free(in);
3685 return out;
3686}
3687
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003688
3689/* same as strstr() but case-insensitive and with limit length */
3690const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3691{
3692 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003693 unsigned int slen, plen;
3694 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003695
3696 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3697 return NULL;
3698
3699 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3700 return str1;
3701
3702 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3703 return NULL;
3704
3705 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3706 while (toupper(*start) != toupper(*str2)) {
3707 start++;
3708 slen--;
3709 tmp1++;
3710
3711 if (tmp1 >= len_str1)
3712 return NULL;
3713
3714 /* if pattern longer than string */
3715 if (slen < plen)
3716 return NULL;
3717 }
3718
3719 sptr = start;
3720 pptr = (char *)str2;
3721
3722 tmp2 = 0;
3723 while (toupper(*sptr) == toupper(*pptr)) {
3724 sptr++;
3725 pptr++;
3726 tmp2++;
3727
3728 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3729 return start;
3730 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3731 return NULL;
3732 }
3733 }
3734 return NULL;
3735}
3736
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003737/* This function read the next valid utf8 char.
3738 * <s> is the byte srray to be decode, <len> is its length.
3739 * The function returns decoded char encoded like this:
3740 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3741 * are the length read. The decoded character is stored in <c>.
3742 */
3743unsigned char utf8_next(const char *s, int len, unsigned int *c)
3744{
3745 const unsigned char *p = (unsigned char *)s;
3746 int dec;
3747 unsigned char code = UTF8_CODE_OK;
3748
3749 if (len < 1)
3750 return UTF8_CODE_OK;
3751
3752 /* Check the type of UTF8 sequence
3753 *
3754 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3755 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3756 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3757 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3758 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3759 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3760 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3761 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3762 */
3763 switch (*p) {
3764 case 0x00 ... 0x7f:
3765 *c = *p;
3766 return UTF8_CODE_OK | 1;
3767
3768 case 0x80 ... 0xbf:
3769 *c = *p;
3770 return UTF8_CODE_BADSEQ | 1;
3771
3772 case 0xc0 ... 0xdf:
3773 if (len < 2) {
3774 *c = *p;
3775 return UTF8_CODE_BADSEQ | 1;
3776 }
3777 *c = *p & 0x1f;
3778 dec = 1;
3779 break;
3780
3781 case 0xe0 ... 0xef:
3782 if (len < 3) {
3783 *c = *p;
3784 return UTF8_CODE_BADSEQ | 1;
3785 }
3786 *c = *p & 0x0f;
3787 dec = 2;
3788 break;
3789
3790 case 0xf0 ... 0xf7:
3791 if (len < 4) {
3792 *c = *p;
3793 return UTF8_CODE_BADSEQ | 1;
3794 }
3795 *c = *p & 0x07;
3796 dec = 3;
3797 break;
3798
3799 case 0xf8 ... 0xfb:
3800 if (len < 5) {
3801 *c = *p;
3802 return UTF8_CODE_BADSEQ | 1;
3803 }
3804 *c = *p & 0x03;
3805 dec = 4;
3806 break;
3807
3808 case 0xfc ... 0xfd:
3809 if (len < 6) {
3810 *c = *p;
3811 return UTF8_CODE_BADSEQ | 1;
3812 }
3813 *c = *p & 0x01;
3814 dec = 5;
3815 break;
3816
3817 case 0xfe ... 0xff:
3818 default:
3819 *c = *p;
3820 return UTF8_CODE_BADSEQ | 1;
3821 }
3822
3823 p++;
3824
3825 while (dec > 0) {
3826
3827 /* need 0x10 for the 2 first bits */
3828 if ( ( *p & 0xc0 ) != 0x80 )
3829 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3830
3831 /* add data at char */
3832 *c = ( *c << 6 ) | ( *p & 0x3f );
3833
3834 dec--;
3835 p++;
3836 }
3837
3838 /* Check ovelong encoding.
3839 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3840 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3841 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3842 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003843 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003844 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3845 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3846 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3847 code |= UTF8_CODE_OVERLONG;
3848
3849 /* Check invalid UTF8 range. */
3850 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3851 (*c >= 0xfffe && *c <= 0xffff))
3852 code |= UTF8_CODE_INVRANGE;
3853
3854 return code | ((p-(unsigned char *)s)&0x0f);
3855}
3856
Maxime de Roucydc887852016-05-13 23:52:54 +02003857/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3858 * On failure : return 0 and <err> filled with an error message.
3859 * The caller is responsible for freeing the <err> and <str> copy
3860 * memory area using free()
3861 */
3862int list_append_word(struct list *li, const char *str, char **err)
3863{
3864 struct wordlist *wl;
3865
3866 wl = calloc(1, sizeof(*wl));
3867 if (!wl) {
3868 memprintf(err, "out of memory");
3869 goto fail_wl;
3870 }
3871
3872 wl->s = strdup(str);
3873 if (!wl->s) {
3874 memprintf(err, "out of memory");
3875 goto fail_wl_s;
3876 }
3877
3878 LIST_ADDQ(li, &wl->list);
3879
3880 return 1;
3881
3882fail_wl_s:
3883 free(wl->s);
3884fail_wl:
3885 free(wl);
3886 return 0;
3887}
3888
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003889/* print a string of text buffer to <out>. The format is :
3890 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3891 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3892 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3893 */
Willy Tarreau83061a82018-07-13 11:56:34 +02003894int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003895{
3896 unsigned char c;
3897 int ptr = 0;
3898
3899 while (buf[ptr] && ptr < bsize) {
3900 c = buf[ptr];
3901 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003902 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003903 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003904 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003905 }
3906 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003907 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003908 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003909 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003910 switch (c) {
3911 case ' ': c = ' '; break;
3912 case '\t': c = 't'; break;
3913 case '\n': c = 'n'; break;
3914 case '\r': c = 'r'; break;
3915 case '\e': c = 'e'; break;
3916 case '\\': c = '\\'; break;
3917 case '=': c = '='; break;
3918 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003919 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003920 }
3921 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003922 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003923 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003924 out->area[out->data++] = '\\';
3925 out->area[out->data++] = 'x';
3926 out->area[out->data++] = hextab[(c >> 4) & 0xF];
3927 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003928 }
3929 ptr++;
3930 }
3931
3932 return ptr;
3933}
3934
3935/* print a buffer in hexa.
3936 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3937 */
Willy Tarreau83061a82018-07-13 11:56:34 +02003938int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003939{
3940 unsigned char c;
3941 int ptr = 0;
3942
3943 while (ptr < bsize) {
3944 c = buf[ptr];
3945
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003946 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003947 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003948 out->area[out->data++] = hextab[(c >> 4) & 0xF];
3949 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003950
3951 ptr++;
3952 }
3953 return ptr;
3954}
3955
3956/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3957 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3958 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3959 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3960 * lines are respected within the limit of 70 output chars. Lines that are
3961 * continuation of a previous truncated line begin with "+" instead of " "
3962 * after the offset. The new pointer is returned.
3963 */
Willy Tarreau83061a82018-07-13 11:56:34 +02003964int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003965 int *line, int ptr)
3966{
3967 int end;
3968 unsigned char c;
3969
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003970 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003971 if (end > out->size)
3972 return ptr;
3973
3974 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3975
3976 while (ptr < len && ptr < bsize) {
3977 c = buf[ptr];
3978 if (isprint(c) && isascii(c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003979 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003980 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003981 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003982 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003983 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003984 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003985 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003986 switch (c) {
3987 case '\t': c = 't'; break;
3988 case '\n': c = 'n'; break;
3989 case '\r': c = 'r'; break;
3990 case '\e': c = 'e'; break;
3991 case '\\': c = '\\'; break;
3992 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003993 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003994 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003995 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003996 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02003997 out->area[out->data++] = '\\';
3998 out->area[out->data++] = 'x';
3999 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4000 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004001 }
4002 if (buf[ptr++] == '\n') {
4003 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004004 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004005 *line = ptr;
4006 return ptr;
4007 }
4008 }
4009 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004010 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004011 return ptr;
4012}
4013
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004014/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004015 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4016 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004017 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004018void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4019 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004020{
Willy Tarreau73459792017-04-11 07:58:08 +02004021 unsigned int i;
4022 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004023
4024 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4025 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004026 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004027 for (j = 0; j < 8; j++) {
4028 if (b + j >= 0 && b + j < len)
4029 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4030 else
4031 fprintf(out, " ");
4032 }
4033
4034 if (b + j >= 0 && b + j < len)
4035 fputc('-', out);
4036 else
4037 fputc(' ', out);
4038
4039 for (j = 8; j < 16; j++) {
4040 if (b + j >= 0 && b + j < len)
4041 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4042 else
4043 fprintf(out, " ");
4044 }
4045
4046 fprintf(out, " ");
4047 for (j = 0; j < 16; j++) {
4048 if (b + j >= 0 && b + j < len) {
4049 if (isprint((unsigned char)buf[b + j]))
4050 fputc((unsigned char)buf[b + j], out);
4051 else
4052 fputc('.', out);
4053 }
4054 else
4055 fputc(' ', out);
4056 }
4057 fputc('\n', out);
4058 }
4059}
4060
Willy Tarreau12963822017-10-24 10:54:08 +02004061/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
4062__attribute__((weak,format(printf, 1, 2)))
4063void trace(char *msg, ...)
4064{
4065}
4066
Willy Tarreaubaaee002006-06-26 02:48:02 +02004067/*
4068 * Local variables:
4069 * c-indent-level: 8
4070 * c-basic-offset: 8
4071 * End:
4072 */