blob: c2d16896d159bbf0a07f9cd31c5299ee83e215e4 [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
628 * returns NULL.
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];
635
636 /* check IPv6 with square brackets */
637 if (str[0] == '[') {
638 size_t iplength = strlen(str);
639
640 if (iplength < 4) {
641 /* minimal size is 4 when using brackets "[::]" */
642 goto fail;
643 }
644 else if (iplength >= sizeof(tmpip)) {
645 /* IPv6 literal can not be larger than tmpip */
646 goto fail;
647 }
648 else {
649 if (str[iplength - 1] != ']') {
650 /* if address started with bracket, it should end with bracket */
651 goto fail;
652 }
653 else {
654 memcpy(tmpip, str + 1, iplength - 2);
655 tmpip[iplength - 2] = '\0';
656 str = tmpip;
657 }
658 }
659 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100660
Willy Tarreaufab5a432011-03-04 15:31:53 +0100661 /* Any IPv6 address */
662 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100663 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
664 sa->ss_family = AF_INET6;
665 else if (sa->ss_family != AF_INET6)
666 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100667 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100668 }
669
Willy Tarreau24709282013-03-10 21:32:12 +0100670 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100671 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100672 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
673 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100674 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100675 }
676
677 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100678 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
679 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100680 sa->ss_family = AF_INET6;
681 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100682 }
683
684 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100685 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
686 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100687 sa->ss_family = AF_INET;
688 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100689 }
690
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100691 if (!resolve)
692 return NULL;
693
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200694 if (!dns_hostname_validation(str, NULL))
695 return NULL;
696
David du Colombierd5f43282011-03-17 10:40:16 +0100697#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200698 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100699 struct addrinfo hints, *result;
700
701 memset(&result, 0, sizeof(result));
702 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100703 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100704 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200705 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100706 hints.ai_protocol = 0;
707
708 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100709 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
710 sa->ss_family = result->ai_family;
711 else if (sa->ss_family != result->ai_family)
712 goto fail;
713
David du Colombierd5f43282011-03-17 10:40:16 +0100714 switch (result->ai_family) {
715 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100716 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
717 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100718 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100719 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
720 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100721 }
722 }
723
Sean Carey58ea0392013-02-15 23:39:18 +0100724 if (result)
725 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100726 }
David du Colombierd5f43282011-03-17 10:40:16 +0100727#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200728 /* try to resolve an IPv4/IPv6 hostname */
729 he = gethostbyname(str);
730 if (he) {
731 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
732 sa->ss_family = he->h_addrtype;
733 else if (sa->ss_family != he->h_addrtype)
734 goto fail;
735
736 switch (sa->ss_family) {
737 case AF_INET:
738 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
739 return sa;
740 case AF_INET6:
741 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
742 return sa;
743 }
744 }
745
David du Colombierd5f43282011-03-17 10:40:16 +0100746 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100747 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100748 return NULL;
749}
750
751/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100752 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
753 * range or offset consisting in two integers that the caller will have to
754 * check to find the relevant input format. The following format are supported :
755 *
756 * String format | address | port | low | high
757 * addr | <addr> | 0 | 0 | 0
758 * addr: | <addr> | 0 | 0 | 0
759 * addr:port | <addr> | <port> | <port> | <port>
760 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
761 * addr:+port | <addr> | <port> | 0 | <port>
762 * addr:-port | <addr> |-<port> | <port> | 0
763 *
764 * The detection of a port range or increment by the caller is made by
765 * comparing <low> and <high>. If both are equal, then port 0 means no port
766 * was specified. The caller may pass NULL for <low> and <high> if it is not
767 * interested in retrieving port ranges.
768 *
769 * Note that <addr> above may also be :
770 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
771 * - "*" => family will be AF_INET and address will be INADDR_ANY
772 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
773 * - a host name => family and address will depend on host name resolving.
774 *
Willy Tarreau24709282013-03-10 21:32:12 +0100775 * A prefix may be passed in before the address above to force the family :
776 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
777 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
778 * - "unix@" => force address to be a path to a UNIX socket even if the
779 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200780 * - 'abns@' -> force address to belong to the abstract namespace (Linux
781 * only). These sockets are just like Unix sockets but without
782 * the need for an underlying file system. The address is a
783 * string. Technically it's like a Unix socket with a zero in
784 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100785 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100786 *
mildisff5d5102015-10-26 18:50:08 +0100787 * IPv6 addresses can be declared with or without square brackets. When using
788 * square brackets for IPv6 addresses, the port separator (colon) is optional.
789 * If not using square brackets, and in order to avoid any ambiguity with
790 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
791 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
792 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100793 *
794 * If <pfx> is non-null, it is used as a string prefix before any path-based
795 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100796 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200797 * if <fqdn> is non-null, it will be filled with :
798 * - a pointer to the FQDN of the server name to resolve if there's one, and
799 * that the caller will have to free(),
800 * - NULL if there was an explicit address that doesn't require resolution.
801 *
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200802 * Hostnames are only resolved if <resolve> is non-null.
803 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100804 * When a file descriptor is passed, its value is put into the s_addr part of
805 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100806 */
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200807struct 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 +0100808{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100809 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100810 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100811 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100812 char *port1, *port2;
813 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200814 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100815
816 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200817 if (fqdn)
818 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200819
Willy Tarreaudad36a32013-03-11 01:20:04 +0100820 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100821 if (str2 == NULL) {
822 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100823 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100824 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200825
Willy Tarreau9f69f462015-09-08 16:01:25 +0200826 if (!*str2) {
827 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
828 goto out;
829 }
830
Willy Tarreau24709282013-03-10 21:32:12 +0100831 memset(&ss, 0, sizeof(ss));
832
833 if (strncmp(str2, "unix@", 5) == 0) {
834 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200835 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100836 ss.ss_family = AF_UNIX;
837 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200838 else if (strncmp(str2, "abns@", 5) == 0) {
839 str2 += 5;
840 abstract = 1;
841 ss.ss_family = AF_UNIX;
842 }
Willy Tarreau24709282013-03-10 21:32:12 +0100843 else if (strncmp(str2, "ipv4@", 5) == 0) {
844 str2 += 5;
845 ss.ss_family = AF_INET;
846 }
847 else if (strncmp(str2, "ipv6@", 5) == 0) {
848 str2 += 5;
849 ss.ss_family = AF_INET6;
850 }
851 else if (*str2 == '/') {
852 ss.ss_family = AF_UNIX;
853 }
854 else
855 ss.ss_family = AF_UNSPEC;
856
Willy Tarreau40aa0702013-03-10 23:51:38 +0100857 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
858 char *endptr;
859
860 str2 += 3;
861 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
862
863 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100864 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100865 goto out;
866 }
867
868 /* we return AF_UNSPEC if we use a file descriptor number */
869 ss.ss_family = AF_UNSPEC;
870 }
871 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100872 int prefix_path_len;
873 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200874 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100875
876 /* complete unix socket path name during startup or soft-restart is
877 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
878 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200879 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100880 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
881 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
882
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200883 adr_len = strlen(str2);
884 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100885 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
886 goto out;
887 }
888
Willy Tarreauccfccef2014-05-10 01:49:15 +0200889 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
890 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200891 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100892 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200893 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100894 }
Willy Tarreau24709282013-03-10 21:32:12 +0100895 else { /* IPv4 and IPv6 */
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200896 int use_fqdn = 0;
mildisff5d5102015-10-26 18:50:08 +0100897 char *end = str2 + strlen(str2);
898 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200899
mildisff5d5102015-10-26 18:50:08 +0100900 /* search for : or ] whatever comes first */
901 for (chr = end-1; chr > str2; chr--) {
902 if (*chr == ']' || *chr == ':')
903 break;
904 }
905
906 if (*chr == ':') {
907 /* Found a colon before a closing-bracket, must be a port separator.
908 * This guarantee backward compatibility.
909 */
910 *chr++ = '\0';
911 port1 = chr;
912 }
913 else {
914 /* Either no colon and no closing-bracket
915 * or directly ending with a closing-bracket.
916 * However, no port.
917 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100918 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100919 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200920
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200921 if (str2ip2(str2, &ss, 0) == NULL) {
922 use_fqdn = 1;
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200923 if (!resolve || str2ip2(str2, &ss, 1) == NULL) {
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200924 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
925 goto out;
926 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100927 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100928
Willy Tarreaua39d1992013-04-01 20:37:42 +0200929 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100930 port2 = strchr(port1, '-');
931 if (port2)
932 *port2++ = '\0';
933 else
934 port2 = port1;
935 portl = atoi(port1);
936 porth = atoi(port2);
937 porta = portl;
938 }
939 else if (*port1 == '-') { /* negative offset */
940 portl = atoi(port1 + 1);
941 porta = -portl;
942 }
943 else if (*port1 == '+') { /* positive offset */
944 porth = atoi(port1 + 1);
945 porta = porth;
946 }
947 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100948 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100949 goto out;
950 }
951 set_host_port(&ss, porta);
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200952
953 if (use_fqdn && fqdn) {
954 if (str2 != back)
955 memmove(back, str2, strlen(str2) + 1);
956 *fqdn = back;
957 back = NULL;
958 }
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100959 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100960
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100961 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100962 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100963 if (low)
964 *low = portl;
965 if (high)
966 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100967 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100968 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200969}
970
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100971/* converts <str> to a struct in_addr containing a network mask. It can be
972 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
973 * if the conversion succeeds otherwise non-zero.
974 */
975int str2mask(const char *str, struct in_addr *mask)
976{
977 if (strchr(str, '.') != NULL) { /* dotted notation */
978 if (!inet_pton(AF_INET, str, mask))
979 return 0;
980 }
981 else { /* mask length */
982 char *err;
983 unsigned long len = strtol(str, &err, 10);
984
985 if (!*str || (err && *err) || (unsigned)len > 32)
986 return 0;
987 if (len)
988 mask->s_addr = htonl(~0UL << (32 - len));
989 else
990 mask->s_addr = 0;
991 }
992 return 1;
993}
994
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100995/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
996 * succeeds otherwise zero.
997 */
998int cidr2dotted(int cidr, struct in_addr *mask) {
999
1000 if (cidr < 0 || cidr > 32)
1001 return 0;
1002
1003 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1004 return 1;
1005}
1006
Thierry Fournier70473a52016-02-17 17:12:14 +01001007/* Convert mask from bit length form to in_addr form.
1008 * This function never fails.
1009 */
1010void len2mask4(int len, struct in_addr *addr)
1011{
1012 if (len >= 32) {
1013 addr->s_addr = 0xffffffff;
1014 return;
1015 }
1016 if (len <= 0) {
1017 addr->s_addr = 0x00000000;
1018 return;
1019 }
1020 addr->s_addr = 0xffffffff << (32 - len);
1021 addr->s_addr = htonl(addr->s_addr);
1022}
1023
1024/* Convert mask from bit length form to in6_addr form.
1025 * This function never fails.
1026 */
1027void len2mask6(int len, struct in6_addr *addr)
1028{
1029 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1030 len -= 32;
1031 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1032 len -= 32;
1033 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1034 len -= 32;
1035 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1036}
1037
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001038/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001039 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001040 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1041 * is optionnal and either in the dotted or CIDR notation.
1042 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1043 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001044int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001045{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001046 __label__ out_free, out_err;
1047 char *c, *s;
1048 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001049
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001050 s = strdup(str);
1051 if (!s)
1052 return 0;
1053
Willy Tarreaubaaee002006-06-26 02:48:02 +02001054 memset(mask, 0, sizeof(*mask));
1055 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001056
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001057 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001058 *c++ = '\0';
1059 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001060 if (!str2mask(c, mask))
1061 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001062 }
1063 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001064 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001065 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001066 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001067 struct hostent *he;
1068
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001069 if (!resolve)
1070 goto out_err;
1071
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001072 if ((he = gethostbyname(s)) == NULL) {
1073 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001074 }
1075 else
1076 *addr = *(struct in_addr *) *(he->h_addr_list);
1077 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001078
1079 ret_val = 1;
1080 out_free:
1081 free(s);
1082 return ret_val;
1083 out_err:
1084 ret_val = 0;
1085 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001086}
1087
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001088
1089/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001090 * converts <str> to two struct in6_addr* which must be pre-allocated.
1091 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1092 * is an optionnal number of bits (128 being the default).
1093 * Returns 1 if OK, 0 if error.
1094 */
1095int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1096{
1097 char *c, *s;
1098 int ret_val = 0;
1099 char *err;
1100 unsigned long len = 128;
1101
1102 s = strdup(str);
1103 if (!s)
1104 return 0;
1105
1106 memset(mask, 0, sizeof(*mask));
1107 memset(addr, 0, sizeof(*addr));
1108
1109 if ((c = strrchr(s, '/')) != NULL) {
1110 *c++ = '\0'; /* c points to the mask */
1111 if (!*c)
1112 goto out_free;
1113
1114 len = strtoul(c, &err, 10);
1115 if ((err && *err) || (unsigned)len > 128)
1116 goto out_free;
1117 }
1118 *mask = len; /* OK we have a valid mask in <len> */
1119
1120 if (!inet_pton(AF_INET6, s, addr))
1121 goto out_free;
1122
1123 ret_val = 1;
1124 out_free:
1125 free(s);
1126 return ret_val;
1127}
1128
1129
1130/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001131 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001132 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001133int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001134{
1135 int saw_digit, octets, ch;
1136 u_char tmp[4], *tp;
1137 const char *cp = addr;
1138
1139 saw_digit = 0;
1140 octets = 0;
1141 *(tp = tmp) = 0;
1142
1143 while (*addr) {
1144 unsigned char digit = (ch = *addr++) - '0';
1145 if (digit > 9 && ch != '.')
1146 break;
1147 if (digit <= 9) {
1148 u_int new = *tp * 10 + digit;
1149 if (new > 255)
1150 return 0;
1151 *tp = new;
1152 if (!saw_digit) {
1153 if (++octets > 4)
1154 return 0;
1155 saw_digit = 1;
1156 }
1157 } else if (ch == '.' && saw_digit) {
1158 if (octets == 4)
1159 return 0;
1160 *++tp = 0;
1161 saw_digit = 0;
1162 } else
1163 return 0;
1164 }
1165
1166 if (octets < 4)
1167 return 0;
1168
1169 memcpy(&dst->s_addr, tmp, 4);
1170 return addr-cp-1;
1171}
1172
1173/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001174 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1175 * <out> contain the code of the dectected scheme, the start and length of
1176 * the hostname. Actually only http and https are supported. <out> can be NULL.
1177 * This function returns the consumed length. It is useful if you parse complete
1178 * url like http://host:port/path, because the consumed length corresponds to
1179 * the first character of the path. If the conversion fails, it returns -1.
1180 *
1181 * This function tries to resolve the DNS name if haproxy is in starting mode.
1182 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001183 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001184int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001185{
1186 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001187 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001188 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001189 unsigned long long int http_code = 0;
1190 int default_port;
1191 struct hostent *he;
1192 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001193
1194 /* Firstly, try to find :// pattern */
1195 while (curr < url+ulen && url_code != 0x3a2f2f) {
1196 url_code = ((url_code & 0xffff) << 8);
1197 url_code += (unsigned char)*curr++;
1198 }
1199
1200 /* Secondly, if :// pattern is found, verify parsed stuff
1201 * before pattern is matching our http pattern.
1202 * If so parse ip address and port in uri.
1203 *
1204 * WARNING: Current code doesn't support dynamic async dns resolver.
1205 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001206 if (url_code != 0x3a2f2f)
1207 return -1;
1208
1209 /* Copy scheme, and utrn to lower case. */
1210 while (cp < curr - 3)
1211 http_code = (http_code << 8) + *cp++;
1212 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001213
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001214 /* HTTP or HTTPS url matching */
1215 if (http_code == 0x2020202068747470ULL) {
1216 default_port = 80;
1217 if (out)
1218 out->scheme = SCH_HTTP;
1219 }
1220 else if (http_code == 0x2020206874747073ULL) {
1221 default_port = 443;
1222 if (out)
1223 out->scheme = SCH_HTTPS;
1224 }
1225 else
1226 return -1;
1227
1228 /* If the next char is '[', the host address is IPv6. */
1229 if (*curr == '[') {
1230 curr++;
1231
1232 /* Check trash size */
1233 if (trash.size < ulen)
1234 return -1;
1235
1236 /* Look for ']' and copy the address in a trash buffer. */
1237 p = trash.str;
1238 for (end = curr;
1239 end < url + ulen && *end != ']';
1240 end++, p++)
1241 *p = *end;
1242 if (*end != ']')
1243 return -1;
1244 *p = '\0';
1245
1246 /* Update out. */
1247 if (out) {
1248 out->host = curr;
1249 out->host_len = end - curr;
1250 }
1251
1252 /* Try IPv6 decoding. */
1253 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1254 return -1;
1255 end++;
1256
1257 /* Decode port. */
1258 if (*end == ':') {
1259 end++;
1260 default_port = read_uint(&end, url + ulen);
1261 }
1262 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1263 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1264 return end - url;
1265 }
1266 else {
1267 /* We are looking for IP address. If you want to parse and
1268 * resolve hostname found in url, you can use str2sa_range(), but
1269 * be warned this can slow down global daemon performances
1270 * while handling lagging dns responses.
1271 */
1272 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1273 if (ret) {
1274 /* Update out. */
1275 if (out) {
1276 out->host = curr;
1277 out->host_len = ret;
1278 }
1279
1280 curr += ret;
1281
1282 /* Decode port. */
1283 if (*curr == ':') {
1284 curr++;
1285 default_port = read_uint(&curr, url + ulen);
1286 }
1287 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1288
1289 /* Set family. */
1290 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1291 return curr - url;
1292 }
1293 else if (global.mode & MODE_STARTING) {
1294 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1295 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001296 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001297
1298 /* look for : or / or end */
1299 for (end = curr;
1300 end < url + ulen && *end != '/' && *end != ':';
1301 end++);
1302 memcpy(trash.str, curr, end - curr);
1303 trash.str[end - curr] = '\0';
1304
1305 /* try to resolve an IPv4/IPv6 hostname */
1306 he = gethostbyname(trash.str);
1307 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001308 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001309
1310 /* Update out. */
1311 if (out) {
1312 out->host = curr;
1313 out->host_len = end - curr;
1314 }
1315
1316 /* Decode port. */
1317 if (*end == ':') {
1318 end++;
1319 default_port = read_uint(&end, url + ulen);
1320 }
1321
1322 /* Copy IP address, set port and family. */
1323 switch (he->h_addrtype) {
1324 case AF_INET:
1325 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1326 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1327 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1328 return end - url;
1329
1330 case AF_INET6:
1331 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1332 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1333 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1334 return end - url;
1335 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001336 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001337 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001338 return -1;
1339}
1340
Willy Tarreau631f01c2011-09-05 00:36:48 +02001341/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1342 * address family is returned so that it's easy for the caller to adapt to the
1343 * output format. Zero is returned if the address family is not supported. -1
1344 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1345 * supported.
1346 */
1347int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1348{
1349
1350 void *ptr;
1351
1352 if (size < 5)
1353 return 0;
1354 *str = '\0';
1355
1356 switch (addr->ss_family) {
1357 case AF_INET:
1358 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1359 break;
1360 case AF_INET6:
1361 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1362 break;
1363 case AF_UNIX:
1364 memcpy(str, "unix", 5);
1365 return addr->ss_family;
1366 default:
1367 return 0;
1368 }
1369
1370 if (inet_ntop(addr->ss_family, ptr, str, size))
1371 return addr->ss_family;
1372
1373 /* failed */
1374 return -1;
1375}
1376
Simon Horman75ab8bd2014-06-16 09:39:41 +09001377/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1378 * address family is returned so that it's easy for the caller to adapt to the
1379 * output format. Zero is returned if the address family is not supported. -1
1380 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1381 * supported.
1382 */
1383int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1384{
1385
1386 uint16_t port;
1387
1388
1389 if (size < 5)
1390 return 0;
1391 *str = '\0';
1392
1393 switch (addr->ss_family) {
1394 case AF_INET:
1395 port = ((struct sockaddr_in *)addr)->sin_port;
1396 break;
1397 case AF_INET6:
1398 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1399 break;
1400 case AF_UNIX:
1401 memcpy(str, "unix", 5);
1402 return addr->ss_family;
1403 default:
1404 return 0;
1405 }
1406
1407 snprintf(str, size, "%u", ntohs(port));
1408 return addr->ss_family;
1409}
1410
Willy Tarreau16e01562016-08-09 16:46:18 +02001411/* check if the given address is local to the system or not. It will return
1412 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1413 * it is. We don't want to iterate over all interfaces for this (and it is not
1414 * portable). So instead we try to bind in UDP to this address on a free non
1415 * privileged port and to connect to the same address, port 0 (connect doesn't
1416 * care). If it succeeds, we own the address. Note that non-inet addresses are
1417 * considered local since they're most likely AF_UNIX.
1418 */
1419int addr_is_local(const struct netns_entry *ns,
1420 const struct sockaddr_storage *orig)
1421{
1422 struct sockaddr_storage addr;
1423 int result;
1424 int fd;
1425
1426 if (!is_inet_addr(orig))
1427 return 1;
1428
1429 memcpy(&addr, orig, sizeof(addr));
1430 set_host_port(&addr, 0);
1431
1432 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1433 if (fd < 0)
1434 return -1;
1435
1436 result = -1;
1437 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1438 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1439 result = 0; // fail, non-local address
1440 else
1441 result = 1; // success, local address
1442 }
1443 else {
1444 if (errno == EADDRNOTAVAIL)
1445 result = 0; // definitely not local :-)
1446 }
1447 close(fd);
1448
1449 return result;
1450}
1451
Willy Tarreaubaaee002006-06-26 02:48:02 +02001452/* will try to encode the string <string> replacing all characters tagged in
1453 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1454 * prefixed by <escape>, and will store the result between <start> (included)
1455 * and <stop> (excluded), and will always terminate the string with a '\0'
1456 * before <stop>. The position of the '\0' is returned if the conversion
1457 * completes. If bytes are missing between <start> and <stop>, then the
1458 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1459 * cannot even be stored so we return <start> without writing the 0.
1460 * The input string must also be zero-terminated.
1461 */
1462const char hextab[16] = "0123456789ABCDEF";
1463char *encode_string(char *start, char *stop,
1464 const char escape, const fd_set *map,
1465 const char *string)
1466{
1467 if (start < stop) {
1468 stop--; /* reserve one byte for the final '\0' */
1469 while (start < stop && *string != '\0') {
1470 if (!FD_ISSET((unsigned char)(*string), map))
1471 *start++ = *string;
1472 else {
1473 if (start + 3 >= stop)
1474 break;
1475 *start++ = escape;
1476 *start++ = hextab[(*string >> 4) & 15];
1477 *start++ = hextab[*string & 15];
1478 }
1479 string++;
1480 }
1481 *start = '\0';
1482 }
1483 return start;
1484}
1485
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001486/*
1487 * Same behavior as encode_string() above, except that it encodes chunk
1488 * <chunk> instead of a string.
1489 */
1490char *encode_chunk(char *start, char *stop,
1491 const char escape, const fd_set *map,
1492 const struct chunk *chunk)
1493{
1494 char *str = chunk->str;
1495 char *end = chunk->str + chunk->len;
1496
1497 if (start < stop) {
1498 stop--; /* reserve one byte for the final '\0' */
1499 while (start < stop && str < end) {
1500 if (!FD_ISSET((unsigned char)(*str), map))
1501 *start++ = *str;
1502 else {
1503 if (start + 3 >= stop)
1504 break;
1505 *start++ = escape;
1506 *start++ = hextab[(*str >> 4) & 15];
1507 *start++ = hextab[*str & 15];
1508 }
1509 str++;
1510 }
1511 *start = '\0';
1512 }
1513 return start;
1514}
1515
Dragan Dosen0edd1092016-02-12 13:23:02 +01001516/*
1517 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001518 * character. The input <string> must be zero-terminated. The result will
1519 * be stored between <start> (included) and <stop> (excluded). This
1520 * function will always try to terminate the resulting string with a '\0'
1521 * before <stop>, and will return its position if the conversion
1522 * completes.
1523 */
1524char *escape_string(char *start, char *stop,
1525 const char escape, const fd_set *map,
1526 const char *string)
1527{
1528 if (start < stop) {
1529 stop--; /* reserve one byte for the final '\0' */
1530 while (start < stop && *string != '\0') {
1531 if (!FD_ISSET((unsigned char)(*string), map))
1532 *start++ = *string;
1533 else {
1534 if (start + 2 >= stop)
1535 break;
1536 *start++ = escape;
1537 *start++ = *string;
1538 }
1539 string++;
1540 }
1541 *start = '\0';
1542 }
1543 return start;
1544}
1545
1546/*
1547 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001548 * character. <chunk> contains the input to be escaped. The result will be
1549 * stored between <start> (included) and <stop> (excluded). The function
1550 * will always try to terminate the resulting string with a '\0' before
1551 * <stop>, and will return its position if the conversion completes.
1552 */
1553char *escape_chunk(char *start, char *stop,
1554 const char escape, const fd_set *map,
1555 const struct chunk *chunk)
1556{
1557 char *str = chunk->str;
1558 char *end = chunk->str + chunk->len;
1559
1560 if (start < stop) {
1561 stop--; /* reserve one byte for the final '\0' */
1562 while (start < stop && str < end) {
1563 if (!FD_ISSET((unsigned char)(*str), map))
1564 *start++ = *str;
1565 else {
1566 if (start + 2 >= stop)
1567 break;
1568 *start++ = escape;
1569 *start++ = *str;
1570 }
1571 str++;
1572 }
1573 *start = '\0';
1574 }
1575 return start;
1576}
1577
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001578/* Check a string for using it in a CSV output format. If the string contains
1579 * one of the following four char <">, <,>, CR or LF, the string is
1580 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1581 * <str> is the input string to be escaped. The function assumes that
1582 * the input string is null-terminated.
1583 *
1584 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001585 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001586 * format.
1587 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001588 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001589 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001590 * If <quote> is 1, the converter puts the quotes only if any reserved character
1591 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001592 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001593 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001594 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001595 * The function returns the converted string on its output. If an error
1596 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001597 * for using the function directly as printf() argument.
1598 *
1599 * If the output buffer is too short to contain the input string, the result
1600 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001601 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001602 * This function appends the encoding to the existing output chunk, and it
1603 * guarantees that it starts immediately at the first available character of
1604 * the chunk. Please use csv_enc() instead if you want to replace the output
1605 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001606 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001607const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001608{
1609 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001610 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001611 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001612
Willy Tarreaub631c292016-01-08 10:04:08 +01001613 if (quote == 1) {
1614 /* automatic quoting: first verify if we'll have to quote the string */
1615 if (!strpbrk(str, "\n\r,\""))
1616 quote = 0;
1617 }
1618
1619 if (quote)
1620 *ptr++ = '"';
1621
Willy Tarreau898529b2016-01-06 18:07:04 +01001622 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1623 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001624 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001625 ptr++;
1626 if (ptr >= end - 2) {
1627 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001628 break;
1629 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001630 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001631 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001632 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001633 str++;
1634 }
1635
Willy Tarreaub631c292016-01-08 10:04:08 +01001636 if (quote)
1637 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001638
Willy Tarreau898529b2016-01-06 18:07:04 +01001639 *ptr = '\0';
1640 output->len = ptr - output->str;
1641 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001642}
1643
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001644/* Decode an URL-encoded string in-place. The resulting string might
1645 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001646 * aborted, the string is truncated before the issue and a negative value is
1647 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001648 */
1649int url_decode(char *string)
1650{
1651 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001652 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001653
1654 in = string;
1655 out = string;
1656 while (*in) {
1657 switch (*in) {
1658 case '+' :
1659 *out++ = ' ';
1660 break;
1661 case '%' :
1662 if (!ishex(in[1]) || !ishex(in[2]))
1663 goto end;
1664 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1665 in += 2;
1666 break;
1667 default:
1668 *out++ = *in;
1669 break;
1670 }
1671 in++;
1672 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001673 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001674 end:
1675 *out = 0;
1676 return ret;
1677}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001678
Willy Tarreau6911fa42007-03-04 18:06:08 +01001679unsigned int str2ui(const char *s)
1680{
1681 return __str2ui(s);
1682}
1683
1684unsigned int str2uic(const char *s)
1685{
1686 return __str2uic(s);
1687}
1688
1689unsigned int strl2ui(const char *s, int len)
1690{
1691 return __strl2ui(s, len);
1692}
1693
1694unsigned int strl2uic(const char *s, int len)
1695{
1696 return __strl2uic(s, len);
1697}
1698
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001699unsigned int read_uint(const char **s, const char *end)
1700{
1701 return __read_uint(s, end);
1702}
1703
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001704/* This function reads an unsigned integer from the string pointed to by <s> and
1705 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1706 * function automatically stops at <end>. If the number overflows, the 2^64-1
1707 * value is returned.
1708 */
1709unsigned long long int read_uint64(const char **s, const char *end)
1710{
1711 const char *ptr = *s;
1712 unsigned long long int i = 0, tmp;
1713 unsigned int j;
1714
1715 while (ptr < end) {
1716
1717 /* read next char */
1718 j = *ptr - '0';
1719 if (j > 9)
1720 goto read_uint64_end;
1721
1722 /* add char to the number and check overflow. */
1723 tmp = i * 10;
1724 if (tmp / 10 != i) {
1725 i = ULLONG_MAX;
1726 goto read_uint64_eat;
1727 }
1728 if (ULLONG_MAX - tmp < j) {
1729 i = ULLONG_MAX;
1730 goto read_uint64_eat;
1731 }
1732 i = tmp + j;
1733 ptr++;
1734 }
1735read_uint64_eat:
1736 /* eat each numeric char */
1737 while (ptr < end) {
1738 if ((unsigned int)(*ptr - '0') > 9)
1739 break;
1740 ptr++;
1741 }
1742read_uint64_end:
1743 *s = ptr;
1744 return i;
1745}
1746
1747/* This function reads an integer from the string pointed to by <s> and returns
1748 * it. The <s> pointer is adjusted to point to the first unread char. The function
1749 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1750 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1751 * returned.
1752 */
1753long long int read_int64(const char **s, const char *end)
1754{
1755 unsigned long long int i = 0;
1756 int neg = 0;
1757
1758 /* Look for minus char. */
1759 if (**s == '-') {
1760 neg = 1;
1761 (*s)++;
1762 }
1763 else if (**s == '+')
1764 (*s)++;
1765
1766 /* convert as positive number. */
1767 i = read_uint64(s, end);
1768
1769 if (neg) {
1770 if (i > 0x8000000000000000ULL)
1771 return LLONG_MIN;
1772 return -i;
1773 }
1774 if (i > 0x7fffffffffffffffULL)
1775 return LLONG_MAX;
1776 return i;
1777}
1778
Willy Tarreau6911fa42007-03-04 18:06:08 +01001779/* This one is 7 times faster than strtol() on athlon with checks.
1780 * It returns the value of the number composed of all valid digits read,
1781 * and can process negative numbers too.
1782 */
1783int strl2ic(const char *s, int len)
1784{
1785 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001786 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001787
1788 if (len > 0) {
1789 if (*s != '-') {
1790 /* positive number */
1791 while (len-- > 0) {
1792 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001793 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001794 if (j > 9)
1795 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001796 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001797 }
1798 } else {
1799 /* negative number */
1800 s++;
1801 while (--len > 0) {
1802 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001803 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001804 if (j > 9)
1805 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001806 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001807 }
1808 }
1809 }
1810 return i;
1811}
1812
1813
1814/* This function reads exactly <len> chars from <s> and converts them to a
1815 * signed integer which it stores into <ret>. It accurately detects any error
1816 * (truncated string, invalid chars, overflows). It is meant to be used in
1817 * applications designed for hostile environments. It returns zero when the
1818 * number has successfully been converted, non-zero otherwise. When an error
1819 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1820 * faster than strtol().
1821 */
1822int strl2irc(const char *s, int len, int *ret)
1823{
1824 int i = 0;
1825 int j;
1826
1827 if (!len)
1828 return 1;
1829
1830 if (*s != '-') {
1831 /* positive number */
1832 while (len-- > 0) {
1833 j = (*s++) - '0';
1834 if (j > 9) return 1; /* invalid char */
1835 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1836 i = i * 10;
1837 if (i + j < i) return 1; /* check for addition overflow */
1838 i = i + j;
1839 }
1840 } else {
1841 /* negative number */
1842 s++;
1843 while (--len > 0) {
1844 j = (*s++) - '0';
1845 if (j > 9) return 1; /* invalid char */
1846 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1847 i = i * 10;
1848 if (i - j > i) return 1; /* check for subtract overflow */
1849 i = i - j;
1850 }
1851 }
1852 *ret = i;
1853 return 0;
1854}
1855
1856
1857/* This function reads exactly <len> chars from <s> and converts them to a
1858 * signed integer which it stores into <ret>. It accurately detects any error
1859 * (truncated string, invalid chars, overflows). It is meant to be used in
1860 * applications designed for hostile environments. It returns zero when the
1861 * number has successfully been converted, non-zero otherwise. When an error
1862 * is returned, the <ret> value is left untouched. It is about 3 times slower
1863 * than str2irc().
1864 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001865
1866int strl2llrc(const char *s, int len, long long *ret)
1867{
1868 long long i = 0;
1869 int j;
1870
1871 if (!len)
1872 return 1;
1873
1874 if (*s != '-') {
1875 /* positive number */
1876 while (len-- > 0) {
1877 j = (*s++) - '0';
1878 if (j > 9) return 1; /* invalid char */
1879 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1880 i = i * 10LL;
1881 if (i + j < i) return 1; /* check for addition overflow */
1882 i = i + j;
1883 }
1884 } else {
1885 /* negative number */
1886 s++;
1887 while (--len > 0) {
1888 j = (*s++) - '0';
1889 if (j > 9) return 1; /* invalid char */
1890 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1891 i = i * 10LL;
1892 if (i - j > i) return 1; /* check for subtract overflow */
1893 i = i - j;
1894 }
1895 }
1896 *ret = i;
1897 return 0;
1898}
1899
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001900/* This function is used with pat_parse_dotted_ver(). It converts a string
1901 * composed by two number separated by a dot. Each part must contain in 16 bits
1902 * because internally they will be represented as a 32-bit quantity stored in
1903 * a 64-bit integer. It returns zero when the number has successfully been
1904 * converted, non-zero otherwise. When an error is returned, the <ret> value
1905 * is left untouched.
1906 *
1907 * "1.3" -> 0x0000000000010003
1908 * "65535.65535" -> 0x00000000ffffffff
1909 */
1910int strl2llrc_dotted(const char *text, int len, long long *ret)
1911{
1912 const char *end = &text[len];
1913 const char *p;
1914 long long major, minor;
1915
1916 /* Look for dot. */
1917 for (p = text; p < end; p++)
1918 if (*p == '.')
1919 break;
1920
1921 /* Convert major. */
1922 if (strl2llrc(text, p - text, &major) != 0)
1923 return 1;
1924
1925 /* Check major. */
1926 if (major >= 65536)
1927 return 1;
1928
1929 /* Convert minor. */
1930 minor = 0;
1931 if (p < end)
1932 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1933 return 1;
1934
1935 /* Check minor. */
1936 if (minor >= 65536)
1937 return 1;
1938
1939 /* Compose value. */
1940 *ret = (major << 16) | (minor & 0xffff);
1941 return 0;
1942}
1943
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001944/* This function parses a time value optionally followed by a unit suffix among
1945 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1946 * expected by the caller. The computation does its best to avoid overflows.
1947 * The value is returned in <ret> if everything is fine, and a NULL is returned
1948 * by the function. In case of error, a pointer to the error is returned and
1949 * <ret> is left untouched. Values are automatically rounded up when needed.
1950 */
1951const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1952{
1953 unsigned imult, idiv;
1954 unsigned omult, odiv;
1955 unsigned value;
1956
1957 omult = odiv = 1;
1958
1959 switch (unit_flags & TIME_UNIT_MASK) {
1960 case TIME_UNIT_US: omult = 1000000; break;
1961 case TIME_UNIT_MS: omult = 1000; break;
1962 case TIME_UNIT_S: break;
1963 case TIME_UNIT_MIN: odiv = 60; break;
1964 case TIME_UNIT_HOUR: odiv = 3600; break;
1965 case TIME_UNIT_DAY: odiv = 86400; break;
1966 default: break;
1967 }
1968
1969 value = 0;
1970
1971 while (1) {
1972 unsigned int j;
1973
1974 j = *text - '0';
1975 if (j > 9)
1976 break;
1977 text++;
1978 value *= 10;
1979 value += j;
1980 }
1981
1982 imult = idiv = 1;
1983 switch (*text) {
1984 case '\0': /* no unit = default unit */
1985 imult = omult = idiv = odiv = 1;
1986 break;
1987 case 's': /* second = unscaled unit */
1988 break;
1989 case 'u': /* microsecond : "us" */
1990 if (text[1] == 's') {
1991 idiv = 1000000;
1992 text++;
1993 }
1994 break;
1995 case 'm': /* millisecond : "ms" or minute: "m" */
1996 if (text[1] == 's') {
1997 idiv = 1000;
1998 text++;
1999 } else
2000 imult = 60;
2001 break;
2002 case 'h': /* hour : "h" */
2003 imult = 3600;
2004 break;
2005 case 'd': /* day : "d" */
2006 imult = 86400;
2007 break;
2008 default:
2009 return text;
2010 break;
2011 }
2012
2013 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2014 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2015 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2016 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2017
2018 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2019 *ret = value;
2020 return NULL;
2021}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002022
Emeric Brun39132b22010-01-04 14:57:24 +01002023/* this function converts the string starting at <text> to an unsigned int
2024 * stored in <ret>. If an error is detected, the pointer to the unexpected
2025 * character is returned. If the conversio is succesful, NULL is returned.
2026 */
2027const char *parse_size_err(const char *text, unsigned *ret) {
2028 unsigned value = 0;
2029
2030 while (1) {
2031 unsigned int j;
2032
2033 j = *text - '0';
2034 if (j > 9)
2035 break;
2036 if (value > ~0U / 10)
2037 return text;
2038 value *= 10;
2039 if (value > (value + j))
2040 return text;
2041 value += j;
2042 text++;
2043 }
2044
2045 switch (*text) {
2046 case '\0':
2047 break;
2048 case 'K':
2049 case 'k':
2050 if (value > ~0U >> 10)
2051 return text;
2052 value = value << 10;
2053 break;
2054 case 'M':
2055 case 'm':
2056 if (value > ~0U >> 20)
2057 return text;
2058 value = value << 20;
2059 break;
2060 case 'G':
2061 case 'g':
2062 if (value > ~0U >> 30)
2063 return text;
2064 value = value << 30;
2065 break;
2066 default:
2067 return text;
2068 }
2069
Godbach58048a22015-01-28 17:36:16 +08002070 if (*text != '\0' && *++text != '\0')
2071 return text;
2072
Emeric Brun39132b22010-01-04 14:57:24 +01002073 *ret = value;
2074 return NULL;
2075}
2076
Willy Tarreau126d4062013-12-03 17:50:47 +01002077/*
2078 * Parse binary string written in hexadecimal (source) and store the decoded
2079 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2080 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002081 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002082 */
2083int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2084{
2085 int len;
2086 const char *p = source;
2087 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002088 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002089
2090 len = strlen(source);
2091 if (len % 2) {
2092 memprintf(err, "an even number of hex digit is expected");
2093 return 0;
2094 }
2095
2096 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002097
Willy Tarreau126d4062013-12-03 17:50:47 +01002098 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002099 *binstr = calloc(len, sizeof(char));
2100 if (!*binstr) {
2101 memprintf(err, "out of memory while loading string pattern");
2102 return 0;
2103 }
2104 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002105 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002106 else {
2107 if (*binstrlen < len) {
2108 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2109 len, *binstrlen);
2110 return 0;
2111 }
2112 alloc = 0;
2113 }
2114 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002115
2116 i = j = 0;
2117 while (j < len) {
2118 if (!ishex(p[i++]))
2119 goto bad_input;
2120 if (!ishex(p[i++]))
2121 goto bad_input;
2122 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2123 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002124 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002125
2126bad_input:
2127 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002128 if (alloc) {
2129 free(*binstr);
2130 *binstr = NULL;
2131 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002132 return 0;
2133}
2134
Willy Tarreau946ba592009-05-10 15:41:18 +02002135/* copies at most <n> characters from <src> and always terminates with '\0' */
2136char *my_strndup(const char *src, int n)
2137{
2138 int len = 0;
2139 char *ret;
2140
2141 while (len < n && src[len])
2142 len++;
2143
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002144 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002145 if (!ret)
2146 return ret;
2147 memcpy(ret, src, len);
2148 ret[len] = '\0';
2149 return ret;
2150}
2151
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002152/*
2153 * search needle in haystack
2154 * returns the pointer if found, returns NULL otherwise
2155 */
2156const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2157{
2158 const void *c = NULL;
2159 unsigned char f;
2160
2161 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2162 return NULL;
2163
2164 f = *(char *)needle;
2165 c = haystack;
2166 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2167 if ((haystacklen - (c - haystack)) < needlelen)
2168 return NULL;
2169
2170 if (memcmp(c, needle, needlelen) == 0)
2171 return c;
2172 ++c;
2173 }
2174 return NULL;
2175}
2176
Willy Tarreau482b00d2009-10-04 22:48:42 +02002177/* This function returns the first unused key greater than or equal to <key> in
2178 * ID tree <root>. Zero is returned if no place is found.
2179 */
2180unsigned int get_next_id(struct eb_root *root, unsigned int key)
2181{
2182 struct eb32_node *used;
2183
2184 do {
2185 used = eb32_lookup_ge(root, key);
2186 if (!used || used->key > key)
2187 return key; /* key is available */
2188 key++;
2189 } while (key);
2190 return key;
2191}
2192
Willy Tarreau348238b2010-01-18 15:05:57 +01002193/* This function compares a sample word possibly followed by blanks to another
2194 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2195 * otherwise zero. This intends to be used when checking HTTP headers for some
2196 * values. Note that it validates a word followed only by blanks but does not
2197 * validate a word followed by blanks then other chars.
2198 */
2199int word_match(const char *sample, int slen, const char *word, int wlen)
2200{
2201 if (slen < wlen)
2202 return 0;
2203
2204 while (wlen) {
2205 char c = *sample ^ *word;
2206 if (c && c != ('A' ^ 'a'))
2207 return 0;
2208 sample++;
2209 word++;
2210 slen--;
2211 wlen--;
2212 }
2213
2214 while (slen) {
2215 if (*sample != ' ' && *sample != '\t')
2216 return 0;
2217 sample++;
2218 slen--;
2219 }
2220 return 1;
2221}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002222
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002223/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2224 * is particularly fast because it avoids expensive operations such as
2225 * multiplies, which are optimized away at the end. It requires a properly
2226 * formated address though (3 points).
2227 */
2228unsigned int inetaddr_host(const char *text)
2229{
2230 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2231 register unsigned int dig100, dig10, dig1;
2232 int s;
2233 const char *p, *d;
2234
2235 dig1 = dig10 = dig100 = ascii_zero;
2236 s = 24;
2237
2238 p = text;
2239 while (1) {
2240 if (((unsigned)(*p - '0')) <= 9) {
2241 p++;
2242 continue;
2243 }
2244
2245 /* here, we have a complete byte between <text> and <p> (exclusive) */
2246 if (p == text)
2247 goto end;
2248
2249 d = p - 1;
2250 dig1 |= (unsigned int)(*d << s);
2251 if (d == text)
2252 goto end;
2253
2254 d--;
2255 dig10 |= (unsigned int)(*d << s);
2256 if (d == text)
2257 goto end;
2258
2259 d--;
2260 dig100 |= (unsigned int)(*d << s);
2261 end:
2262 if (!s || *p != '.')
2263 break;
2264
2265 s -= 8;
2266 text = ++p;
2267 }
2268
2269 dig100 -= ascii_zero;
2270 dig10 -= ascii_zero;
2271 dig1 -= ascii_zero;
2272 return ((dig100 * 10) + dig10) * 10 + dig1;
2273}
2274
2275/*
2276 * Idem except the first unparsed character has to be passed in <stop>.
2277 */
2278unsigned int inetaddr_host_lim(const char *text, const char *stop)
2279{
2280 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2281 register unsigned int dig100, dig10, dig1;
2282 int s;
2283 const char *p, *d;
2284
2285 dig1 = dig10 = dig100 = ascii_zero;
2286 s = 24;
2287
2288 p = text;
2289 while (1) {
2290 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2291 p++;
2292 continue;
2293 }
2294
2295 /* here, we have a complete byte between <text> and <p> (exclusive) */
2296 if (p == text)
2297 goto end;
2298
2299 d = p - 1;
2300 dig1 |= (unsigned int)(*d << s);
2301 if (d == text)
2302 goto end;
2303
2304 d--;
2305 dig10 |= (unsigned int)(*d << s);
2306 if (d == text)
2307 goto end;
2308
2309 d--;
2310 dig100 |= (unsigned int)(*d << s);
2311 end:
2312 if (!s || p == stop || *p != '.')
2313 break;
2314
2315 s -= 8;
2316 text = ++p;
2317 }
2318
2319 dig100 -= ascii_zero;
2320 dig10 -= ascii_zero;
2321 dig1 -= ascii_zero;
2322 return ((dig100 * 10) + dig10) * 10 + dig1;
2323}
2324
2325/*
2326 * Idem except the pointer to first unparsed byte is returned into <ret> which
2327 * must not be NULL.
2328 */
Willy Tarreau74172752010-10-15 23:21:42 +02002329unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002330{
2331 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2332 register unsigned int dig100, dig10, dig1;
2333 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002334 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002335
2336 dig1 = dig10 = dig100 = ascii_zero;
2337 s = 24;
2338
2339 p = text;
2340 while (1) {
2341 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2342 p++;
2343 continue;
2344 }
2345
2346 /* here, we have a complete byte between <text> and <p> (exclusive) */
2347 if (p == text)
2348 goto end;
2349
2350 d = p - 1;
2351 dig1 |= (unsigned int)(*d << s);
2352 if (d == text)
2353 goto end;
2354
2355 d--;
2356 dig10 |= (unsigned int)(*d << s);
2357 if (d == text)
2358 goto end;
2359
2360 d--;
2361 dig100 |= (unsigned int)(*d << s);
2362 end:
2363 if (!s || p == stop || *p != '.')
2364 break;
2365
2366 s -= 8;
2367 text = ++p;
2368 }
2369
2370 *ret = p;
2371 dig100 -= ascii_zero;
2372 dig10 -= ascii_zero;
2373 dig1 -= ascii_zero;
2374 return ((dig100 * 10) + dig10) * 10 + dig1;
2375}
2376
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002377/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2378 * or the number of chars read in case of success. Maybe this could be replaced
2379 * by one of the functions above. Also, apparently this function does not support
2380 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002381 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002382 */
2383int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2384{
2385 const char *addr;
2386 int saw_digit, octets, ch;
2387 u_char tmp[4], *tp;
2388 const char *cp = buf;
2389
2390 saw_digit = 0;
2391 octets = 0;
2392 *(tp = tmp) = 0;
2393
2394 for (addr = buf; addr - buf < len; addr++) {
2395 unsigned char digit = (ch = *addr) - '0';
2396
2397 if (digit > 9 && ch != '.')
2398 break;
2399
2400 if (digit <= 9) {
2401 u_int new = *tp * 10 + digit;
2402
2403 if (new > 255)
2404 return 0;
2405
2406 *tp = new;
2407
2408 if (!saw_digit) {
2409 if (++octets > 4)
2410 return 0;
2411 saw_digit = 1;
2412 }
2413 } else if (ch == '.' && saw_digit) {
2414 if (octets == 4)
2415 return 0;
2416
2417 *++tp = 0;
2418 saw_digit = 0;
2419 } else
2420 return 0;
2421 }
2422
2423 if (octets < 4)
2424 return 0;
2425
2426 memcpy(&dst->s_addr, tmp, 4);
2427 return addr - cp;
2428}
2429
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002430/* This function converts the string in <buf> of the len <len> to
2431 * struct in6_addr <dst> which must be allocated by the caller.
2432 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002433 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002434 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002435int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2436{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002437 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002438 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002439
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002440 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002441 return 0;
2442
2443 memcpy(null_term_ip6, buf, len);
2444 null_term_ip6[len] = '\0';
2445
Willy Tarreau075415a2013-12-12 11:29:39 +01002446 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002447 return 0;
2448
Willy Tarreau075415a2013-12-12 11:29:39 +01002449 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002450 return 1;
2451}
2452
Willy Tarreauacf95772010-06-14 19:09:21 +02002453/* To be used to quote config arg positions. Returns the short string at <ptr>
2454 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2455 * if ptr is NULL or empty. The string is locally allocated.
2456 */
2457const char *quote_arg(const char *ptr)
2458{
2459 static char val[32];
2460 int i;
2461
2462 if (!ptr || !*ptr)
2463 return "end of line";
2464 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002465 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002466 val[i] = *ptr++;
2467 val[i++] = '\'';
2468 val[i] = '\0';
2469 return val;
2470}
2471
Willy Tarreau5b180202010-07-18 10:40:48 +02002472/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2473int get_std_op(const char *str)
2474{
2475 int ret = -1;
2476
2477 if (*str == 'e' && str[1] == 'q')
2478 ret = STD_OP_EQ;
2479 else if (*str == 'n' && str[1] == 'e')
2480 ret = STD_OP_NE;
2481 else if (*str == 'l') {
2482 if (str[1] == 'e') ret = STD_OP_LE;
2483 else if (str[1] == 't') ret = STD_OP_LT;
2484 }
2485 else if (*str == 'g') {
2486 if (str[1] == 'e') ret = STD_OP_GE;
2487 else if (str[1] == 't') ret = STD_OP_GT;
2488 }
2489
2490 if (ret == -1 || str[2] != '\0')
2491 return -1;
2492 return ret;
2493}
2494
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002495/* hash a 32-bit integer to another 32-bit integer */
2496unsigned int full_hash(unsigned int a)
2497{
2498 return __full_hash(a);
2499}
2500
David du Colombier4f92d322011-03-24 11:09:31 +01002501/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002502 * otherwise zero. Note that <addr> may not necessarily be aligned
2503 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002504 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002505int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002506{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002507 struct in_addr addr_copy;
2508
2509 memcpy(&addr_copy, addr, sizeof(addr_copy));
2510 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002511}
2512
2513/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002514 * otherwise zero. Note that <addr> may not necessarily be aligned
2515 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002516 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002517int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002518{
2519 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002520 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002521
Willy Tarreaueec1d382016-07-13 11:59:39 +02002522 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002523 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002524 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002525 (((int *)net)[i] & ((int *)mask)[i]))
2526 return 0;
2527 return 1;
2528}
2529
2530/* RFC 4291 prefix */
2531const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2532 0x00, 0x00, 0x00, 0x00,
2533 0x00, 0x00, 0xFF, 0xFF };
2534
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002535/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2536 * Input and output may overlap.
2537 */
David du Colombier4f92d322011-03-24 11:09:31 +01002538void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2539{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002540 struct in_addr tmp_addr;
2541
2542 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002543 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002544 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002545}
2546
2547/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2548 * Return true if conversion is possible and false otherwise.
2549 */
2550int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2551{
2552 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2553 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2554 sizeof(struct in_addr));
2555 return 1;
2556 }
2557
2558 return 0;
2559}
2560
William Lallemand421f5b52012-02-06 18:15:57 +01002561char *human_time(int t, short hz_div) {
2562 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2563 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002564 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002565 int cnt=2; // print two numbers
2566
2567 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002568 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002569 return rv;
2570 }
2571
2572 if (unlikely(hz_div > 1))
2573 t /= hz_div;
2574
2575 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002576 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002577 cnt--;
2578 }
2579
2580 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002581 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002582 cnt--;
2583 }
2584
2585 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002586 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002587 cnt--;
2588 }
2589
2590 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002591 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002592
2593 return rv;
2594}
2595
2596const char *monthname[12] = {
2597 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2598 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2599};
2600
2601/* date2str_log: write a date in the format :
2602 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2603 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2604 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2605 *
2606 * without using sprintf. return a pointer to the last char written (\0) or
2607 * NULL if there isn't enough space.
2608 */
2609char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2610{
2611
2612 if (size < 25) /* the size is fixed: 24 chars + \0 */
2613 return NULL;
2614
2615 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2616 *dst++ = '/';
2617 memcpy(dst, monthname[tm->tm_mon], 3); // month
2618 dst += 3;
2619 *dst++ = '/';
2620 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2621 *dst++ = ':';
2622 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2623 *dst++ = ':';
2624 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2625 *dst++ = ':';
2626 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2627 *dst++ = '.';
2628 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2629 dst += 3; // only the 3 first digits
2630 *dst = '\0';
2631
2632 return dst;
2633}
2634
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002635/* Base year used to compute leap years */
2636#define TM_YEAR_BASE 1900
2637
2638/* Return the difference in seconds between two times (leap seconds are ignored).
2639 * Retrieved from glibc 2.18 source code.
2640 */
2641static int my_tm_diff(const struct tm *a, const struct tm *b)
2642{
2643 /* Compute intervening leap days correctly even if year is negative.
2644 * Take care to avoid int overflow in leap day calculations,
2645 * but it's OK to assume that A and B are close to each other.
2646 */
2647 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2648 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2649 int a100 = a4 / 25 - (a4 % 25 < 0);
2650 int b100 = b4 / 25 - (b4 % 25 < 0);
2651 int a400 = a100 >> 2;
2652 int b400 = b100 >> 2;
2653 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2654 int years = a->tm_year - b->tm_year;
2655 int days = (365 * years + intervening_leap_days
2656 + (a->tm_yday - b->tm_yday));
2657 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2658 + (a->tm_min - b->tm_min))
2659 + (a->tm_sec - b->tm_sec));
2660}
2661
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002662/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002663 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002664 * The string returned has the same format as returned by strftime(... "%z", tm).
2665 * Offsets are kept in an internal cache for better performances.
2666 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002667const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002668{
2669 /* Cache offsets from GMT (depending on whether DST is active or not) */
2670 static char gmt_offsets[2][5+1] = { "", "" };
2671
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002672 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002673 struct tm tm_gmt;
2674 int diff;
2675 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002676
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002677 /* Pretend DST not active if its status is unknown */
2678 if (isdst < 0)
2679 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002680
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002681 /* Fetch the offset and initialize it if needed */
2682 gmt_offset = gmt_offsets[isdst & 0x01];
2683 if (unlikely(!*gmt_offset)) {
2684 get_gmtime(t, &tm_gmt);
2685 diff = my_tm_diff(tm, &tm_gmt);
2686 if (diff < 0) {
2687 diff = -diff;
2688 *gmt_offset = '-';
2689 } else {
2690 *gmt_offset = '+';
2691 }
2692 diff /= 60; /* Convert to minutes */
2693 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2694 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002695
2696 return gmt_offset;
2697}
2698
William Lallemand421f5b52012-02-06 18:15:57 +01002699/* gmt2str_log: write a date in the format :
2700 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2701 * return a pointer to the last char written (\0) or
2702 * NULL if there isn't enough space.
2703 */
2704char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2705{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002706 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002707 return NULL;
2708
2709 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2710 *dst++ = '/';
2711 memcpy(dst, monthname[tm->tm_mon], 3); // month
2712 dst += 3;
2713 *dst++ = '/';
2714 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2715 *dst++ = ':';
2716 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2717 *dst++ = ':';
2718 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2719 *dst++ = ':';
2720 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2721 *dst++ = ' ';
2722 *dst++ = '+';
2723 *dst++ = '0';
2724 *dst++ = '0';
2725 *dst++ = '0';
2726 *dst++ = '0';
2727 *dst = '\0';
2728
2729 return dst;
2730}
2731
Yuxans Yao4e25b012012-10-19 10:36:09 +08002732/* localdate2str_log: write a date in the format :
2733 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002734 * Both t and tm must represent the same time.
2735 * return a pointer to the last char written (\0) or
2736 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002737 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002738char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002739{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002740 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002741 if (size < 27) /* the size is fixed: 26 chars + \0 */
2742 return NULL;
2743
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002744 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002745
Yuxans Yao4e25b012012-10-19 10:36:09 +08002746 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2747 *dst++ = '/';
2748 memcpy(dst, monthname[tm->tm_mon], 3); // month
2749 dst += 3;
2750 *dst++ = '/';
2751 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2752 *dst++ = ':';
2753 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2754 *dst++ = ':';
2755 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2756 *dst++ = ':';
2757 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2758 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002759 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002760 dst += 5;
2761 *dst = '\0';
2762
2763 return dst;
2764}
2765
Thierry Fournier93127942016-01-20 18:49:45 +01002766/* This function check a char. It returns true and updates
2767 * <date> and <len> pointer to the new position if the
2768 * character is found.
2769 */
2770static inline int parse_expect_char(const char **date, int *len, char c)
2771{
2772 if (*len < 1 || **date != c)
2773 return 0;
2774 (*len)--;
2775 (*date)++;
2776 return 1;
2777}
2778
2779/* This function expects a string <str> of len <l>. It return true and updates.
2780 * <date> and <len> if the string matches, otherwise, it returns false.
2781 */
2782static inline int parse_strcmp(const char **date, int *len, char *str, int l)
2783{
2784 if (*len < l || strncmp(*date, str, l) != 0)
2785 return 0;
2786 (*len) -= l;
2787 (*date) += l;
2788 return 1;
2789}
2790
2791/* This macro converts 3 chars name in integer. */
2792#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
2793
2794/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
2795 * / %x54.75.65 ; "Tue", case-sensitive
2796 * / %x57.65.64 ; "Wed", case-sensitive
2797 * / %x54.68.75 ; "Thu", case-sensitive
2798 * / %x46.72.69 ; "Fri", case-sensitive
2799 * / %x53.61.74 ; "Sat", case-sensitive
2800 * / %x53.75.6E ; "Sun", case-sensitive
2801 *
2802 * This array must be alphabetically sorted
2803 */
2804static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
2805{
2806 if (*len < 3)
2807 return 0;
2808 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2809 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
2810 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
2811 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
2812 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
2813 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
2814 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
2815 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
2816 default: return 0;
2817 }
2818 *len -= 3;
2819 *date += 3;
2820 return 1;
2821}
2822
2823/* month = %x4A.61.6E ; "Jan", case-sensitive
2824 * / %x46.65.62 ; "Feb", case-sensitive
2825 * / %x4D.61.72 ; "Mar", case-sensitive
2826 * / %x41.70.72 ; "Apr", case-sensitive
2827 * / %x4D.61.79 ; "May", case-sensitive
2828 * / %x4A.75.6E ; "Jun", case-sensitive
2829 * / %x4A.75.6C ; "Jul", case-sensitive
2830 * / %x41.75.67 ; "Aug", case-sensitive
2831 * / %x53.65.70 ; "Sep", case-sensitive
2832 * / %x4F.63.74 ; "Oct", case-sensitive
2833 * / %x4E.6F.76 ; "Nov", case-sensitive
2834 * / %x44.65.63 ; "Dec", case-sensitive
2835 *
2836 * This array must be alphabetically sorted
2837 */
2838static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
2839{
2840 if (*len < 3)
2841 return 0;
2842 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2843 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
2844 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
2845 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
2846 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
2847 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
2848 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
2849 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
2850 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
2851 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
2852 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
2853 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
2854 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
2855 default: return 0;
2856 }
2857 *len -= 3;
2858 *date += 3;
2859 return 1;
2860}
2861
2862/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
2863 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
2864 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
2865 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
2866 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
2867 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
2868 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
2869 *
2870 * This array must be alphabetically sorted
2871 */
2872static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
2873{
2874 if (*len < 6) /* Minimum length. */
2875 return 0;
2876 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2877 case STR2I3('M','o','n'):
2878 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
2879 tm->tm_wday = 1;
2880 return 1;
2881 case STR2I3('T','u','e'):
2882 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
2883 tm->tm_wday = 2;
2884 return 1;
2885 case STR2I3('W','e','d'):
2886 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
2887 tm->tm_wday = 3;
2888 return 1;
2889 case STR2I3('T','h','u'):
2890 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
2891 tm->tm_wday = 4;
2892 return 1;
2893 case STR2I3('F','r','i'):
2894 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
2895 tm->tm_wday = 5;
2896 return 1;
2897 case STR2I3('S','a','t'):
2898 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
2899 tm->tm_wday = 6;
2900 return 1;
2901 case STR2I3('S','u','n'):
2902 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
2903 tm->tm_wday = 7;
2904 return 1;
2905 }
2906 return 0;
2907}
2908
2909/* This function parses exactly 1 digit and returns the numeric value in "digit". */
2910static inline int parse_digit(const char **date, int *len, int *digit)
2911{
2912 if (*len < 1 || **date < '0' || **date > '9')
2913 return 0;
2914 *digit = (**date - '0');
2915 (*date)++;
2916 (*len)--;
2917 return 1;
2918}
2919
2920/* This function parses exactly 2 digits and returns the numeric value in "digit". */
2921static inline int parse_2digit(const char **date, int *len, int *digit)
2922{
2923 int value;
2924
2925 RET0_UNLESS(parse_digit(date, len, &value));
2926 (*digit) = value * 10;
2927 RET0_UNLESS(parse_digit(date, len, &value));
2928 (*digit) += value;
2929
2930 return 1;
2931}
2932
2933/* This function parses exactly 4 digits and returns the numeric value in "digit". */
2934static inline int parse_4digit(const char **date, int *len, int *digit)
2935{
2936 int value;
2937
2938 RET0_UNLESS(parse_digit(date, len, &value));
2939 (*digit) = value * 1000;
2940
2941 RET0_UNLESS(parse_digit(date, len, &value));
2942 (*digit) += value * 100;
2943
2944 RET0_UNLESS(parse_digit(date, len, &value));
2945 (*digit) += value * 10;
2946
2947 RET0_UNLESS(parse_digit(date, len, &value));
2948 (*digit) += value;
2949
2950 return 1;
2951}
2952
2953/* time-of-day = hour ":" minute ":" second
2954 * ; 00:00:00 - 23:59:60 (leap second)
2955 *
2956 * hour = 2DIGIT
2957 * minute = 2DIGIT
2958 * second = 2DIGIT
2959 */
2960static inline int parse_http_time(const char **date, int *len, struct tm *tm)
2961{
2962 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
2963 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
2964 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
2965 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
2966 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
2967 return 1;
2968}
2969
2970/* From RFC7231
2971 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
2972 *
2973 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
2974 * ; fixed length/zone/capitalization subset of the format
2975 * ; see Section 3.3 of [RFC5322]
2976 *
2977 *
2978 * date1 = day SP month SP year
2979 * ; e.g., 02 Jun 1982
2980 *
2981 * day = 2DIGIT
2982 * year = 4DIGIT
2983 *
2984 * GMT = %x47.4D.54 ; "GMT", case-sensitive
2985 *
2986 * time-of-day = hour ":" minute ":" second
2987 * ; 00:00:00 - 23:59:60 (leap second)
2988 *
2989 * hour = 2DIGIT
2990 * minute = 2DIGIT
2991 * second = 2DIGIT
2992 *
2993 * DIGIT = decimal 0-9
2994 */
2995int parse_imf_date(const char *date, int len, struct tm *tm)
2996{
2997 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
2998 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
2999 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3000 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3001 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3002 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3003 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3004 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3005 tm->tm_year -= 1900;
3006 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3007 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3008 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3009 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3010 tm->tm_isdst = -1;
3011 tm->tm_gmtoff = 0;
3012 return 1;
3013}
3014
3015/* From RFC7231
3016 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3017 *
3018 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3019 * date2 = day "-" month "-" 2DIGIT
3020 * ; e.g., 02-Jun-82
3021 *
3022 * day = 2DIGIT
3023 */
3024int parse_rfc850_date(const char *date, int len, struct tm *tm)
3025{
3026 int year;
3027
3028 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3029 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3030 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3031 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3032 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3033 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3034 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3035
3036 /* year = 2DIGIT
3037 *
3038 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3039 * two-digit year, MUST interpret a timestamp that appears to be more
3040 * than 50 years in the future as representing the most recent year in
3041 * the past that had the same last two digits.
3042 */
3043 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3044
3045 /* expect SP */
3046 if (!parse_expect_char(&date, &len, ' ')) {
3047 /* Maybe we have the date with 4 digits. */
3048 RET0_UNLESS(parse_2digit(&date, &len, &year));
3049 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3050 /* expect SP */
3051 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3052 } else {
3053 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3054 * tm_year is the number of year since 1900, so for +1900, we
3055 * do nothing, and for +2000, we add 100.
3056 */
3057 if (tm->tm_year <= 60)
3058 tm->tm_year += 100;
3059 }
3060
3061 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3062 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3063 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3064 tm->tm_isdst = -1;
3065 tm->tm_gmtoff = 0;
3066
3067 return 1;
3068}
3069
3070/* From RFC7231
3071 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3072 *
3073 * asctime-date = day-name SP date3 SP time-of-day SP year
3074 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3075 * ; e.g., Jun 2
3076 *
3077 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3078 * whitespace in an HTTP-date beyond that specifically included as SP in
3079 * the grammar.
3080 */
3081int parse_asctime_date(const char *date, int len, struct tm *tm)
3082{
3083 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3084 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3085 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3086 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3087
3088 /* expect SP and 1DIGIT or 2DIGIT */
3089 if (parse_expect_char(&date, &len, ' '))
3090 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3091 else
3092 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3093
3094 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3095 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3096 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3097 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3098 tm->tm_year -= 1900;
3099 tm->tm_isdst = -1;
3100 tm->tm_gmtoff = 0;
3101 return 1;
3102}
3103
3104/* From RFC7231
3105 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3106 *
3107 * HTTP-date = IMF-fixdate / obs-date
3108 * obs-date = rfc850-date / asctime-date
3109 *
3110 * parses an HTTP date in the RFC format and is accepted
3111 * alternatives. <date> is the strinf containing the date,
3112 * len is the len of the string. <tm> is filled with the
3113 * parsed time. We must considers this time as GMT.
3114 */
3115int parse_http_date(const char *date, int len, struct tm *tm)
3116{
3117 if (parse_imf_date(date, len, tm))
3118 return 1;
3119
3120 if (parse_rfc850_date(date, len, tm))
3121 return 1;
3122
3123 if (parse_asctime_date(date, len, tm))
3124 return 1;
3125
3126 return 0;
3127}
3128
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003129/* Dynamically allocates a string of the proper length to hold the formatted
3130 * output. NULL is returned on error. The caller is responsible for freeing the
3131 * memory area using free(). The resulting string is returned in <out> if the
3132 * pointer is not NULL. A previous version of <out> might be used to build the
3133 * new string, and it will be freed before returning if it is not NULL, which
3134 * makes it possible to build complex strings from iterative calls without
3135 * having to care about freeing intermediate values, as in the example below :
3136 *
3137 * memprintf(&err, "invalid argument: '%s'", arg);
3138 * ...
3139 * memprintf(&err, "parser said : <%s>\n", *err);
3140 * ...
3141 * free(*err);
3142 *
3143 * This means that <err> must be initialized to NULL before first invocation.
3144 * The return value also holds the allocated string, which eases error checking
3145 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003146 * passed instead and it will be ignored. The returned message will then also
3147 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003148 *
3149 * It is also convenient to use it without any free except the last one :
3150 * err = NULL;
3151 * if (!fct1(err)) report(*err);
3152 * if (!fct2(err)) report(*err);
3153 * if (!fct3(err)) report(*err);
3154 * free(*err);
3155 */
3156char *memprintf(char **out, const char *format, ...)
3157{
3158 va_list args;
3159 char *ret = NULL;
3160 int allocated = 0;
3161 int needed = 0;
3162
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003163 if (!out)
3164 return NULL;
3165
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003166 do {
3167 /* vsnprintf() will return the required length even when the
3168 * target buffer is NULL. We do this in a loop just in case
3169 * intermediate evaluations get wrong.
3170 */
3171 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003172 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003173 va_end(args);
3174
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003175 if (needed < allocated) {
3176 /* Note: on Solaris 8, the first iteration always
3177 * returns -1 if allocated is zero, so we force a
3178 * retry.
3179 */
3180 if (!allocated)
3181 needed = 0;
3182 else
3183 break;
3184 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003185
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003186 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003187 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003188 } while (ret);
3189
3190 if (needed < 0) {
3191 /* an error was encountered */
3192 free(ret);
3193 ret = NULL;
3194 }
3195
3196 if (out) {
3197 free(*out);
3198 *out = ret;
3199 }
3200
3201 return ret;
3202}
William Lallemand421f5b52012-02-06 18:15:57 +01003203
Willy Tarreau21c705b2012-09-14 11:40:36 +02003204/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3205 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003206 * freed by the caller. It also supports being passed a NULL which results in the same
3207 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003208 * Example of use :
3209 * parse(cmd, &err); (callee: memprintf(&err, ...))
3210 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3211 * free(err);
3212 */
3213char *indent_msg(char **out, int level)
3214{
3215 char *ret, *in, *p;
3216 int needed = 0;
3217 int lf = 0;
3218 int lastlf = 0;
3219 int len;
3220
Willy Tarreau70eec382012-10-10 08:56:47 +02003221 if (!out || !*out)
3222 return NULL;
3223
Willy Tarreau21c705b2012-09-14 11:40:36 +02003224 in = *out - 1;
3225 while ((in = strchr(in + 1, '\n')) != NULL) {
3226 lastlf = in - *out;
3227 lf++;
3228 }
3229
3230 if (!lf) /* single line, no LF, return it as-is */
3231 return *out;
3232
3233 len = strlen(*out);
3234
3235 if (lf == 1 && lastlf == len - 1) {
3236 /* single line, LF at end, strip it and return as-is */
3237 (*out)[lastlf] = 0;
3238 return *out;
3239 }
3240
3241 /* OK now we have at least one LF, we need to process the whole string
3242 * as a multi-line string. What we'll do :
3243 * - prefix with an LF if there is none
3244 * - add <level> spaces before each line
3245 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3246 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3247 */
3248
3249 needed = 1 + level * (lf + 1) + len + 1;
3250 p = ret = malloc(needed);
3251 in = *out;
3252
3253 /* skip initial LFs */
3254 while (*in == '\n')
3255 in++;
3256
3257 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3258 while (*in) {
3259 *p++ = '\n';
3260 memset(p, ' ', level);
3261 p += level;
3262 do {
3263 *p++ = *in++;
3264 } while (*in && *in != '\n');
3265 if (*in)
3266 in++;
3267 }
3268 *p = 0;
3269
3270 free(*out);
3271 *out = ret;
3272
3273 return ret;
3274}
3275
Willy Tarreaudad36a32013-03-11 01:20:04 +01003276/* Convert occurrences of environment variables in the input string to their
3277 * corresponding value. A variable is identified as a series of alphanumeric
3278 * characters or underscores following a '$' sign. The <in> string must be
3279 * free()able. NULL returns NULL. The resulting string might be reallocated if
3280 * some expansion is made. Variable names may also be enclosed into braces if
3281 * needed (eg: to concatenate alphanum characters).
3282 */
3283char *env_expand(char *in)
3284{
3285 char *txt_beg;
3286 char *out;
3287 char *txt_end;
3288 char *var_beg;
3289 char *var_end;
3290 char *value;
3291 char *next;
3292 int out_len;
3293 int val_len;
3294
3295 if (!in)
3296 return in;
3297
3298 value = out = NULL;
3299 out_len = 0;
3300
3301 txt_beg = in;
3302 do {
3303 /* look for next '$' sign in <in> */
3304 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3305
3306 if (!*txt_end && !out) /* end and no expansion performed */
3307 return in;
3308
3309 val_len = 0;
3310 next = txt_end;
3311 if (*txt_end == '$') {
3312 char save;
3313
3314 var_beg = txt_end + 1;
3315 if (*var_beg == '{')
3316 var_beg++;
3317
3318 var_end = var_beg;
3319 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3320 var_end++;
3321 }
3322
3323 next = var_end;
3324 if (*var_end == '}' && (var_beg > txt_end + 1))
3325 next++;
3326
3327 /* get value of the variable name at this location */
3328 save = *var_end;
3329 *var_end = '\0';
3330 value = getenv(var_beg);
3331 *var_end = save;
3332 val_len = value ? strlen(value) : 0;
3333 }
3334
Hubert Verstraete831962e2016-06-28 22:44:26 +02003335 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003336 if (txt_end > txt_beg) {
3337 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3338 out_len += txt_end - txt_beg;
3339 }
3340 if (val_len) {
3341 memcpy(out + out_len, value, val_len);
3342 out_len += val_len;
3343 }
3344 out[out_len] = 0;
3345 txt_beg = next;
3346 } while (*txt_beg);
3347
3348 /* here we know that <out> was allocated and that we don't need <in> anymore */
3349 free(in);
3350 return out;
3351}
3352
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003353
3354/* same as strstr() but case-insensitive and with limit length */
3355const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3356{
3357 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003358 unsigned int slen, plen;
3359 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003360
3361 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3362 return NULL;
3363
3364 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3365 return str1;
3366
3367 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3368 return NULL;
3369
3370 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3371 while (toupper(*start) != toupper(*str2)) {
3372 start++;
3373 slen--;
3374 tmp1++;
3375
3376 if (tmp1 >= len_str1)
3377 return NULL;
3378
3379 /* if pattern longer than string */
3380 if (slen < plen)
3381 return NULL;
3382 }
3383
3384 sptr = start;
3385 pptr = (char *)str2;
3386
3387 tmp2 = 0;
3388 while (toupper(*sptr) == toupper(*pptr)) {
3389 sptr++;
3390 pptr++;
3391 tmp2++;
3392
3393 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3394 return start;
3395 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3396 return NULL;
3397 }
3398 }
3399 return NULL;
3400}
3401
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003402/* This function read the next valid utf8 char.
3403 * <s> is the byte srray to be decode, <len> is its length.
3404 * The function returns decoded char encoded like this:
3405 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3406 * are the length read. The decoded character is stored in <c>.
3407 */
3408unsigned char utf8_next(const char *s, int len, unsigned int *c)
3409{
3410 const unsigned char *p = (unsigned char *)s;
3411 int dec;
3412 unsigned char code = UTF8_CODE_OK;
3413
3414 if (len < 1)
3415 return UTF8_CODE_OK;
3416
3417 /* Check the type of UTF8 sequence
3418 *
3419 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3420 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3421 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3422 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3423 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3424 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3425 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3426 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3427 */
3428 switch (*p) {
3429 case 0x00 ... 0x7f:
3430 *c = *p;
3431 return UTF8_CODE_OK | 1;
3432
3433 case 0x80 ... 0xbf:
3434 *c = *p;
3435 return UTF8_CODE_BADSEQ | 1;
3436
3437 case 0xc0 ... 0xdf:
3438 if (len < 2) {
3439 *c = *p;
3440 return UTF8_CODE_BADSEQ | 1;
3441 }
3442 *c = *p & 0x1f;
3443 dec = 1;
3444 break;
3445
3446 case 0xe0 ... 0xef:
3447 if (len < 3) {
3448 *c = *p;
3449 return UTF8_CODE_BADSEQ | 1;
3450 }
3451 *c = *p & 0x0f;
3452 dec = 2;
3453 break;
3454
3455 case 0xf0 ... 0xf7:
3456 if (len < 4) {
3457 *c = *p;
3458 return UTF8_CODE_BADSEQ | 1;
3459 }
3460 *c = *p & 0x07;
3461 dec = 3;
3462 break;
3463
3464 case 0xf8 ... 0xfb:
3465 if (len < 5) {
3466 *c = *p;
3467 return UTF8_CODE_BADSEQ | 1;
3468 }
3469 *c = *p & 0x03;
3470 dec = 4;
3471 break;
3472
3473 case 0xfc ... 0xfd:
3474 if (len < 6) {
3475 *c = *p;
3476 return UTF8_CODE_BADSEQ | 1;
3477 }
3478 *c = *p & 0x01;
3479 dec = 5;
3480 break;
3481
3482 case 0xfe ... 0xff:
3483 default:
3484 *c = *p;
3485 return UTF8_CODE_BADSEQ | 1;
3486 }
3487
3488 p++;
3489
3490 while (dec > 0) {
3491
3492 /* need 0x10 for the 2 first bits */
3493 if ( ( *p & 0xc0 ) != 0x80 )
3494 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3495
3496 /* add data at char */
3497 *c = ( *c << 6 ) | ( *p & 0x3f );
3498
3499 dec--;
3500 p++;
3501 }
3502
3503 /* Check ovelong encoding.
3504 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3505 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3506 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3507 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003508 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003509 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3510 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3511 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3512 code |= UTF8_CODE_OVERLONG;
3513
3514 /* Check invalid UTF8 range. */
3515 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3516 (*c >= 0xfffe && *c <= 0xffff))
3517 code |= UTF8_CODE_INVRANGE;
3518
3519 return code | ((p-(unsigned char *)s)&0x0f);
3520}
3521
Maxime de Roucydc887852016-05-13 23:52:54 +02003522/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3523 * On failure : return 0 and <err> filled with an error message.
3524 * The caller is responsible for freeing the <err> and <str> copy
3525 * memory area using free()
3526 */
3527int list_append_word(struct list *li, const char *str, char **err)
3528{
3529 struct wordlist *wl;
3530
3531 wl = calloc(1, sizeof(*wl));
3532 if (!wl) {
3533 memprintf(err, "out of memory");
3534 goto fail_wl;
3535 }
3536
3537 wl->s = strdup(str);
3538 if (!wl->s) {
3539 memprintf(err, "out of memory");
3540 goto fail_wl_s;
3541 }
3542
3543 LIST_ADDQ(li, &wl->list);
3544
3545 return 1;
3546
3547fail_wl_s:
3548 free(wl->s);
3549fail_wl:
3550 free(wl);
3551 return 0;
3552}
3553
Willy Tarreaubaaee002006-06-26 02:48:02 +02003554/*
3555 * Local variables:
3556 * c-indent-level: 8
3557 * c-basic-offset: 8
3558 * End:
3559 */