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