blob: 468b15bce84426c43e9062008a1fc262866266bd [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) {
961 if (!resolve && fqdn) {
962 /* we'll still want to store the port, so let's
963 * force it to IPv4 for now.
964 */
965 memset(&ss, 0, sizeof(ss));
966 ss.ss_family = AF_INET;
967 }
968 else if ((!resolve && !fqdn) ||
969 (resolve && str2ip2(str2, &ss, 1) == NULL)) {
970 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
971 goto out;
972 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200973
Willy Tarreauceccdd72016-11-02 22:27:10 +0100974 if (fqdn) {
975 if (str2 != back)
976 memmove(back, str2, strlen(str2) + 1);
977 *fqdn = back;
978 back = NULL;
979 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200980 }
Willy Tarreauceccdd72016-11-02 22:27:10 +0100981 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100982 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100983
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100984 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100985 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +0100986 if (port)
987 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100988 if (low)
989 *low = portl;
990 if (high)
991 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100992 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100993 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200994}
995
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100996/* converts <str> to a struct in_addr containing a network mask. It can be
997 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
998 * if the conversion succeeds otherwise non-zero.
999 */
1000int str2mask(const char *str, struct in_addr *mask)
1001{
1002 if (strchr(str, '.') != NULL) { /* dotted notation */
1003 if (!inet_pton(AF_INET, str, mask))
1004 return 0;
1005 }
1006 else { /* mask length */
1007 char *err;
1008 unsigned long len = strtol(str, &err, 10);
1009
1010 if (!*str || (err && *err) || (unsigned)len > 32)
1011 return 0;
1012 if (len)
1013 mask->s_addr = htonl(~0UL << (32 - len));
1014 else
1015 mask->s_addr = 0;
1016 }
1017 return 1;
1018}
1019
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001020/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1021 * succeeds otherwise zero.
1022 */
1023int cidr2dotted(int cidr, struct in_addr *mask) {
1024
1025 if (cidr < 0 || cidr > 32)
1026 return 0;
1027
1028 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1029 return 1;
1030}
1031
Thierry Fournier70473a52016-02-17 17:12:14 +01001032/* Convert mask from bit length form to in_addr form.
1033 * This function never fails.
1034 */
1035void len2mask4(int len, struct in_addr *addr)
1036{
1037 if (len >= 32) {
1038 addr->s_addr = 0xffffffff;
1039 return;
1040 }
1041 if (len <= 0) {
1042 addr->s_addr = 0x00000000;
1043 return;
1044 }
1045 addr->s_addr = 0xffffffff << (32 - len);
1046 addr->s_addr = htonl(addr->s_addr);
1047}
1048
1049/* Convert mask from bit length form to in6_addr form.
1050 * This function never fails.
1051 */
1052void len2mask6(int len, struct in6_addr *addr)
1053{
1054 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1055 len -= 32;
1056 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1057 len -= 32;
1058 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1059 len -= 32;
1060 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1061}
1062
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001063/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001064 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001065 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1066 * is optionnal and either in the dotted or CIDR notation.
1067 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1068 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001069int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001070{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001071 __label__ out_free, out_err;
1072 char *c, *s;
1073 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001074
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001075 s = strdup(str);
1076 if (!s)
1077 return 0;
1078
Willy Tarreaubaaee002006-06-26 02:48:02 +02001079 memset(mask, 0, sizeof(*mask));
1080 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001081
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001082 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001083 *c++ = '\0';
1084 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001085 if (!str2mask(c, mask))
1086 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001087 }
1088 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001089 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001090 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001091 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001092 struct hostent *he;
1093
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001094 if (!resolve)
1095 goto out_err;
1096
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001097 if ((he = gethostbyname(s)) == NULL) {
1098 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001099 }
1100 else
1101 *addr = *(struct in_addr *) *(he->h_addr_list);
1102 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001103
1104 ret_val = 1;
1105 out_free:
1106 free(s);
1107 return ret_val;
1108 out_err:
1109 ret_val = 0;
1110 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001111}
1112
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001113
1114/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001115 * converts <str> to two struct in6_addr* which must be pre-allocated.
1116 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1117 * is an optionnal number of bits (128 being the default).
1118 * Returns 1 if OK, 0 if error.
1119 */
1120int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1121{
1122 char *c, *s;
1123 int ret_val = 0;
1124 char *err;
1125 unsigned long len = 128;
1126
1127 s = strdup(str);
1128 if (!s)
1129 return 0;
1130
1131 memset(mask, 0, sizeof(*mask));
1132 memset(addr, 0, sizeof(*addr));
1133
1134 if ((c = strrchr(s, '/')) != NULL) {
1135 *c++ = '\0'; /* c points to the mask */
1136 if (!*c)
1137 goto out_free;
1138
1139 len = strtoul(c, &err, 10);
1140 if ((err && *err) || (unsigned)len > 128)
1141 goto out_free;
1142 }
1143 *mask = len; /* OK we have a valid mask in <len> */
1144
1145 if (!inet_pton(AF_INET6, s, addr))
1146 goto out_free;
1147
1148 ret_val = 1;
1149 out_free:
1150 free(s);
1151 return ret_val;
1152}
1153
1154
1155/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001156 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001157 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001158int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001159{
1160 int saw_digit, octets, ch;
1161 u_char tmp[4], *tp;
1162 const char *cp = addr;
1163
1164 saw_digit = 0;
1165 octets = 0;
1166 *(tp = tmp) = 0;
1167
1168 while (*addr) {
1169 unsigned char digit = (ch = *addr++) - '0';
1170 if (digit > 9 && ch != '.')
1171 break;
1172 if (digit <= 9) {
1173 u_int new = *tp * 10 + digit;
1174 if (new > 255)
1175 return 0;
1176 *tp = new;
1177 if (!saw_digit) {
1178 if (++octets > 4)
1179 return 0;
1180 saw_digit = 1;
1181 }
1182 } else if (ch == '.' && saw_digit) {
1183 if (octets == 4)
1184 return 0;
1185 *++tp = 0;
1186 saw_digit = 0;
1187 } else
1188 return 0;
1189 }
1190
1191 if (octets < 4)
1192 return 0;
1193
1194 memcpy(&dst->s_addr, tmp, 4);
1195 return addr-cp-1;
1196}
1197
1198/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001199 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1200 * <out> contain the code of the dectected scheme, the start and length of
1201 * the hostname. Actually only http and https are supported. <out> can be NULL.
1202 * This function returns the consumed length. It is useful if you parse complete
1203 * url like http://host:port/path, because the consumed length corresponds to
1204 * the first character of the path. If the conversion fails, it returns -1.
1205 *
1206 * This function tries to resolve the DNS name if haproxy is in starting mode.
1207 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001208 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001209int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001210{
1211 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001212 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001213 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001214 unsigned long long int http_code = 0;
1215 int default_port;
1216 struct hostent *he;
1217 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001218
1219 /* Firstly, try to find :// pattern */
1220 while (curr < url+ulen && url_code != 0x3a2f2f) {
1221 url_code = ((url_code & 0xffff) << 8);
1222 url_code += (unsigned char)*curr++;
1223 }
1224
1225 /* Secondly, if :// pattern is found, verify parsed stuff
1226 * before pattern is matching our http pattern.
1227 * If so parse ip address and port in uri.
1228 *
1229 * WARNING: Current code doesn't support dynamic async dns resolver.
1230 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001231 if (url_code != 0x3a2f2f)
1232 return -1;
1233
1234 /* Copy scheme, and utrn to lower case. */
1235 while (cp < curr - 3)
1236 http_code = (http_code << 8) + *cp++;
1237 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001238
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001239 /* HTTP or HTTPS url matching */
1240 if (http_code == 0x2020202068747470ULL) {
1241 default_port = 80;
1242 if (out)
1243 out->scheme = SCH_HTTP;
1244 }
1245 else if (http_code == 0x2020206874747073ULL) {
1246 default_port = 443;
1247 if (out)
1248 out->scheme = SCH_HTTPS;
1249 }
1250 else
1251 return -1;
1252
1253 /* If the next char is '[', the host address is IPv6. */
1254 if (*curr == '[') {
1255 curr++;
1256
1257 /* Check trash size */
1258 if (trash.size < ulen)
1259 return -1;
1260
1261 /* Look for ']' and copy the address in a trash buffer. */
1262 p = trash.str;
1263 for (end = curr;
1264 end < url + ulen && *end != ']';
1265 end++, p++)
1266 *p = *end;
1267 if (*end != ']')
1268 return -1;
1269 *p = '\0';
1270
1271 /* Update out. */
1272 if (out) {
1273 out->host = curr;
1274 out->host_len = end - curr;
1275 }
1276
1277 /* Try IPv6 decoding. */
1278 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1279 return -1;
1280 end++;
1281
1282 /* Decode port. */
1283 if (*end == ':') {
1284 end++;
1285 default_port = read_uint(&end, url + ulen);
1286 }
1287 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1288 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1289 return end - url;
1290 }
1291 else {
1292 /* We are looking for IP address. If you want to parse and
1293 * resolve hostname found in url, you can use str2sa_range(), but
1294 * be warned this can slow down global daemon performances
1295 * while handling lagging dns responses.
1296 */
1297 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1298 if (ret) {
1299 /* Update out. */
1300 if (out) {
1301 out->host = curr;
1302 out->host_len = ret;
1303 }
1304
1305 curr += ret;
1306
1307 /* Decode port. */
1308 if (*curr == ':') {
1309 curr++;
1310 default_port = read_uint(&curr, url + ulen);
1311 }
1312 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1313
1314 /* Set family. */
1315 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1316 return curr - url;
1317 }
1318 else if (global.mode & MODE_STARTING) {
1319 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1320 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001321 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001322
1323 /* look for : or / or end */
1324 for (end = curr;
1325 end < url + ulen && *end != '/' && *end != ':';
1326 end++);
1327 memcpy(trash.str, curr, end - curr);
1328 trash.str[end - curr] = '\0';
1329
1330 /* try to resolve an IPv4/IPv6 hostname */
1331 he = gethostbyname(trash.str);
1332 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001333 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001334
1335 /* Update out. */
1336 if (out) {
1337 out->host = curr;
1338 out->host_len = end - curr;
1339 }
1340
1341 /* Decode port. */
1342 if (*end == ':') {
1343 end++;
1344 default_port = read_uint(&end, url + ulen);
1345 }
1346
1347 /* Copy IP address, set port and family. */
1348 switch (he->h_addrtype) {
1349 case AF_INET:
1350 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1351 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1352 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1353 return end - url;
1354
1355 case AF_INET6:
1356 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1357 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1358 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1359 return end - url;
1360 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001361 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001362 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001363 return -1;
1364}
1365
Willy Tarreau631f01c2011-09-05 00:36:48 +02001366/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1367 * address family is returned so that it's easy for the caller to adapt to the
1368 * output format. Zero is returned if the address family is not supported. -1
1369 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1370 * supported.
1371 */
1372int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1373{
1374
1375 void *ptr;
1376
1377 if (size < 5)
1378 return 0;
1379 *str = '\0';
1380
1381 switch (addr->ss_family) {
1382 case AF_INET:
1383 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1384 break;
1385 case AF_INET6:
1386 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1387 break;
1388 case AF_UNIX:
1389 memcpy(str, "unix", 5);
1390 return addr->ss_family;
1391 default:
1392 return 0;
1393 }
1394
1395 if (inet_ntop(addr->ss_family, ptr, str, size))
1396 return addr->ss_family;
1397
1398 /* failed */
1399 return -1;
1400}
1401
Simon Horman75ab8bd2014-06-16 09:39:41 +09001402/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1403 * address family is returned so that it's easy for the caller to adapt to the
1404 * output format. Zero is returned if the address family is not supported. -1
1405 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1406 * supported.
1407 */
1408int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1409{
1410
1411 uint16_t port;
1412
1413
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001414 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001415 return 0;
1416 *str = '\0';
1417
1418 switch (addr->ss_family) {
1419 case AF_INET:
1420 port = ((struct sockaddr_in *)addr)->sin_port;
1421 break;
1422 case AF_INET6:
1423 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1424 break;
1425 case AF_UNIX:
1426 memcpy(str, "unix", 5);
1427 return addr->ss_family;
1428 default:
1429 return 0;
1430 }
1431
1432 snprintf(str, size, "%u", ntohs(port));
1433 return addr->ss_family;
1434}
1435
Willy Tarreau16e01562016-08-09 16:46:18 +02001436/* check if the given address is local to the system or not. It will return
1437 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1438 * it is. We don't want to iterate over all interfaces for this (and it is not
1439 * portable). So instead we try to bind in UDP to this address on a free non
1440 * privileged port and to connect to the same address, port 0 (connect doesn't
1441 * care). If it succeeds, we own the address. Note that non-inet addresses are
1442 * considered local since they're most likely AF_UNIX.
1443 */
1444int addr_is_local(const struct netns_entry *ns,
1445 const struct sockaddr_storage *orig)
1446{
1447 struct sockaddr_storage addr;
1448 int result;
1449 int fd;
1450
1451 if (!is_inet_addr(orig))
1452 return 1;
1453
1454 memcpy(&addr, orig, sizeof(addr));
1455 set_host_port(&addr, 0);
1456
1457 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1458 if (fd < 0)
1459 return -1;
1460
1461 result = -1;
1462 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1463 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1464 result = 0; // fail, non-local address
1465 else
1466 result = 1; // success, local address
1467 }
1468 else {
1469 if (errno == EADDRNOTAVAIL)
1470 result = 0; // definitely not local :-)
1471 }
1472 close(fd);
1473
1474 return result;
1475}
1476
Willy Tarreaubaaee002006-06-26 02:48:02 +02001477/* will try to encode the string <string> replacing all characters tagged in
1478 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1479 * prefixed by <escape>, and will store the result between <start> (included)
1480 * and <stop> (excluded), and will always terminate the string with a '\0'
1481 * before <stop>. The position of the '\0' is returned if the conversion
1482 * completes. If bytes are missing between <start> and <stop>, then the
1483 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1484 * cannot even be stored so we return <start> without writing the 0.
1485 * The input string must also be zero-terminated.
1486 */
1487const char hextab[16] = "0123456789ABCDEF";
1488char *encode_string(char *start, char *stop,
1489 const char escape, const fd_set *map,
1490 const char *string)
1491{
1492 if (start < stop) {
1493 stop--; /* reserve one byte for the final '\0' */
1494 while (start < stop && *string != '\0') {
1495 if (!FD_ISSET((unsigned char)(*string), map))
1496 *start++ = *string;
1497 else {
1498 if (start + 3 >= stop)
1499 break;
1500 *start++ = escape;
1501 *start++ = hextab[(*string >> 4) & 15];
1502 *start++ = hextab[*string & 15];
1503 }
1504 string++;
1505 }
1506 *start = '\0';
1507 }
1508 return start;
1509}
1510
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001511/*
1512 * Same behavior as encode_string() above, except that it encodes chunk
1513 * <chunk> instead of a string.
1514 */
1515char *encode_chunk(char *start, char *stop,
1516 const char escape, const fd_set *map,
1517 const struct chunk *chunk)
1518{
1519 char *str = chunk->str;
1520 char *end = chunk->str + chunk->len;
1521
1522 if (start < stop) {
1523 stop--; /* reserve one byte for the final '\0' */
1524 while (start < stop && str < end) {
1525 if (!FD_ISSET((unsigned char)(*str), map))
1526 *start++ = *str;
1527 else {
1528 if (start + 3 >= stop)
1529 break;
1530 *start++ = escape;
1531 *start++ = hextab[(*str >> 4) & 15];
1532 *start++ = hextab[*str & 15];
1533 }
1534 str++;
1535 }
1536 *start = '\0';
1537 }
1538 return start;
1539}
1540
Dragan Dosen0edd1092016-02-12 13:23:02 +01001541/*
1542 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001543 * character. The input <string> must be zero-terminated. The result will
1544 * be stored between <start> (included) and <stop> (excluded). This
1545 * function will always try to terminate the resulting string with a '\0'
1546 * before <stop>, and will return its position if the conversion
1547 * completes.
1548 */
1549char *escape_string(char *start, char *stop,
1550 const char escape, const fd_set *map,
1551 const char *string)
1552{
1553 if (start < stop) {
1554 stop--; /* reserve one byte for the final '\0' */
1555 while (start < stop && *string != '\0') {
1556 if (!FD_ISSET((unsigned char)(*string), map))
1557 *start++ = *string;
1558 else {
1559 if (start + 2 >= stop)
1560 break;
1561 *start++ = escape;
1562 *start++ = *string;
1563 }
1564 string++;
1565 }
1566 *start = '\0';
1567 }
1568 return start;
1569}
1570
1571/*
1572 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001573 * character. <chunk> contains the input to be escaped. The result will be
1574 * stored between <start> (included) and <stop> (excluded). The function
1575 * will always try to terminate the resulting string with a '\0' before
1576 * <stop>, and will return its position if the conversion completes.
1577 */
1578char *escape_chunk(char *start, char *stop,
1579 const char escape, const fd_set *map,
1580 const struct chunk *chunk)
1581{
1582 char *str = chunk->str;
1583 char *end = chunk->str + chunk->len;
1584
1585 if (start < stop) {
1586 stop--; /* reserve one byte for the final '\0' */
1587 while (start < stop && str < end) {
1588 if (!FD_ISSET((unsigned char)(*str), map))
1589 *start++ = *str;
1590 else {
1591 if (start + 2 >= stop)
1592 break;
1593 *start++ = escape;
1594 *start++ = *str;
1595 }
1596 str++;
1597 }
1598 *start = '\0';
1599 }
1600 return start;
1601}
1602
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001603/* Check a string for using it in a CSV output format. If the string contains
1604 * one of the following four char <">, <,>, CR or LF, the string is
1605 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1606 * <str> is the input string to be escaped. The function assumes that
1607 * the input string is null-terminated.
1608 *
1609 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001610 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001611 * format.
1612 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001613 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001614 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001615 * If <quote> is 1, the converter puts the quotes only if any reserved character
1616 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001617 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001618 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001619 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001620 * The function returns the converted string on its output. If an error
1621 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001622 * for using the function directly as printf() argument.
1623 *
1624 * If the output buffer is too short to contain the input string, the result
1625 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001626 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001627 * This function appends the encoding to the existing output chunk, and it
1628 * guarantees that it starts immediately at the first available character of
1629 * the chunk. Please use csv_enc() instead if you want to replace the output
1630 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001631 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001632const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001633{
1634 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001635 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001636 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001637
Willy Tarreaub631c292016-01-08 10:04:08 +01001638 if (quote == 1) {
1639 /* automatic quoting: first verify if we'll have to quote the string */
1640 if (!strpbrk(str, "\n\r,\""))
1641 quote = 0;
1642 }
1643
1644 if (quote)
1645 *ptr++ = '"';
1646
Willy Tarreau898529b2016-01-06 18:07:04 +01001647 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1648 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001649 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001650 ptr++;
1651 if (ptr >= end - 2) {
1652 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001653 break;
1654 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001655 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001656 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001657 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001658 str++;
1659 }
1660
Willy Tarreaub631c292016-01-08 10:04:08 +01001661 if (quote)
1662 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001663
Willy Tarreau898529b2016-01-06 18:07:04 +01001664 *ptr = '\0';
1665 output->len = ptr - output->str;
1666 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001667}
1668
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001669/* Decode an URL-encoded string in-place. The resulting string might
1670 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001671 * aborted, the string is truncated before the issue and a negative value is
1672 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001673 */
1674int url_decode(char *string)
1675{
1676 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001677 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001678
1679 in = string;
1680 out = string;
1681 while (*in) {
1682 switch (*in) {
1683 case '+' :
1684 *out++ = ' ';
1685 break;
1686 case '%' :
1687 if (!ishex(in[1]) || !ishex(in[2]))
1688 goto end;
1689 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1690 in += 2;
1691 break;
1692 default:
1693 *out++ = *in;
1694 break;
1695 }
1696 in++;
1697 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001698 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001699 end:
1700 *out = 0;
1701 return ret;
1702}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001703
Willy Tarreau6911fa42007-03-04 18:06:08 +01001704unsigned int str2ui(const char *s)
1705{
1706 return __str2ui(s);
1707}
1708
1709unsigned int str2uic(const char *s)
1710{
1711 return __str2uic(s);
1712}
1713
1714unsigned int strl2ui(const char *s, int len)
1715{
1716 return __strl2ui(s, len);
1717}
1718
1719unsigned int strl2uic(const char *s, int len)
1720{
1721 return __strl2uic(s, len);
1722}
1723
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001724unsigned int read_uint(const char **s, const char *end)
1725{
1726 return __read_uint(s, end);
1727}
1728
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001729/* This function reads an unsigned integer from the string pointed to by <s> and
1730 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1731 * function automatically stops at <end>. If the number overflows, the 2^64-1
1732 * value is returned.
1733 */
1734unsigned long long int read_uint64(const char **s, const char *end)
1735{
1736 const char *ptr = *s;
1737 unsigned long long int i = 0, tmp;
1738 unsigned int j;
1739
1740 while (ptr < end) {
1741
1742 /* read next char */
1743 j = *ptr - '0';
1744 if (j > 9)
1745 goto read_uint64_end;
1746
1747 /* add char to the number and check overflow. */
1748 tmp = i * 10;
1749 if (tmp / 10 != i) {
1750 i = ULLONG_MAX;
1751 goto read_uint64_eat;
1752 }
1753 if (ULLONG_MAX - tmp < j) {
1754 i = ULLONG_MAX;
1755 goto read_uint64_eat;
1756 }
1757 i = tmp + j;
1758 ptr++;
1759 }
1760read_uint64_eat:
1761 /* eat each numeric char */
1762 while (ptr < end) {
1763 if ((unsigned int)(*ptr - '0') > 9)
1764 break;
1765 ptr++;
1766 }
1767read_uint64_end:
1768 *s = ptr;
1769 return i;
1770}
1771
1772/* This function reads an integer from the string pointed to by <s> and returns
1773 * it. The <s> pointer is adjusted to point to the first unread char. The function
1774 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1775 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1776 * returned.
1777 */
1778long long int read_int64(const char **s, const char *end)
1779{
1780 unsigned long long int i = 0;
1781 int neg = 0;
1782
1783 /* Look for minus char. */
1784 if (**s == '-') {
1785 neg = 1;
1786 (*s)++;
1787 }
1788 else if (**s == '+')
1789 (*s)++;
1790
1791 /* convert as positive number. */
1792 i = read_uint64(s, end);
1793
1794 if (neg) {
1795 if (i > 0x8000000000000000ULL)
1796 return LLONG_MIN;
1797 return -i;
1798 }
1799 if (i > 0x7fffffffffffffffULL)
1800 return LLONG_MAX;
1801 return i;
1802}
1803
Willy Tarreau6911fa42007-03-04 18:06:08 +01001804/* This one is 7 times faster than strtol() on athlon with checks.
1805 * It returns the value of the number composed of all valid digits read,
1806 * and can process negative numbers too.
1807 */
1808int strl2ic(const char *s, int len)
1809{
1810 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001811 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001812
1813 if (len > 0) {
1814 if (*s != '-') {
1815 /* positive number */
1816 while (len-- > 0) {
1817 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001818 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001819 if (j > 9)
1820 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001821 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001822 }
1823 } else {
1824 /* negative number */
1825 s++;
1826 while (--len > 0) {
1827 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001828 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001829 if (j > 9)
1830 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001831 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001832 }
1833 }
1834 }
1835 return i;
1836}
1837
1838
1839/* This function reads exactly <len> chars from <s> and converts them to a
1840 * signed integer which it stores into <ret>. It accurately detects any error
1841 * (truncated string, invalid chars, overflows). It is meant to be used in
1842 * applications designed for hostile environments. It returns zero when the
1843 * number has successfully been converted, non-zero otherwise. When an error
1844 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1845 * faster than strtol().
1846 */
1847int strl2irc(const char *s, int len, int *ret)
1848{
1849 int i = 0;
1850 int j;
1851
1852 if (!len)
1853 return 1;
1854
1855 if (*s != '-') {
1856 /* positive number */
1857 while (len-- > 0) {
1858 j = (*s++) - '0';
1859 if (j > 9) return 1; /* invalid char */
1860 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1861 i = i * 10;
1862 if (i + j < i) return 1; /* check for addition overflow */
1863 i = i + j;
1864 }
1865 } else {
1866 /* negative number */
1867 s++;
1868 while (--len > 0) {
1869 j = (*s++) - '0';
1870 if (j > 9) return 1; /* invalid char */
1871 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1872 i = i * 10;
1873 if (i - j > i) return 1; /* check for subtract overflow */
1874 i = i - j;
1875 }
1876 }
1877 *ret = i;
1878 return 0;
1879}
1880
1881
1882/* This function reads exactly <len> chars from <s> and converts them to a
1883 * signed integer which it stores into <ret>. It accurately detects any error
1884 * (truncated string, invalid chars, overflows). It is meant to be used in
1885 * applications designed for hostile environments. It returns zero when the
1886 * number has successfully been converted, non-zero otherwise. When an error
1887 * is returned, the <ret> value is left untouched. It is about 3 times slower
1888 * than str2irc().
1889 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001890
1891int strl2llrc(const char *s, int len, long long *ret)
1892{
1893 long long i = 0;
1894 int j;
1895
1896 if (!len)
1897 return 1;
1898
1899 if (*s != '-') {
1900 /* positive number */
1901 while (len-- > 0) {
1902 j = (*s++) - '0';
1903 if (j > 9) return 1; /* invalid char */
1904 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1905 i = i * 10LL;
1906 if (i + j < i) return 1; /* check for addition overflow */
1907 i = i + j;
1908 }
1909 } else {
1910 /* negative number */
1911 s++;
1912 while (--len > 0) {
1913 j = (*s++) - '0';
1914 if (j > 9) return 1; /* invalid char */
1915 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1916 i = i * 10LL;
1917 if (i - j > i) return 1; /* check for subtract overflow */
1918 i = i - j;
1919 }
1920 }
1921 *ret = i;
1922 return 0;
1923}
1924
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001925/* This function is used with pat_parse_dotted_ver(). It converts a string
1926 * composed by two number separated by a dot. Each part must contain in 16 bits
1927 * because internally they will be represented as a 32-bit quantity stored in
1928 * a 64-bit integer. It returns zero when the number has successfully been
1929 * converted, non-zero otherwise. When an error is returned, the <ret> value
1930 * is left untouched.
1931 *
1932 * "1.3" -> 0x0000000000010003
1933 * "65535.65535" -> 0x00000000ffffffff
1934 */
1935int strl2llrc_dotted(const char *text, int len, long long *ret)
1936{
1937 const char *end = &text[len];
1938 const char *p;
1939 long long major, minor;
1940
1941 /* Look for dot. */
1942 for (p = text; p < end; p++)
1943 if (*p == '.')
1944 break;
1945
1946 /* Convert major. */
1947 if (strl2llrc(text, p - text, &major) != 0)
1948 return 1;
1949
1950 /* Check major. */
1951 if (major >= 65536)
1952 return 1;
1953
1954 /* Convert minor. */
1955 minor = 0;
1956 if (p < end)
1957 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1958 return 1;
1959
1960 /* Check minor. */
1961 if (minor >= 65536)
1962 return 1;
1963
1964 /* Compose value. */
1965 *ret = (major << 16) | (minor & 0xffff);
1966 return 0;
1967}
1968
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001969/* This function parses a time value optionally followed by a unit suffix among
1970 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1971 * expected by the caller. The computation does its best to avoid overflows.
1972 * The value is returned in <ret> if everything is fine, and a NULL is returned
1973 * by the function. In case of error, a pointer to the error is returned and
1974 * <ret> is left untouched. Values are automatically rounded up when needed.
1975 */
1976const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1977{
1978 unsigned imult, idiv;
1979 unsigned omult, odiv;
1980 unsigned value;
1981
1982 omult = odiv = 1;
1983
1984 switch (unit_flags & TIME_UNIT_MASK) {
1985 case TIME_UNIT_US: omult = 1000000; break;
1986 case TIME_UNIT_MS: omult = 1000; break;
1987 case TIME_UNIT_S: break;
1988 case TIME_UNIT_MIN: odiv = 60; break;
1989 case TIME_UNIT_HOUR: odiv = 3600; break;
1990 case TIME_UNIT_DAY: odiv = 86400; break;
1991 default: break;
1992 }
1993
1994 value = 0;
1995
1996 while (1) {
1997 unsigned int j;
1998
1999 j = *text - '0';
2000 if (j > 9)
2001 break;
2002 text++;
2003 value *= 10;
2004 value += j;
2005 }
2006
2007 imult = idiv = 1;
2008 switch (*text) {
2009 case '\0': /* no unit = default unit */
2010 imult = omult = idiv = odiv = 1;
2011 break;
2012 case 's': /* second = unscaled unit */
2013 break;
2014 case 'u': /* microsecond : "us" */
2015 if (text[1] == 's') {
2016 idiv = 1000000;
2017 text++;
2018 }
2019 break;
2020 case 'm': /* millisecond : "ms" or minute: "m" */
2021 if (text[1] == 's') {
2022 idiv = 1000;
2023 text++;
2024 } else
2025 imult = 60;
2026 break;
2027 case 'h': /* hour : "h" */
2028 imult = 3600;
2029 break;
2030 case 'd': /* day : "d" */
2031 imult = 86400;
2032 break;
2033 default:
2034 return text;
2035 break;
2036 }
2037
2038 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2039 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2040 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2041 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2042
2043 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2044 *ret = value;
2045 return NULL;
2046}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002047
Emeric Brun39132b22010-01-04 14:57:24 +01002048/* this function converts the string starting at <text> to an unsigned int
2049 * stored in <ret>. If an error is detected, the pointer to the unexpected
2050 * character is returned. If the conversio is succesful, NULL is returned.
2051 */
2052const char *parse_size_err(const char *text, unsigned *ret) {
2053 unsigned value = 0;
2054
2055 while (1) {
2056 unsigned int j;
2057
2058 j = *text - '0';
2059 if (j > 9)
2060 break;
2061 if (value > ~0U / 10)
2062 return text;
2063 value *= 10;
2064 if (value > (value + j))
2065 return text;
2066 value += j;
2067 text++;
2068 }
2069
2070 switch (*text) {
2071 case '\0':
2072 break;
2073 case 'K':
2074 case 'k':
2075 if (value > ~0U >> 10)
2076 return text;
2077 value = value << 10;
2078 break;
2079 case 'M':
2080 case 'm':
2081 if (value > ~0U >> 20)
2082 return text;
2083 value = value << 20;
2084 break;
2085 case 'G':
2086 case 'g':
2087 if (value > ~0U >> 30)
2088 return text;
2089 value = value << 30;
2090 break;
2091 default:
2092 return text;
2093 }
2094
Godbach58048a22015-01-28 17:36:16 +08002095 if (*text != '\0' && *++text != '\0')
2096 return text;
2097
Emeric Brun39132b22010-01-04 14:57:24 +01002098 *ret = value;
2099 return NULL;
2100}
2101
Willy Tarreau126d4062013-12-03 17:50:47 +01002102/*
2103 * Parse binary string written in hexadecimal (source) and store the decoded
2104 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2105 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002106 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002107 */
2108int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2109{
2110 int len;
2111 const char *p = source;
2112 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002113 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002114
2115 len = strlen(source);
2116 if (len % 2) {
2117 memprintf(err, "an even number of hex digit is expected");
2118 return 0;
2119 }
2120
2121 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002122
Willy Tarreau126d4062013-12-03 17:50:47 +01002123 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002124 *binstr = calloc(len, sizeof(char));
2125 if (!*binstr) {
2126 memprintf(err, "out of memory while loading string pattern");
2127 return 0;
2128 }
2129 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002130 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002131 else {
2132 if (*binstrlen < len) {
2133 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2134 len, *binstrlen);
2135 return 0;
2136 }
2137 alloc = 0;
2138 }
2139 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002140
2141 i = j = 0;
2142 while (j < len) {
2143 if (!ishex(p[i++]))
2144 goto bad_input;
2145 if (!ishex(p[i++]))
2146 goto bad_input;
2147 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2148 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002149 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002150
2151bad_input:
2152 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002153 if (alloc) {
2154 free(*binstr);
2155 *binstr = NULL;
2156 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002157 return 0;
2158}
2159
Willy Tarreau946ba592009-05-10 15:41:18 +02002160/* copies at most <n> characters from <src> and always terminates with '\0' */
2161char *my_strndup(const char *src, int n)
2162{
2163 int len = 0;
2164 char *ret;
2165
2166 while (len < n && src[len])
2167 len++;
2168
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002169 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002170 if (!ret)
2171 return ret;
2172 memcpy(ret, src, len);
2173 ret[len] = '\0';
2174 return ret;
2175}
2176
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002177/*
2178 * search needle in haystack
2179 * returns the pointer if found, returns NULL otherwise
2180 */
2181const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2182{
2183 const void *c = NULL;
2184 unsigned char f;
2185
2186 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2187 return NULL;
2188
2189 f = *(char *)needle;
2190 c = haystack;
2191 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2192 if ((haystacklen - (c - haystack)) < needlelen)
2193 return NULL;
2194
2195 if (memcmp(c, needle, needlelen) == 0)
2196 return c;
2197 ++c;
2198 }
2199 return NULL;
2200}
2201
Willy Tarreau482b00d2009-10-04 22:48:42 +02002202/* This function returns the first unused key greater than or equal to <key> in
2203 * ID tree <root>. Zero is returned if no place is found.
2204 */
2205unsigned int get_next_id(struct eb_root *root, unsigned int key)
2206{
2207 struct eb32_node *used;
2208
2209 do {
2210 used = eb32_lookup_ge(root, key);
2211 if (!used || used->key > key)
2212 return key; /* key is available */
2213 key++;
2214 } while (key);
2215 return key;
2216}
2217
Willy Tarreau348238b2010-01-18 15:05:57 +01002218/* This function compares a sample word possibly followed by blanks to another
2219 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2220 * otherwise zero. This intends to be used when checking HTTP headers for some
2221 * values. Note that it validates a word followed only by blanks but does not
2222 * validate a word followed by blanks then other chars.
2223 */
2224int word_match(const char *sample, int slen, const char *word, int wlen)
2225{
2226 if (slen < wlen)
2227 return 0;
2228
2229 while (wlen) {
2230 char c = *sample ^ *word;
2231 if (c && c != ('A' ^ 'a'))
2232 return 0;
2233 sample++;
2234 word++;
2235 slen--;
2236 wlen--;
2237 }
2238
2239 while (slen) {
2240 if (*sample != ' ' && *sample != '\t')
2241 return 0;
2242 sample++;
2243 slen--;
2244 }
2245 return 1;
2246}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002247
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002248/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2249 * is particularly fast because it avoids expensive operations such as
2250 * multiplies, which are optimized away at the end. It requires a properly
2251 * formated address though (3 points).
2252 */
2253unsigned int inetaddr_host(const char *text)
2254{
2255 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2256 register unsigned int dig100, dig10, dig1;
2257 int s;
2258 const char *p, *d;
2259
2260 dig1 = dig10 = dig100 = ascii_zero;
2261 s = 24;
2262
2263 p = text;
2264 while (1) {
2265 if (((unsigned)(*p - '0')) <= 9) {
2266 p++;
2267 continue;
2268 }
2269
2270 /* here, we have a complete byte between <text> and <p> (exclusive) */
2271 if (p == text)
2272 goto end;
2273
2274 d = p - 1;
2275 dig1 |= (unsigned int)(*d << s);
2276 if (d == text)
2277 goto end;
2278
2279 d--;
2280 dig10 |= (unsigned int)(*d << s);
2281 if (d == text)
2282 goto end;
2283
2284 d--;
2285 dig100 |= (unsigned int)(*d << s);
2286 end:
2287 if (!s || *p != '.')
2288 break;
2289
2290 s -= 8;
2291 text = ++p;
2292 }
2293
2294 dig100 -= ascii_zero;
2295 dig10 -= ascii_zero;
2296 dig1 -= ascii_zero;
2297 return ((dig100 * 10) + dig10) * 10 + dig1;
2298}
2299
2300/*
2301 * Idem except the first unparsed character has to be passed in <stop>.
2302 */
2303unsigned int inetaddr_host_lim(const char *text, const char *stop)
2304{
2305 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2306 register unsigned int dig100, dig10, dig1;
2307 int s;
2308 const char *p, *d;
2309
2310 dig1 = dig10 = dig100 = ascii_zero;
2311 s = 24;
2312
2313 p = text;
2314 while (1) {
2315 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2316 p++;
2317 continue;
2318 }
2319
2320 /* here, we have a complete byte between <text> and <p> (exclusive) */
2321 if (p == text)
2322 goto end;
2323
2324 d = p - 1;
2325 dig1 |= (unsigned int)(*d << s);
2326 if (d == text)
2327 goto end;
2328
2329 d--;
2330 dig10 |= (unsigned int)(*d << s);
2331 if (d == text)
2332 goto end;
2333
2334 d--;
2335 dig100 |= (unsigned int)(*d << s);
2336 end:
2337 if (!s || p == stop || *p != '.')
2338 break;
2339
2340 s -= 8;
2341 text = ++p;
2342 }
2343
2344 dig100 -= ascii_zero;
2345 dig10 -= ascii_zero;
2346 dig1 -= ascii_zero;
2347 return ((dig100 * 10) + dig10) * 10 + dig1;
2348}
2349
2350/*
2351 * Idem except the pointer to first unparsed byte is returned into <ret> which
2352 * must not be NULL.
2353 */
Willy Tarreau74172752010-10-15 23:21:42 +02002354unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002355{
2356 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2357 register unsigned int dig100, dig10, dig1;
2358 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002359 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002360
2361 dig1 = dig10 = dig100 = ascii_zero;
2362 s = 24;
2363
2364 p = text;
2365 while (1) {
2366 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2367 p++;
2368 continue;
2369 }
2370
2371 /* here, we have a complete byte between <text> and <p> (exclusive) */
2372 if (p == text)
2373 goto end;
2374
2375 d = p - 1;
2376 dig1 |= (unsigned int)(*d << s);
2377 if (d == text)
2378 goto end;
2379
2380 d--;
2381 dig10 |= (unsigned int)(*d << s);
2382 if (d == text)
2383 goto end;
2384
2385 d--;
2386 dig100 |= (unsigned int)(*d << s);
2387 end:
2388 if (!s || p == stop || *p != '.')
2389 break;
2390
2391 s -= 8;
2392 text = ++p;
2393 }
2394
2395 *ret = p;
2396 dig100 -= ascii_zero;
2397 dig10 -= ascii_zero;
2398 dig1 -= ascii_zero;
2399 return ((dig100 * 10) + dig10) * 10 + dig1;
2400}
2401
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002402/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2403 * or the number of chars read in case of success. Maybe this could be replaced
2404 * by one of the functions above. Also, apparently this function does not support
2405 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002406 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002407 */
2408int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2409{
2410 const char *addr;
2411 int saw_digit, octets, ch;
2412 u_char tmp[4], *tp;
2413 const char *cp = buf;
2414
2415 saw_digit = 0;
2416 octets = 0;
2417 *(tp = tmp) = 0;
2418
2419 for (addr = buf; addr - buf < len; addr++) {
2420 unsigned char digit = (ch = *addr) - '0';
2421
2422 if (digit > 9 && ch != '.')
2423 break;
2424
2425 if (digit <= 9) {
2426 u_int new = *tp * 10 + digit;
2427
2428 if (new > 255)
2429 return 0;
2430
2431 *tp = new;
2432
2433 if (!saw_digit) {
2434 if (++octets > 4)
2435 return 0;
2436 saw_digit = 1;
2437 }
2438 } else if (ch == '.' && saw_digit) {
2439 if (octets == 4)
2440 return 0;
2441
2442 *++tp = 0;
2443 saw_digit = 0;
2444 } else
2445 return 0;
2446 }
2447
2448 if (octets < 4)
2449 return 0;
2450
2451 memcpy(&dst->s_addr, tmp, 4);
2452 return addr - cp;
2453}
2454
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002455/* This function converts the string in <buf> of the len <len> to
2456 * struct in6_addr <dst> which must be allocated by the caller.
2457 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002458 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002459 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002460int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2461{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002462 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002463 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002464
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002465 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002466 return 0;
2467
2468 memcpy(null_term_ip6, buf, len);
2469 null_term_ip6[len] = '\0';
2470
Willy Tarreau075415a2013-12-12 11:29:39 +01002471 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002472 return 0;
2473
Willy Tarreau075415a2013-12-12 11:29:39 +01002474 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002475 return 1;
2476}
2477
Willy Tarreauacf95772010-06-14 19:09:21 +02002478/* To be used to quote config arg positions. Returns the short string at <ptr>
2479 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2480 * if ptr is NULL or empty. The string is locally allocated.
2481 */
2482const char *quote_arg(const char *ptr)
2483{
2484 static char val[32];
2485 int i;
2486
2487 if (!ptr || !*ptr)
2488 return "end of line";
2489 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002490 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002491 val[i] = *ptr++;
2492 val[i++] = '\'';
2493 val[i] = '\0';
2494 return val;
2495}
2496
Willy Tarreau5b180202010-07-18 10:40:48 +02002497/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2498int get_std_op(const char *str)
2499{
2500 int ret = -1;
2501
2502 if (*str == 'e' && str[1] == 'q')
2503 ret = STD_OP_EQ;
2504 else if (*str == 'n' && str[1] == 'e')
2505 ret = STD_OP_NE;
2506 else if (*str == 'l') {
2507 if (str[1] == 'e') ret = STD_OP_LE;
2508 else if (str[1] == 't') ret = STD_OP_LT;
2509 }
2510 else if (*str == 'g') {
2511 if (str[1] == 'e') ret = STD_OP_GE;
2512 else if (str[1] == 't') ret = STD_OP_GT;
2513 }
2514
2515 if (ret == -1 || str[2] != '\0')
2516 return -1;
2517 return ret;
2518}
2519
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002520/* hash a 32-bit integer to another 32-bit integer */
2521unsigned int full_hash(unsigned int a)
2522{
2523 return __full_hash(a);
2524}
2525
David du Colombier4f92d322011-03-24 11:09:31 +01002526/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002527 * otherwise zero. Note that <addr> may not necessarily be aligned
2528 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002529 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002530int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002531{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002532 struct in_addr addr_copy;
2533
2534 memcpy(&addr_copy, addr, sizeof(addr_copy));
2535 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002536}
2537
2538/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002539 * otherwise zero. Note that <addr> may not necessarily be aligned
2540 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002541 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002542int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002543{
2544 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002545 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002546
Willy Tarreaueec1d382016-07-13 11:59:39 +02002547 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002548 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002549 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002550 (((int *)net)[i] & ((int *)mask)[i]))
2551 return 0;
2552 return 1;
2553}
2554
2555/* RFC 4291 prefix */
2556const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2557 0x00, 0x00, 0x00, 0x00,
2558 0x00, 0x00, 0xFF, 0xFF };
2559
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002560/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2561 * Input and output may overlap.
2562 */
David du Colombier4f92d322011-03-24 11:09:31 +01002563void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2564{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002565 struct in_addr tmp_addr;
2566
2567 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002568 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002569 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002570}
2571
2572/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2573 * Return true if conversion is possible and false otherwise.
2574 */
2575int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2576{
2577 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2578 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2579 sizeof(struct in_addr));
2580 return 1;
2581 }
2582
2583 return 0;
2584}
2585
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002586/* compare two struct sockaddr_storage and return:
2587 * 0 (true) if the addr is the same in both
2588 * 1 (false) if the addr is not the same in both
2589 * -1 (unable) if one of the addr is not AF_INET*
2590 */
2591int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2592{
2593 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2594 return -1;
2595
2596 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2597 return -1;
2598
2599 if (ss1->ss_family != ss2->ss_family)
2600 return 1;
2601
2602 switch (ss1->ss_family) {
2603 case AF_INET:
2604 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2605 &((struct sockaddr_in *)ss2)->sin_addr,
2606 sizeof(struct in_addr)) != 0;
2607 case AF_INET6:
2608 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2609 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2610 sizeof(struct in6_addr)) != 0;
2611 }
2612
2613 return 1;
2614}
2615
Baptiste Assmann08396c82016-01-31 00:27:17 +01002616/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002617 * The caller must allocate and clear <dest> before calling.
2618 * The source must be in either AF_INET or AF_INET6 family, or the destination
2619 * address will be undefined. If the destination address used to hold a port,
2620 * it is preserved, so that this function can be used to switch to another
2621 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002622 */
2623struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2624{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002625 int prev_port;
2626
2627 prev_port = get_net_port(dest);
2628 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002629 dest->ss_family = source->ss_family;
2630
2631 /* copy new addr and apply it */
2632 switch (source->ss_family) {
2633 case AF_INET:
2634 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002635 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002636 break;
2637 case AF_INET6:
2638 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 +01002639 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002640 break;
2641 }
2642
2643 return dest;
2644}
2645
William Lallemand421f5b52012-02-06 18:15:57 +01002646char *human_time(int t, short hz_div) {
2647 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2648 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002649 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002650 int cnt=2; // print two numbers
2651
2652 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002653 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002654 return rv;
2655 }
2656
2657 if (unlikely(hz_div > 1))
2658 t /= hz_div;
2659
2660 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002661 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002662 cnt--;
2663 }
2664
2665 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002666 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002667 cnt--;
2668 }
2669
2670 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002671 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002672 cnt--;
2673 }
2674
2675 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002676 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002677
2678 return rv;
2679}
2680
2681const char *monthname[12] = {
2682 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2683 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2684};
2685
2686/* date2str_log: write a date in the format :
2687 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2688 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2689 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2690 *
2691 * without using sprintf. return a pointer to the last char written (\0) or
2692 * NULL if there isn't enough space.
2693 */
2694char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2695{
2696
2697 if (size < 25) /* the size is fixed: 24 chars + \0 */
2698 return NULL;
2699
2700 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2701 *dst++ = '/';
2702 memcpy(dst, monthname[tm->tm_mon], 3); // month
2703 dst += 3;
2704 *dst++ = '/';
2705 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2706 *dst++ = ':';
2707 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2708 *dst++ = ':';
2709 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2710 *dst++ = ':';
2711 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2712 *dst++ = '.';
2713 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2714 dst += 3; // only the 3 first digits
2715 *dst = '\0';
2716
2717 return dst;
2718}
2719
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002720/* Base year used to compute leap years */
2721#define TM_YEAR_BASE 1900
2722
2723/* Return the difference in seconds between two times (leap seconds are ignored).
2724 * Retrieved from glibc 2.18 source code.
2725 */
2726static int my_tm_diff(const struct tm *a, const struct tm *b)
2727{
2728 /* Compute intervening leap days correctly even if year is negative.
2729 * Take care to avoid int overflow in leap day calculations,
2730 * but it's OK to assume that A and B are close to each other.
2731 */
2732 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2733 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2734 int a100 = a4 / 25 - (a4 % 25 < 0);
2735 int b100 = b4 / 25 - (b4 % 25 < 0);
2736 int a400 = a100 >> 2;
2737 int b400 = b100 >> 2;
2738 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2739 int years = a->tm_year - b->tm_year;
2740 int days = (365 * years + intervening_leap_days
2741 + (a->tm_yday - b->tm_yday));
2742 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2743 + (a->tm_min - b->tm_min))
2744 + (a->tm_sec - b->tm_sec));
2745}
2746
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002747/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002748 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002749 * The string returned has the same format as returned by strftime(... "%z", tm).
2750 * Offsets are kept in an internal cache for better performances.
2751 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002752const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002753{
2754 /* Cache offsets from GMT (depending on whether DST is active or not) */
2755 static char gmt_offsets[2][5+1] = { "", "" };
2756
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002757 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002758 struct tm tm_gmt;
2759 int diff;
2760 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002761
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002762 /* Pretend DST not active if its status is unknown */
2763 if (isdst < 0)
2764 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002765
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002766 /* Fetch the offset and initialize it if needed */
2767 gmt_offset = gmt_offsets[isdst & 0x01];
2768 if (unlikely(!*gmt_offset)) {
2769 get_gmtime(t, &tm_gmt);
2770 diff = my_tm_diff(tm, &tm_gmt);
2771 if (diff < 0) {
2772 diff = -diff;
2773 *gmt_offset = '-';
2774 } else {
2775 *gmt_offset = '+';
2776 }
2777 diff /= 60; /* Convert to minutes */
2778 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2779 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002780
2781 return gmt_offset;
2782}
2783
William Lallemand421f5b52012-02-06 18:15:57 +01002784/* gmt2str_log: write a date in the format :
2785 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2786 * return a pointer to the last char written (\0) or
2787 * NULL if there isn't enough space.
2788 */
2789char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2790{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002791 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002792 return NULL;
2793
2794 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2795 *dst++ = '/';
2796 memcpy(dst, monthname[tm->tm_mon], 3); // month
2797 dst += 3;
2798 *dst++ = '/';
2799 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2800 *dst++ = ':';
2801 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2802 *dst++ = ':';
2803 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2804 *dst++ = ':';
2805 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2806 *dst++ = ' ';
2807 *dst++ = '+';
2808 *dst++ = '0';
2809 *dst++ = '0';
2810 *dst++ = '0';
2811 *dst++ = '0';
2812 *dst = '\0';
2813
2814 return dst;
2815}
2816
Yuxans Yao4e25b012012-10-19 10:36:09 +08002817/* localdate2str_log: write a date in the format :
2818 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002819 * Both t and tm must represent the same time.
2820 * return a pointer to the last char written (\0) or
2821 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002822 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002823char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002824{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002825 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002826 if (size < 27) /* the size is fixed: 26 chars + \0 */
2827 return NULL;
2828
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002829 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002830
Yuxans Yao4e25b012012-10-19 10:36:09 +08002831 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2832 *dst++ = '/';
2833 memcpy(dst, monthname[tm->tm_mon], 3); // month
2834 dst += 3;
2835 *dst++ = '/';
2836 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2837 *dst++ = ':';
2838 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2839 *dst++ = ':';
2840 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2841 *dst++ = ':';
2842 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2843 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002844 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002845 dst += 5;
2846 *dst = '\0';
2847
2848 return dst;
2849}
2850
Thierry Fournier93127942016-01-20 18:49:45 +01002851/* This function check a char. It returns true and updates
2852 * <date> and <len> pointer to the new position if the
2853 * character is found.
2854 */
2855static inline int parse_expect_char(const char **date, int *len, char c)
2856{
2857 if (*len < 1 || **date != c)
2858 return 0;
2859 (*len)--;
2860 (*date)++;
2861 return 1;
2862}
2863
2864/* This function expects a string <str> of len <l>. It return true and updates.
2865 * <date> and <len> if the string matches, otherwise, it returns false.
2866 */
2867static inline int parse_strcmp(const char **date, int *len, char *str, int l)
2868{
2869 if (*len < l || strncmp(*date, str, l) != 0)
2870 return 0;
2871 (*len) -= l;
2872 (*date) += l;
2873 return 1;
2874}
2875
2876/* This macro converts 3 chars name in integer. */
2877#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
2878
2879/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
2880 * / %x54.75.65 ; "Tue", case-sensitive
2881 * / %x57.65.64 ; "Wed", case-sensitive
2882 * / %x54.68.75 ; "Thu", case-sensitive
2883 * / %x46.72.69 ; "Fri", case-sensitive
2884 * / %x53.61.74 ; "Sat", case-sensitive
2885 * / %x53.75.6E ; "Sun", case-sensitive
2886 *
2887 * This array must be alphabetically sorted
2888 */
2889static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
2890{
2891 if (*len < 3)
2892 return 0;
2893 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2894 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
2895 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
2896 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
2897 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
2898 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
2899 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
2900 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
2901 default: return 0;
2902 }
2903 *len -= 3;
2904 *date += 3;
2905 return 1;
2906}
2907
2908/* month = %x4A.61.6E ; "Jan", case-sensitive
2909 * / %x46.65.62 ; "Feb", case-sensitive
2910 * / %x4D.61.72 ; "Mar", case-sensitive
2911 * / %x41.70.72 ; "Apr", case-sensitive
2912 * / %x4D.61.79 ; "May", case-sensitive
2913 * / %x4A.75.6E ; "Jun", case-sensitive
2914 * / %x4A.75.6C ; "Jul", case-sensitive
2915 * / %x41.75.67 ; "Aug", case-sensitive
2916 * / %x53.65.70 ; "Sep", case-sensitive
2917 * / %x4F.63.74 ; "Oct", case-sensitive
2918 * / %x4E.6F.76 ; "Nov", case-sensitive
2919 * / %x44.65.63 ; "Dec", case-sensitive
2920 *
2921 * This array must be alphabetically sorted
2922 */
2923static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
2924{
2925 if (*len < 3)
2926 return 0;
2927 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2928 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
2929 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
2930 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
2931 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
2932 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
2933 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
2934 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
2935 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
2936 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
2937 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
2938 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
2939 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
2940 default: return 0;
2941 }
2942 *len -= 3;
2943 *date += 3;
2944 return 1;
2945}
2946
2947/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
2948 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
2949 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
2950 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
2951 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
2952 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
2953 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
2954 *
2955 * This array must be alphabetically sorted
2956 */
2957static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
2958{
2959 if (*len < 6) /* Minimum length. */
2960 return 0;
2961 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2962 case STR2I3('M','o','n'):
2963 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
2964 tm->tm_wday = 1;
2965 return 1;
2966 case STR2I3('T','u','e'):
2967 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
2968 tm->tm_wday = 2;
2969 return 1;
2970 case STR2I3('W','e','d'):
2971 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
2972 tm->tm_wday = 3;
2973 return 1;
2974 case STR2I3('T','h','u'):
2975 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
2976 tm->tm_wday = 4;
2977 return 1;
2978 case STR2I3('F','r','i'):
2979 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
2980 tm->tm_wday = 5;
2981 return 1;
2982 case STR2I3('S','a','t'):
2983 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
2984 tm->tm_wday = 6;
2985 return 1;
2986 case STR2I3('S','u','n'):
2987 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
2988 tm->tm_wday = 7;
2989 return 1;
2990 }
2991 return 0;
2992}
2993
2994/* This function parses exactly 1 digit and returns the numeric value in "digit". */
2995static inline int parse_digit(const char **date, int *len, int *digit)
2996{
2997 if (*len < 1 || **date < '0' || **date > '9')
2998 return 0;
2999 *digit = (**date - '0');
3000 (*date)++;
3001 (*len)--;
3002 return 1;
3003}
3004
3005/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3006static inline int parse_2digit(const char **date, int *len, int *digit)
3007{
3008 int value;
3009
3010 RET0_UNLESS(parse_digit(date, len, &value));
3011 (*digit) = value * 10;
3012 RET0_UNLESS(parse_digit(date, len, &value));
3013 (*digit) += value;
3014
3015 return 1;
3016}
3017
3018/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3019static inline int parse_4digit(const char **date, int *len, int *digit)
3020{
3021 int value;
3022
3023 RET0_UNLESS(parse_digit(date, len, &value));
3024 (*digit) = value * 1000;
3025
3026 RET0_UNLESS(parse_digit(date, len, &value));
3027 (*digit) += value * 100;
3028
3029 RET0_UNLESS(parse_digit(date, len, &value));
3030 (*digit) += value * 10;
3031
3032 RET0_UNLESS(parse_digit(date, len, &value));
3033 (*digit) += value;
3034
3035 return 1;
3036}
3037
3038/* time-of-day = hour ":" minute ":" second
3039 * ; 00:00:00 - 23:59:60 (leap second)
3040 *
3041 * hour = 2DIGIT
3042 * minute = 2DIGIT
3043 * second = 2DIGIT
3044 */
3045static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3046{
3047 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3048 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3049 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3050 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3051 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3052 return 1;
3053}
3054
3055/* From RFC7231
3056 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3057 *
3058 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3059 * ; fixed length/zone/capitalization subset of the format
3060 * ; see Section 3.3 of [RFC5322]
3061 *
3062 *
3063 * date1 = day SP month SP year
3064 * ; e.g., 02 Jun 1982
3065 *
3066 * day = 2DIGIT
3067 * year = 4DIGIT
3068 *
3069 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3070 *
3071 * time-of-day = hour ":" minute ":" second
3072 * ; 00:00:00 - 23:59:60 (leap second)
3073 *
3074 * hour = 2DIGIT
3075 * minute = 2DIGIT
3076 * second = 2DIGIT
3077 *
3078 * DIGIT = decimal 0-9
3079 */
3080int parse_imf_date(const char *date, int len, struct tm *tm)
3081{
David Carlier327298c2016-11-20 10:42:38 +00003082 /* tm_gmtoff, if present, ought to be zero'ed */
3083 memset(tm, 0, sizeof(*tm));
3084
Thierry Fournier93127942016-01-20 18:49:45 +01003085 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3086 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3087 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3088 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3089 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3090 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3091 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3092 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3093 tm->tm_year -= 1900;
3094 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3095 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3096 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3097 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3098 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003099 return 1;
3100}
3101
3102/* From RFC7231
3103 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3104 *
3105 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3106 * date2 = day "-" month "-" 2DIGIT
3107 * ; e.g., 02-Jun-82
3108 *
3109 * day = 2DIGIT
3110 */
3111int parse_rfc850_date(const char *date, int len, struct tm *tm)
3112{
3113 int year;
3114
David Carlier327298c2016-11-20 10:42:38 +00003115 /* tm_gmtoff, if present, ought to be zero'ed */
3116 memset(tm, 0, sizeof(*tm));
3117
Thierry Fournier93127942016-01-20 18:49:45 +01003118 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3119 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3120 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3121 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3122 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3123 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3124 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3125
3126 /* year = 2DIGIT
3127 *
3128 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3129 * two-digit year, MUST interpret a timestamp that appears to be more
3130 * than 50 years in the future as representing the most recent year in
3131 * the past that had the same last two digits.
3132 */
3133 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3134
3135 /* expect SP */
3136 if (!parse_expect_char(&date, &len, ' ')) {
3137 /* Maybe we have the date with 4 digits. */
3138 RET0_UNLESS(parse_2digit(&date, &len, &year));
3139 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3140 /* expect SP */
3141 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3142 } else {
3143 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3144 * tm_year is the number of year since 1900, so for +1900, we
3145 * do nothing, and for +2000, we add 100.
3146 */
3147 if (tm->tm_year <= 60)
3148 tm->tm_year += 100;
3149 }
3150
3151 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3152 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3153 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3154 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003155
3156 return 1;
3157}
3158
3159/* From RFC7231
3160 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3161 *
3162 * asctime-date = day-name SP date3 SP time-of-day SP year
3163 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3164 * ; e.g., Jun 2
3165 *
3166 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3167 * whitespace in an HTTP-date beyond that specifically included as SP in
3168 * the grammar.
3169 */
3170int parse_asctime_date(const char *date, int len, struct tm *tm)
3171{
David Carlier327298c2016-11-20 10:42:38 +00003172 /* tm_gmtoff, if present, ought to be zero'ed */
3173 memset(tm, 0, sizeof(*tm));
3174
Thierry Fournier93127942016-01-20 18:49:45 +01003175 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3176 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3177 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3178 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3179
3180 /* expect SP and 1DIGIT or 2DIGIT */
3181 if (parse_expect_char(&date, &len, ' '))
3182 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3183 else
3184 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3185
3186 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3187 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3188 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3189 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3190 tm->tm_year -= 1900;
3191 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003192 return 1;
3193}
3194
3195/* From RFC7231
3196 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3197 *
3198 * HTTP-date = IMF-fixdate / obs-date
3199 * obs-date = rfc850-date / asctime-date
3200 *
3201 * parses an HTTP date in the RFC format and is accepted
3202 * alternatives. <date> is the strinf containing the date,
3203 * len is the len of the string. <tm> is filled with the
3204 * parsed time. We must considers this time as GMT.
3205 */
3206int parse_http_date(const char *date, int len, struct tm *tm)
3207{
3208 if (parse_imf_date(date, len, tm))
3209 return 1;
3210
3211 if (parse_rfc850_date(date, len, tm))
3212 return 1;
3213
3214 if (parse_asctime_date(date, len, tm))
3215 return 1;
3216
3217 return 0;
3218}
3219
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003220/* Dynamically allocates a string of the proper length to hold the formatted
3221 * output. NULL is returned on error. The caller is responsible for freeing the
3222 * memory area using free(). The resulting string is returned in <out> if the
3223 * pointer is not NULL. A previous version of <out> might be used to build the
3224 * new string, and it will be freed before returning if it is not NULL, which
3225 * makes it possible to build complex strings from iterative calls without
3226 * having to care about freeing intermediate values, as in the example below :
3227 *
3228 * memprintf(&err, "invalid argument: '%s'", arg);
3229 * ...
3230 * memprintf(&err, "parser said : <%s>\n", *err);
3231 * ...
3232 * free(*err);
3233 *
3234 * This means that <err> must be initialized to NULL before first invocation.
3235 * The return value also holds the allocated string, which eases error checking
3236 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003237 * passed instead and it will be ignored. The returned message will then also
3238 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003239 *
3240 * It is also convenient to use it without any free except the last one :
3241 * err = NULL;
3242 * if (!fct1(err)) report(*err);
3243 * if (!fct2(err)) report(*err);
3244 * if (!fct3(err)) report(*err);
3245 * free(*err);
3246 */
3247char *memprintf(char **out, const char *format, ...)
3248{
3249 va_list args;
3250 char *ret = NULL;
3251 int allocated = 0;
3252 int needed = 0;
3253
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003254 if (!out)
3255 return NULL;
3256
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003257 do {
3258 /* vsnprintf() will return the required length even when the
3259 * target buffer is NULL. We do this in a loop just in case
3260 * intermediate evaluations get wrong.
3261 */
3262 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003263 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003264 va_end(args);
3265
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003266 if (needed < allocated) {
3267 /* Note: on Solaris 8, the first iteration always
3268 * returns -1 if allocated is zero, so we force a
3269 * retry.
3270 */
3271 if (!allocated)
3272 needed = 0;
3273 else
3274 break;
3275 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003276
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003277 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003278 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003279 } while (ret);
3280
3281 if (needed < 0) {
3282 /* an error was encountered */
3283 free(ret);
3284 ret = NULL;
3285 }
3286
3287 if (out) {
3288 free(*out);
3289 *out = ret;
3290 }
3291
3292 return ret;
3293}
William Lallemand421f5b52012-02-06 18:15:57 +01003294
Willy Tarreau21c705b2012-09-14 11:40:36 +02003295/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3296 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003297 * freed by the caller. It also supports being passed a NULL which results in the same
3298 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003299 * Example of use :
3300 * parse(cmd, &err); (callee: memprintf(&err, ...))
3301 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3302 * free(err);
3303 */
3304char *indent_msg(char **out, int level)
3305{
3306 char *ret, *in, *p;
3307 int needed = 0;
3308 int lf = 0;
3309 int lastlf = 0;
3310 int len;
3311
Willy Tarreau70eec382012-10-10 08:56:47 +02003312 if (!out || !*out)
3313 return NULL;
3314
Willy Tarreau21c705b2012-09-14 11:40:36 +02003315 in = *out - 1;
3316 while ((in = strchr(in + 1, '\n')) != NULL) {
3317 lastlf = in - *out;
3318 lf++;
3319 }
3320
3321 if (!lf) /* single line, no LF, return it as-is */
3322 return *out;
3323
3324 len = strlen(*out);
3325
3326 if (lf == 1 && lastlf == len - 1) {
3327 /* single line, LF at end, strip it and return as-is */
3328 (*out)[lastlf] = 0;
3329 return *out;
3330 }
3331
3332 /* OK now we have at least one LF, we need to process the whole string
3333 * as a multi-line string. What we'll do :
3334 * - prefix with an LF if there is none
3335 * - add <level> spaces before each line
3336 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3337 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3338 */
3339
3340 needed = 1 + level * (lf + 1) + len + 1;
3341 p = ret = malloc(needed);
3342 in = *out;
3343
3344 /* skip initial LFs */
3345 while (*in == '\n')
3346 in++;
3347
3348 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3349 while (*in) {
3350 *p++ = '\n';
3351 memset(p, ' ', level);
3352 p += level;
3353 do {
3354 *p++ = *in++;
3355 } while (*in && *in != '\n');
3356 if (*in)
3357 in++;
3358 }
3359 *p = 0;
3360
3361 free(*out);
3362 *out = ret;
3363
3364 return ret;
3365}
3366
Willy Tarreaudad36a32013-03-11 01:20:04 +01003367/* Convert occurrences of environment variables in the input string to their
3368 * corresponding value. A variable is identified as a series of alphanumeric
3369 * characters or underscores following a '$' sign. The <in> string must be
3370 * free()able. NULL returns NULL. The resulting string might be reallocated if
3371 * some expansion is made. Variable names may also be enclosed into braces if
3372 * needed (eg: to concatenate alphanum characters).
3373 */
3374char *env_expand(char *in)
3375{
3376 char *txt_beg;
3377 char *out;
3378 char *txt_end;
3379 char *var_beg;
3380 char *var_end;
3381 char *value;
3382 char *next;
3383 int out_len;
3384 int val_len;
3385
3386 if (!in)
3387 return in;
3388
3389 value = out = NULL;
3390 out_len = 0;
3391
3392 txt_beg = in;
3393 do {
3394 /* look for next '$' sign in <in> */
3395 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3396
3397 if (!*txt_end && !out) /* end and no expansion performed */
3398 return in;
3399
3400 val_len = 0;
3401 next = txt_end;
3402 if (*txt_end == '$') {
3403 char save;
3404
3405 var_beg = txt_end + 1;
3406 if (*var_beg == '{')
3407 var_beg++;
3408
3409 var_end = var_beg;
3410 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3411 var_end++;
3412 }
3413
3414 next = var_end;
3415 if (*var_end == '}' && (var_beg > txt_end + 1))
3416 next++;
3417
3418 /* get value of the variable name at this location */
3419 save = *var_end;
3420 *var_end = '\0';
3421 value = getenv(var_beg);
3422 *var_end = save;
3423 val_len = value ? strlen(value) : 0;
3424 }
3425
Hubert Verstraete831962e2016-06-28 22:44:26 +02003426 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003427 if (txt_end > txt_beg) {
3428 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3429 out_len += txt_end - txt_beg;
3430 }
3431 if (val_len) {
3432 memcpy(out + out_len, value, val_len);
3433 out_len += val_len;
3434 }
3435 out[out_len] = 0;
3436 txt_beg = next;
3437 } while (*txt_beg);
3438
3439 /* here we know that <out> was allocated and that we don't need <in> anymore */
3440 free(in);
3441 return out;
3442}
3443
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003444
3445/* same as strstr() but case-insensitive and with limit length */
3446const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3447{
3448 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003449 unsigned int slen, plen;
3450 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003451
3452 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3453 return NULL;
3454
3455 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3456 return str1;
3457
3458 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3459 return NULL;
3460
3461 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3462 while (toupper(*start) != toupper(*str2)) {
3463 start++;
3464 slen--;
3465 tmp1++;
3466
3467 if (tmp1 >= len_str1)
3468 return NULL;
3469
3470 /* if pattern longer than string */
3471 if (slen < plen)
3472 return NULL;
3473 }
3474
3475 sptr = start;
3476 pptr = (char *)str2;
3477
3478 tmp2 = 0;
3479 while (toupper(*sptr) == toupper(*pptr)) {
3480 sptr++;
3481 pptr++;
3482 tmp2++;
3483
3484 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3485 return start;
3486 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3487 return NULL;
3488 }
3489 }
3490 return NULL;
3491}
3492
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003493/* This function read the next valid utf8 char.
3494 * <s> is the byte srray to be decode, <len> is its length.
3495 * The function returns decoded char encoded like this:
3496 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3497 * are the length read. The decoded character is stored in <c>.
3498 */
3499unsigned char utf8_next(const char *s, int len, unsigned int *c)
3500{
3501 const unsigned char *p = (unsigned char *)s;
3502 int dec;
3503 unsigned char code = UTF8_CODE_OK;
3504
3505 if (len < 1)
3506 return UTF8_CODE_OK;
3507
3508 /* Check the type of UTF8 sequence
3509 *
3510 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3511 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3512 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3513 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3514 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3515 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3516 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3517 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3518 */
3519 switch (*p) {
3520 case 0x00 ... 0x7f:
3521 *c = *p;
3522 return UTF8_CODE_OK | 1;
3523
3524 case 0x80 ... 0xbf:
3525 *c = *p;
3526 return UTF8_CODE_BADSEQ | 1;
3527
3528 case 0xc0 ... 0xdf:
3529 if (len < 2) {
3530 *c = *p;
3531 return UTF8_CODE_BADSEQ | 1;
3532 }
3533 *c = *p & 0x1f;
3534 dec = 1;
3535 break;
3536
3537 case 0xe0 ... 0xef:
3538 if (len < 3) {
3539 *c = *p;
3540 return UTF8_CODE_BADSEQ | 1;
3541 }
3542 *c = *p & 0x0f;
3543 dec = 2;
3544 break;
3545
3546 case 0xf0 ... 0xf7:
3547 if (len < 4) {
3548 *c = *p;
3549 return UTF8_CODE_BADSEQ | 1;
3550 }
3551 *c = *p & 0x07;
3552 dec = 3;
3553 break;
3554
3555 case 0xf8 ... 0xfb:
3556 if (len < 5) {
3557 *c = *p;
3558 return UTF8_CODE_BADSEQ | 1;
3559 }
3560 *c = *p & 0x03;
3561 dec = 4;
3562 break;
3563
3564 case 0xfc ... 0xfd:
3565 if (len < 6) {
3566 *c = *p;
3567 return UTF8_CODE_BADSEQ | 1;
3568 }
3569 *c = *p & 0x01;
3570 dec = 5;
3571 break;
3572
3573 case 0xfe ... 0xff:
3574 default:
3575 *c = *p;
3576 return UTF8_CODE_BADSEQ | 1;
3577 }
3578
3579 p++;
3580
3581 while (dec > 0) {
3582
3583 /* need 0x10 for the 2 first bits */
3584 if ( ( *p & 0xc0 ) != 0x80 )
3585 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3586
3587 /* add data at char */
3588 *c = ( *c << 6 ) | ( *p & 0x3f );
3589
3590 dec--;
3591 p++;
3592 }
3593
3594 /* Check ovelong encoding.
3595 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3596 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3597 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3598 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003599 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003600 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3601 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3602 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3603 code |= UTF8_CODE_OVERLONG;
3604
3605 /* Check invalid UTF8 range. */
3606 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3607 (*c >= 0xfffe && *c <= 0xffff))
3608 code |= UTF8_CODE_INVRANGE;
3609
3610 return code | ((p-(unsigned char *)s)&0x0f);
3611}
3612
Maxime de Roucydc887852016-05-13 23:52:54 +02003613/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3614 * On failure : return 0 and <err> filled with an error message.
3615 * The caller is responsible for freeing the <err> and <str> copy
3616 * memory area using free()
3617 */
3618int list_append_word(struct list *li, const char *str, char **err)
3619{
3620 struct wordlist *wl;
3621
3622 wl = calloc(1, sizeof(*wl));
3623 if (!wl) {
3624 memprintf(err, "out of memory");
3625 goto fail_wl;
3626 }
3627
3628 wl->s = strdup(str);
3629 if (!wl->s) {
3630 memprintf(err, "out of memory");
3631 goto fail_wl_s;
3632 }
3633
3634 LIST_ADDQ(li, &wl->list);
3635
3636 return 1;
3637
3638fail_wl_s:
3639 free(wl->s);
3640fail_wl:
3641 free(wl);
3642 return 0;
3643}
3644
Willy Tarreau97c2ae12016-11-22 18:00:20 +01003645/* print a string of text buffer to <out>. The format is :
3646 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
3647 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
3648 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
3649 */
3650int dump_text(struct chunk *out, const char *buf, int bsize)
3651{
3652 unsigned char c;
3653 int ptr = 0;
3654
3655 while (buf[ptr] && ptr < bsize) {
3656 c = buf[ptr];
3657 if (isprint(c) && isascii(c) && c != '\\' && c != ' ' && c != '=') {
3658 if (out->len > out->size - 1)
3659 break;
3660 out->str[out->len++] = c;
3661 }
3662 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
3663 if (out->len > out->size - 2)
3664 break;
3665 out->str[out->len++] = '\\';
3666 switch (c) {
3667 case ' ': c = ' '; break;
3668 case '\t': c = 't'; break;
3669 case '\n': c = 'n'; break;
3670 case '\r': c = 'r'; break;
3671 case '\e': c = 'e'; break;
3672 case '\\': c = '\\'; break;
3673 case '=': c = '='; break;
3674 }
3675 out->str[out->len++] = c;
3676 }
3677 else {
3678 if (out->len > out->size - 4)
3679 break;
3680 out->str[out->len++] = '\\';
3681 out->str[out->len++] = 'x';
3682 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3683 out->str[out->len++] = hextab[c & 0xF];
3684 }
3685 ptr++;
3686 }
3687
3688 return ptr;
3689}
3690
3691/* print a buffer in hexa.
3692 * Print stopped if <bsize> is reached, or if no more place in the chunk.
3693 */
3694int dump_binary(struct chunk *out, const char *buf, int bsize)
3695{
3696 unsigned char c;
3697 int ptr = 0;
3698
3699 while (ptr < bsize) {
3700 c = buf[ptr];
3701
3702 if (out->len > out->size - 2)
3703 break;
3704 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3705 out->str[out->len++] = hextab[c & 0xF];
3706
3707 ptr++;
3708 }
3709 return ptr;
3710}
3711
3712/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
3713 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
3714 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
3715 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
3716 * lines are respected within the limit of 70 output chars. Lines that are
3717 * continuation of a previous truncated line begin with "+" instead of " "
3718 * after the offset. The new pointer is returned.
3719 */
3720int dump_text_line(struct chunk *out, const char *buf, int bsize, int len,
3721 int *line, int ptr)
3722{
3723 int end;
3724 unsigned char c;
3725
3726 end = out->len + 80;
3727 if (end > out->size)
3728 return ptr;
3729
3730 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
3731
3732 while (ptr < len && ptr < bsize) {
3733 c = buf[ptr];
3734 if (isprint(c) && isascii(c) && c != '\\') {
3735 if (out->len > end - 2)
3736 break;
3737 out->str[out->len++] = c;
3738 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
3739 if (out->len > end - 3)
3740 break;
3741 out->str[out->len++] = '\\';
3742 switch (c) {
3743 case '\t': c = 't'; break;
3744 case '\n': c = 'n'; break;
3745 case '\r': c = 'r'; break;
3746 case '\e': c = 'e'; break;
3747 case '\\': c = '\\'; break;
3748 }
3749 out->str[out->len++] = c;
3750 } else {
3751 if (out->len > end - 5)
3752 break;
3753 out->str[out->len++] = '\\';
3754 out->str[out->len++] = 'x';
3755 out->str[out->len++] = hextab[(c >> 4) & 0xF];
3756 out->str[out->len++] = hextab[c & 0xF];
3757 }
3758 if (buf[ptr++] == '\n') {
3759 /* we had a line break, let's return now */
3760 out->str[out->len++] = '\n';
3761 *line = ptr;
3762 return ptr;
3763 }
3764 }
3765 /* we have an incomplete line, we return it as-is */
3766 out->str[out->len++] = '\n';
3767 return ptr;
3768}
3769
Willy Tarreau0ebb5112016-12-05 00:10:57 +01003770/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
3771 * has address <baseaddr>. The output is emitted to file <out>.
3772 */
3773void debug_hexdump(FILE *out, char *buf, unsigned int baseaddr, int len)
3774{
3775 unsigned int i, j;
3776 int b;
3777
3778 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
3779 b = i - (baseaddr & 15);
3780 fprintf(out, "%08x: ", i + (baseaddr & ~15));
3781 for (j = 0; j < 8; j++) {
3782 if (b + j >= 0 && b + j < len)
3783 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
3784 else
3785 fprintf(out, " ");
3786 }
3787
3788 if (b + j >= 0 && b + j < len)
3789 fputc('-', out);
3790 else
3791 fputc(' ', out);
3792
3793 for (j = 8; j < 16; j++) {
3794 if (b + j >= 0 && b + j < len)
3795 fprintf(out, " %02x", (unsigned char)buf[b + j]);
3796 else
3797 fprintf(out, " ");
3798 }
3799
3800 fprintf(out, " ");
3801 for (j = 0; j < 16; j++) {
3802 if (b + j >= 0 && b + j < len) {
3803 if (isprint((unsigned char)buf[b + j]))
3804 fputc((unsigned char)buf[b + j], out);
3805 else
3806 fputc('.', out);
3807 }
3808 else
3809 fputc(' ', out);
3810 }
3811 fputc('\n', out);
3812 }
3813}
3814
Willy Tarreaubaaee002006-06-26 02:48:02 +02003815/*
3816 * Local variables:
3817 * c-indent-level: 8
3818 * c-basic-offset: 8
3819 * End:
3820 */