blob: db312dd1892f48838da1215371b1233a44d2f920 [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 Tarreaubaaee002006-06-26 02:48:02 +020034
Thierry Fournier93127942016-01-20 18:49:45 +010035/* This macro returns false if the test __x is false. Many
36 * of the following parsing function must be abort the processing
37 * if it returns 0, so this macro is useful for writing light code.
38 */
39#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
40
Willy Tarreau56adcf22012-12-23 18:00:29 +010041/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020042 * 2^64-1 = 18446744073709551615 or
43 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020044 *
45 * The HTML version needs room for adding the 25 characters
46 * '<span class="rls"></span>' around digits at positions 3N+1 in order
47 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020048 */
Willy Tarreau56adcf22012-12-23 18:00:29 +010049char itoa_str[NB_ITOA_STR][171];
50int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020051
Willy Tarreau588297f2014-06-16 15:16:40 +020052/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
53 * to quote strings larger than a max configuration line.
54 */
55char quoted_str[NB_QSTR][QSTR_SIZE + 1];
56int quoted_idx = 0;
57
Willy Tarreaubaaee002006-06-26 02:48:02 +020058/*
William Lallemande7340ec2012-01-24 11:15:39 +010059 * unsigned long long ASCII representation
60 *
61 * return the last char '\0' or NULL if no enough
62 * space in dst
63 */
64char *ulltoa(unsigned long long n, char *dst, size_t size)
65{
66 int i = 0;
67 char *res;
68
69 switch(n) {
70 case 1ULL ... 9ULL:
71 i = 0;
72 break;
73
74 case 10ULL ... 99ULL:
75 i = 1;
76 break;
77
78 case 100ULL ... 999ULL:
79 i = 2;
80 break;
81
82 case 1000ULL ... 9999ULL:
83 i = 3;
84 break;
85
86 case 10000ULL ... 99999ULL:
87 i = 4;
88 break;
89
90 case 100000ULL ... 999999ULL:
91 i = 5;
92 break;
93
94 case 1000000ULL ... 9999999ULL:
95 i = 6;
96 break;
97
98 case 10000000ULL ... 99999999ULL:
99 i = 7;
100 break;
101
102 case 100000000ULL ... 999999999ULL:
103 i = 8;
104 break;
105
106 case 1000000000ULL ... 9999999999ULL:
107 i = 9;
108 break;
109
110 case 10000000000ULL ... 99999999999ULL:
111 i = 10;
112 break;
113
114 case 100000000000ULL ... 999999999999ULL:
115 i = 11;
116 break;
117
118 case 1000000000000ULL ... 9999999999999ULL:
119 i = 12;
120 break;
121
122 case 10000000000000ULL ... 99999999999999ULL:
123 i = 13;
124 break;
125
126 case 100000000000000ULL ... 999999999999999ULL:
127 i = 14;
128 break;
129
130 case 1000000000000000ULL ... 9999999999999999ULL:
131 i = 15;
132 break;
133
134 case 10000000000000000ULL ... 99999999999999999ULL:
135 i = 16;
136 break;
137
138 case 100000000000000000ULL ... 999999999999999999ULL:
139 i = 17;
140 break;
141
142 case 1000000000000000000ULL ... 9999999999999999999ULL:
143 i = 18;
144 break;
145
146 case 10000000000000000000ULL ... ULLONG_MAX:
147 i = 19;
148 break;
149 }
150 if (i + 2 > size) // (i + 1) + '\0'
151 return NULL; // too long
152 res = dst + i + 1;
153 *res = '\0';
154 for (; i >= 0; i--) {
155 dst[i] = n % 10ULL + '0';
156 n /= 10ULL;
157 }
158 return res;
159}
160
161/*
162 * unsigned long ASCII representation
163 *
164 * return the last char '\0' or NULL if no enough
165 * space in dst
166 */
167char *ultoa_o(unsigned long n, char *dst, size_t size)
168{
169 int i = 0;
170 char *res;
171
172 switch (n) {
173 case 0U ... 9UL:
174 i = 0;
175 break;
176
177 case 10U ... 99UL:
178 i = 1;
179 break;
180
181 case 100U ... 999UL:
182 i = 2;
183 break;
184
185 case 1000U ... 9999UL:
186 i = 3;
187 break;
188
189 case 10000U ... 99999UL:
190 i = 4;
191 break;
192
193 case 100000U ... 999999UL:
194 i = 5;
195 break;
196
197 case 1000000U ... 9999999UL:
198 i = 6;
199 break;
200
201 case 10000000U ... 99999999UL:
202 i = 7;
203 break;
204
205 case 100000000U ... 999999999UL:
206 i = 8;
207 break;
208#if __WORDSIZE == 32
209
210 case 1000000000ULL ... ULONG_MAX:
211 i = 9;
212 break;
213
214#elif __WORDSIZE == 64
215
216 case 1000000000ULL ... 9999999999UL:
217 i = 9;
218 break;
219
220 case 10000000000ULL ... 99999999999UL:
221 i = 10;
222 break;
223
224 case 100000000000ULL ... 999999999999UL:
225 i = 11;
226 break;
227
228 case 1000000000000ULL ... 9999999999999UL:
229 i = 12;
230 break;
231
232 case 10000000000000ULL ... 99999999999999UL:
233 i = 13;
234 break;
235
236 case 100000000000000ULL ... 999999999999999UL:
237 i = 14;
238 break;
239
240 case 1000000000000000ULL ... 9999999999999999UL:
241 i = 15;
242 break;
243
244 case 10000000000000000ULL ... 99999999999999999UL:
245 i = 16;
246 break;
247
248 case 100000000000000000ULL ... 999999999999999999UL:
249 i = 17;
250 break;
251
252 case 1000000000000000000ULL ... 9999999999999999999UL:
253 i = 18;
254 break;
255
256 case 10000000000000000000ULL ... ULONG_MAX:
257 i = 19;
258 break;
259
260#endif
261 }
262 if (i + 2 > size) // (i + 1) + '\0'
263 return NULL; // too long
264 res = dst + i + 1;
265 *res = '\0';
266 for (; i >= 0; i--) {
267 dst[i] = n % 10U + '0';
268 n /= 10U;
269 }
270 return res;
271}
272
273/*
274 * signed long ASCII representation
275 *
276 * return the last char '\0' or NULL if no enough
277 * space in dst
278 */
279char *ltoa_o(long int n, char *dst, size_t size)
280{
281 char *pos = dst;
282
283 if (n < 0) {
284 if (size < 3)
285 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
286 *pos = '-';
287 pos++;
288 dst = ultoa_o(-n, pos, size - 1);
289 } else {
290 dst = ultoa_o(n, dst, size);
291 }
292 return dst;
293}
294
295/*
296 * signed long long ASCII representation
297 *
298 * return the last char '\0' or NULL if no enough
299 * space in dst
300 */
301char *lltoa(long long n, char *dst, size_t size)
302{
303 char *pos = dst;
304
305 if (n < 0) {
306 if (size < 3)
307 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
308 *pos = '-';
309 pos++;
310 dst = ulltoa(-n, pos, size - 1);
311 } else {
312 dst = ulltoa(n, dst, size);
313 }
314 return dst;
315}
316
317/*
318 * write a ascii representation of a unsigned into dst,
319 * return a pointer to the last character
320 * Pad the ascii representation with '0', using size.
321 */
322char *utoa_pad(unsigned int n, char *dst, size_t size)
323{
324 int i = 0;
325 char *ret;
326
327 switch(n) {
328 case 0U ... 9U:
329 i = 0;
330 break;
331
332 case 10U ... 99U:
333 i = 1;
334 break;
335
336 case 100U ... 999U:
337 i = 2;
338 break;
339
340 case 1000U ... 9999U:
341 i = 3;
342 break;
343
344 case 10000U ... 99999U:
345 i = 4;
346 break;
347
348 case 100000U ... 999999U:
349 i = 5;
350 break;
351
352 case 1000000U ... 9999999U:
353 i = 6;
354 break;
355
356 case 10000000U ... 99999999U:
357 i = 7;
358 break;
359
360 case 100000000U ... 999999999U:
361 i = 8;
362 break;
363
364 case 1000000000U ... 4294967295U:
365 i = 9;
366 break;
367 }
368 if (i + 2 > size) // (i + 1) + '\0'
369 return NULL; // too long
370 if (i < size)
371 i = size - 2; // padding - '\0'
372
373 ret = dst + i + 1;
374 *ret = '\0';
375 for (; i >= 0; i--) {
376 dst[i] = n % 10U + '0';
377 n /= 10U;
378 }
379 return ret;
380}
381
382/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200383 * copies at most <size-1> chars from <src> to <dst>. Last char is always
384 * set to 0, unless <size> is 0. The number of chars copied is returned
385 * (excluding the terminating zero).
386 * This code has been optimized for size and speed : on x86, it's 45 bytes
387 * long, uses only registers, and consumes only 4 cycles per char.
388 */
389int strlcpy2(char *dst, const char *src, int size)
390{
391 char *orig = dst;
392 if (size) {
393 while (--size && (*dst = *src)) {
394 src++; dst++;
395 }
396 *dst = 0;
397 }
398 return dst - orig;
399}
400
401/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200402 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200403 * the ascii representation for number 'n' in decimal.
404 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100405char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200406{
407 char *pos;
408
Willy Tarreau72d759c2007-10-25 12:14:10 +0200409 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200410 *pos-- = '\0';
411
412 do {
413 *pos-- = '0' + n % 10;
414 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200415 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200416 return pos + 1;
417}
418
Willy Tarreau91092e52007-10-25 16:58:42 +0200419/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200420 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200421 * the ascii representation for number 'n' in decimal.
422 */
423char *lltoa_r(long long int in, char *buffer, int size)
424{
425 char *pos;
426 int neg = 0;
427 unsigned long long int n;
428
429 pos = buffer + size - 1;
430 *pos-- = '\0';
431
432 if (in < 0) {
433 neg = 1;
434 n = -in;
435 }
436 else
437 n = in;
438
439 do {
440 *pos-- = '0' + n % 10;
441 n /= 10;
442 } while (n && pos >= buffer);
443 if (neg && pos > buffer)
444 *pos-- = '-';
445 return pos + 1;
446}
447
448/*
449 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200450 * the ascii representation for signed number 'n' in decimal.
451 */
452char *sltoa_r(long n, char *buffer, int size)
453{
454 char *pos;
455
456 if (n >= 0)
457 return ultoa_r(n, buffer, size);
458
459 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
460 *pos = '-';
461 return pos;
462}
463
464/*
465 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200466 * the ascii representation for number 'n' in decimal, formatted for
467 * HTML output with tags to create visual grouping by 3 digits. The
468 * output needs to support at least 171 characters.
469 */
470const char *ulltoh_r(unsigned long long n, char *buffer, int size)
471{
472 char *start;
473 int digit = 0;
474
475 start = buffer + size;
476 *--start = '\0';
477
478 do {
479 if (digit == 3 && start >= buffer + 7)
480 memcpy(start -= 7, "</span>", 7);
481
482 if (start >= buffer + 1) {
483 *--start = '0' + n % 10;
484 n /= 10;
485 }
486
487 if (digit == 3 && start >= buffer + 18)
488 memcpy(start -= 18, "<span class=\"rls\">", 18);
489
490 if (digit++ == 3)
491 digit = 1;
492 } while (n && start > buffer);
493 return start;
494}
495
496/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200497 * This function simply returns a locally allocated string containing the ascii
498 * representation for number 'n' in decimal, unless n is 0 in which case it
499 * returns the alternate string (or an empty string if the alternate string is
500 * NULL). It use is intended for limits reported in reports, where it's
501 * desirable not to display anything if there is no limit. Warning! it shares
502 * the same vector as ultoa_r().
503 */
504const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
505{
506 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
507}
508
Willy Tarreau588297f2014-06-16 15:16:40 +0200509/* returns a locally allocated string containing the quoted encoding of the
510 * input string. The output may be truncated to QSTR_SIZE chars, but it is
511 * guaranteed that the string will always be properly terminated. Quotes are
512 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
513 * always be at least 4 chars.
514 */
515const char *qstr(const char *str)
516{
517 char *ret = quoted_str[quoted_idx];
518 char *p, *end;
519
520 if (++quoted_idx >= NB_QSTR)
521 quoted_idx = 0;
522
523 p = ret;
524 end = ret + QSTR_SIZE;
525
526 *p++ = '"';
527
528 /* always keep 3 chars to support passing "" and the ending " */
529 while (*str && p < end - 3) {
530 if (*str == '"') {
531 *p++ = '"';
532 *p++ = '"';
533 }
534 else
535 *p++ = *str;
536 str++;
537 }
538 *p++ = '"';
539 return ret;
540}
541
Robert Tsai81ae1952007-12-05 10:47:29 +0100542/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200543 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
544 *
545 * It looks like this one would be a good candidate for inlining, but this is
546 * not interesting because it around 35 bytes long and often called multiple
547 * times within the same function.
548 */
549int ishex(char s)
550{
551 s -= '0';
552 if ((unsigned char)s <= 9)
553 return 1;
554 s -= 'A' - '0';
555 if ((unsigned char)s <= 5)
556 return 1;
557 s -= 'a' - 'A';
558 if ((unsigned char)s <= 5)
559 return 1;
560 return 0;
561}
562
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100563/* rounds <i> down to the closest value having max 2 digits */
564unsigned int round_2dig(unsigned int i)
565{
566 unsigned int mul = 1;
567
568 while (i >= 100) {
569 i /= 10;
570 mul *= 10;
571 }
572 return i * mul;
573}
574
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100575/*
576 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
577 * invalid character is found, a pointer to it is returned. If everything is
578 * fine, NULL is returned.
579 */
580const char *invalid_char(const char *name)
581{
582 if (!*name)
583 return name;
584
585 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100586 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100587 *name != '_' && *name != '-')
588 return name;
589 name++;
590 }
591 return NULL;
592}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200593
594/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200595 * Checks <name> for invalid characters. Valid chars are [_.-] and those
596 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200597 * If an invalid character is found, a pointer to it is returned.
598 * If everything is fine, NULL is returned.
599 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200600static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200601
602 if (!*name)
603 return name;
604
605 while (*name) {
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200606 if (!f((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200607 *name != '_' && *name != '-')
608 return name;
609
610 name++;
611 }
612
613 return NULL;
614}
615
616/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200617 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
618 * If an invalid character is found, a pointer to it is returned.
619 * If everything is fine, NULL is returned.
620 */
621const char *invalid_domainchar(const char *name) {
622 return __invalid_char(name, isalnum);
623}
624
625/*
626 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
627 * If an invalid character is found, a pointer to it is returned.
628 * If everything is fine, NULL is returned.
629 */
630const char *invalid_prefix_char(const char *name) {
631 return __invalid_char(name, isalpha);
632}
633
634/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100635 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100636 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
637 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
638 * the function tries to guess the address family from the syntax. If the
639 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100640 * string is assumed to contain only an address, no port. The address can be a
641 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
642 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
643 * The return address will only have the address family and the address set,
644 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100645 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
646 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100647 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200648 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100649struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200650{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100651 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100652 /* max IPv6 length, including brackets and terminating NULL */
653 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100654 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100655
656 /* check IPv6 with square brackets */
657 if (str[0] == '[') {
658 size_t iplength = strlen(str);
659
660 if (iplength < 4) {
661 /* minimal size is 4 when using brackets "[::]" */
662 goto fail;
663 }
664 else if (iplength >= sizeof(tmpip)) {
665 /* IPv6 literal can not be larger than tmpip */
666 goto fail;
667 }
668 else {
669 if (str[iplength - 1] != ']') {
670 /* if address started with bracket, it should end with bracket */
671 goto fail;
672 }
673 else {
674 memcpy(tmpip, str + 1, iplength - 2);
675 tmpip[iplength - 2] = '\0';
676 str = tmpip;
677 }
678 }
679 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100680
Willy Tarreaufab5a432011-03-04 15:31:53 +0100681 /* Any IPv6 address */
682 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100683 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
684 sa->ss_family = AF_INET6;
685 else if (sa->ss_family != AF_INET6)
686 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100687 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100688 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100689 }
690
Willy Tarreau24709282013-03-10 21:32:12 +0100691 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100692 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100693 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
694 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100695 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100696 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100697 }
698
699 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100700 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
701 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100702 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100703 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100704 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100705 }
706
707 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100708 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
709 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100710 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100711 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100712 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100713 }
714
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100715 if (!resolve)
716 return NULL;
717
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200718 if (!dns_hostname_validation(str, NULL))
719 return NULL;
720
David du Colombierd5f43282011-03-17 10:40:16 +0100721#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200722 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100723 struct addrinfo hints, *result;
724
725 memset(&result, 0, sizeof(result));
726 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100727 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100728 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200729 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100730 hints.ai_protocol = 0;
731
732 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100733 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
734 sa->ss_family = result->ai_family;
735 else if (sa->ss_family != result->ai_family)
736 goto fail;
737
David du Colombierd5f43282011-03-17 10:40:16 +0100738 switch (result->ai_family) {
739 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100740 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100741 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100742 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100743 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100744 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100745 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100746 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100747 }
748 }
749
Sean Carey58ea0392013-02-15 23:39:18 +0100750 if (result)
751 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100752 }
David du Colombierd5f43282011-03-17 10:40:16 +0100753#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200754 /* try to resolve an IPv4/IPv6 hostname */
755 he = gethostbyname(str);
756 if (he) {
757 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
758 sa->ss_family = he->h_addrtype;
759 else if (sa->ss_family != he->h_addrtype)
760 goto fail;
761
762 switch (sa->ss_family) {
763 case AF_INET:
764 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100765 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200766 return sa;
767 case AF_INET6:
768 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100769 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200770 return sa;
771 }
772 }
773
David du Colombierd5f43282011-03-17 10:40:16 +0100774 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100775 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100776 return NULL;
777}
778
779/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100780 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
781 * range or offset consisting in two integers that the caller will have to
782 * check to find the relevant input format. The following format are supported :
783 *
784 * String format | address | port | low | high
785 * addr | <addr> | 0 | 0 | 0
786 * addr: | <addr> | 0 | 0 | 0
787 * addr:port | <addr> | <port> | <port> | <port>
788 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
789 * addr:+port | <addr> | <port> | 0 | <port>
790 * addr:-port | <addr> |-<port> | <port> | 0
791 *
792 * The detection of a port range or increment by the caller is made by
793 * comparing <low> and <high>. If both are equal, then port 0 means no port
794 * was specified. The caller may pass NULL for <low> and <high> if it is not
795 * interested in retrieving port ranges.
796 *
797 * Note that <addr> above may also be :
798 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
799 * - "*" => family will be AF_INET and address will be INADDR_ANY
800 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
801 * - a host name => family and address will depend on host name resolving.
802 *
Willy Tarreau24709282013-03-10 21:32:12 +0100803 * A prefix may be passed in before the address above to force the family :
804 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
805 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
806 * - "unix@" => force address to be a path to a UNIX socket even if the
807 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200808 * - 'abns@' -> force address to belong to the abstract namespace (Linux
809 * only). These sockets are just like Unix sockets but without
810 * the need for an underlying file system. The address is a
811 * string. Technically it's like a Unix socket with a zero in
812 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100813 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100814 *
mildisff5d5102015-10-26 18:50:08 +0100815 * IPv6 addresses can be declared with or without square brackets. When using
816 * square brackets for IPv6 addresses, the port separator (colon) is optional.
817 * If not using square brackets, and in order to avoid any ambiguity with
818 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
819 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
820 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100821 *
822 * If <pfx> is non-null, it is used as a string prefix before any path-based
823 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100824 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200825 * if <fqdn> is non-null, it will be filled with :
826 * - a pointer to the FQDN of the server name to resolve if there's one, and
827 * that the caller will have to free(),
828 * - NULL if there was an explicit address that doesn't require resolution.
829 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100830 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
831 * is null, <fqdn> is still honnored so it is possible for the caller to know
832 * whether a resolution failed by setting <resolve> to null and checking if
833 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200834 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100835 * When a file descriptor is passed, its value is put into the s_addr part of
836 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100837 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100838struct 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 +0100839{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100840 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100841 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100842 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100843 char *port1, *port2;
844 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200845 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100846
847 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200848 if (fqdn)
849 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200850
Willy Tarreaudad36a32013-03-11 01:20:04 +0100851 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100852 if (str2 == NULL) {
853 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100854 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100855 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200856
Willy Tarreau9f69f462015-09-08 16:01:25 +0200857 if (!*str2) {
858 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
859 goto out;
860 }
861
Willy Tarreau24709282013-03-10 21:32:12 +0100862 memset(&ss, 0, sizeof(ss));
863
864 if (strncmp(str2, "unix@", 5) == 0) {
865 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200866 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100867 ss.ss_family = AF_UNIX;
868 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200869 else if (strncmp(str2, "abns@", 5) == 0) {
870 str2 += 5;
871 abstract = 1;
872 ss.ss_family = AF_UNIX;
873 }
Willy Tarreau24709282013-03-10 21:32:12 +0100874 else if (strncmp(str2, "ipv4@", 5) == 0) {
875 str2 += 5;
876 ss.ss_family = AF_INET;
877 }
878 else if (strncmp(str2, "ipv6@", 5) == 0) {
879 str2 += 5;
880 ss.ss_family = AF_INET6;
881 }
882 else if (*str2 == '/') {
883 ss.ss_family = AF_UNIX;
884 }
885 else
886 ss.ss_family = AF_UNSPEC;
887
Willy Tarreau40aa0702013-03-10 23:51:38 +0100888 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
889 char *endptr;
890
891 str2 += 3;
892 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
893
894 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100895 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100896 goto out;
897 }
898
899 /* we return AF_UNSPEC if we use a file descriptor number */
900 ss.ss_family = AF_UNSPEC;
901 }
902 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100903 int prefix_path_len;
904 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200905 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100906
907 /* complete unix socket path name during startup or soft-restart is
908 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
909 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200910 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100911 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
912 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
913
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200914 adr_len = strlen(str2);
915 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100916 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
917 goto out;
918 }
919
Willy Tarreauccfccef2014-05-10 01:49:15 +0200920 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
921 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200922 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100923 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200924 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100925 }
Willy Tarreau24709282013-03-10 21:32:12 +0100926 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100927 char *end = str2 + strlen(str2);
928 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200929
mildisff5d5102015-10-26 18:50:08 +0100930 /* search for : or ] whatever comes first */
931 for (chr = end-1; chr > str2; chr--) {
932 if (*chr == ']' || *chr == ':')
933 break;
934 }
935
936 if (*chr == ':') {
937 /* Found a colon before a closing-bracket, must be a port separator.
938 * This guarantee backward compatibility.
939 */
940 *chr++ = '\0';
941 port1 = chr;
942 }
943 else {
944 /* Either no colon and no closing-bracket
945 * or directly ending with a closing-bracket.
946 * However, no port.
947 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100948 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100949 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200950
Willy Tarreaua39d1992013-04-01 20:37:42 +0200951 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100952 port2 = strchr(port1, '-');
953 if (port2)
954 *port2++ = '\0';
955 else
956 port2 = port1;
957 portl = atoi(port1);
958 porth = atoi(port2);
959 porta = portl;
960 }
961 else if (*port1 == '-') { /* negative offset */
962 portl = atoi(port1 + 1);
963 porta = -portl;
964 }
965 else if (*port1 == '+') { /* positive offset */
966 porth = atoi(port1 + 1);
967 porta = porth;
968 }
969 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100970 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100971 goto out;
972 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100973
974 /* first try to parse the IP without resolving. If it fails, it
975 * tells us we need to keep a copy of the FQDN to resolve later
976 * and to enable DNS. In this case we can proceed if <fqdn> is
977 * set or if resolve is set, otherwise it's an error.
978 */
979 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +0100980 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +0100981 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
982 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
983 goto out;
984 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200985
Willy Tarreauceccdd72016-11-02 22:27:10 +0100986 if (fqdn) {
987 if (str2 != back)
988 memmove(back, str2, strlen(str2) + 1);
989 *fqdn = back;
990 back = NULL;
991 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200992 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100993 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100994 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100995
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100996 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100997 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100998 if (port)
999 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001000 if (low)
1001 *low = portl;
1002 if (high)
1003 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +01001004 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001005 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001006}
1007
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001008/* converts <str> to a struct in_addr containing a network mask. It can be
1009 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001010 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001011 */
1012int str2mask(const char *str, struct in_addr *mask)
1013{
1014 if (strchr(str, '.') != NULL) { /* dotted notation */
1015 if (!inet_pton(AF_INET, str, mask))
1016 return 0;
1017 }
1018 else { /* mask length */
1019 char *err;
1020 unsigned long len = strtol(str, &err, 10);
1021
1022 if (!*str || (err && *err) || (unsigned)len > 32)
1023 return 0;
1024 if (len)
1025 mask->s_addr = htonl(~0UL << (32 - len));
1026 else
1027 mask->s_addr = 0;
1028 }
1029 return 1;
1030}
1031
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001032/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1033 * succeeds otherwise zero.
1034 */
1035int cidr2dotted(int cidr, struct in_addr *mask) {
1036
1037 if (cidr < 0 || cidr > 32)
1038 return 0;
1039
1040 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1041 return 1;
1042}
1043
Thierry Fournier70473a52016-02-17 17:12:14 +01001044/* Convert mask from bit length form to in_addr form.
1045 * This function never fails.
1046 */
1047void len2mask4(int len, struct in_addr *addr)
1048{
1049 if (len >= 32) {
1050 addr->s_addr = 0xffffffff;
1051 return;
1052 }
1053 if (len <= 0) {
1054 addr->s_addr = 0x00000000;
1055 return;
1056 }
1057 addr->s_addr = 0xffffffff << (32 - len);
1058 addr->s_addr = htonl(addr->s_addr);
1059}
1060
1061/* Convert mask from bit length form to in6_addr form.
1062 * This function never fails.
1063 */
1064void len2mask6(int len, struct in6_addr *addr)
1065{
1066 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1067 len -= 32;
1068 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1069 len -= 32;
1070 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1071 len -= 32;
1072 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1073}
1074
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001075/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001076 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001077 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1078 * is optionnal and either in the dotted or CIDR notation.
1079 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1080 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001081int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001082{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001083 __label__ out_free, out_err;
1084 char *c, *s;
1085 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001086
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001087 s = strdup(str);
1088 if (!s)
1089 return 0;
1090
Willy Tarreaubaaee002006-06-26 02:48:02 +02001091 memset(mask, 0, sizeof(*mask));
1092 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001093
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001094 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001095 *c++ = '\0';
1096 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001097 if (!str2mask(c, mask))
1098 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001099 }
1100 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001101 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001102 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001103 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001104 struct hostent *he;
1105
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001106 if (!resolve)
1107 goto out_err;
1108
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001109 if ((he = gethostbyname(s)) == NULL) {
1110 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001111 }
1112 else
1113 *addr = *(struct in_addr *) *(he->h_addr_list);
1114 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001115
1116 ret_val = 1;
1117 out_free:
1118 free(s);
1119 return ret_val;
1120 out_err:
1121 ret_val = 0;
1122 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001123}
1124
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001125
1126/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001127 * converts <str> to two struct in6_addr* which must be pre-allocated.
1128 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1129 * is an optionnal number of bits (128 being the default).
1130 * Returns 1 if OK, 0 if error.
1131 */
1132int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1133{
1134 char *c, *s;
1135 int ret_val = 0;
1136 char *err;
1137 unsigned long len = 128;
1138
1139 s = strdup(str);
1140 if (!s)
1141 return 0;
1142
1143 memset(mask, 0, sizeof(*mask));
1144 memset(addr, 0, sizeof(*addr));
1145
1146 if ((c = strrchr(s, '/')) != NULL) {
1147 *c++ = '\0'; /* c points to the mask */
1148 if (!*c)
1149 goto out_free;
1150
1151 len = strtoul(c, &err, 10);
1152 if ((err && *err) || (unsigned)len > 128)
1153 goto out_free;
1154 }
1155 *mask = len; /* OK we have a valid mask in <len> */
1156
1157 if (!inet_pton(AF_INET6, s, addr))
1158 goto out_free;
1159
1160 ret_val = 1;
1161 out_free:
1162 free(s);
1163 return ret_val;
1164}
1165
1166
1167/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001168 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001169 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001170int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001171{
1172 int saw_digit, octets, ch;
1173 u_char tmp[4], *tp;
1174 const char *cp = addr;
1175
1176 saw_digit = 0;
1177 octets = 0;
1178 *(tp = tmp) = 0;
1179
1180 while (*addr) {
1181 unsigned char digit = (ch = *addr++) - '0';
1182 if (digit > 9 && ch != '.')
1183 break;
1184 if (digit <= 9) {
1185 u_int new = *tp * 10 + digit;
1186 if (new > 255)
1187 return 0;
1188 *tp = new;
1189 if (!saw_digit) {
1190 if (++octets > 4)
1191 return 0;
1192 saw_digit = 1;
1193 }
1194 } else if (ch == '.' && saw_digit) {
1195 if (octets == 4)
1196 return 0;
1197 *++tp = 0;
1198 saw_digit = 0;
1199 } else
1200 return 0;
1201 }
1202
1203 if (octets < 4)
1204 return 0;
1205
1206 memcpy(&dst->s_addr, tmp, 4);
1207 return addr-cp-1;
1208}
1209
1210/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001211 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1212 * <out> contain the code of the dectected scheme, the start and length of
1213 * the hostname. Actually only http and https are supported. <out> can be NULL.
1214 * This function returns the consumed length. It is useful if you parse complete
1215 * url like http://host:port/path, because the consumed length corresponds to
1216 * the first character of the path. If the conversion fails, it returns -1.
1217 *
1218 * This function tries to resolve the DNS name if haproxy is in starting mode.
1219 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001220 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001221int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001222{
1223 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001224 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001225 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001226 unsigned long long int http_code = 0;
1227 int default_port;
1228 struct hostent *he;
1229 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001230
1231 /* Firstly, try to find :// pattern */
1232 while (curr < url+ulen && url_code != 0x3a2f2f) {
1233 url_code = ((url_code & 0xffff) << 8);
1234 url_code += (unsigned char)*curr++;
1235 }
1236
1237 /* Secondly, if :// pattern is found, verify parsed stuff
1238 * before pattern is matching our http pattern.
1239 * If so parse ip address and port in uri.
1240 *
1241 * WARNING: Current code doesn't support dynamic async dns resolver.
1242 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001243 if (url_code != 0x3a2f2f)
1244 return -1;
1245
1246 /* Copy scheme, and utrn to lower case. */
1247 while (cp < curr - 3)
1248 http_code = (http_code << 8) + *cp++;
1249 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001250
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001251 /* HTTP or HTTPS url matching */
1252 if (http_code == 0x2020202068747470ULL) {
1253 default_port = 80;
1254 if (out)
1255 out->scheme = SCH_HTTP;
1256 }
1257 else if (http_code == 0x2020206874747073ULL) {
1258 default_port = 443;
1259 if (out)
1260 out->scheme = SCH_HTTPS;
1261 }
1262 else
1263 return -1;
1264
1265 /* If the next char is '[', the host address is IPv6. */
1266 if (*curr == '[') {
1267 curr++;
1268
1269 /* Check trash size */
1270 if (trash.size < ulen)
1271 return -1;
1272
1273 /* Look for ']' and copy the address in a trash buffer. */
1274 p = trash.str;
1275 for (end = curr;
1276 end < url + ulen && *end != ']';
1277 end++, p++)
1278 *p = *end;
1279 if (*end != ']')
1280 return -1;
1281 *p = '\0';
1282
1283 /* Update out. */
1284 if (out) {
1285 out->host = curr;
1286 out->host_len = end - curr;
1287 }
1288
1289 /* Try IPv6 decoding. */
1290 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1291 return -1;
1292 end++;
1293
1294 /* Decode port. */
1295 if (*end == ':') {
1296 end++;
1297 default_port = read_uint(&end, url + ulen);
1298 }
1299 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1300 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1301 return end - url;
1302 }
1303 else {
1304 /* We are looking for IP address. If you want to parse and
1305 * resolve hostname found in url, you can use str2sa_range(), but
1306 * be warned this can slow down global daemon performances
1307 * while handling lagging dns responses.
1308 */
1309 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1310 if (ret) {
1311 /* Update out. */
1312 if (out) {
1313 out->host = curr;
1314 out->host_len = ret;
1315 }
1316
1317 curr += ret;
1318
1319 /* Decode port. */
1320 if (*curr == ':') {
1321 curr++;
1322 default_port = read_uint(&curr, url + ulen);
1323 }
1324 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1325
1326 /* Set family. */
1327 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1328 return curr - url;
1329 }
1330 else if (global.mode & MODE_STARTING) {
1331 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1332 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001333 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001334
1335 /* look for : or / or end */
1336 for (end = curr;
1337 end < url + ulen && *end != '/' && *end != ':';
1338 end++);
1339 memcpy(trash.str, curr, end - curr);
1340 trash.str[end - curr] = '\0';
1341
1342 /* try to resolve an IPv4/IPv6 hostname */
1343 he = gethostbyname(trash.str);
1344 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001345 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001346
1347 /* Update out. */
1348 if (out) {
1349 out->host = curr;
1350 out->host_len = end - curr;
1351 }
1352
1353 /* Decode port. */
1354 if (*end == ':') {
1355 end++;
1356 default_port = read_uint(&end, url + ulen);
1357 }
1358
1359 /* Copy IP address, set port and family. */
1360 switch (he->h_addrtype) {
1361 case AF_INET:
1362 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1363 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1364 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1365 return end - url;
1366
1367 case AF_INET6:
1368 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1369 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1370 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1371 return end - url;
1372 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001373 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001374 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001375 return -1;
1376}
1377
Willy Tarreau631f01c2011-09-05 00:36:48 +02001378/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1379 * address family is returned so that it's easy for the caller to adapt to the
1380 * output format. Zero is returned if the address family is not supported. -1
1381 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1382 * supported.
1383 */
1384int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1385{
1386
1387 void *ptr;
1388
1389 if (size < 5)
1390 return 0;
1391 *str = '\0';
1392
1393 switch (addr->ss_family) {
1394 case AF_INET:
1395 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1396 break;
1397 case AF_INET6:
1398 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1399 break;
1400 case AF_UNIX:
1401 memcpy(str, "unix", 5);
1402 return addr->ss_family;
1403 default:
1404 return 0;
1405 }
1406
1407 if (inet_ntop(addr->ss_family, ptr, str, size))
1408 return addr->ss_family;
1409
1410 /* failed */
1411 return -1;
1412}
1413
Simon Horman75ab8bd2014-06-16 09:39:41 +09001414/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1415 * address family is returned so that it's easy for the caller to adapt to the
1416 * output format. Zero is returned if the address family is not supported. -1
1417 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1418 * supported.
1419 */
1420int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1421{
1422
1423 uint16_t port;
1424
1425
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001426 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001427 return 0;
1428 *str = '\0';
1429
1430 switch (addr->ss_family) {
1431 case AF_INET:
1432 port = ((struct sockaddr_in *)addr)->sin_port;
1433 break;
1434 case AF_INET6:
1435 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1436 break;
1437 case AF_UNIX:
1438 memcpy(str, "unix", 5);
1439 return addr->ss_family;
1440 default:
1441 return 0;
1442 }
1443
1444 snprintf(str, size, "%u", ntohs(port));
1445 return addr->ss_family;
1446}
1447
Willy Tarreau16e01562016-08-09 16:46:18 +02001448/* check if the given address is local to the system or not. It will return
1449 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1450 * it is. We don't want to iterate over all interfaces for this (and it is not
1451 * portable). So instead we try to bind in UDP to this address on a free non
1452 * privileged port and to connect to the same address, port 0 (connect doesn't
1453 * care). If it succeeds, we own the address. Note that non-inet addresses are
1454 * considered local since they're most likely AF_UNIX.
1455 */
1456int addr_is_local(const struct netns_entry *ns,
1457 const struct sockaddr_storage *orig)
1458{
1459 struct sockaddr_storage addr;
1460 int result;
1461 int fd;
1462
1463 if (!is_inet_addr(orig))
1464 return 1;
1465
1466 memcpy(&addr, orig, sizeof(addr));
1467 set_host_port(&addr, 0);
1468
1469 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1470 if (fd < 0)
1471 return -1;
1472
1473 result = -1;
1474 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1475 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1476 result = 0; // fail, non-local address
1477 else
1478 result = 1; // success, local address
1479 }
1480 else {
1481 if (errno == EADDRNOTAVAIL)
1482 result = 0; // definitely not local :-)
1483 }
1484 close(fd);
1485
1486 return result;
1487}
1488
Willy Tarreaubaaee002006-06-26 02:48:02 +02001489/* will try to encode the string <string> replacing all characters tagged in
1490 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1491 * prefixed by <escape>, and will store the result between <start> (included)
1492 * and <stop> (excluded), and will always terminate the string with a '\0'
1493 * before <stop>. The position of the '\0' is returned if the conversion
1494 * completes. If bytes are missing between <start> and <stop>, then the
1495 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1496 * cannot even be stored so we return <start> without writing the 0.
1497 * The input string must also be zero-terminated.
1498 */
1499const char hextab[16] = "0123456789ABCDEF";
1500char *encode_string(char *start, char *stop,
1501 const char escape, const fd_set *map,
1502 const char *string)
1503{
1504 if (start < stop) {
1505 stop--; /* reserve one byte for the final '\0' */
1506 while (start < stop && *string != '\0') {
1507 if (!FD_ISSET((unsigned char)(*string), map))
1508 *start++ = *string;
1509 else {
1510 if (start + 3 >= stop)
1511 break;
1512 *start++ = escape;
1513 *start++ = hextab[(*string >> 4) & 15];
1514 *start++ = hextab[*string & 15];
1515 }
1516 string++;
1517 }
1518 *start = '\0';
1519 }
1520 return start;
1521}
1522
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001523/*
1524 * Same behavior as encode_string() above, except that it encodes chunk
1525 * <chunk> instead of a string.
1526 */
1527char *encode_chunk(char *start, char *stop,
1528 const char escape, const fd_set *map,
1529 const struct chunk *chunk)
1530{
1531 char *str = chunk->str;
1532 char *end = chunk->str + chunk->len;
1533
1534 if (start < stop) {
1535 stop--; /* reserve one byte for the final '\0' */
1536 while (start < stop && str < end) {
1537 if (!FD_ISSET((unsigned char)(*str), map))
1538 *start++ = *str;
1539 else {
1540 if (start + 3 >= stop)
1541 break;
1542 *start++ = escape;
1543 *start++ = hextab[(*str >> 4) & 15];
1544 *start++ = hextab[*str & 15];
1545 }
1546 str++;
1547 }
1548 *start = '\0';
1549 }
1550 return start;
1551}
1552
Dragan Dosen0edd1092016-02-12 13:23:02 +01001553/*
1554 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001555 * character. The input <string> must be zero-terminated. The result will
1556 * be stored between <start> (included) and <stop> (excluded). This
1557 * function will always try to terminate the resulting string with a '\0'
1558 * before <stop>, and will return its position if the conversion
1559 * completes.
1560 */
1561char *escape_string(char *start, char *stop,
1562 const char escape, const fd_set *map,
1563 const char *string)
1564{
1565 if (start < stop) {
1566 stop--; /* reserve one byte for the final '\0' */
1567 while (start < stop && *string != '\0') {
1568 if (!FD_ISSET((unsigned char)(*string), map))
1569 *start++ = *string;
1570 else {
1571 if (start + 2 >= stop)
1572 break;
1573 *start++ = escape;
1574 *start++ = *string;
1575 }
1576 string++;
1577 }
1578 *start = '\0';
1579 }
1580 return start;
1581}
1582
1583/*
1584 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001585 * character. <chunk> contains the input to be escaped. The result will be
1586 * stored between <start> (included) and <stop> (excluded). The function
1587 * will always try to terminate the resulting string with a '\0' before
1588 * <stop>, and will return its position if the conversion completes.
1589 */
1590char *escape_chunk(char *start, char *stop,
1591 const char escape, const fd_set *map,
1592 const struct chunk *chunk)
1593{
1594 char *str = chunk->str;
1595 char *end = chunk->str + chunk->len;
1596
1597 if (start < stop) {
1598 stop--; /* reserve one byte for the final '\0' */
1599 while (start < stop && str < end) {
1600 if (!FD_ISSET((unsigned char)(*str), map))
1601 *start++ = *str;
1602 else {
1603 if (start + 2 >= stop)
1604 break;
1605 *start++ = escape;
1606 *start++ = *str;
1607 }
1608 str++;
1609 }
1610 *start = '\0';
1611 }
1612 return start;
1613}
1614
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001615/* Check a string for using it in a CSV output format. If the string contains
1616 * one of the following four char <">, <,>, CR or LF, the string is
1617 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1618 * <str> is the input string to be escaped. The function assumes that
1619 * the input string is null-terminated.
1620 *
1621 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001622 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001623 * format.
1624 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001625 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001626 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001627 * If <quote> is 1, the converter puts the quotes only if any reserved character
1628 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001629 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001630 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001631 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001632 * The function returns the converted string on its output. If an error
1633 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001634 * for using the function directly as printf() argument.
1635 *
1636 * If the output buffer is too short to contain the input string, the result
1637 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001638 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001639 * This function appends the encoding to the existing output chunk, and it
1640 * guarantees that it starts immediately at the first available character of
1641 * the chunk. Please use csv_enc() instead if you want to replace the output
1642 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001643 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001644const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001645{
1646 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001647 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001648 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001649
Willy Tarreaub631c292016-01-08 10:04:08 +01001650 if (quote == 1) {
1651 /* automatic quoting: first verify if we'll have to quote the string */
1652 if (!strpbrk(str, "\n\r,\""))
1653 quote = 0;
1654 }
1655
1656 if (quote)
1657 *ptr++ = '"';
1658
Willy Tarreau898529b2016-01-06 18:07:04 +01001659 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1660 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001661 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001662 ptr++;
1663 if (ptr >= end - 2) {
1664 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001665 break;
1666 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001667 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001668 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001669 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001670 str++;
1671 }
1672
Willy Tarreaub631c292016-01-08 10:04:08 +01001673 if (quote)
1674 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001675
Willy Tarreau898529b2016-01-06 18:07:04 +01001676 *ptr = '\0';
1677 output->len = ptr - output->str;
1678 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001679}
1680
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001681/* Decode an URL-encoded string in-place. The resulting string might
1682 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001683 * aborted, the string is truncated before the issue and a negative value is
1684 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001685 */
1686int url_decode(char *string)
1687{
1688 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001689 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001690
1691 in = string;
1692 out = string;
1693 while (*in) {
1694 switch (*in) {
1695 case '+' :
1696 *out++ = ' ';
1697 break;
1698 case '%' :
1699 if (!ishex(in[1]) || !ishex(in[2]))
1700 goto end;
1701 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1702 in += 2;
1703 break;
1704 default:
1705 *out++ = *in;
1706 break;
1707 }
1708 in++;
1709 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001710 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001711 end:
1712 *out = 0;
1713 return ret;
1714}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001715
Willy Tarreau6911fa42007-03-04 18:06:08 +01001716unsigned int str2ui(const char *s)
1717{
1718 return __str2ui(s);
1719}
1720
1721unsigned int str2uic(const char *s)
1722{
1723 return __str2uic(s);
1724}
1725
1726unsigned int strl2ui(const char *s, int len)
1727{
1728 return __strl2ui(s, len);
1729}
1730
1731unsigned int strl2uic(const char *s, int len)
1732{
1733 return __strl2uic(s, len);
1734}
1735
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001736unsigned int read_uint(const char **s, const char *end)
1737{
1738 return __read_uint(s, end);
1739}
1740
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001741/* This function reads an unsigned integer from the string pointed to by <s> and
1742 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1743 * function automatically stops at <end>. If the number overflows, the 2^64-1
1744 * value is returned.
1745 */
1746unsigned long long int read_uint64(const char **s, const char *end)
1747{
1748 const char *ptr = *s;
1749 unsigned long long int i = 0, tmp;
1750 unsigned int j;
1751
1752 while (ptr < end) {
1753
1754 /* read next char */
1755 j = *ptr - '0';
1756 if (j > 9)
1757 goto read_uint64_end;
1758
1759 /* add char to the number and check overflow. */
1760 tmp = i * 10;
1761 if (tmp / 10 != i) {
1762 i = ULLONG_MAX;
1763 goto read_uint64_eat;
1764 }
1765 if (ULLONG_MAX - tmp < j) {
1766 i = ULLONG_MAX;
1767 goto read_uint64_eat;
1768 }
1769 i = tmp + j;
1770 ptr++;
1771 }
1772read_uint64_eat:
1773 /* eat each numeric char */
1774 while (ptr < end) {
1775 if ((unsigned int)(*ptr - '0') > 9)
1776 break;
1777 ptr++;
1778 }
1779read_uint64_end:
1780 *s = ptr;
1781 return i;
1782}
1783
1784/* This function reads an integer from the string pointed to by <s> and returns
1785 * it. The <s> pointer is adjusted to point to the first unread char. The function
1786 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1787 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1788 * returned.
1789 */
1790long long int read_int64(const char **s, const char *end)
1791{
1792 unsigned long long int i = 0;
1793 int neg = 0;
1794
1795 /* Look for minus char. */
1796 if (**s == '-') {
1797 neg = 1;
1798 (*s)++;
1799 }
1800 else if (**s == '+')
1801 (*s)++;
1802
1803 /* convert as positive number. */
1804 i = read_uint64(s, end);
1805
1806 if (neg) {
1807 if (i > 0x8000000000000000ULL)
1808 return LLONG_MIN;
1809 return -i;
1810 }
1811 if (i > 0x7fffffffffffffffULL)
1812 return LLONG_MAX;
1813 return i;
1814}
1815
Willy Tarreau6911fa42007-03-04 18:06:08 +01001816/* This one is 7 times faster than strtol() on athlon with checks.
1817 * It returns the value of the number composed of all valid digits read,
1818 * and can process negative numbers too.
1819 */
1820int strl2ic(const char *s, int len)
1821{
1822 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001823 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001824
1825 if (len > 0) {
1826 if (*s != '-') {
1827 /* positive number */
1828 while (len-- > 0) {
1829 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001830 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001831 if (j > 9)
1832 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001833 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001834 }
1835 } else {
1836 /* negative number */
1837 s++;
1838 while (--len > 0) {
1839 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001840 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001841 if (j > 9)
1842 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001843 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001844 }
1845 }
1846 }
1847 return i;
1848}
1849
1850
1851/* This function reads exactly <len> chars from <s> and converts them to a
1852 * signed integer which it stores into <ret>. It accurately detects any error
1853 * (truncated string, invalid chars, overflows). It is meant to be used in
1854 * applications designed for hostile environments. It returns zero when the
1855 * number has successfully been converted, non-zero otherwise. When an error
1856 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1857 * faster than strtol().
1858 */
1859int strl2irc(const char *s, int len, int *ret)
1860{
1861 int i = 0;
1862 int j;
1863
1864 if (!len)
1865 return 1;
1866
1867 if (*s != '-') {
1868 /* positive number */
1869 while (len-- > 0) {
1870 j = (*s++) - '0';
1871 if (j > 9) return 1; /* invalid char */
1872 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1873 i = i * 10;
1874 if (i + j < i) return 1; /* check for addition overflow */
1875 i = i + j;
1876 }
1877 } else {
1878 /* negative number */
1879 s++;
1880 while (--len > 0) {
1881 j = (*s++) - '0';
1882 if (j > 9) return 1; /* invalid char */
1883 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1884 i = i * 10;
1885 if (i - j > i) return 1; /* check for subtract overflow */
1886 i = i - j;
1887 }
1888 }
1889 *ret = i;
1890 return 0;
1891}
1892
1893
1894/* This function reads exactly <len> chars from <s> and converts them to a
1895 * signed integer which it stores into <ret>. It accurately detects any error
1896 * (truncated string, invalid chars, overflows). It is meant to be used in
1897 * applications designed for hostile environments. It returns zero when the
1898 * number has successfully been converted, non-zero otherwise. When an error
1899 * is returned, the <ret> value is left untouched. It is about 3 times slower
1900 * than str2irc().
1901 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001902
1903int strl2llrc(const char *s, int len, long long *ret)
1904{
1905 long long i = 0;
1906 int j;
1907
1908 if (!len)
1909 return 1;
1910
1911 if (*s != '-') {
1912 /* positive number */
1913 while (len-- > 0) {
1914 j = (*s++) - '0';
1915 if (j > 9) return 1; /* invalid char */
1916 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1917 i = i * 10LL;
1918 if (i + j < i) return 1; /* check for addition overflow */
1919 i = i + j;
1920 }
1921 } else {
1922 /* negative number */
1923 s++;
1924 while (--len > 0) {
1925 j = (*s++) - '0';
1926 if (j > 9) return 1; /* invalid char */
1927 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1928 i = i * 10LL;
1929 if (i - j > i) return 1; /* check for subtract overflow */
1930 i = i - j;
1931 }
1932 }
1933 *ret = i;
1934 return 0;
1935}
1936
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001937/* This function is used with pat_parse_dotted_ver(). It converts a string
1938 * composed by two number separated by a dot. Each part must contain in 16 bits
1939 * because internally they will be represented as a 32-bit quantity stored in
1940 * a 64-bit integer. It returns zero when the number has successfully been
1941 * converted, non-zero otherwise. When an error is returned, the <ret> value
1942 * is left untouched.
1943 *
1944 * "1.3" -> 0x0000000000010003
1945 * "65535.65535" -> 0x00000000ffffffff
1946 */
1947int strl2llrc_dotted(const char *text, int len, long long *ret)
1948{
1949 const char *end = &text[len];
1950 const char *p;
1951 long long major, minor;
1952
1953 /* Look for dot. */
1954 for (p = text; p < end; p++)
1955 if (*p == '.')
1956 break;
1957
1958 /* Convert major. */
1959 if (strl2llrc(text, p - text, &major) != 0)
1960 return 1;
1961
1962 /* Check major. */
1963 if (major >= 65536)
1964 return 1;
1965
1966 /* Convert minor. */
1967 minor = 0;
1968 if (p < end)
1969 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1970 return 1;
1971
1972 /* Check minor. */
1973 if (minor >= 65536)
1974 return 1;
1975
1976 /* Compose value. */
1977 *ret = (major << 16) | (minor & 0xffff);
1978 return 0;
1979}
1980
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001981/* This function parses a time value optionally followed by a unit suffix among
1982 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1983 * expected by the caller. The computation does its best to avoid overflows.
1984 * The value is returned in <ret> if everything is fine, and a NULL is returned
1985 * by the function. In case of error, a pointer to the error is returned and
1986 * <ret> is left untouched. Values are automatically rounded up when needed.
1987 */
1988const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1989{
1990 unsigned imult, idiv;
1991 unsigned omult, odiv;
1992 unsigned value;
1993
1994 omult = odiv = 1;
1995
1996 switch (unit_flags & TIME_UNIT_MASK) {
1997 case TIME_UNIT_US: omult = 1000000; break;
1998 case TIME_UNIT_MS: omult = 1000; break;
1999 case TIME_UNIT_S: break;
2000 case TIME_UNIT_MIN: odiv = 60; break;
2001 case TIME_UNIT_HOUR: odiv = 3600; break;
2002 case TIME_UNIT_DAY: odiv = 86400; break;
2003 default: break;
2004 }
2005
2006 value = 0;
2007
2008 while (1) {
2009 unsigned int j;
2010
2011 j = *text - '0';
2012 if (j > 9)
2013 break;
2014 text++;
2015 value *= 10;
2016 value += j;
2017 }
2018
2019 imult = idiv = 1;
2020 switch (*text) {
2021 case '\0': /* no unit = default unit */
2022 imult = omult = idiv = odiv = 1;
2023 break;
2024 case 's': /* second = unscaled unit */
2025 break;
2026 case 'u': /* microsecond : "us" */
2027 if (text[1] == 's') {
2028 idiv = 1000000;
2029 text++;
2030 }
2031 break;
2032 case 'm': /* millisecond : "ms" or minute: "m" */
2033 if (text[1] == 's') {
2034 idiv = 1000;
2035 text++;
2036 } else
2037 imult = 60;
2038 break;
2039 case 'h': /* hour : "h" */
2040 imult = 3600;
2041 break;
2042 case 'd': /* day : "d" */
2043 imult = 86400;
2044 break;
2045 default:
2046 return text;
2047 break;
2048 }
2049
2050 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2051 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2052 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2053 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2054
2055 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2056 *ret = value;
2057 return NULL;
2058}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002059
Emeric Brun39132b22010-01-04 14:57:24 +01002060/* this function converts the string starting at <text> to an unsigned int
2061 * stored in <ret>. If an error is detected, the pointer to the unexpected
2062 * character is returned. If the conversio is succesful, NULL is returned.
2063 */
2064const char *parse_size_err(const char *text, unsigned *ret) {
2065 unsigned value = 0;
2066
2067 while (1) {
2068 unsigned int j;
2069
2070 j = *text - '0';
2071 if (j > 9)
2072 break;
2073 if (value > ~0U / 10)
2074 return text;
2075 value *= 10;
2076 if (value > (value + j))
2077 return text;
2078 value += j;
2079 text++;
2080 }
2081
2082 switch (*text) {
2083 case '\0':
2084 break;
2085 case 'K':
2086 case 'k':
2087 if (value > ~0U >> 10)
2088 return text;
2089 value = value << 10;
2090 break;
2091 case 'M':
2092 case 'm':
2093 if (value > ~0U >> 20)
2094 return text;
2095 value = value << 20;
2096 break;
2097 case 'G':
2098 case 'g':
2099 if (value > ~0U >> 30)
2100 return text;
2101 value = value << 30;
2102 break;
2103 default:
2104 return text;
2105 }
2106
Godbach58048a22015-01-28 17:36:16 +08002107 if (*text != '\0' && *++text != '\0')
2108 return text;
2109
Emeric Brun39132b22010-01-04 14:57:24 +01002110 *ret = value;
2111 return NULL;
2112}
2113
Willy Tarreau126d4062013-12-03 17:50:47 +01002114/*
2115 * Parse binary string written in hexadecimal (source) and store the decoded
2116 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2117 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002118 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002119 */
2120int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2121{
2122 int len;
2123 const char *p = source;
2124 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002125 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002126
2127 len = strlen(source);
2128 if (len % 2) {
2129 memprintf(err, "an even number of hex digit is expected");
2130 return 0;
2131 }
2132
2133 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002134
Willy Tarreau126d4062013-12-03 17:50:47 +01002135 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002136 *binstr = calloc(len, sizeof(char));
2137 if (!*binstr) {
2138 memprintf(err, "out of memory while loading string pattern");
2139 return 0;
2140 }
2141 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002142 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002143 else {
2144 if (*binstrlen < len) {
2145 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2146 len, *binstrlen);
2147 return 0;
2148 }
2149 alloc = 0;
2150 }
2151 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002152
2153 i = j = 0;
2154 while (j < len) {
2155 if (!ishex(p[i++]))
2156 goto bad_input;
2157 if (!ishex(p[i++]))
2158 goto bad_input;
2159 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2160 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002161 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002162
2163bad_input:
2164 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002165 if (alloc) {
2166 free(*binstr);
2167 *binstr = NULL;
2168 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002169 return 0;
2170}
2171
Willy Tarreau946ba592009-05-10 15:41:18 +02002172/* copies at most <n> characters from <src> and always terminates with '\0' */
2173char *my_strndup(const char *src, int n)
2174{
2175 int len = 0;
2176 char *ret;
2177
2178 while (len < n && src[len])
2179 len++;
2180
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002181 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002182 if (!ret)
2183 return ret;
2184 memcpy(ret, src, len);
2185 ret[len] = '\0';
2186 return ret;
2187}
2188
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002189/*
2190 * search needle in haystack
2191 * returns the pointer if found, returns NULL otherwise
2192 */
2193const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2194{
2195 const void *c = NULL;
2196 unsigned char f;
2197
2198 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2199 return NULL;
2200
2201 f = *(char *)needle;
2202 c = haystack;
2203 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2204 if ((haystacklen - (c - haystack)) < needlelen)
2205 return NULL;
2206
2207 if (memcmp(c, needle, needlelen) == 0)
2208 return c;
2209 ++c;
2210 }
2211 return NULL;
2212}
2213
Willy Tarreau482b00d2009-10-04 22:48:42 +02002214/* This function returns the first unused key greater than or equal to <key> in
2215 * ID tree <root>. Zero is returned if no place is found.
2216 */
2217unsigned int get_next_id(struct eb_root *root, unsigned int key)
2218{
2219 struct eb32_node *used;
2220
2221 do {
2222 used = eb32_lookup_ge(root, key);
2223 if (!used || used->key > key)
2224 return key; /* key is available */
2225 key++;
2226 } while (key);
2227 return key;
2228}
2229
Willy Tarreau348238b2010-01-18 15:05:57 +01002230/* This function compares a sample word possibly followed by blanks to another
2231 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2232 * otherwise zero. This intends to be used when checking HTTP headers for some
2233 * values. Note that it validates a word followed only by blanks but does not
2234 * validate a word followed by blanks then other chars.
2235 */
2236int word_match(const char *sample, int slen, const char *word, int wlen)
2237{
2238 if (slen < wlen)
2239 return 0;
2240
2241 while (wlen) {
2242 char c = *sample ^ *word;
2243 if (c && c != ('A' ^ 'a'))
2244 return 0;
2245 sample++;
2246 word++;
2247 slen--;
2248 wlen--;
2249 }
2250
2251 while (slen) {
2252 if (*sample != ' ' && *sample != '\t')
2253 return 0;
2254 sample++;
2255 slen--;
2256 }
2257 return 1;
2258}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002259
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002260/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2261 * is particularly fast because it avoids expensive operations such as
2262 * multiplies, which are optimized away at the end. It requires a properly
2263 * formated address though (3 points).
2264 */
2265unsigned int inetaddr_host(const char *text)
2266{
2267 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2268 register unsigned int dig100, dig10, dig1;
2269 int s;
2270 const char *p, *d;
2271
2272 dig1 = dig10 = dig100 = ascii_zero;
2273 s = 24;
2274
2275 p = text;
2276 while (1) {
2277 if (((unsigned)(*p - '0')) <= 9) {
2278 p++;
2279 continue;
2280 }
2281
2282 /* here, we have a complete byte between <text> and <p> (exclusive) */
2283 if (p == text)
2284 goto end;
2285
2286 d = p - 1;
2287 dig1 |= (unsigned int)(*d << s);
2288 if (d == text)
2289 goto end;
2290
2291 d--;
2292 dig10 |= (unsigned int)(*d << s);
2293 if (d == text)
2294 goto end;
2295
2296 d--;
2297 dig100 |= (unsigned int)(*d << s);
2298 end:
2299 if (!s || *p != '.')
2300 break;
2301
2302 s -= 8;
2303 text = ++p;
2304 }
2305
2306 dig100 -= ascii_zero;
2307 dig10 -= ascii_zero;
2308 dig1 -= ascii_zero;
2309 return ((dig100 * 10) + dig10) * 10 + dig1;
2310}
2311
2312/*
2313 * Idem except the first unparsed character has to be passed in <stop>.
2314 */
2315unsigned int inetaddr_host_lim(const char *text, const char *stop)
2316{
2317 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2318 register unsigned int dig100, dig10, dig1;
2319 int s;
2320 const char *p, *d;
2321
2322 dig1 = dig10 = dig100 = ascii_zero;
2323 s = 24;
2324
2325 p = text;
2326 while (1) {
2327 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2328 p++;
2329 continue;
2330 }
2331
2332 /* here, we have a complete byte between <text> and <p> (exclusive) */
2333 if (p == text)
2334 goto end;
2335
2336 d = p - 1;
2337 dig1 |= (unsigned int)(*d << s);
2338 if (d == text)
2339 goto end;
2340
2341 d--;
2342 dig10 |= (unsigned int)(*d << s);
2343 if (d == text)
2344 goto end;
2345
2346 d--;
2347 dig100 |= (unsigned int)(*d << s);
2348 end:
2349 if (!s || p == stop || *p != '.')
2350 break;
2351
2352 s -= 8;
2353 text = ++p;
2354 }
2355
2356 dig100 -= ascii_zero;
2357 dig10 -= ascii_zero;
2358 dig1 -= ascii_zero;
2359 return ((dig100 * 10) + dig10) * 10 + dig1;
2360}
2361
2362/*
2363 * Idem except the pointer to first unparsed byte is returned into <ret> which
2364 * must not be NULL.
2365 */
Willy Tarreau74172752010-10-15 23:21:42 +02002366unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002367{
2368 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2369 register unsigned int dig100, dig10, dig1;
2370 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002371 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002372
2373 dig1 = dig10 = dig100 = ascii_zero;
2374 s = 24;
2375
2376 p = text;
2377 while (1) {
2378 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2379 p++;
2380 continue;
2381 }
2382
2383 /* here, we have a complete byte between <text> and <p> (exclusive) */
2384 if (p == text)
2385 goto end;
2386
2387 d = p - 1;
2388 dig1 |= (unsigned int)(*d << s);
2389 if (d == text)
2390 goto end;
2391
2392 d--;
2393 dig10 |= (unsigned int)(*d << s);
2394 if (d == text)
2395 goto end;
2396
2397 d--;
2398 dig100 |= (unsigned int)(*d << s);
2399 end:
2400 if (!s || p == stop || *p != '.')
2401 break;
2402
2403 s -= 8;
2404 text = ++p;
2405 }
2406
2407 *ret = p;
2408 dig100 -= ascii_zero;
2409 dig10 -= ascii_zero;
2410 dig1 -= ascii_zero;
2411 return ((dig100 * 10) + dig10) * 10 + dig1;
2412}
2413
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002414/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2415 * or the number of chars read in case of success. Maybe this could be replaced
2416 * by one of the functions above. Also, apparently this function does not support
2417 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002418 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002419 */
2420int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2421{
2422 const char *addr;
2423 int saw_digit, octets, ch;
2424 u_char tmp[4], *tp;
2425 const char *cp = buf;
2426
2427 saw_digit = 0;
2428 octets = 0;
2429 *(tp = tmp) = 0;
2430
2431 for (addr = buf; addr - buf < len; addr++) {
2432 unsigned char digit = (ch = *addr) - '0';
2433
2434 if (digit > 9 && ch != '.')
2435 break;
2436
2437 if (digit <= 9) {
2438 u_int new = *tp * 10 + digit;
2439
2440 if (new > 255)
2441 return 0;
2442
2443 *tp = new;
2444
2445 if (!saw_digit) {
2446 if (++octets > 4)
2447 return 0;
2448 saw_digit = 1;
2449 }
2450 } else if (ch == '.' && saw_digit) {
2451 if (octets == 4)
2452 return 0;
2453
2454 *++tp = 0;
2455 saw_digit = 0;
2456 } else
2457 return 0;
2458 }
2459
2460 if (octets < 4)
2461 return 0;
2462
2463 memcpy(&dst->s_addr, tmp, 4);
2464 return addr - cp;
2465}
2466
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002467/* This function converts the string in <buf> of the len <len> to
2468 * struct in6_addr <dst> which must be allocated by the caller.
2469 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002470 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002471 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002472int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2473{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002474 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002475 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002476
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002477 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002478 return 0;
2479
2480 memcpy(null_term_ip6, buf, len);
2481 null_term_ip6[len] = '\0';
2482
Willy Tarreau075415a2013-12-12 11:29:39 +01002483 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002484 return 0;
2485
Willy Tarreau075415a2013-12-12 11:29:39 +01002486 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002487 return 1;
2488}
2489
Willy Tarreauacf95772010-06-14 19:09:21 +02002490/* To be used to quote config arg positions. Returns the short string at <ptr>
2491 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2492 * if ptr is NULL or empty. The string is locally allocated.
2493 */
2494const char *quote_arg(const char *ptr)
2495{
2496 static char val[32];
2497 int i;
2498
2499 if (!ptr || !*ptr)
2500 return "end of line";
2501 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002502 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002503 val[i] = *ptr++;
2504 val[i++] = '\'';
2505 val[i] = '\0';
2506 return val;
2507}
2508
Willy Tarreau5b180202010-07-18 10:40:48 +02002509/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2510int get_std_op(const char *str)
2511{
2512 int ret = -1;
2513
2514 if (*str == 'e' && str[1] == 'q')
2515 ret = STD_OP_EQ;
2516 else if (*str == 'n' && str[1] == 'e')
2517 ret = STD_OP_NE;
2518 else if (*str == 'l') {
2519 if (str[1] == 'e') ret = STD_OP_LE;
2520 else if (str[1] == 't') ret = STD_OP_LT;
2521 }
2522 else if (*str == 'g') {
2523 if (str[1] == 'e') ret = STD_OP_GE;
2524 else if (str[1] == 't') ret = STD_OP_GT;
2525 }
2526
2527 if (ret == -1 || str[2] != '\0')
2528 return -1;
2529 return ret;
2530}
2531
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002532/* hash a 32-bit integer to another 32-bit integer */
2533unsigned int full_hash(unsigned int a)
2534{
2535 return __full_hash(a);
2536}
2537
David du Colombier4f92d322011-03-24 11:09:31 +01002538/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002539 * otherwise zero. Note that <addr> may not necessarily be aligned
2540 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002541 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002542int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002543{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002544 struct in_addr addr_copy;
2545
2546 memcpy(&addr_copy, addr, sizeof(addr_copy));
2547 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002548}
2549
2550/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002551 * otherwise zero. Note that <addr> may not necessarily be aligned
2552 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002553 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002554int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002555{
2556 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002557 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002558
Willy Tarreaueec1d382016-07-13 11:59:39 +02002559 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002560 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002561 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002562 (((int *)net)[i] & ((int *)mask)[i]))
2563 return 0;
2564 return 1;
2565}
2566
2567/* RFC 4291 prefix */
2568const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2569 0x00, 0x00, 0x00, 0x00,
2570 0x00, 0x00, 0xFF, 0xFF };
2571
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002572/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2573 * Input and output may overlap.
2574 */
David du Colombier4f92d322011-03-24 11:09:31 +01002575void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2576{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002577 struct in_addr tmp_addr;
2578
2579 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002580 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002581 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002582}
2583
2584/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2585 * Return true if conversion is possible and false otherwise.
2586 */
2587int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2588{
2589 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2590 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2591 sizeof(struct in_addr));
2592 return 1;
2593 }
2594
2595 return 0;
2596}
2597
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002598/* compare two struct sockaddr_storage and return:
2599 * 0 (true) if the addr is the same in both
2600 * 1 (false) if the addr is not the same in both
2601 * -1 (unable) if one of the addr is not AF_INET*
2602 */
2603int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2604{
2605 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2606 return -1;
2607
2608 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2609 return -1;
2610
2611 if (ss1->ss_family != ss2->ss_family)
2612 return 1;
2613
2614 switch (ss1->ss_family) {
2615 case AF_INET:
2616 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2617 &((struct sockaddr_in *)ss2)->sin_addr,
2618 sizeof(struct in_addr)) != 0;
2619 case AF_INET6:
2620 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2621 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2622 sizeof(struct in6_addr)) != 0;
2623 }
2624
2625 return 1;
2626}
2627
Baptiste Assmann08396c82016-01-31 00:27:17 +01002628/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002629 * The caller must allocate and clear <dest> before calling.
2630 * The source must be in either AF_INET or AF_INET6 family, or the destination
2631 * address will be undefined. If the destination address used to hold a port,
2632 * it is preserved, so that this function can be used to switch to another
2633 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002634 */
2635struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2636{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002637 int prev_port;
2638
2639 prev_port = get_net_port(dest);
2640 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002641 dest->ss_family = source->ss_family;
2642
2643 /* copy new addr and apply it */
2644 switch (source->ss_family) {
2645 case AF_INET:
2646 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002647 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002648 break;
2649 case AF_INET6:
2650 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 +01002651 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002652 break;
2653 }
2654
2655 return dest;
2656}
2657
William Lallemand421f5b52012-02-06 18:15:57 +01002658char *human_time(int t, short hz_div) {
2659 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2660 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002661 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002662 int cnt=2; // print two numbers
2663
2664 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002665 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002666 return rv;
2667 }
2668
2669 if (unlikely(hz_div > 1))
2670 t /= hz_div;
2671
2672 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002673 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002674 cnt--;
2675 }
2676
2677 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002678 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002679 cnt--;
2680 }
2681
2682 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002683 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002684 cnt--;
2685 }
2686
2687 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002688 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002689
2690 return rv;
2691}
2692
2693const char *monthname[12] = {
2694 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2695 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2696};
2697
2698/* date2str_log: write a date in the format :
2699 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2700 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2701 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2702 *
2703 * without using sprintf. return a pointer to the last char written (\0) or
2704 * NULL if there isn't enough space.
2705 */
2706char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2707{
2708
2709 if (size < 25) /* the size is fixed: 24 chars + \0 */
2710 return NULL;
2711
2712 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2713 *dst++ = '/';
2714 memcpy(dst, monthname[tm->tm_mon], 3); // month
2715 dst += 3;
2716 *dst++ = '/';
2717 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2718 *dst++ = ':';
2719 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2720 *dst++ = ':';
2721 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2722 *dst++ = ':';
2723 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2724 *dst++ = '.';
2725 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2726 dst += 3; // only the 3 first digits
2727 *dst = '\0';
2728
2729 return dst;
2730}
2731
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002732/* Base year used to compute leap years */
2733#define TM_YEAR_BASE 1900
2734
2735/* Return the difference in seconds between two times (leap seconds are ignored).
2736 * Retrieved from glibc 2.18 source code.
2737 */
2738static int my_tm_diff(const struct tm *a, const struct tm *b)
2739{
2740 /* Compute intervening leap days correctly even if year is negative.
2741 * Take care to avoid int overflow in leap day calculations,
2742 * but it's OK to assume that A and B are close to each other.
2743 */
2744 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2745 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2746 int a100 = a4 / 25 - (a4 % 25 < 0);
2747 int b100 = b4 / 25 - (b4 % 25 < 0);
2748 int a400 = a100 >> 2;
2749 int b400 = b100 >> 2;
2750 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2751 int years = a->tm_year - b->tm_year;
2752 int days = (365 * years + intervening_leap_days
2753 + (a->tm_yday - b->tm_yday));
2754 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2755 + (a->tm_min - b->tm_min))
2756 + (a->tm_sec - b->tm_sec));
2757}
2758
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002759/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002760 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002761 * The string returned has the same format as returned by strftime(... "%z", tm).
2762 * Offsets are kept in an internal cache for better performances.
2763 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002764const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002765{
2766 /* Cache offsets from GMT (depending on whether DST is active or not) */
2767 static char gmt_offsets[2][5+1] = { "", "" };
2768
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002769 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002770 struct tm tm_gmt;
2771 int diff;
2772 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002773
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002774 /* Pretend DST not active if its status is unknown */
2775 if (isdst < 0)
2776 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002777
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002778 /* Fetch the offset and initialize it if needed */
2779 gmt_offset = gmt_offsets[isdst & 0x01];
2780 if (unlikely(!*gmt_offset)) {
2781 get_gmtime(t, &tm_gmt);
2782 diff = my_tm_diff(tm, &tm_gmt);
2783 if (diff < 0) {
2784 diff = -diff;
2785 *gmt_offset = '-';
2786 } else {
2787 *gmt_offset = '+';
2788 }
2789 diff /= 60; /* Convert to minutes */
2790 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2791 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002792
2793 return gmt_offset;
2794}
2795
William Lallemand421f5b52012-02-06 18:15:57 +01002796/* gmt2str_log: write a date in the format :
2797 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2798 * return a pointer to the last char written (\0) or
2799 * NULL if there isn't enough space.
2800 */
2801char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2802{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002803 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002804 return NULL;
2805
2806 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2807 *dst++ = '/';
2808 memcpy(dst, monthname[tm->tm_mon], 3); // month
2809 dst += 3;
2810 *dst++ = '/';
2811 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2812 *dst++ = ':';
2813 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2814 *dst++ = ':';
2815 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2816 *dst++ = ':';
2817 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2818 *dst++ = ' ';
2819 *dst++ = '+';
2820 *dst++ = '0';
2821 *dst++ = '0';
2822 *dst++ = '0';
2823 *dst++ = '0';
2824 *dst = '\0';
2825
2826 return dst;
2827}
2828
Yuxans Yao4e25b012012-10-19 10:36:09 +08002829/* localdate2str_log: write a date in the format :
2830 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002831 * Both t and tm must represent the same time.
2832 * return a pointer to the last char written (\0) or
2833 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002834 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002835char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002836{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002837 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002838 if (size < 27) /* the size is fixed: 26 chars + \0 */
2839 return NULL;
2840
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002841 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002842
Yuxans Yao4e25b012012-10-19 10:36:09 +08002843 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2844 *dst++ = '/';
2845 memcpy(dst, monthname[tm->tm_mon], 3); // month
2846 dst += 3;
2847 *dst++ = '/';
2848 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2849 *dst++ = ':';
2850 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2851 *dst++ = ':';
2852 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2853 *dst++ = ':';
2854 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2855 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002856 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002857 dst += 5;
2858 *dst = '\0';
2859
2860 return dst;
2861}
2862
Willy Tarreaucb1949b2017-07-19 19:05:29 +02002863/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
2864 * It is meant as a portable replacement for timegm() for use with valid inputs.
2865 * Returns undefined results for invalid dates (eg: months out of range 0..11).
2866 */
2867time_t my_timegm(const struct tm *tm)
2868{
2869 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
2870 * is thus (current month - 1)*28 + cumulated_N[month] to count the
2871 * sum of the extra N days for elapsed months. The sum of all these N
2872 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
2873 * in a 5-bit word. This means that with 60 bits we can represent a
2874 * matrix of all these values at once, which is fast and efficient to
2875 * access. The extra February day for leap years is not counted here.
2876 *
2877 * Jan : none = 0 (0)
2878 * Feb : Jan = 3 (3)
2879 * Mar : Jan..Feb = 3 (3 + 0)
2880 * Apr : Jan..Mar = 6 (3 + 0 + 3)
2881 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
2882 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
2883 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
2884 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
2885 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
2886 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
2887 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
2888 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
2889 */
2890 uint64_t extra =
2891 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
2892 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
2893 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
2894 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
2895
2896 unsigned int y = tm->tm_year + 1900;
2897 unsigned int m = tm->tm_mon;
2898 unsigned long days = 0;
2899
2900 /* days since 1/1/1970 for full years */
2901 days += days_since_zero(y) - days_since_zero(1970);
2902
2903 /* days for full months in the current year */
2904 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
2905
2906 /* count + 1 after March for leap years. A leap year is a year multiple
2907 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
2908 * is leap, 1900 isn't, 1904 is.
2909 */
2910 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
2911 days++;
2912
2913 days += tm->tm_mday - 1;
2914 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
2915}
2916
Thierry Fournier93127942016-01-20 18:49:45 +01002917/* This function check a char. It returns true and updates
2918 * <date> and <len> pointer to the new position if the
2919 * character is found.
2920 */
2921static inline int parse_expect_char(const char **date, int *len, char c)
2922{
2923 if (*len < 1 || **date != c)
2924 return 0;
2925 (*len)--;
2926 (*date)++;
2927 return 1;
2928}
2929
2930/* This function expects a string <str> of len <l>. It return true and updates.
2931 * <date> and <len> if the string matches, otherwise, it returns false.
2932 */
2933static inline int parse_strcmp(const char **date, int *len, char *str, int l)
2934{
2935 if (*len < l || strncmp(*date, str, l) != 0)
2936 return 0;
2937 (*len) -= l;
2938 (*date) += l;
2939 return 1;
2940}
2941
2942/* This macro converts 3 chars name in integer. */
2943#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
2944
2945/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
2946 * / %x54.75.65 ; "Tue", case-sensitive
2947 * / %x57.65.64 ; "Wed", case-sensitive
2948 * / %x54.68.75 ; "Thu", case-sensitive
2949 * / %x46.72.69 ; "Fri", case-sensitive
2950 * / %x53.61.74 ; "Sat", case-sensitive
2951 * / %x53.75.6E ; "Sun", case-sensitive
2952 *
2953 * This array must be alphabetically sorted
2954 */
2955static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
2956{
2957 if (*len < 3)
2958 return 0;
2959 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2960 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
2961 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
2962 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
2963 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
2964 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
2965 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
2966 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
2967 default: return 0;
2968 }
2969 *len -= 3;
2970 *date += 3;
2971 return 1;
2972}
2973
2974/* month = %x4A.61.6E ; "Jan", case-sensitive
2975 * / %x46.65.62 ; "Feb", case-sensitive
2976 * / %x4D.61.72 ; "Mar", case-sensitive
2977 * / %x41.70.72 ; "Apr", case-sensitive
2978 * / %x4D.61.79 ; "May", case-sensitive
2979 * / %x4A.75.6E ; "Jun", case-sensitive
2980 * / %x4A.75.6C ; "Jul", case-sensitive
2981 * / %x41.75.67 ; "Aug", case-sensitive
2982 * / %x53.65.70 ; "Sep", case-sensitive
2983 * / %x4F.63.74 ; "Oct", case-sensitive
2984 * / %x4E.6F.76 ; "Nov", case-sensitive
2985 * / %x44.65.63 ; "Dec", case-sensitive
2986 *
2987 * This array must be alphabetically sorted
2988 */
2989static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
2990{
2991 if (*len < 3)
2992 return 0;
2993 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2994 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
2995 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
2996 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
2997 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
2998 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
2999 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3000 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3001 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3002 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3003 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3004 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3005 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3006 default: return 0;
3007 }
3008 *len -= 3;
3009 *date += 3;
3010 return 1;
3011}
3012
3013/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3014 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3015 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3016 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3017 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3018 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3019 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3020 *
3021 * This array must be alphabetically sorted
3022 */
3023static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3024{
3025 if (*len < 6) /* Minimum length. */
3026 return 0;
3027 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3028 case STR2I3('M','o','n'):
3029 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3030 tm->tm_wday = 1;
3031 return 1;
3032 case STR2I3('T','u','e'):
3033 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3034 tm->tm_wday = 2;
3035 return 1;
3036 case STR2I3('W','e','d'):
3037 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3038 tm->tm_wday = 3;
3039 return 1;
3040 case STR2I3('T','h','u'):
3041 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3042 tm->tm_wday = 4;
3043 return 1;
3044 case STR2I3('F','r','i'):
3045 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3046 tm->tm_wday = 5;
3047 return 1;
3048 case STR2I3('S','a','t'):
3049 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3050 tm->tm_wday = 6;
3051 return 1;
3052 case STR2I3('S','u','n'):
3053 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3054 tm->tm_wday = 7;
3055 return 1;
3056 }
3057 return 0;
3058}
3059
3060/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3061static inline int parse_digit(const char **date, int *len, int *digit)
3062{
3063 if (*len < 1 || **date < '0' || **date > '9')
3064 return 0;
3065 *digit = (**date - '0');
3066 (*date)++;
3067 (*len)--;
3068 return 1;
3069}
3070
3071/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3072static inline int parse_2digit(const char **date, int *len, int *digit)
3073{
3074 int value;
3075
3076 RET0_UNLESS(parse_digit(date, len, &value));
3077 (*digit) = value * 10;
3078 RET0_UNLESS(parse_digit(date, len, &value));
3079 (*digit) += value;
3080
3081 return 1;
3082}
3083
3084/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3085static inline int parse_4digit(const char **date, int *len, int *digit)
3086{
3087 int value;
3088
3089 RET0_UNLESS(parse_digit(date, len, &value));
3090 (*digit) = value * 1000;
3091
3092 RET0_UNLESS(parse_digit(date, len, &value));
3093 (*digit) += value * 100;
3094
3095 RET0_UNLESS(parse_digit(date, len, &value));
3096 (*digit) += value * 10;
3097
3098 RET0_UNLESS(parse_digit(date, len, &value));
3099 (*digit) += value;
3100
3101 return 1;
3102}
3103
3104/* time-of-day = hour ":" minute ":" second
3105 * ; 00:00:00 - 23:59:60 (leap second)
3106 *
3107 * hour = 2DIGIT
3108 * minute = 2DIGIT
3109 * second = 2DIGIT
3110 */
3111static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3112{
3113 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3114 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3115 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3116 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3117 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3118 return 1;
3119}
3120
3121/* From RFC7231
3122 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3123 *
3124 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3125 * ; fixed length/zone/capitalization subset of the format
3126 * ; see Section 3.3 of [RFC5322]
3127 *
3128 *
3129 * date1 = day SP month SP year
3130 * ; e.g., 02 Jun 1982
3131 *
3132 * day = 2DIGIT
3133 * year = 4DIGIT
3134 *
3135 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3136 *
3137 * time-of-day = hour ":" minute ":" second
3138 * ; 00:00:00 - 23:59:60 (leap second)
3139 *
3140 * hour = 2DIGIT
3141 * minute = 2DIGIT
3142 * second = 2DIGIT
3143 *
3144 * DIGIT = decimal 0-9
3145 */
3146int parse_imf_date(const char *date, int len, struct tm *tm)
3147{
David Carlier327298c2016-11-20 10:42:38 +00003148 /* tm_gmtoff, if present, ought to be zero'ed */
3149 memset(tm, 0, sizeof(*tm));
3150
Thierry Fournier93127942016-01-20 18:49:45 +01003151 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3152 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3153 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3154 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3155 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3156 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3157 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3158 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3159 tm->tm_year -= 1900;
3160 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3161 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3162 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3163 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3164 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003165 return 1;
3166}
3167
3168/* From RFC7231
3169 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3170 *
3171 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3172 * date2 = day "-" month "-" 2DIGIT
3173 * ; e.g., 02-Jun-82
3174 *
3175 * day = 2DIGIT
3176 */
3177int parse_rfc850_date(const char *date, int len, struct tm *tm)
3178{
3179 int year;
3180
David Carlier327298c2016-11-20 10:42:38 +00003181 /* tm_gmtoff, if present, ought to be zero'ed */
3182 memset(tm, 0, sizeof(*tm));
3183
Thierry Fournier93127942016-01-20 18:49:45 +01003184 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3185 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3186 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3187 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3188 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3189 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3190 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3191
3192 /* year = 2DIGIT
3193 *
3194 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3195 * two-digit year, MUST interpret a timestamp that appears to be more
3196 * than 50 years in the future as representing the most recent year in
3197 * the past that had the same last two digits.
3198 */
3199 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3200
3201 /* expect SP */
3202 if (!parse_expect_char(&date, &len, ' ')) {
3203 /* Maybe we have the date with 4 digits. */
3204 RET0_UNLESS(parse_2digit(&date, &len, &year));
3205 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3206 /* expect SP */
3207 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3208 } else {
3209 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3210 * tm_year is the number of year since 1900, so for +1900, we
3211 * do nothing, and for +2000, we add 100.
3212 */
3213 if (tm->tm_year <= 60)
3214 tm->tm_year += 100;
3215 }
3216
3217 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3218 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3219 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3220 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003221
3222 return 1;
3223}
3224
3225/* From RFC7231
3226 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3227 *
3228 * asctime-date = day-name SP date3 SP time-of-day SP year
3229 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3230 * ; e.g., Jun 2
3231 *
3232 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3233 * whitespace in an HTTP-date beyond that specifically included as SP in
3234 * the grammar.
3235 */
3236int parse_asctime_date(const char *date, int len, struct tm *tm)
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_dayname(&date, &len, tm)); /* day-name */
3242 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3243 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3244 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3245
3246 /* expect SP and 1DIGIT or 2DIGIT */
3247 if (parse_expect_char(&date, &len, ' '))
3248 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3249 else
3250 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3251
3252 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3253 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3254 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3255 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3256 tm->tm_year -= 1900;
3257 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003258 return 1;
3259}
3260
3261/* From RFC7231
3262 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3263 *
3264 * HTTP-date = IMF-fixdate / obs-date
3265 * obs-date = rfc850-date / asctime-date
3266 *
3267 * parses an HTTP date in the RFC format and is accepted
3268 * alternatives. <date> is the strinf containing the date,
3269 * len is the len of the string. <tm> is filled with the
3270 * parsed time. We must considers this time as GMT.
3271 */
3272int parse_http_date(const char *date, int len, struct tm *tm)
3273{
3274 if (parse_imf_date(date, len, tm))
3275 return 1;
3276
3277 if (parse_rfc850_date(date, len, tm))
3278 return 1;
3279
3280 if (parse_asctime_date(date, len, tm))
3281 return 1;
3282
3283 return 0;
3284}
3285
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003286/* Dynamically allocates a string of the proper length to hold the formatted
3287 * output. NULL is returned on error. The caller is responsible for freeing the
3288 * memory area using free(). The resulting string is returned in <out> if the
3289 * pointer is not NULL. A previous version of <out> might be used to build the
3290 * new string, and it will be freed before returning if it is not NULL, which
3291 * makes it possible to build complex strings from iterative calls without
3292 * having to care about freeing intermediate values, as in the example below :
3293 *
3294 * memprintf(&err, "invalid argument: '%s'", arg);
3295 * ...
3296 * memprintf(&err, "parser said : <%s>\n", *err);
3297 * ...
3298 * free(*err);
3299 *
3300 * This means that <err> must be initialized to NULL before first invocation.
3301 * The return value also holds the allocated string, which eases error checking
3302 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003303 * passed instead and it will be ignored. The returned message will then also
3304 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003305 *
3306 * It is also convenient to use it without any free except the last one :
3307 * err = NULL;
3308 * if (!fct1(err)) report(*err);
3309 * if (!fct2(err)) report(*err);
3310 * if (!fct3(err)) report(*err);
3311 * free(*err);
3312 */
3313char *memprintf(char **out, const char *format, ...)
3314{
3315 va_list args;
3316 char *ret = NULL;
3317 int allocated = 0;
3318 int needed = 0;
3319
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003320 if (!out)
3321 return NULL;
3322
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003323 do {
3324 /* vsnprintf() will return the required length even when the
3325 * target buffer is NULL. We do this in a loop just in case
3326 * intermediate evaluations get wrong.
3327 */
3328 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003329 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003330 va_end(args);
3331
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003332 if (needed < allocated) {
3333 /* Note: on Solaris 8, the first iteration always
3334 * returns -1 if allocated is zero, so we force a
3335 * retry.
3336 */
3337 if (!allocated)
3338 needed = 0;
3339 else
3340 break;
3341 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003342
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003343 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003344 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003345 } while (ret);
3346
3347 if (needed < 0) {
3348 /* an error was encountered */
3349 free(ret);
3350 ret = NULL;
3351 }
3352
3353 if (out) {
3354 free(*out);
3355 *out = ret;
3356 }
3357
3358 return ret;
3359}
William Lallemand421f5b52012-02-06 18:15:57 +01003360
Willy Tarreau21c705b2012-09-14 11:40:36 +02003361/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3362 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003363 * freed by the caller. It also supports being passed a NULL which results in the same
3364 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003365 * Example of use :
3366 * parse(cmd, &err); (callee: memprintf(&err, ...))
3367 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3368 * free(err);
3369 */
3370char *indent_msg(char **out, int level)
3371{
3372 char *ret, *in, *p;
3373 int needed = 0;
3374 int lf = 0;
3375 int lastlf = 0;
3376 int len;
3377
Willy Tarreau70eec382012-10-10 08:56:47 +02003378 if (!out || !*out)
3379 return NULL;
3380
Willy Tarreau21c705b2012-09-14 11:40:36 +02003381 in = *out - 1;
3382 while ((in = strchr(in + 1, '\n')) != NULL) {
3383 lastlf = in - *out;
3384 lf++;
3385 }
3386
3387 if (!lf) /* single line, no LF, return it as-is */
3388 return *out;
3389
3390 len = strlen(*out);
3391
3392 if (lf == 1 && lastlf == len - 1) {
3393 /* single line, LF at end, strip it and return as-is */
3394 (*out)[lastlf] = 0;
3395 return *out;
3396 }
3397
3398 /* OK now we have at least one LF, we need to process the whole string
3399 * as a multi-line string. What we'll do :
3400 * - prefix with an LF if there is none
3401 * - add <level> spaces before each line
3402 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3403 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3404 */
3405
3406 needed = 1 + level * (lf + 1) + len + 1;
3407 p = ret = malloc(needed);
3408 in = *out;
3409
3410 /* skip initial LFs */
3411 while (*in == '\n')
3412 in++;
3413
3414 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3415 while (*in) {
3416 *p++ = '\n';
3417 memset(p, ' ', level);
3418 p += level;
3419 do {
3420 *p++ = *in++;
3421 } while (*in && *in != '\n');
3422 if (*in)
3423 in++;
3424 }
3425 *p = 0;
3426
3427 free(*out);
3428 *out = ret;
3429
3430 return ret;
3431}
3432
Willy Tarreaudad36a32013-03-11 01:20:04 +01003433/* Convert occurrences of environment variables in the input string to their
3434 * corresponding value. A variable is identified as a series of alphanumeric
3435 * characters or underscores following a '$' sign. The <in> string must be
3436 * free()able. NULL returns NULL. The resulting string might be reallocated if
3437 * some expansion is made. Variable names may also be enclosed into braces if
3438 * needed (eg: to concatenate alphanum characters).
3439 */
3440char *env_expand(char *in)
3441{
3442 char *txt_beg;
3443 char *out;
3444 char *txt_end;
3445 char *var_beg;
3446 char *var_end;
3447 char *value;
3448 char *next;
3449 int out_len;
3450 int val_len;
3451
3452 if (!in)
3453 return in;
3454
3455 value = out = NULL;
3456 out_len = 0;
3457
3458 txt_beg = in;
3459 do {
3460 /* look for next '$' sign in <in> */
3461 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3462
3463 if (!*txt_end && !out) /* end and no expansion performed */
3464 return in;
3465
3466 val_len = 0;
3467 next = txt_end;
3468 if (*txt_end == '$') {
3469 char save;
3470
3471 var_beg = txt_end + 1;
3472 if (*var_beg == '{')
3473 var_beg++;
3474
3475 var_end = var_beg;
3476 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3477 var_end++;
3478 }
3479
3480 next = var_end;
3481 if (*var_end == '}' && (var_beg > txt_end + 1))
3482 next++;
3483
3484 /* get value of the variable name at this location */
3485 save = *var_end;
3486 *var_end = '\0';
3487 value = getenv(var_beg);
3488 *var_end = save;
3489 val_len = value ? strlen(value) : 0;
3490 }
3491
Hubert Verstraete831962e2016-06-28 22:44:26 +02003492 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003493 if (txt_end > txt_beg) {
3494 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3495 out_len += txt_end - txt_beg;
3496 }
3497 if (val_len) {
3498 memcpy(out + out_len, value, val_len);
3499 out_len += val_len;
3500 }
3501 out[out_len] = 0;
3502 txt_beg = next;
3503 } while (*txt_beg);
3504
3505 /* here we know that <out> was allocated and that we don't need <in> anymore */
3506 free(in);
3507 return out;
3508}
3509
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003510
3511/* same as strstr() but case-insensitive and with limit length */
3512const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3513{
3514 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003515 unsigned int slen, plen;
3516 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003517
3518 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3519 return NULL;
3520
3521 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3522 return str1;
3523
3524 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3525 return NULL;
3526
3527 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3528 while (toupper(*start) != toupper(*str2)) {
3529 start++;
3530 slen--;
3531 tmp1++;
3532
3533 if (tmp1 >= len_str1)
3534 return NULL;
3535
3536 /* if pattern longer than string */
3537 if (slen < plen)
3538 return NULL;
3539 }
3540
3541 sptr = start;
3542 pptr = (char *)str2;
3543
3544 tmp2 = 0;
3545 while (toupper(*sptr) == toupper(*pptr)) {
3546 sptr++;
3547 pptr++;
3548 tmp2++;
3549
3550 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3551 return start;
3552 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3553 return NULL;
3554 }
3555 }
3556 return NULL;
3557}
3558
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003559/* This function read the next valid utf8 char.
3560 * <s> is the byte srray to be decode, <len> is its length.
3561 * The function returns decoded char encoded like this:
3562 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3563 * are the length read. The decoded character is stored in <c>.
3564 */
3565unsigned char utf8_next(const char *s, int len, unsigned int *c)
3566{
3567 const unsigned char *p = (unsigned char *)s;
3568 int dec;
3569 unsigned char code = UTF8_CODE_OK;
3570
3571 if (len < 1)
3572 return UTF8_CODE_OK;
3573
3574 /* Check the type of UTF8 sequence
3575 *
3576 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3577 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3578 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3579 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3580 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3581 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3582 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3583 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3584 */
3585 switch (*p) {
3586 case 0x00 ... 0x7f:
3587 *c = *p;
3588 return UTF8_CODE_OK | 1;
3589
3590 case 0x80 ... 0xbf:
3591 *c = *p;
3592 return UTF8_CODE_BADSEQ | 1;
3593
3594 case 0xc0 ... 0xdf:
3595 if (len < 2) {
3596 *c = *p;
3597 return UTF8_CODE_BADSEQ | 1;
3598 }
3599 *c = *p & 0x1f;
3600 dec = 1;
3601 break;
3602
3603 case 0xe0 ... 0xef:
3604 if (len < 3) {
3605 *c = *p;
3606 return UTF8_CODE_BADSEQ | 1;
3607 }
3608 *c = *p & 0x0f;
3609 dec = 2;
3610 break;
3611
3612 case 0xf0 ... 0xf7:
3613 if (len < 4) {
3614 *c = *p;
3615 return UTF8_CODE_BADSEQ | 1;
3616 }
3617 *c = *p & 0x07;
3618 dec = 3;
3619 break;
3620
3621 case 0xf8 ... 0xfb:
3622 if (len < 5) {
3623 *c = *p;
3624 return UTF8_CODE_BADSEQ | 1;
3625 }
3626 *c = *p & 0x03;
3627 dec = 4;
3628 break;
3629
3630 case 0xfc ... 0xfd:
3631 if (len < 6) {
3632 *c = *p;
3633 return UTF8_CODE_BADSEQ | 1;
3634 }
3635 *c = *p & 0x01;
3636 dec = 5;
3637 break;
3638
3639 case 0xfe ... 0xff:
3640 default:
3641 *c = *p;
3642 return UTF8_CODE_BADSEQ | 1;
3643 }
3644
3645 p++;
3646
3647 while (dec > 0) {
3648
3649 /* need 0x10 for the 2 first bits */
3650 if ( ( *p & 0xc0 ) != 0x80 )
3651 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3652
3653 /* add data at char */
3654 *c = ( *c << 6 ) | ( *p & 0x3f );
3655
3656 dec--;
3657 p++;
3658 }
3659
3660 /* Check ovelong encoding.
3661 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3662 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3663 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3664 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003665 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003666 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3667 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3668 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3669 code |= UTF8_CODE_OVERLONG;
3670
3671 /* Check invalid UTF8 range. */
3672 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3673 (*c >= 0xfffe && *c <= 0xffff))
3674 code |= UTF8_CODE_INVRANGE;
3675
3676 return code | ((p-(unsigned char *)s)&0x0f);
3677}
3678
Maxime de Roucydc887852016-05-13 23:52:54 +02003679/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3680 * On failure : return 0 and <err> filled with an error message.
3681 * The caller is responsible for freeing the <err> and <str> copy
3682 * memory area using free()
3683 */
3684int list_append_word(struct list *li, const char *str, char **err)
3685{
3686 struct wordlist *wl;
3687
3688 wl = calloc(1, sizeof(*wl));
3689 if (!wl) {
3690 memprintf(err, "out of memory");
3691 goto fail_wl;
3692 }
3693
3694 wl->s = strdup(str);
3695 if (!wl->s) {
3696 memprintf(err, "out of memory");
3697 goto fail_wl_s;
3698 }
3699
3700 LIST_ADDQ(li, &wl->list);
3701
3702 return 1;
3703
3704fail_wl_s:
3705 free(wl->s);
3706fail_wl:
3707 free(wl);
3708 return 0;
3709}
3710
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003711/* print a string of text buffer to <out>. The format is :
3712 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3713 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3714 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3715 */
3716int dump_text(struct chunk *out, const char *buf, int bsize)
3717{
3718 unsigned char c;
3719 int ptr = 0;
3720
3721 while (buf[ptr] && ptr < bsize) {
3722 c = buf[ptr];
3723 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
3724 if (out->len > out->size - 1)
3725 break;
3726 out->str[out->len++] = c;
3727 }
3728 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
3729 if (out->len > out->size - 2)
3730 break;
3731 out->str[out->len++] = '\\';
3732 switch (c) {
3733 case ' ': c = ' '; break;
3734 case '\t': c = 't'; break;
3735 case '\n': c = 'n'; break;
3736 case '\r': c = 'r'; break;
3737 case '\e': c = 'e'; break;
3738 case '\\': c = '\\'; break;
3739 case '=': c = '='; break;
3740 }
3741 out->str[out->len++] = c;
3742 }
3743 else {
3744 if (out->len > out->size - 4)
3745 break;
3746 out->str[out->len++] = '\\';
3747 out->str[out->len++] = 'x';
3748 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3749 out->str[out->len++] = hextab[c & 0xF];
3750 }
3751 ptr++;
3752 }
3753
3754 return ptr;
3755}
3756
3757/* print a buffer in hexa.
3758 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3759 */
3760int dump_binary(struct chunk *out, const char *buf, int bsize)
3761{
3762 unsigned char c;
3763 int ptr = 0;
3764
3765 while (ptr < bsize) {
3766 c = buf[ptr];
3767
3768 if (out->len > out->size - 2)
3769 break;
3770 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3771 out->str[out->len++] = hextab[c & 0xF];
3772
3773 ptr++;
3774 }
3775 return ptr;
3776}
3777
3778/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3779 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3780 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3781 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3782 * lines are respected within the limit of 70 output chars. Lines that are
3783 * continuation of a previous truncated line begin with "+" instead of " "
3784 * after the offset. The new pointer is returned.
3785 */
3786int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3787 int *line, int ptr)
3788{
3789 int end;
3790 unsigned char c;
3791
3792 end = out->len + 80;
3793 if (end > out->size)
3794 return ptr;
3795
3796 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3797
3798 while (ptr < len && ptr < bsize) {
3799 c = buf[ptr];
3800 if (isprint(c) && isascii(c) && c != '\\') {
3801 if (out->len > end - 2)
3802 break;
3803 out->str[out->len++] = c;
3804 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3805 if (out->len > end - 3)
3806 break;
3807 out->str[out->len++] = '\\';
3808 switch (c) {
3809 case '\t': c = 't'; break;
3810 case '\n': c = 'n'; break;
3811 case '\r': c = 'r'; break;
3812 case '\e': c = 'e'; break;
3813 case '\\': c = '\\'; break;
3814 }
3815 out->str[out->len++] = c;
3816 } else {
3817 if (out->len > end - 5)
3818 break;
3819 out->str[out->len++] = '\\';
3820 out->str[out->len++] = 'x';
3821 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3822 out->str[out->len++] = hextab[c & 0xF];
3823 }
3824 if (buf[ptr++] == '\n') {
3825 /* we had a line break, let's return now */
3826 out->str[out->len++] = '\n';
3827 *line = ptr;
3828 return ptr;
3829 }
3830 }
3831 /* we have an incomplete line, we return it as-is */
3832 out->str[out->len++] = '\n';
3833 return ptr;
3834}
3835
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003836/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02003837 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
3838 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003839 */
Willy Tarreaued936c52017-04-27 18:03:20 +02003840void debug_hexdump(FILE *out, const char *pfx, const char *buf,
3841 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003842{
Willy Tarreau73459792017-04-11 07:58:08 +02003843 unsigned int i;
3844 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003845
3846 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3847 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02003848 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003849 for (j = 0; j < 8; j++) {
3850 if (b + j >= 0 && b + j < len)
3851 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3852 else
3853 fprintf(out, " ");
3854 }
3855
3856 if (b + j >= 0 && b + j < len)
3857 fputc('-', out);
3858 else
3859 fputc(' ', out);
3860
3861 for (j = 8; j < 16; j++) {
3862 if (b + j >= 0 && b + j < len)
3863 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3864 else
3865 fprintf(out, " ");
3866 }
3867
3868 fprintf(out, " ");
3869 for (j = 0; j < 16; j++) {
3870 if (b + j >= 0 && b + j < len) {
3871 if (isprint((unsigned char)buf[b + j]))
3872 fputc((unsigned char)buf[b + j], out);
3873 else
3874 fputc('.', out);
3875 }
3876 else
3877 fputc(' ', out);
3878 }
3879 fputc('\n', out);
3880 }
3881}
3882
Willy Tarreau12963822017-10-24 10:54:08 +02003883/* do nothing, just a placeholder for debugging calls, the real one is in trace.c */
3884__attribute__((weak,format(printf, 1, 2)))
3885void trace(char *msg, ...)
3886{
3887}
3888
Willy Tarreaubaaee002006-06-26 02:48:02 +02003889/*
3890 * Local variables:
3891 * c-indent-level: 8
3892 * c-basic-offset: 8
3893 * End:
3894 */