blob: 99f7066bb867b2049458e89e425bddc8fc2be7c2 [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/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200595 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
596 * If an invalid character is found, a pointer to it is returned.
597 * If everything is fine, NULL is returned.
598 */
599const char *invalid_domainchar(const char *name) {
600
601 if (!*name)
602 return name;
603
604 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100605 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200606 *name != '_' && *name != '-')
607 return name;
608
609 name++;
610 }
611
612 return NULL;
613}
614
615/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100616 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100617 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
618 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
619 * the function tries to guess the address family from the syntax. If the
620 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100621 * string is assumed to contain only an address, no port. The address can be a
622 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
623 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
624 * The return address will only have the address family and the address set,
625 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100626 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
627 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100628 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200629 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100630struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200631{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100632 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100633 /* max IPv6 length, including brackets and terminating NULL */
634 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100635 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100636
637 /* check IPv6 with square brackets */
638 if (str[0] == '[') {
639 size_t iplength = strlen(str);
640
641 if (iplength < 4) {
642 /* minimal size is 4 when using brackets "[::]" */
643 goto fail;
644 }
645 else if (iplength >= sizeof(tmpip)) {
646 /* IPv6 literal can not be larger than tmpip */
647 goto fail;
648 }
649 else {
650 if (str[iplength - 1] != ']') {
651 /* if address started with bracket, it should end with bracket */
652 goto fail;
653 }
654 else {
655 memcpy(tmpip, str + 1, iplength - 2);
656 tmpip[iplength - 2] = '\0';
657 str = tmpip;
658 }
659 }
660 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100661
Willy Tarreaufab5a432011-03-04 15:31:53 +0100662 /* Any IPv6 address */
663 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100664 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
665 sa->ss_family = AF_INET6;
666 else if (sa->ss_family != AF_INET6)
667 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100668 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100669 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100670 }
671
Willy Tarreau24709282013-03-10 21:32:12 +0100672 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100673 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100674 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
675 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100676 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100677 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100678 }
679
680 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100681 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
682 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100683 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100684 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100685 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100686 }
687
688 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100689 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
690 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100691 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100692 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100693 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100694 }
695
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100696 if (!resolve)
697 return NULL;
698
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200699 if (!dns_hostname_validation(str, NULL))
700 return NULL;
701
David du Colombierd5f43282011-03-17 10:40:16 +0100702#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200703 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100704 struct addrinfo hints, *result;
705
706 memset(&result, 0, sizeof(result));
707 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100708 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100709 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200710 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100711 hints.ai_protocol = 0;
712
713 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100714 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
715 sa->ss_family = result->ai_family;
716 else if (sa->ss_family != result->ai_family)
717 goto fail;
718
David du Colombierd5f43282011-03-17 10:40:16 +0100719 switch (result->ai_family) {
720 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100721 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100722 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100723 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100724 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100726 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100727 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100728 }
729 }
730
Sean Carey58ea0392013-02-15 23:39:18 +0100731 if (result)
732 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100733 }
David du Colombierd5f43282011-03-17 10:40:16 +0100734#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200735 /* try to resolve an IPv4/IPv6 hostname */
736 he = gethostbyname(str);
737 if (he) {
738 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
739 sa->ss_family = he->h_addrtype;
740 else if (sa->ss_family != he->h_addrtype)
741 goto fail;
742
743 switch (sa->ss_family) {
744 case AF_INET:
745 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100746 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200747 return sa;
748 case AF_INET6:
749 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100750 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200751 return sa;
752 }
753 }
754
David du Colombierd5f43282011-03-17 10:40:16 +0100755 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100756 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100757 return NULL;
758}
759
760/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100761 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
762 * range or offset consisting in two integers that the caller will have to
763 * check to find the relevant input format. The following format are supported :
764 *
765 * String format | address | port | low | high
766 * addr | <addr> | 0 | 0 | 0
767 * addr: | <addr> | 0 | 0 | 0
768 * addr:port | <addr> | <port> | <port> | <port>
769 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
770 * addr:+port | <addr> | <port> | 0 | <port>
771 * addr:-port | <addr> |-<port> | <port> | 0
772 *
773 * The detection of a port range or increment by the caller is made by
774 * comparing <low> and <high>. If both are equal, then port 0 means no port
775 * was specified. The caller may pass NULL for <low> and <high> if it is not
776 * interested in retrieving port ranges.
777 *
778 * Note that <addr> above may also be :
779 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
780 * - "*" => family will be AF_INET and address will be INADDR_ANY
781 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
782 * - a host name => family and address will depend on host name resolving.
783 *
Willy Tarreau24709282013-03-10 21:32:12 +0100784 * A prefix may be passed in before the address above to force the family :
785 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
786 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
787 * - "unix@" => force address to be a path to a UNIX socket even if the
788 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200789 * - 'abns@' -> force address to belong to the abstract namespace (Linux
790 * only). These sockets are just like Unix sockets but without
791 * the need for an underlying file system. The address is a
792 * string. Technically it's like a Unix socket with a zero in
793 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100794 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100795 *
mildisff5d5102015-10-26 18:50:08 +0100796 * IPv6 addresses can be declared with or without square brackets. When using
797 * square brackets for IPv6 addresses, the port separator (colon) is optional.
798 * If not using square brackets, and in order to avoid any ambiguity with
799 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
800 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
801 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100802 *
803 * If <pfx> is non-null, it is used as a string prefix before any path-based
804 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100805 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200806 * if <fqdn> is non-null, it will be filled with :
807 * - a pointer to the FQDN of the server name to resolve if there's one, and
808 * that the caller will have to free(),
809 * - NULL if there was an explicit address that doesn't require resolution.
810 *
Willy Tarreauceccdd72016-11-02 22:27:10 +0100811 * Hostnames are only resolved if <resolve> is non-null. Note that if <resolve>
812 * is null, <fqdn> is still honnored so it is possible for the caller to know
813 * whether a resolution failed by setting <resolve> to null and checking if
814 * <fqdn> was filled, indicating the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200815 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100816 * When a file descriptor is passed, its value is put into the s_addr part of
817 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100818 */
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100819struct 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 +0100820{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100821 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100822 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100823 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100824 char *port1, *port2;
825 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200826 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100827
828 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200829 if (fqdn)
830 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200831
Willy Tarreaudad36a32013-03-11 01:20:04 +0100832 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100833 if (str2 == NULL) {
834 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100835 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100836 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200837
Willy Tarreau9f69f462015-09-08 16:01:25 +0200838 if (!*str2) {
839 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
840 goto out;
841 }
842
Willy Tarreau24709282013-03-10 21:32:12 +0100843 memset(&ss, 0, sizeof(ss));
844
845 if (strncmp(str2, "unix@", 5) == 0) {
846 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200847 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100848 ss.ss_family = AF_UNIX;
849 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200850 else if (strncmp(str2, "abns@", 5) == 0) {
851 str2 += 5;
852 abstract = 1;
853 ss.ss_family = AF_UNIX;
854 }
Willy Tarreau24709282013-03-10 21:32:12 +0100855 else if (strncmp(str2, "ipv4@", 5) == 0) {
856 str2 += 5;
857 ss.ss_family = AF_INET;
858 }
859 else if (strncmp(str2, "ipv6@", 5) == 0) {
860 str2 += 5;
861 ss.ss_family = AF_INET6;
862 }
863 else if (*str2 == '/') {
864 ss.ss_family = AF_UNIX;
865 }
866 else
867 ss.ss_family = AF_UNSPEC;
868
Willy Tarreau40aa0702013-03-10 23:51:38 +0100869 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
870 char *endptr;
871
872 str2 += 3;
873 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
874
875 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100876 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100877 goto out;
878 }
879
880 /* we return AF_UNSPEC if we use a file descriptor number */
881 ss.ss_family = AF_UNSPEC;
882 }
883 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100884 int prefix_path_len;
885 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200886 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100887
888 /* complete unix socket path name during startup or soft-restart is
889 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
890 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200891 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100892 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
893 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
894
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200895 adr_len = strlen(str2);
896 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100897 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
898 goto out;
899 }
900
Willy Tarreauccfccef2014-05-10 01:49:15 +0200901 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
902 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200903 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100904 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200905 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100906 }
Willy Tarreau24709282013-03-10 21:32:12 +0100907 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +0100908 char *end = str2 + strlen(str2);
909 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200910
mildisff5d5102015-10-26 18:50:08 +0100911 /* search for : or ] whatever comes first */
912 for (chr = end-1; chr > str2; chr--) {
913 if (*chr == ']' || *chr == ':')
914 break;
915 }
916
917 if (*chr == ':') {
918 /* Found a colon before a closing-bracket, must be a port separator.
919 * This guarantee backward compatibility.
920 */
921 *chr++ = '\0';
922 port1 = chr;
923 }
924 else {
925 /* Either no colon and no closing-bracket
926 * or directly ending with a closing-bracket.
927 * However, no port.
928 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100929 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100930 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200931
Willy Tarreaua39d1992013-04-01 20:37:42 +0200932 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100933 port2 = strchr(port1, '-');
934 if (port2)
935 *port2++ = '\0';
936 else
937 port2 = port1;
938 portl = atoi(port1);
939 porth = atoi(port2);
940 porta = portl;
941 }
942 else if (*port1 == '-') { /* negative offset */
943 portl = atoi(port1 + 1);
944 porta = -portl;
945 }
946 else if (*port1 == '+') { /* positive offset */
947 porth = atoi(port1 + 1);
948 porta = porth;
949 }
950 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100951 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100952 goto out;
953 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100954
955 /* first try to parse the IP without resolving. If it fails, it
956 * tells us we need to keep a copy of the FQDN to resolve later
957 * and to enable DNS. In this case we can proceed if <fqdn> is
958 * set or if resolve is set, otherwise it's an error.
959 */
960 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreau7b760c92017-01-06 19:23:20 +0100961 if ((!resolve && !fqdn) ||
Willy Tarreauceccdd72016-11-02 22:27:10 +0100962 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
963 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
964 goto out;
965 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200966
Willy Tarreauceccdd72016-11-02 22:27:10 +0100967 if (fqdn) {
968 if (str2 != back)
969 memmove(back, str2, strlen(str2) + 1);
970 *fqdn = back;
971 back = NULL;
972 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200973 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100974 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100975 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100976
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100977 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100978 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100979 if (port)
980 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100981 if (low)
982 *low = portl;
983 if (high)
984 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100985 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100986 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200987}
988
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100989/* converts <str> to a struct in_addr containing a network mask. It can be
990 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
991 * if the conversion succeeds otherwise non-zero.
992 */
993int str2mask(const char *str, struct in_addr *mask)
994{
995 if (strchr(str, '.') != NULL) { /* dotted notation */
996 if (!inet_pton(AF_INET, str, mask))
997 return 0;
998 }
999 else { /* mask length */
1000 char *err;
1001 unsigned long len = strtol(str, &err, 10);
1002
1003 if (!*str || (err && *err) || (unsigned)len > 32)
1004 return 0;
1005 if (len)
1006 mask->s_addr = htonl(~0UL << (32 - len));
1007 else
1008 mask->s_addr = 0;
1009 }
1010 return 1;
1011}
1012
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001013/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1014 * succeeds otherwise zero.
1015 */
1016int cidr2dotted(int cidr, struct in_addr *mask) {
1017
1018 if (cidr < 0 || cidr > 32)
1019 return 0;
1020
1021 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1022 return 1;
1023}
1024
Thierry Fournier70473a52016-02-17 17:12:14 +01001025/* Convert mask from bit length form to in_addr form.
1026 * This function never fails.
1027 */
1028void len2mask4(int len, struct in_addr *addr)
1029{
1030 if (len >= 32) {
1031 addr->s_addr = 0xffffffff;
1032 return;
1033 }
1034 if (len <= 0) {
1035 addr->s_addr = 0x00000000;
1036 return;
1037 }
1038 addr->s_addr = 0xffffffff << (32 - len);
1039 addr->s_addr = htonl(addr->s_addr);
1040}
1041
1042/* Convert mask from bit length form to in6_addr form.
1043 * This function never fails.
1044 */
1045void len2mask6(int len, struct in6_addr *addr)
1046{
1047 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1048 len -= 32;
1049 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1050 len -= 32;
1051 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1052 len -= 32;
1053 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1054}
1055
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001056/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001057 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001058 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1059 * is optionnal and either in the dotted or CIDR notation.
1060 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1061 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001062int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001063{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001064 __label__ out_free, out_err;
1065 char *c, *s;
1066 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001067
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001068 s = strdup(str);
1069 if (!s)
1070 return 0;
1071
Willy Tarreaubaaee002006-06-26 02:48:02 +02001072 memset(mask, 0, sizeof(*mask));
1073 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001074
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001075 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001076 *c++ = '\0';
1077 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001078 if (!str2mask(c, mask))
1079 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001080 }
1081 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001082 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001083 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001084 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001085 struct hostent *he;
1086
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001087 if (!resolve)
1088 goto out_err;
1089
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001090 if ((he = gethostbyname(s)) == NULL) {
1091 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001092 }
1093 else
1094 *addr = *(struct in_addr *) *(he->h_addr_list);
1095 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001096
1097 ret_val = 1;
1098 out_free:
1099 free(s);
1100 return ret_val;
1101 out_err:
1102 ret_val = 0;
1103 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001104}
1105
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001106
1107/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001108 * converts <str> to two struct in6_addr* which must be pre-allocated.
1109 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1110 * is an optionnal number of bits (128 being the default).
1111 * Returns 1 if OK, 0 if error.
1112 */
1113int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1114{
1115 char *c, *s;
1116 int ret_val = 0;
1117 char *err;
1118 unsigned long len = 128;
1119
1120 s = strdup(str);
1121 if (!s)
1122 return 0;
1123
1124 memset(mask, 0, sizeof(*mask));
1125 memset(addr, 0, sizeof(*addr));
1126
1127 if ((c = strrchr(s, '/')) != NULL) {
1128 *c++ = '\0'; /* c points to the mask */
1129 if (!*c)
1130 goto out_free;
1131
1132 len = strtoul(c, &err, 10);
1133 if ((err && *err) || (unsigned)len > 128)
1134 goto out_free;
1135 }
1136 *mask = len; /* OK we have a valid mask in <len> */
1137
1138 if (!inet_pton(AF_INET6, s, addr))
1139 goto out_free;
1140
1141 ret_val = 1;
1142 out_free:
1143 free(s);
1144 return ret_val;
1145}
1146
1147
1148/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001149 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001150 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001151int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001152{
1153 int saw_digit, octets, ch;
1154 u_char tmp[4], *tp;
1155 const char *cp = addr;
1156
1157 saw_digit = 0;
1158 octets = 0;
1159 *(tp = tmp) = 0;
1160
1161 while (*addr) {
1162 unsigned char digit = (ch = *addr++) - '0';
1163 if (digit > 9 && ch != '.')
1164 break;
1165 if (digit <= 9) {
1166 u_int new = *tp * 10 + digit;
1167 if (new > 255)
1168 return 0;
1169 *tp = new;
1170 if (!saw_digit) {
1171 if (++octets > 4)
1172 return 0;
1173 saw_digit = 1;
1174 }
1175 } else if (ch == '.' && saw_digit) {
1176 if (octets == 4)
1177 return 0;
1178 *++tp = 0;
1179 saw_digit = 0;
1180 } else
1181 return 0;
1182 }
1183
1184 if (octets < 4)
1185 return 0;
1186
1187 memcpy(&dst->s_addr, tmp, 4);
1188 return addr-cp-1;
1189}
1190
1191/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001192 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1193 * <out> contain the code of the dectected scheme, the start and length of
1194 * the hostname. Actually only http and https are supported. <out> can be NULL.
1195 * This function returns the consumed length. It is useful if you parse complete
1196 * url like http://host:port/path, because the consumed length corresponds to
1197 * the first character of the path. If the conversion fails, it returns -1.
1198 *
1199 * This function tries to resolve the DNS name if haproxy is in starting mode.
1200 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001201 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001202int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001203{
1204 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001205 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001206 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001207 unsigned long long int http_code = 0;
1208 int default_port;
1209 struct hostent *he;
1210 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001211
1212 /* Firstly, try to find :// pattern */
1213 while (curr < url+ulen && url_code != 0x3a2f2f) {
1214 url_code = ((url_code & 0xffff) << 8);
1215 url_code += (unsigned char)*curr++;
1216 }
1217
1218 /* Secondly, if :// pattern is found, verify parsed stuff
1219 * before pattern is matching our http pattern.
1220 * If so parse ip address and port in uri.
1221 *
1222 * WARNING: Current code doesn't support dynamic async dns resolver.
1223 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001224 if (url_code != 0x3a2f2f)
1225 return -1;
1226
1227 /* Copy scheme, and utrn to lower case. */
1228 while (cp < curr - 3)
1229 http_code = (http_code << 8) + *cp++;
1230 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001231
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001232 /* HTTP or HTTPS url matching */
1233 if (http_code == 0x2020202068747470ULL) {
1234 default_port = 80;
1235 if (out)
1236 out->scheme = SCH_HTTP;
1237 }
1238 else if (http_code == 0x2020206874747073ULL) {
1239 default_port = 443;
1240 if (out)
1241 out->scheme = SCH_HTTPS;
1242 }
1243 else
1244 return -1;
1245
1246 /* If the next char is '[', the host address is IPv6. */
1247 if (*curr == '[') {
1248 curr++;
1249
1250 /* Check trash size */
1251 if (trash.size < ulen)
1252 return -1;
1253
1254 /* Look for ']' and copy the address in a trash buffer. */
1255 p = trash.str;
1256 for (end = curr;
1257 end < url + ulen && *end != ']';
1258 end++, p++)
1259 *p = *end;
1260 if (*end != ']')
1261 return -1;
1262 *p = '\0';
1263
1264 /* Update out. */
1265 if (out) {
1266 out->host = curr;
1267 out->host_len = end - curr;
1268 }
1269
1270 /* Try IPv6 decoding. */
1271 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1272 return -1;
1273 end++;
1274
1275 /* Decode port. */
1276 if (*end == ':') {
1277 end++;
1278 default_port = read_uint(&end, url + ulen);
1279 }
1280 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1281 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1282 return end - url;
1283 }
1284 else {
1285 /* We are looking for IP address. If you want to parse and
1286 * resolve hostname found in url, you can use str2sa_range(), but
1287 * be warned this can slow down global daemon performances
1288 * while handling lagging dns responses.
1289 */
1290 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1291 if (ret) {
1292 /* Update out. */
1293 if (out) {
1294 out->host = curr;
1295 out->host_len = ret;
1296 }
1297
1298 curr += ret;
1299
1300 /* Decode port. */
1301 if (*curr == ':') {
1302 curr++;
1303 default_port = read_uint(&curr, url + ulen);
1304 }
1305 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1306
1307 /* Set family. */
1308 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1309 return curr - url;
1310 }
1311 else if (global.mode & MODE_STARTING) {
1312 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1313 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001314 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001315
1316 /* look for : or / or end */
1317 for (end = curr;
1318 end < url + ulen && *end != '/' && *end != ':';
1319 end++);
1320 memcpy(trash.str, curr, end - curr);
1321 trash.str[end - curr] = '\0';
1322
1323 /* try to resolve an IPv4/IPv6 hostname */
1324 he = gethostbyname(trash.str);
1325 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001326 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001327
1328 /* Update out. */
1329 if (out) {
1330 out->host = curr;
1331 out->host_len = end - curr;
1332 }
1333
1334 /* Decode port. */
1335 if (*end == ':') {
1336 end++;
1337 default_port = read_uint(&end, url + ulen);
1338 }
1339
1340 /* Copy IP address, set port and family. */
1341 switch (he->h_addrtype) {
1342 case AF_INET:
1343 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1344 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1345 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1346 return end - url;
1347
1348 case AF_INET6:
1349 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1350 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1351 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1352 return end - url;
1353 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001354 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001355 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001356 return -1;
1357}
1358
Willy Tarreau631f01c2011-09-05 00:36:48 +02001359/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1360 * address family is returned so that it's easy for the caller to adapt to the
1361 * output format. Zero is returned if the address family is not supported. -1
1362 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1363 * supported.
1364 */
1365int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1366{
1367
1368 void *ptr;
1369
1370 if (size < 5)
1371 return 0;
1372 *str = '\0';
1373
1374 switch (addr->ss_family) {
1375 case AF_INET:
1376 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1377 break;
1378 case AF_INET6:
1379 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1380 break;
1381 case AF_UNIX:
1382 memcpy(str, "unix", 5);
1383 return addr->ss_family;
1384 default:
1385 return 0;
1386 }
1387
1388 if (inet_ntop(addr->ss_family, ptr, str, size))
1389 return addr->ss_family;
1390
1391 /* failed */
1392 return -1;
1393}
1394
Simon Horman75ab8bd2014-06-16 09:39:41 +09001395/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1396 * address family is returned so that it's easy for the caller to adapt to the
1397 * output format. Zero is returned if the address family is not supported. -1
1398 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1399 * supported.
1400 */
1401int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1402{
1403
1404 uint16_t port;
1405
1406
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001407 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001408 return 0;
1409 *str = '\0';
1410
1411 switch (addr->ss_family) {
1412 case AF_INET:
1413 port = ((struct sockaddr_in *)addr)->sin_port;
1414 break;
1415 case AF_INET6:
1416 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1417 break;
1418 case AF_UNIX:
1419 memcpy(str, "unix", 5);
1420 return addr->ss_family;
1421 default:
1422 return 0;
1423 }
1424
1425 snprintf(str, size, "%u", ntohs(port));
1426 return addr->ss_family;
1427}
1428
Willy Tarreau16e01562016-08-09 16:46:18 +02001429/* check if the given address is local to the system or not. It will return
1430 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1431 * it is. We don't want to iterate over all interfaces for this (and it is not
1432 * portable). So instead we try to bind in UDP to this address on a free non
1433 * privileged port and to connect to the same address, port 0 (connect doesn't
1434 * care). If it succeeds, we own the address. Note that non-inet addresses are
1435 * considered local since they're most likely AF_UNIX.
1436 */
1437int addr_is_local(const struct netns_entry *ns,
1438 const struct sockaddr_storage *orig)
1439{
1440 struct sockaddr_storage addr;
1441 int result;
1442 int fd;
1443
1444 if (!is_inet_addr(orig))
1445 return 1;
1446
1447 memcpy(&addr, orig, sizeof(addr));
1448 set_host_port(&addr, 0);
1449
1450 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1451 if (fd < 0)
1452 return -1;
1453
1454 result = -1;
1455 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1456 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1457 result = 0; // fail, non-local address
1458 else
1459 result = 1; // success, local address
1460 }
1461 else {
1462 if (errno == EADDRNOTAVAIL)
1463 result = 0; // definitely not local :-)
1464 }
1465 close(fd);
1466
1467 return result;
1468}
1469
Willy Tarreaubaaee002006-06-26 02:48:02 +02001470/* will try to encode the string <string> replacing all characters tagged in
1471 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1472 * prefixed by <escape>, and will store the result between <start> (included)
1473 * and <stop> (excluded), and will always terminate the string with a '\0'
1474 * before <stop>. The position of the '\0' is returned if the conversion
1475 * completes. If bytes are missing between <start> and <stop>, then the
1476 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1477 * cannot even be stored so we return <start> without writing the 0.
1478 * The input string must also be zero-terminated.
1479 */
1480const char hextab[16] = "0123456789ABCDEF";
1481char *encode_string(char *start, char *stop,
1482 const char escape, const fd_set *map,
1483 const char *string)
1484{
1485 if (start < stop) {
1486 stop--; /* reserve one byte for the final '\0' */
1487 while (start < stop && *string != '\0') {
1488 if (!FD_ISSET((unsigned char)(*string), map))
1489 *start++ = *string;
1490 else {
1491 if (start + 3 >= stop)
1492 break;
1493 *start++ = escape;
1494 *start++ = hextab[(*string >> 4) & 15];
1495 *start++ = hextab[*string & 15];
1496 }
1497 string++;
1498 }
1499 *start = '\0';
1500 }
1501 return start;
1502}
1503
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001504/*
1505 * Same behavior as encode_string() above, except that it encodes chunk
1506 * <chunk> instead of a string.
1507 */
1508char *encode_chunk(char *start, char *stop,
1509 const char escape, const fd_set *map,
1510 const struct chunk *chunk)
1511{
1512 char *str = chunk->str;
1513 char *end = chunk->str + chunk->len;
1514
1515 if (start < stop) {
1516 stop--; /* reserve one byte for the final '\0' */
1517 while (start < stop && str < end) {
1518 if (!FD_ISSET((unsigned char)(*str), map))
1519 *start++ = *str;
1520 else {
1521 if (start + 3 >= stop)
1522 break;
1523 *start++ = escape;
1524 *start++ = hextab[(*str >> 4) & 15];
1525 *start++ = hextab[*str & 15];
1526 }
1527 str++;
1528 }
1529 *start = '\0';
1530 }
1531 return start;
1532}
1533
Dragan Dosen0edd1092016-02-12 13:23:02 +01001534/*
1535 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001536 * character. The input <string> must be zero-terminated. The result will
1537 * be stored between <start> (included) and <stop> (excluded). This
1538 * function will always try to terminate the resulting string with a '\0'
1539 * before <stop>, and will return its position if the conversion
1540 * completes.
1541 */
1542char *escape_string(char *start, char *stop,
1543 const char escape, const fd_set *map,
1544 const char *string)
1545{
1546 if (start < stop) {
1547 stop--; /* reserve one byte for the final '\0' */
1548 while (start < stop && *string != '\0') {
1549 if (!FD_ISSET((unsigned char)(*string), map))
1550 *start++ = *string;
1551 else {
1552 if (start + 2 >= stop)
1553 break;
1554 *start++ = escape;
1555 *start++ = *string;
1556 }
1557 string++;
1558 }
1559 *start = '\0';
1560 }
1561 return start;
1562}
1563
1564/*
1565 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001566 * character. <chunk> contains the input to be escaped. The result will be
1567 * stored between <start> (included) and <stop> (excluded). The function
1568 * will always try to terminate the resulting string with a '\0' before
1569 * <stop>, and will return its position if the conversion completes.
1570 */
1571char *escape_chunk(char *start, char *stop,
1572 const char escape, const fd_set *map,
1573 const struct chunk *chunk)
1574{
1575 char *str = chunk->str;
1576 char *end = chunk->str + chunk->len;
1577
1578 if (start < stop) {
1579 stop--; /* reserve one byte for the final '\0' */
1580 while (start < stop && str < end) {
1581 if (!FD_ISSET((unsigned char)(*str), map))
1582 *start++ = *str;
1583 else {
1584 if (start + 2 >= stop)
1585 break;
1586 *start++ = escape;
1587 *start++ = *str;
1588 }
1589 str++;
1590 }
1591 *start = '\0';
1592 }
1593 return start;
1594}
1595
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001596/* Check a string for using it in a CSV output format. If the string contains
1597 * one of the following four char <">, <,>, CR or LF, the string is
1598 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1599 * <str> is the input string to be escaped. The function assumes that
1600 * the input string is null-terminated.
1601 *
1602 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001603 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001604 * format.
1605 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001606 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001607 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001608 * If <quote> is 1, the converter puts the quotes only if any reserved character
1609 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001610 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001611 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001612 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001613 * The function returns the converted string on its output. If an error
1614 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001615 * for using the function directly as printf() argument.
1616 *
1617 * If the output buffer is too short to contain the input string, the result
1618 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001619 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001620 * This function appends the encoding to the existing output chunk, and it
1621 * guarantees that it starts immediately at the first available character of
1622 * the chunk. Please use csv_enc() instead if you want to replace the output
1623 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001624 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001625const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001626{
1627 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001628 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001629 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001630
Willy Tarreaub631c292016-01-08 10:04:08 +01001631 if (quote == 1) {
1632 /* automatic quoting: first verify if we'll have to quote the string */
1633 if (!strpbrk(str, "\n\r,\""))
1634 quote = 0;
1635 }
1636
1637 if (quote)
1638 *ptr++ = '"';
1639
Willy Tarreau898529b2016-01-06 18:07:04 +01001640 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1641 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001642 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001643 ptr++;
1644 if (ptr >= end - 2) {
1645 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001646 break;
1647 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001648 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001649 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001650 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001651 str++;
1652 }
1653
Willy Tarreaub631c292016-01-08 10:04:08 +01001654 if (quote)
1655 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001656
Willy Tarreau898529b2016-01-06 18:07:04 +01001657 *ptr = '\0';
1658 output->len = ptr - output->str;
1659 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001660}
1661
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001662/* Decode an URL-encoded string in-place. The resulting string might
1663 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001664 * aborted, the string is truncated before the issue and a negative value is
1665 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001666 */
1667int url_decode(char *string)
1668{
1669 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001670 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001671
1672 in = string;
1673 out = string;
1674 while (*in) {
1675 switch (*in) {
1676 case '+' :
1677 *out++ = ' ';
1678 break;
1679 case '%' :
1680 if (!ishex(in[1]) || !ishex(in[2]))
1681 goto end;
1682 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1683 in += 2;
1684 break;
1685 default:
1686 *out++ = *in;
1687 break;
1688 }
1689 in++;
1690 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001691 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001692 end:
1693 *out = 0;
1694 return ret;
1695}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001696
Willy Tarreau6911fa42007-03-04 18:06:08 +01001697unsigned int str2ui(const char *s)
1698{
1699 return __str2ui(s);
1700}
1701
1702unsigned int str2uic(const char *s)
1703{
1704 return __str2uic(s);
1705}
1706
1707unsigned int strl2ui(const char *s, int len)
1708{
1709 return __strl2ui(s, len);
1710}
1711
1712unsigned int strl2uic(const char *s, int len)
1713{
1714 return __strl2uic(s, len);
1715}
1716
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001717unsigned int read_uint(const char **s, const char *end)
1718{
1719 return __read_uint(s, end);
1720}
1721
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001722/* This function reads an unsigned integer from the string pointed to by <s> and
1723 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1724 * function automatically stops at <end>. If the number overflows, the 2^64-1
1725 * value is returned.
1726 */
1727unsigned long long int read_uint64(const char **s, const char *end)
1728{
1729 const char *ptr = *s;
1730 unsigned long long int i = 0, tmp;
1731 unsigned int j;
1732
1733 while (ptr < end) {
1734
1735 /* read next char */
1736 j = *ptr - '0';
1737 if (j > 9)
1738 goto read_uint64_end;
1739
1740 /* add char to the number and check overflow. */
1741 tmp = i * 10;
1742 if (tmp / 10 != i) {
1743 i = ULLONG_MAX;
1744 goto read_uint64_eat;
1745 }
1746 if (ULLONG_MAX - tmp < j) {
1747 i = ULLONG_MAX;
1748 goto read_uint64_eat;
1749 }
1750 i = tmp + j;
1751 ptr++;
1752 }
1753read_uint64_eat:
1754 /* eat each numeric char */
1755 while (ptr < end) {
1756 if ((unsigned int)(*ptr - '0') > 9)
1757 break;
1758 ptr++;
1759 }
1760read_uint64_end:
1761 *s = ptr;
1762 return i;
1763}
1764
1765/* This function reads an integer from the string pointed to by <s> and returns
1766 * it. The <s> pointer is adjusted to point to the first unread char. The function
1767 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1768 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1769 * returned.
1770 */
1771long long int read_int64(const char **s, const char *end)
1772{
1773 unsigned long long int i = 0;
1774 int neg = 0;
1775
1776 /* Look for minus char. */
1777 if (**s == '-') {
1778 neg = 1;
1779 (*s)++;
1780 }
1781 else if (**s == '+')
1782 (*s)++;
1783
1784 /* convert as positive number. */
1785 i = read_uint64(s, end);
1786
1787 if (neg) {
1788 if (i > 0x8000000000000000ULL)
1789 return LLONG_MIN;
1790 return -i;
1791 }
1792 if (i > 0x7fffffffffffffffULL)
1793 return LLONG_MAX;
1794 return i;
1795}
1796
Willy Tarreau6911fa42007-03-04 18:06:08 +01001797/* This one is 7 times faster than strtol() on athlon with checks.
1798 * It returns the value of the number composed of all valid digits read,
1799 * and can process negative numbers too.
1800 */
1801int strl2ic(const char *s, int len)
1802{
1803 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001804 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001805
1806 if (len > 0) {
1807 if (*s != '-') {
1808 /* positive number */
1809 while (len-- > 0) {
1810 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001811 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001812 if (j > 9)
1813 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001814 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001815 }
1816 } else {
1817 /* negative number */
1818 s++;
1819 while (--len > 0) {
1820 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001821 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001822 if (j > 9)
1823 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001824 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001825 }
1826 }
1827 }
1828 return i;
1829}
1830
1831
1832/* This function reads exactly <len> chars from <s> and converts them to a
1833 * signed integer which it stores into <ret>. It accurately detects any error
1834 * (truncated string, invalid chars, overflows). It is meant to be used in
1835 * applications designed for hostile environments. It returns zero when the
1836 * number has successfully been converted, non-zero otherwise. When an error
1837 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1838 * faster than strtol().
1839 */
1840int strl2irc(const char *s, int len, int *ret)
1841{
1842 int i = 0;
1843 int j;
1844
1845 if (!len)
1846 return 1;
1847
1848 if (*s != '-') {
1849 /* positive number */
1850 while (len-- > 0) {
1851 j = (*s++) - '0';
1852 if (j > 9) return 1; /* invalid char */
1853 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1854 i = i * 10;
1855 if (i + j < i) return 1; /* check for addition overflow */
1856 i = i + j;
1857 }
1858 } else {
1859 /* negative number */
1860 s++;
1861 while (--len > 0) {
1862 j = (*s++) - '0';
1863 if (j > 9) return 1; /* invalid char */
1864 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1865 i = i * 10;
1866 if (i - j > i) return 1; /* check for subtract overflow */
1867 i = i - j;
1868 }
1869 }
1870 *ret = i;
1871 return 0;
1872}
1873
1874
1875/* This function reads exactly <len> chars from <s> and converts them to a
1876 * signed integer which it stores into <ret>. It accurately detects any error
1877 * (truncated string, invalid chars, overflows). It is meant to be used in
1878 * applications designed for hostile environments. It returns zero when the
1879 * number has successfully been converted, non-zero otherwise. When an error
1880 * is returned, the <ret> value is left untouched. It is about 3 times slower
1881 * than str2irc().
1882 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001883
1884int strl2llrc(const char *s, int len, long long *ret)
1885{
1886 long long i = 0;
1887 int j;
1888
1889 if (!len)
1890 return 1;
1891
1892 if (*s != '-') {
1893 /* positive number */
1894 while (len-- > 0) {
1895 j = (*s++) - '0';
1896 if (j > 9) return 1; /* invalid char */
1897 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1898 i = i * 10LL;
1899 if (i + j < i) return 1; /* check for addition overflow */
1900 i = i + j;
1901 }
1902 } else {
1903 /* negative number */
1904 s++;
1905 while (--len > 0) {
1906 j = (*s++) - '0';
1907 if (j > 9) return 1; /* invalid char */
1908 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1909 i = i * 10LL;
1910 if (i - j > i) return 1; /* check for subtract overflow */
1911 i = i - j;
1912 }
1913 }
1914 *ret = i;
1915 return 0;
1916}
1917
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001918/* This function is used with pat_parse_dotted_ver(). It converts a string
1919 * composed by two number separated by a dot. Each part must contain in 16 bits
1920 * because internally they will be represented as a 32-bit quantity stored in
1921 * a 64-bit integer. It returns zero when the number has successfully been
1922 * converted, non-zero otherwise. When an error is returned, the <ret> value
1923 * is left untouched.
1924 *
1925 * "1.3" -> 0x0000000000010003
1926 * "65535.65535" -> 0x00000000ffffffff
1927 */
1928int strl2llrc_dotted(const char *text, int len, long long *ret)
1929{
1930 const char *end = &text[len];
1931 const char *p;
1932 long long major, minor;
1933
1934 /* Look for dot. */
1935 for (p = text; p < end; p++)
1936 if (*p == '.')
1937 break;
1938
1939 /* Convert major. */
1940 if (strl2llrc(text, p - text, &major) != 0)
1941 return 1;
1942
1943 /* Check major. */
1944 if (major >= 65536)
1945 return 1;
1946
1947 /* Convert minor. */
1948 minor = 0;
1949 if (p < end)
1950 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1951 return 1;
1952
1953 /* Check minor. */
1954 if (minor >= 65536)
1955 return 1;
1956
1957 /* Compose value. */
1958 *ret = (major << 16) | (minor & 0xffff);
1959 return 0;
1960}
1961
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001962/* This function parses a time value optionally followed by a unit suffix among
1963 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1964 * expected by the caller. The computation does its best to avoid overflows.
1965 * The value is returned in <ret> if everything is fine, and a NULL is returned
1966 * by the function. In case of error, a pointer to the error is returned and
1967 * <ret> is left untouched. Values are automatically rounded up when needed.
1968 */
1969const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1970{
1971 unsigned imult, idiv;
1972 unsigned omult, odiv;
1973 unsigned value;
1974
1975 omult = odiv = 1;
1976
1977 switch (unit_flags & TIME_UNIT_MASK) {
1978 case TIME_UNIT_US: omult = 1000000; break;
1979 case TIME_UNIT_MS: omult = 1000; break;
1980 case TIME_UNIT_S: break;
1981 case TIME_UNIT_MIN: odiv = 60; break;
1982 case TIME_UNIT_HOUR: odiv = 3600; break;
1983 case TIME_UNIT_DAY: odiv = 86400; break;
1984 default: break;
1985 }
1986
1987 value = 0;
1988
1989 while (1) {
1990 unsigned int j;
1991
1992 j = *text - '0';
1993 if (j > 9)
1994 break;
1995 text++;
1996 value *= 10;
1997 value += j;
1998 }
1999
2000 imult = idiv = 1;
2001 switch (*text) {
2002 case '\0': /* no unit = default unit */
2003 imult = omult = idiv = odiv = 1;
2004 break;
2005 case 's': /* second = unscaled unit */
2006 break;
2007 case 'u': /* microsecond : "us" */
2008 if (text[1] == 's') {
2009 idiv = 1000000;
2010 text++;
2011 }
2012 break;
2013 case 'm': /* millisecond : "ms" or minute: "m" */
2014 if (text[1] == 's') {
2015 idiv = 1000;
2016 text++;
2017 } else
2018 imult = 60;
2019 break;
2020 case 'h': /* hour : "h" */
2021 imult = 3600;
2022 break;
2023 case 'd': /* day : "d" */
2024 imult = 86400;
2025 break;
2026 default:
2027 return text;
2028 break;
2029 }
2030
2031 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2032 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2033 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2034 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2035
2036 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2037 *ret = value;
2038 return NULL;
2039}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002040
Emeric Brun39132b22010-01-04 14:57:24 +01002041/* this function converts the string starting at <text> to an unsigned int
2042 * stored in <ret>. If an error is detected, the pointer to the unexpected
2043 * character is returned. If the conversio is succesful, NULL is returned.
2044 */
2045const char *parse_size_err(const char *text, unsigned *ret) {
2046 unsigned value = 0;
2047
2048 while (1) {
2049 unsigned int j;
2050
2051 j = *text - '0';
2052 if (j > 9)
2053 break;
2054 if (value > ~0U / 10)
2055 return text;
2056 value *= 10;
2057 if (value > (value + j))
2058 return text;
2059 value += j;
2060 text++;
2061 }
2062
2063 switch (*text) {
2064 case '\0':
2065 break;
2066 case 'K':
2067 case 'k':
2068 if (value > ~0U >> 10)
2069 return text;
2070 value = value << 10;
2071 break;
2072 case 'M':
2073 case 'm':
2074 if (value > ~0U >> 20)
2075 return text;
2076 value = value << 20;
2077 break;
2078 case 'G':
2079 case 'g':
2080 if (value > ~0U >> 30)
2081 return text;
2082 value = value << 30;
2083 break;
2084 default:
2085 return text;
2086 }
2087
Godbach58048a22015-01-28 17:36:16 +08002088 if (*text != '\0' && *++text != '\0')
2089 return text;
2090
Emeric Brun39132b22010-01-04 14:57:24 +01002091 *ret = value;
2092 return NULL;
2093}
2094
Willy Tarreau126d4062013-12-03 17:50:47 +01002095/*
2096 * Parse binary string written in hexadecimal (source) and store the decoded
2097 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2098 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002099 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002100 */
2101int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2102{
2103 int len;
2104 const char *p = source;
2105 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002106 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002107
2108 len = strlen(source);
2109 if (len % 2) {
2110 memprintf(err, "an even number of hex digit is expected");
2111 return 0;
2112 }
2113
2114 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002115
Willy Tarreau126d4062013-12-03 17:50:47 +01002116 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002117 *binstr = calloc(len, sizeof(char));
2118 if (!*binstr) {
2119 memprintf(err, "out of memory while loading string pattern");
2120 return 0;
2121 }
2122 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002123 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002124 else {
2125 if (*binstrlen < len) {
2126 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2127 len, *binstrlen);
2128 return 0;
2129 }
2130 alloc = 0;
2131 }
2132 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002133
2134 i = j = 0;
2135 while (j < len) {
2136 if (!ishex(p[i++]))
2137 goto bad_input;
2138 if (!ishex(p[i++]))
2139 goto bad_input;
2140 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2141 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002142 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002143
2144bad_input:
2145 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002146 if (alloc) {
2147 free(*binstr);
2148 *binstr = NULL;
2149 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002150 return 0;
2151}
2152
Willy Tarreau946ba592009-05-10 15:41:18 +02002153/* copies at most <n> characters from <src> and always terminates with '\0' */
2154char *my_strndup(const char *src, int n)
2155{
2156 int len = 0;
2157 char *ret;
2158
2159 while (len < n && src[len])
2160 len++;
2161
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002162 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002163 if (!ret)
2164 return ret;
2165 memcpy(ret, src, len);
2166 ret[len] = '\0';
2167 return ret;
2168}
2169
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002170/*
2171 * search needle in haystack
2172 * returns the pointer if found, returns NULL otherwise
2173 */
2174const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2175{
2176 const void *c = NULL;
2177 unsigned char f;
2178
2179 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2180 return NULL;
2181
2182 f = *(char *)needle;
2183 c = haystack;
2184 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2185 if ((haystacklen - (c - haystack)) < needlelen)
2186 return NULL;
2187
2188 if (memcmp(c, needle, needlelen) == 0)
2189 return c;
2190 ++c;
2191 }
2192 return NULL;
2193}
2194
Willy Tarreau482b00d2009-10-04 22:48:42 +02002195/* This function returns the first unused key greater than or equal to <key> in
2196 * ID tree <root>. Zero is returned if no place is found.
2197 */
2198unsigned int get_next_id(struct eb_root *root, unsigned int key)
2199{
2200 struct eb32_node *used;
2201
2202 do {
2203 used = eb32_lookup_ge(root, key);
2204 if (!used || used->key > key)
2205 return key; /* key is available */
2206 key++;
2207 } while (key);
2208 return key;
2209}
2210
Willy Tarreau348238b2010-01-18 15:05:57 +01002211/* This function compares a sample word possibly followed by blanks to another
2212 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2213 * otherwise zero. This intends to be used when checking HTTP headers for some
2214 * values. Note that it validates a word followed only by blanks but does not
2215 * validate a word followed by blanks then other chars.
2216 */
2217int word_match(const char *sample, int slen, const char *word, int wlen)
2218{
2219 if (slen < wlen)
2220 return 0;
2221
2222 while (wlen) {
2223 char c = *sample ^ *word;
2224 if (c && c != ('A' ^ 'a'))
2225 return 0;
2226 sample++;
2227 word++;
2228 slen--;
2229 wlen--;
2230 }
2231
2232 while (slen) {
2233 if (*sample != ' ' && *sample != '\t')
2234 return 0;
2235 sample++;
2236 slen--;
2237 }
2238 return 1;
2239}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002240
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002241/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2242 * is particularly fast because it avoids expensive operations such as
2243 * multiplies, which are optimized away at the end. It requires a properly
2244 * formated address though (3 points).
2245 */
2246unsigned int inetaddr_host(const char *text)
2247{
2248 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2249 register unsigned int dig100, dig10, dig1;
2250 int s;
2251 const char *p, *d;
2252
2253 dig1 = dig10 = dig100 = ascii_zero;
2254 s = 24;
2255
2256 p = text;
2257 while (1) {
2258 if (((unsigned)(*p - '0')) <= 9) {
2259 p++;
2260 continue;
2261 }
2262
2263 /* here, we have a complete byte between <text> and <p> (exclusive) */
2264 if (p == text)
2265 goto end;
2266
2267 d = p - 1;
2268 dig1 |= (unsigned int)(*d << s);
2269 if (d == text)
2270 goto end;
2271
2272 d--;
2273 dig10 |= (unsigned int)(*d << s);
2274 if (d == text)
2275 goto end;
2276
2277 d--;
2278 dig100 |= (unsigned int)(*d << s);
2279 end:
2280 if (!s || *p != '.')
2281 break;
2282
2283 s -= 8;
2284 text = ++p;
2285 }
2286
2287 dig100 -= ascii_zero;
2288 dig10 -= ascii_zero;
2289 dig1 -= ascii_zero;
2290 return ((dig100 * 10) + dig10) * 10 + dig1;
2291}
2292
2293/*
2294 * Idem except the first unparsed character has to be passed in <stop>.
2295 */
2296unsigned int inetaddr_host_lim(const char *text, const char *stop)
2297{
2298 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2299 register unsigned int dig100, dig10, dig1;
2300 int s;
2301 const char *p, *d;
2302
2303 dig1 = dig10 = dig100 = ascii_zero;
2304 s = 24;
2305
2306 p = text;
2307 while (1) {
2308 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2309 p++;
2310 continue;
2311 }
2312
2313 /* here, we have a complete byte between <text> and <p> (exclusive) */
2314 if (p == text)
2315 goto end;
2316
2317 d = p - 1;
2318 dig1 |= (unsigned int)(*d << s);
2319 if (d == text)
2320 goto end;
2321
2322 d--;
2323 dig10 |= (unsigned int)(*d << s);
2324 if (d == text)
2325 goto end;
2326
2327 d--;
2328 dig100 |= (unsigned int)(*d << s);
2329 end:
2330 if (!s || p == stop || *p != '.')
2331 break;
2332
2333 s -= 8;
2334 text = ++p;
2335 }
2336
2337 dig100 -= ascii_zero;
2338 dig10 -= ascii_zero;
2339 dig1 -= ascii_zero;
2340 return ((dig100 * 10) + dig10) * 10 + dig1;
2341}
2342
2343/*
2344 * Idem except the pointer to first unparsed byte is returned into <ret> which
2345 * must not be NULL.
2346 */
Willy Tarreau74172752010-10-15 23:21:42 +02002347unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002348{
2349 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2350 register unsigned int dig100, dig10, dig1;
2351 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002352 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002353
2354 dig1 = dig10 = dig100 = ascii_zero;
2355 s = 24;
2356
2357 p = text;
2358 while (1) {
2359 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2360 p++;
2361 continue;
2362 }
2363
2364 /* here, we have a complete byte between <text> and <p> (exclusive) */
2365 if (p == text)
2366 goto end;
2367
2368 d = p - 1;
2369 dig1 |= (unsigned int)(*d << s);
2370 if (d == text)
2371 goto end;
2372
2373 d--;
2374 dig10 |= (unsigned int)(*d << s);
2375 if (d == text)
2376 goto end;
2377
2378 d--;
2379 dig100 |= (unsigned int)(*d << s);
2380 end:
2381 if (!s || p == stop || *p != '.')
2382 break;
2383
2384 s -= 8;
2385 text = ++p;
2386 }
2387
2388 *ret = p;
2389 dig100 -= ascii_zero;
2390 dig10 -= ascii_zero;
2391 dig1 -= ascii_zero;
2392 return ((dig100 * 10) + dig10) * 10 + dig1;
2393}
2394
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002395/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2396 * or the number of chars read in case of success. Maybe this could be replaced
2397 * by one of the functions above. Also, apparently this function does not support
2398 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002399 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002400 */
2401int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2402{
2403 const char *addr;
2404 int saw_digit, octets, ch;
2405 u_char tmp[4], *tp;
2406 const char *cp = buf;
2407
2408 saw_digit = 0;
2409 octets = 0;
2410 *(tp = tmp) = 0;
2411
2412 for (addr = buf; addr - buf < len; addr++) {
2413 unsigned char digit = (ch = *addr) - '0';
2414
2415 if (digit > 9 && ch != '.')
2416 break;
2417
2418 if (digit <= 9) {
2419 u_int new = *tp * 10 + digit;
2420
2421 if (new > 255)
2422 return 0;
2423
2424 *tp = new;
2425
2426 if (!saw_digit) {
2427 if (++octets > 4)
2428 return 0;
2429 saw_digit = 1;
2430 }
2431 } else if (ch == '.' && saw_digit) {
2432 if (octets == 4)
2433 return 0;
2434
2435 *++tp = 0;
2436 saw_digit = 0;
2437 } else
2438 return 0;
2439 }
2440
2441 if (octets < 4)
2442 return 0;
2443
2444 memcpy(&dst->s_addr, tmp, 4);
2445 return addr - cp;
2446}
2447
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002448/* This function converts the string in <buf> of the len <len> to
2449 * struct in6_addr <dst> which must be allocated by the caller.
2450 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002451 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002452 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002453int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2454{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002455 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002456 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002457
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002458 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002459 return 0;
2460
2461 memcpy(null_term_ip6, buf, len);
2462 null_term_ip6[len] = '\0';
2463
Willy Tarreau075415a2013-12-12 11:29:39 +01002464 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002465 return 0;
2466
Willy Tarreau075415a2013-12-12 11:29:39 +01002467 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002468 return 1;
2469}
2470
Willy Tarreauacf95772010-06-14 19:09:21 +02002471/* To be used to quote config arg positions. Returns the short string at <ptr>
2472 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2473 * if ptr is NULL or empty. The string is locally allocated.
2474 */
2475const char *quote_arg(const char *ptr)
2476{
2477 static char val[32];
2478 int i;
2479
2480 if (!ptr || !*ptr)
2481 return "end of line";
2482 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002483 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002484 val[i] = *ptr++;
2485 val[i++] = '\'';
2486 val[i] = '\0';
2487 return val;
2488}
2489
Willy Tarreau5b180202010-07-18 10:40:48 +02002490/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2491int get_std_op(const char *str)
2492{
2493 int ret = -1;
2494
2495 if (*str == 'e' && str[1] == 'q')
2496 ret = STD_OP_EQ;
2497 else if (*str == 'n' && str[1] == 'e')
2498 ret = STD_OP_NE;
2499 else if (*str == 'l') {
2500 if (str[1] == 'e') ret = STD_OP_LE;
2501 else if (str[1] == 't') ret = STD_OP_LT;
2502 }
2503 else if (*str == 'g') {
2504 if (str[1] == 'e') ret = STD_OP_GE;
2505 else if (str[1] == 't') ret = STD_OP_GT;
2506 }
2507
2508 if (ret == -1 || str[2] != '\0')
2509 return -1;
2510 return ret;
2511}
2512
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002513/* hash a 32-bit integer to another 32-bit integer */
2514unsigned int full_hash(unsigned int a)
2515{
2516 return __full_hash(a);
2517}
2518
David du Colombier4f92d322011-03-24 11:09:31 +01002519/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002520 * otherwise zero. Note that <addr> may not necessarily be aligned
2521 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002522 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002523int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002524{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002525 struct in_addr addr_copy;
2526
2527 memcpy(&addr_copy, addr, sizeof(addr_copy));
2528 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002529}
2530
2531/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002532 * otherwise zero. Note that <addr> may not necessarily be aligned
2533 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002534 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002535int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002536{
2537 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002538 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002539
Willy Tarreaueec1d382016-07-13 11:59:39 +02002540 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002541 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002542 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002543 (((int *)net)[i] & ((int *)mask)[i]))
2544 return 0;
2545 return 1;
2546}
2547
2548/* RFC 4291 prefix */
2549const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2550 0x00, 0x00, 0x00, 0x00,
2551 0x00, 0x00, 0xFF, 0xFF };
2552
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002553/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2554 * Input and output may overlap.
2555 */
David du Colombier4f92d322011-03-24 11:09:31 +01002556void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2557{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002558 struct in_addr tmp_addr;
2559
2560 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002561 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002562 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002563}
2564
2565/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2566 * Return true if conversion is possible and false otherwise.
2567 */
2568int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2569{
2570 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2571 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2572 sizeof(struct in_addr));
2573 return 1;
2574 }
2575
2576 return 0;
2577}
2578
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002579/* compare two struct sockaddr_storage and return:
2580 * 0 (true) if the addr is the same in both
2581 * 1 (false) if the addr is not the same in both
2582 * -1 (unable) if one of the addr is not AF_INET*
2583 */
2584int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2585{
2586 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2587 return -1;
2588
2589 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2590 return -1;
2591
2592 if (ss1->ss_family != ss2->ss_family)
2593 return 1;
2594
2595 switch (ss1->ss_family) {
2596 case AF_INET:
2597 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2598 &((struct sockaddr_in *)ss2)->sin_addr,
2599 sizeof(struct in_addr)) != 0;
2600 case AF_INET6:
2601 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2602 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2603 sizeof(struct in6_addr)) != 0;
2604 }
2605
2606 return 1;
2607}
2608
Baptiste Assmann08396c82016-01-31 00:27:17 +01002609/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002610 * The caller must allocate and clear <dest> before calling.
2611 * The source must be in either AF_INET or AF_INET6 family, or the destination
2612 * address will be undefined. If the destination address used to hold a port,
2613 * it is preserved, so that this function can be used to switch to another
2614 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002615 */
2616struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2617{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002618 int prev_port;
2619
2620 prev_port = get_net_port(dest);
2621 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002622 dest->ss_family = source->ss_family;
2623
2624 /* copy new addr and apply it */
2625 switch (source->ss_family) {
2626 case AF_INET:
2627 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002628 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002629 break;
2630 case AF_INET6:
2631 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 +01002632 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002633 break;
2634 }
2635
2636 return dest;
2637}
2638
William Lallemand421f5b52012-02-06 18:15:57 +01002639char *human_time(int t, short hz_div) {
2640 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2641 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002642 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002643 int cnt=2; // print two numbers
2644
2645 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002646 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002647 return rv;
2648 }
2649
2650 if (unlikely(hz_div > 1))
2651 t /= hz_div;
2652
2653 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002654 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002655 cnt--;
2656 }
2657
2658 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002659 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002660 cnt--;
2661 }
2662
2663 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002664 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002665 cnt--;
2666 }
2667
2668 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002669 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002670
2671 return rv;
2672}
2673
2674const char *monthname[12] = {
2675 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2676 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2677};
2678
2679/* date2str_log: write a date in the format :
2680 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2681 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2682 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2683 *
2684 * without using sprintf. return a pointer to the last char written (\0) or
2685 * NULL if there isn't enough space.
2686 */
2687char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2688{
2689
2690 if (size < 25) /* the size is fixed: 24 chars + \0 */
2691 return NULL;
2692
2693 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2694 *dst++ = '/';
2695 memcpy(dst, monthname[tm->tm_mon], 3); // month
2696 dst += 3;
2697 *dst++ = '/';
2698 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2699 *dst++ = ':';
2700 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2701 *dst++ = ':';
2702 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2703 *dst++ = ':';
2704 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2705 *dst++ = '.';
2706 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2707 dst += 3; // only the 3 first digits
2708 *dst = '\0';
2709
2710 return dst;
2711}
2712
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002713/* Base year used to compute leap years */
2714#define TM_YEAR_BASE 1900
2715
2716/* Return the difference in seconds between two times (leap seconds are ignored).
2717 * Retrieved from glibc 2.18 source code.
2718 */
2719static int my_tm_diff(const struct tm *a, const struct tm *b)
2720{
2721 /* Compute intervening leap days correctly even if year is negative.
2722 * Take care to avoid int overflow in leap day calculations,
2723 * but it's OK to assume that A and B are close to each other.
2724 */
2725 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2726 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2727 int a100 = a4 / 25 - (a4 % 25 < 0);
2728 int b100 = b4 / 25 - (b4 % 25 < 0);
2729 int a400 = a100 >> 2;
2730 int b400 = b100 >> 2;
2731 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2732 int years = a->tm_year - b->tm_year;
2733 int days = (365 * years + intervening_leap_days
2734 + (a->tm_yday - b->tm_yday));
2735 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2736 + (a->tm_min - b->tm_min))
2737 + (a->tm_sec - b->tm_sec));
2738}
2739
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002740/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002741 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002742 * The string returned has the same format as returned by strftime(... "%z", tm).
2743 * Offsets are kept in an internal cache for better performances.
2744 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002745const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002746{
2747 /* Cache offsets from GMT (depending on whether DST is active or not) */
2748 static char gmt_offsets[2][5+1] = { "", "" };
2749
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002750 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002751 struct tm tm_gmt;
2752 int diff;
2753 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002754
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002755 /* Pretend DST not active if its status is unknown */
2756 if (isdst < 0)
2757 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002758
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002759 /* Fetch the offset and initialize it if needed */
2760 gmt_offset = gmt_offsets[isdst & 0x01];
2761 if (unlikely(!*gmt_offset)) {
2762 get_gmtime(t, &tm_gmt);
2763 diff = my_tm_diff(tm, &tm_gmt);
2764 if (diff < 0) {
2765 diff = -diff;
2766 *gmt_offset = '-';
2767 } else {
2768 *gmt_offset = '+';
2769 }
2770 diff /= 60; /* Convert to minutes */
2771 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2772 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002773
2774 return gmt_offset;
2775}
2776
William Lallemand421f5b52012-02-06 18:15:57 +01002777/* gmt2str_log: write a date in the format :
2778 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2779 * return a pointer to the last char written (\0) or
2780 * NULL if there isn't enough space.
2781 */
2782char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2783{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002784 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002785 return NULL;
2786
2787 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2788 *dst++ = '/';
2789 memcpy(dst, monthname[tm->tm_mon], 3); // month
2790 dst += 3;
2791 *dst++ = '/';
2792 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2793 *dst++ = ':';
2794 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2795 *dst++ = ':';
2796 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2797 *dst++ = ':';
2798 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2799 *dst++ = ' ';
2800 *dst++ = '+';
2801 *dst++ = '0';
2802 *dst++ = '0';
2803 *dst++ = '0';
2804 *dst++ = '0';
2805 *dst = '\0';
2806
2807 return dst;
2808}
2809
Yuxans Yao4e25b012012-10-19 10:36:09 +08002810/* localdate2str_log: write a date in the format :
2811 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002812 * Both t and tm must represent the same time.
2813 * return a pointer to the last char written (\0) or
2814 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002815 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002816char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002817{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002818 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002819 if (size < 27) /* the size is fixed: 26 chars + \0 */
2820 return NULL;
2821
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002822 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002823
Yuxans Yao4e25b012012-10-19 10:36:09 +08002824 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2825 *dst++ = '/';
2826 memcpy(dst, monthname[tm->tm_mon], 3); // month
2827 dst += 3;
2828 *dst++ = '/';
2829 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2830 *dst++ = ':';
2831 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2832 *dst++ = ':';
2833 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2834 *dst++ = ':';
2835 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2836 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002837 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002838 dst += 5;
2839 *dst = '\0';
2840
2841 return dst;
2842}
2843
Thierry Fournier93127942016-01-20 18:49:45 +01002844/* This function check a char. It returns true and updates
2845 * <date> and <len> pointer to the new position if the
2846 * character is found.
2847 */
2848static inline int parse_expect_char(const char **date, int *len, char c)
2849{
2850 if (*len < 1 || **date != c)
2851 return 0;
2852 (*len)--;
2853 (*date)++;
2854 return 1;
2855}
2856
2857/* This function expects a string <str> of len <l>. It return true and updates.
2858 * <date> and <len> if the string matches, otherwise, it returns false.
2859 */
2860static inline int parse_strcmp(const char **date, int *len, char *str, int l)
2861{
2862 if (*len < l || strncmp(*date, str, l) != 0)
2863 return 0;
2864 (*len) -= l;
2865 (*date) += l;
2866 return 1;
2867}
2868
2869/* This macro converts 3 chars name in integer. */
2870#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
2871
2872/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
2873 * / %x54.75.65 ; "Tue", case-sensitive
2874 * / %x57.65.64 ; "Wed", case-sensitive
2875 * / %x54.68.75 ; "Thu", case-sensitive
2876 * / %x46.72.69 ; "Fri", case-sensitive
2877 * / %x53.61.74 ; "Sat", case-sensitive
2878 * / %x53.75.6E ; "Sun", case-sensitive
2879 *
2880 * This array must be alphabetically sorted
2881 */
2882static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
2883{
2884 if (*len < 3)
2885 return 0;
2886 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2887 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
2888 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
2889 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
2890 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
2891 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
2892 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
2893 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
2894 default: return 0;
2895 }
2896 *len -= 3;
2897 *date += 3;
2898 return 1;
2899}
2900
2901/* month = %x4A.61.6E ; "Jan", case-sensitive
2902 * / %x46.65.62 ; "Feb", case-sensitive
2903 * / %x4D.61.72 ; "Mar", case-sensitive
2904 * / %x41.70.72 ; "Apr", case-sensitive
2905 * / %x4D.61.79 ; "May", case-sensitive
2906 * / %x4A.75.6E ; "Jun", case-sensitive
2907 * / %x4A.75.6C ; "Jul", case-sensitive
2908 * / %x41.75.67 ; "Aug", case-sensitive
2909 * / %x53.65.70 ; "Sep", case-sensitive
2910 * / %x4F.63.74 ; "Oct", case-sensitive
2911 * / %x4E.6F.76 ; "Nov", case-sensitive
2912 * / %x44.65.63 ; "Dec", case-sensitive
2913 *
2914 * This array must be alphabetically sorted
2915 */
2916static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
2917{
2918 if (*len < 3)
2919 return 0;
2920 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2921 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
2922 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
2923 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
2924 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
2925 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
2926 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
2927 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
2928 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
2929 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
2930 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
2931 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
2932 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
2933 default: return 0;
2934 }
2935 *len -= 3;
2936 *date += 3;
2937 return 1;
2938}
2939
2940/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
2941 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
2942 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
2943 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
2944 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
2945 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
2946 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
2947 *
2948 * This array must be alphabetically sorted
2949 */
2950static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
2951{
2952 if (*len < 6) /* Minimum length. */
2953 return 0;
2954 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2955 case STR2I3('M','o','n'):
2956 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
2957 tm->tm_wday = 1;
2958 return 1;
2959 case STR2I3('T','u','e'):
2960 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
2961 tm->tm_wday = 2;
2962 return 1;
2963 case STR2I3('W','e','d'):
2964 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
2965 tm->tm_wday = 3;
2966 return 1;
2967 case STR2I3('T','h','u'):
2968 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
2969 tm->tm_wday = 4;
2970 return 1;
2971 case STR2I3('F','r','i'):
2972 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
2973 tm->tm_wday = 5;
2974 return 1;
2975 case STR2I3('S','a','t'):
2976 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
2977 tm->tm_wday = 6;
2978 return 1;
2979 case STR2I3('S','u','n'):
2980 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
2981 tm->tm_wday = 7;
2982 return 1;
2983 }
2984 return 0;
2985}
2986
2987/* This function parses exactly 1 digit and returns the numeric value in "digit". */
2988static inline int parse_digit(const char **date, int *len, int *digit)
2989{
2990 if (*len < 1 || **date < '0' || **date > '9')
2991 return 0;
2992 *digit = (**date - '0');
2993 (*date)++;
2994 (*len)--;
2995 return 1;
2996}
2997
2998/* This function parses exactly 2 digits and returns the numeric value in "digit". */
2999static inline int parse_2digit(const char **date, int *len, int *digit)
3000{
3001 int value;
3002
3003 RET0_UNLESS(parse_digit(date, len, &value));
3004 (*digit) = value * 10;
3005 RET0_UNLESS(parse_digit(date, len, &value));
3006 (*digit) += value;
3007
3008 return 1;
3009}
3010
3011/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3012static inline int parse_4digit(const char **date, int *len, int *digit)
3013{
3014 int value;
3015
3016 RET0_UNLESS(parse_digit(date, len, &value));
3017 (*digit) = value * 1000;
3018
3019 RET0_UNLESS(parse_digit(date, len, &value));
3020 (*digit) += value * 100;
3021
3022 RET0_UNLESS(parse_digit(date, len, &value));
3023 (*digit) += value * 10;
3024
3025 RET0_UNLESS(parse_digit(date, len, &value));
3026 (*digit) += value;
3027
3028 return 1;
3029}
3030
3031/* time-of-day = hour ":" minute ":" second
3032 * ; 00:00:00 - 23:59:60 (leap second)
3033 *
3034 * hour = 2DIGIT
3035 * minute = 2DIGIT
3036 * second = 2DIGIT
3037 */
3038static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3039{
3040 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3041 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3042 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3043 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3044 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3045 return 1;
3046}
3047
3048/* From RFC7231
3049 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3050 *
3051 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3052 * ; fixed length/zone/capitalization subset of the format
3053 * ; see Section 3.3 of [RFC5322]
3054 *
3055 *
3056 * date1 = day SP month SP year
3057 * ; e.g., 02 Jun 1982
3058 *
3059 * day = 2DIGIT
3060 * year = 4DIGIT
3061 *
3062 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3063 *
3064 * time-of-day = hour ":" minute ":" second
3065 * ; 00:00:00 - 23:59:60 (leap second)
3066 *
3067 * hour = 2DIGIT
3068 * minute = 2DIGIT
3069 * second = 2DIGIT
3070 *
3071 * DIGIT = decimal 0-9
3072 */
3073int parse_imf_date(const char *date, int len, struct tm *tm)
3074{
David Carlier327298c2016-11-20 10:42:38 +00003075 /* tm_gmtoff, if present, ought to be zero'ed */
3076 memset(tm, 0, sizeof(*tm));
3077
Thierry Fournier93127942016-01-20 18:49:45 +01003078 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3079 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3080 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3081 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3082 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3083 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3084 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3085 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3086 tm->tm_year -= 1900;
3087 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3088 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3089 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3090 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3091 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003092 return 1;
3093}
3094
3095/* From RFC7231
3096 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3097 *
3098 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3099 * date2 = day "-" month "-" 2DIGIT
3100 * ; e.g., 02-Jun-82
3101 *
3102 * day = 2DIGIT
3103 */
3104int parse_rfc850_date(const char *date, int len, struct tm *tm)
3105{
3106 int year;
3107
David Carlier327298c2016-11-20 10:42:38 +00003108 /* tm_gmtoff, if present, ought to be zero'ed */
3109 memset(tm, 0, sizeof(*tm));
3110
Thierry Fournier93127942016-01-20 18:49:45 +01003111 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3112 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3113 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3114 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3115 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3116 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3117 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3118
3119 /* year = 2DIGIT
3120 *
3121 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3122 * two-digit year, MUST interpret a timestamp that appears to be more
3123 * than 50 years in the future as representing the most recent year in
3124 * the past that had the same last two digits.
3125 */
3126 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3127
3128 /* expect SP */
3129 if (!parse_expect_char(&date, &len, ' ')) {
3130 /* Maybe we have the date with 4 digits. */
3131 RET0_UNLESS(parse_2digit(&date, &len, &year));
3132 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3133 /* expect SP */
3134 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3135 } else {
3136 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3137 * tm_year is the number of year since 1900, so for +1900, we
3138 * do nothing, and for +2000, we add 100.
3139 */
3140 if (tm->tm_year <= 60)
3141 tm->tm_year += 100;
3142 }
3143
3144 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3145 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3146 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3147 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003148
3149 return 1;
3150}
3151
3152/* From RFC7231
3153 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3154 *
3155 * asctime-date = day-name SP date3 SP time-of-day SP year
3156 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3157 * ; e.g., Jun 2
3158 *
3159 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3160 * whitespace in an HTTP-date beyond that specifically included as SP in
3161 * the grammar.
3162 */
3163int parse_asctime_date(const char *date, int len, struct tm *tm)
3164{
David Carlier327298c2016-11-20 10:42:38 +00003165 /* tm_gmtoff, if present, ought to be zero'ed */
3166 memset(tm, 0, sizeof(*tm));
3167
Thierry Fournier93127942016-01-20 18:49:45 +01003168 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3169 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3170 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3171 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3172
3173 /* expect SP and 1DIGIT or 2DIGIT */
3174 if (parse_expect_char(&date, &len, ' '))
3175 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3176 else
3177 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3178
3179 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3180 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3181 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3182 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3183 tm->tm_year -= 1900;
3184 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003185 return 1;
3186}
3187
3188/* From RFC7231
3189 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3190 *
3191 * HTTP-date = IMF-fixdate / obs-date
3192 * obs-date = rfc850-date / asctime-date
3193 *
3194 * parses an HTTP date in the RFC format and is accepted
3195 * alternatives. <date> is the strinf containing the date,
3196 * len is the len of the string. <tm> is filled with the
3197 * parsed time. We must considers this time as GMT.
3198 */
3199int parse_http_date(const char *date, int len, struct tm *tm)
3200{
3201 if (parse_imf_date(date, len, tm))
3202 return 1;
3203
3204 if (parse_rfc850_date(date, len, tm))
3205 return 1;
3206
3207 if (parse_asctime_date(date, len, tm))
3208 return 1;
3209
3210 return 0;
3211}
3212
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003213/* Dynamically allocates a string of the proper length to hold the formatted
3214 * output. NULL is returned on error. The caller is responsible for freeing the
3215 * memory area using free(). The resulting string is returned in <out> if the
3216 * pointer is not NULL. A previous version of <out> might be used to build the
3217 * new string, and it will be freed before returning if it is not NULL, which
3218 * makes it possible to build complex strings from iterative calls without
3219 * having to care about freeing intermediate values, as in the example below :
3220 *
3221 * memprintf(&err, "invalid argument: '%s'", arg);
3222 * ...
3223 * memprintf(&err, "parser said : <%s>\n", *err);
3224 * ...
3225 * free(*err);
3226 *
3227 * This means that <err> must be initialized to NULL before first invocation.
3228 * The return value also holds the allocated string, which eases error checking
3229 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003230 * passed instead and it will be ignored. The returned message will then also
3231 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003232 *
3233 * It is also convenient to use it without any free except the last one :
3234 * err = NULL;
3235 * if (!fct1(err)) report(*err);
3236 * if (!fct2(err)) report(*err);
3237 * if (!fct3(err)) report(*err);
3238 * free(*err);
3239 */
3240char *memprintf(char **out, const char *format, ...)
3241{
3242 va_list args;
3243 char *ret = NULL;
3244 int allocated = 0;
3245 int needed = 0;
3246
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003247 if (!out)
3248 return NULL;
3249
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003250 do {
3251 /* vsnprintf() will return the required length even when the
3252 * target buffer is NULL. We do this in a loop just in case
3253 * intermediate evaluations get wrong.
3254 */
3255 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003256 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003257 va_end(args);
3258
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003259 if (needed < allocated) {
3260 /* Note: on Solaris 8, the first iteration always
3261 * returns -1 if allocated is zero, so we force a
3262 * retry.
3263 */
3264 if (!allocated)
3265 needed = 0;
3266 else
3267 break;
3268 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003269
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003270 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003271 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003272 } while (ret);
3273
3274 if (needed < 0) {
3275 /* an error was encountered */
3276 free(ret);
3277 ret = NULL;
3278 }
3279
3280 if (out) {
3281 free(*out);
3282 *out = ret;
3283 }
3284
3285 return ret;
3286}
William Lallemand421f5b52012-02-06 18:15:57 +01003287
Willy Tarreau21c705b2012-09-14 11:40:36 +02003288/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3289 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003290 * freed by the caller. It also supports being passed a NULL which results in the same
3291 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003292 * Example of use :
3293 * parse(cmd, &err); (callee: memprintf(&err, ...))
3294 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3295 * free(err);
3296 */
3297char *indent_msg(char **out, int level)
3298{
3299 char *ret, *in, *p;
3300 int needed = 0;
3301 int lf = 0;
3302 int lastlf = 0;
3303 int len;
3304
Willy Tarreau70eec382012-10-10 08:56:47 +02003305 if (!out || !*out)
3306 return NULL;
3307
Willy Tarreau21c705b2012-09-14 11:40:36 +02003308 in = *out - 1;
3309 while ((in = strchr(in + 1, '\n')) != NULL) {
3310 lastlf = in - *out;
3311 lf++;
3312 }
3313
3314 if (!lf) /* single line, no LF, return it as-is */
3315 return *out;
3316
3317 len = strlen(*out);
3318
3319 if (lf == 1 && lastlf == len - 1) {
3320 /* single line, LF at end, strip it and return as-is */
3321 (*out)[lastlf] = 0;
3322 return *out;
3323 }
3324
3325 /* OK now we have at least one LF, we need to process the whole string
3326 * as a multi-line string. What we'll do :
3327 * - prefix with an LF if there is none
3328 * - add <level> spaces before each line
3329 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3330 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3331 */
3332
3333 needed = 1 + level * (lf + 1) + len + 1;
3334 p = ret = malloc(needed);
3335 in = *out;
3336
3337 /* skip initial LFs */
3338 while (*in == '\n')
3339 in++;
3340
3341 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3342 while (*in) {
3343 *p++ = '\n';
3344 memset(p, ' ', level);
3345 p += level;
3346 do {
3347 *p++ = *in++;
3348 } while (*in && *in != '\n');
3349 if (*in)
3350 in++;
3351 }
3352 *p = 0;
3353
3354 free(*out);
3355 *out = ret;
3356
3357 return ret;
3358}
3359
Willy Tarreaudad36a32013-03-11 01:20:04 +01003360/* Convert occurrences of environment variables in the input string to their
3361 * corresponding value. A variable is identified as a series of alphanumeric
3362 * characters or underscores following a '$' sign. The <in> string must be
3363 * free()able. NULL returns NULL. The resulting string might be reallocated if
3364 * some expansion is made. Variable names may also be enclosed into braces if
3365 * needed (eg: to concatenate alphanum characters).
3366 */
3367char *env_expand(char *in)
3368{
3369 char *txt_beg;
3370 char *out;
3371 char *txt_end;
3372 char *var_beg;
3373 char *var_end;
3374 char *value;
3375 char *next;
3376 int out_len;
3377 int val_len;
3378
3379 if (!in)
3380 return in;
3381
3382 value = out = NULL;
3383 out_len = 0;
3384
3385 txt_beg = in;
3386 do {
3387 /* look for next '$' sign in <in> */
3388 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3389
3390 if (!*txt_end && !out) /* end and no expansion performed */
3391 return in;
3392
3393 val_len = 0;
3394 next = txt_end;
3395 if (*txt_end == '$') {
3396 char save;
3397
3398 var_beg = txt_end + 1;
3399 if (*var_beg == '{')
3400 var_beg++;
3401
3402 var_end = var_beg;
3403 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3404 var_end++;
3405 }
3406
3407 next = var_end;
3408 if (*var_end == '}' && (var_beg > txt_end + 1))
3409 next++;
3410
3411 /* get value of the variable name at this location */
3412 save = *var_end;
3413 *var_end = '\0';
3414 value = getenv(var_beg);
3415 *var_end = save;
3416 val_len = value ? strlen(value) : 0;
3417 }
3418
Hubert Verstraete831962e2016-06-28 22:44:26 +02003419 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003420 if (txt_end > txt_beg) {
3421 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3422 out_len += txt_end - txt_beg;
3423 }
3424 if (val_len) {
3425 memcpy(out + out_len, value, val_len);
3426 out_len += val_len;
3427 }
3428 out[out_len] = 0;
3429 txt_beg = next;
3430 } while (*txt_beg);
3431
3432 /* here we know that <out> was allocated and that we don't need <in> anymore */
3433 free(in);
3434 return out;
3435}
3436
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003437
3438/* same as strstr() but case-insensitive and with limit length */
3439const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3440{
3441 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003442 unsigned int slen, plen;
3443 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003444
3445 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3446 return NULL;
3447
3448 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3449 return str1;
3450
3451 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3452 return NULL;
3453
3454 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3455 while (toupper(*start) != toupper(*str2)) {
3456 start++;
3457 slen--;
3458 tmp1++;
3459
3460 if (tmp1 >= len_str1)
3461 return NULL;
3462
3463 /* if pattern longer than string */
3464 if (slen < plen)
3465 return NULL;
3466 }
3467
3468 sptr = start;
3469 pptr = (char *)str2;
3470
3471 tmp2 = 0;
3472 while (toupper(*sptr) == toupper(*pptr)) {
3473 sptr++;
3474 pptr++;
3475 tmp2++;
3476
3477 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3478 return start;
3479 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3480 return NULL;
3481 }
3482 }
3483 return NULL;
3484}
3485
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003486/* This function read the next valid utf8 char.
3487 * <s> is the byte srray to be decode, <len> is its length.
3488 * The function returns decoded char encoded like this:
3489 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3490 * are the length read. The decoded character is stored in <c>.
3491 */
3492unsigned char utf8_next(const char *s, int len, unsigned int *c)
3493{
3494 const unsigned char *p = (unsigned char *)s;
3495 int dec;
3496 unsigned char code = UTF8_CODE_OK;
3497
3498 if (len < 1)
3499 return UTF8_CODE_OK;
3500
3501 /* Check the type of UTF8 sequence
3502 *
3503 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3504 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3505 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3506 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3507 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3508 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3509 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3510 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3511 */
3512 switch (*p) {
3513 case 0x00 ... 0x7f:
3514 *c = *p;
3515 return UTF8_CODE_OK | 1;
3516
3517 case 0x80 ... 0xbf:
3518 *c = *p;
3519 return UTF8_CODE_BADSEQ | 1;
3520
3521 case 0xc0 ... 0xdf:
3522 if (len < 2) {
3523 *c = *p;
3524 return UTF8_CODE_BADSEQ | 1;
3525 }
3526 *c = *p & 0x1f;
3527 dec = 1;
3528 break;
3529
3530 case 0xe0 ... 0xef:
3531 if (len < 3) {
3532 *c = *p;
3533 return UTF8_CODE_BADSEQ | 1;
3534 }
3535 *c = *p & 0x0f;
3536 dec = 2;
3537 break;
3538
3539 case 0xf0 ... 0xf7:
3540 if (len < 4) {
3541 *c = *p;
3542 return UTF8_CODE_BADSEQ | 1;
3543 }
3544 *c = *p & 0x07;
3545 dec = 3;
3546 break;
3547
3548 case 0xf8 ... 0xfb:
3549 if (len < 5) {
3550 *c = *p;
3551 return UTF8_CODE_BADSEQ | 1;
3552 }
3553 *c = *p & 0x03;
3554 dec = 4;
3555 break;
3556
3557 case 0xfc ... 0xfd:
3558 if (len < 6) {
3559 *c = *p;
3560 return UTF8_CODE_BADSEQ | 1;
3561 }
3562 *c = *p & 0x01;
3563 dec = 5;
3564 break;
3565
3566 case 0xfe ... 0xff:
3567 default:
3568 *c = *p;
3569 return UTF8_CODE_BADSEQ | 1;
3570 }
3571
3572 p++;
3573
3574 while (dec > 0) {
3575
3576 /* need 0x10 for the 2 first bits */
3577 if ( ( *p & 0xc0 ) != 0x80 )
3578 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3579
3580 /* add data at char */
3581 *c = ( *c << 6 ) | ( *p & 0x3f );
3582
3583 dec--;
3584 p++;
3585 }
3586
3587 /* Check ovelong encoding.
3588 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3589 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3590 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3591 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003592 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003593 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3594 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3595 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3596 code |= UTF8_CODE_OVERLONG;
3597
3598 /* Check invalid UTF8 range. */
3599 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3600 (*c >= 0xfffe && *c <= 0xffff))
3601 code |= UTF8_CODE_INVRANGE;
3602
3603 return code | ((p-(unsigned char *)s)&0x0f);
3604}
3605
Maxime de Roucydc887852016-05-13 23:52:54 +02003606/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3607 * On failure : return 0 and <err> filled with an error message.
3608 * The caller is responsible for freeing the <err> and <str> copy
3609 * memory area using free()
3610 */
3611int list_append_word(struct list *li, const char *str, char **err)
3612{
3613 struct wordlist *wl;
3614
3615 wl = calloc(1, sizeof(*wl));
3616 if (!wl) {
3617 memprintf(err, "out of memory");
3618 goto fail_wl;
3619 }
3620
3621 wl->s = strdup(str);
3622 if (!wl->s) {
3623 memprintf(err, "out of memory");
3624 goto fail_wl_s;
3625 }
3626
3627 LIST_ADDQ(li, &wl->list);
3628
3629 return 1;
3630
3631fail_wl_s:
3632 free(wl->s);
3633fail_wl:
3634 free(wl);
3635 return 0;
3636}
3637
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003638/* print a string of text buffer to <out>. The format is :
3639 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3640 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3641 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3642 */
3643int dump_text(struct chunk *out, const char *buf, int bsize)
3644{
3645 unsigned char c;
3646 int ptr = 0;
3647
3648 while (buf[ptr] && ptr < bsize) {
3649 c = buf[ptr];
3650 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
3651 if (out->len > out->size - 1)
3652 break;
3653 out->str[out->len++] = c;
3654 }
3655 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
3656 if (out->len > out->size - 2)
3657 break;
3658 out->str[out->len++] = '\\';
3659 switch (c) {
3660 case ' ': c = ' '; break;
3661 case '\t': c = 't'; break;
3662 case '\n': c = 'n'; break;
3663 case '\r': c = 'r'; break;
3664 case '\e': c = 'e'; break;
3665 case '\\': c = '\\'; break;
3666 case '=': c = '='; break;
3667 }
3668 out->str[out->len++] = c;
3669 }
3670 else {
3671 if (out->len > out->size - 4)
3672 break;
3673 out->str[out->len++] = '\\';
3674 out->str[out->len++] = 'x';
3675 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3676 out->str[out->len++] = hextab[c & 0xF];
3677 }
3678 ptr++;
3679 }
3680
3681 return ptr;
3682}
3683
3684/* print a buffer in hexa.
3685 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3686 */
3687int dump_binary(struct chunk *out, const char *buf, int bsize)
3688{
3689 unsigned char c;
3690 int ptr = 0;
3691
3692 while (ptr < bsize) {
3693 c = buf[ptr];
3694
3695 if (out->len > out->size - 2)
3696 break;
3697 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3698 out->str[out->len++] = hextab[c & 0xF];
3699
3700 ptr++;
3701 }
3702 return ptr;
3703}
3704
3705/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3706 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3707 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3708 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3709 * lines are respected within the limit of 70 output chars. Lines that are
3710 * continuation of a previous truncated line begin with "+" instead of " "
3711 * after the offset. The new pointer is returned.
3712 */
3713int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3714 int *line, int ptr)
3715{
3716 int end;
3717 unsigned char c;
3718
3719 end = out->len + 80;
3720 if (end > out->size)
3721 return ptr;
3722
3723 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3724
3725 while (ptr < len && ptr < bsize) {
3726 c = buf[ptr];
3727 if (isprint(c) && isascii(c) && c != '\\') {
3728 if (out->len > end - 2)
3729 break;
3730 out->str[out->len++] = c;
3731 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3732 if (out->len > end - 3)
3733 break;
3734 out->str[out->len++] = '\\';
3735 switch (c) {
3736 case '\t': c = 't'; break;
3737 case '\n': c = 'n'; break;
3738 case '\r': c = 'r'; break;
3739 case '\e': c = 'e'; break;
3740 case '\\': c = '\\'; break;
3741 }
3742 out->str[out->len++] = c;
3743 } else {
3744 if (out->len > end - 5)
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 if (buf[ptr++] == '\n') {
3752 /* we had a line break, let's return now */
3753 out->str[out->len++] = '\n';
3754 *line = ptr;
3755 return ptr;
3756 }
3757 }
3758 /* we have an incomplete line, we return it as-is */
3759 out->str[out->len++] = '\n';
3760 return ptr;
3761}
3762
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003763/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
3764 * has address <baseaddr>. The output is emitted to file <out>.
3765 */
3766void debug_hexdump(FILE *out, char *buf, unsigned int baseaddr, int len)
3767{
Willy Tarreau73459792017-04-11 07:58:08 +02003768 unsigned int i;
3769 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003770
3771 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3772 b = i - (baseaddr & 15);
3773 fprintf(out, "%08x: ", i + (baseaddr & ~15));
3774 for (j = 0; j < 8; j++) {
3775 if (b + j >= 0 && b + j < len)
3776 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3777 else
3778 fprintf(out, " ");
3779 }
3780
3781 if (b + j >= 0 && b + j < len)
3782 fputc('-', out);
3783 else
3784 fputc(' ', out);
3785
3786 for (j = 8; j < 16; j++) {
3787 if (b + j >= 0 && b + j < len)
3788 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3789 else
3790 fprintf(out, " ");
3791 }
3792
3793 fprintf(out, " ");
3794 for (j = 0; j < 16; j++) {
3795 if (b + j >= 0 && b + j < len) {
3796 if (isprint((unsigned char)buf[b + j]))
3797 fputc((unsigned char)buf[b + j], out);
3798 else
3799 fputc('.', out);
3800 }
3801 else
3802 fputc(' ', out);
3803 }
3804 fputc('\n', out);
3805 }
3806}
3807
Willy Tarreaubaaee002006-06-26 02:48:02 +02003808/*
3809 * Local variables:
3810 * c-indent-level: 8
3811 * c-basic-offset: 8
3812 * End:
3813 */