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