blob: fed847777fe93716901b9e518756975abe399fa7 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010013#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020014#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020015#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020016#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020017#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020018#include <stdlib.h>
19#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010020#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020021#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010022#include <sys/socket.h>
23#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <netinet/in.h>
25#include <arpa/inet.h>
26
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010027#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020028#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020029#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010030#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010031#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020032#include <proto/dns.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010033#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020034
Thierry Fournier93127942016-01-20 18:49:45 +010035/* This macro returns false if the test __x is false. Many
36 * of the following parsing function must be abort the processing
37 * if it returns 0, so this macro is useful for writing light code.
38 */
39#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
40
Willy Tarreau56adcf22012-12-23 18:00:29 +010041/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020042 * 2^64-1 = 18446744073709551615 or
43 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020044 *
45 * The HTML version needs room for adding the 25 characters
46 * '<span class="rls"></span>' around digits at positions 3N+1 in order
47 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020048 */
Willy Tarreau56adcf22012-12-23 18:00:29 +010049char itoa_str[NB_ITOA_STR][171];
50int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020051
Willy Tarreau588297f2014-06-16 15:16:40 +020052/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
53 * to quote strings larger than a max configuration line.
54 */
55char quoted_str[NB_QSTR][QSTR_SIZE + 1];
56int quoted_idx = 0;
57
Willy Tarreaubaaee002006-06-26 02:48:02 +020058/*
William Lallemande7340ec2012-01-24 11:15:39 +010059 * unsigned long long ASCII representation
60 *
61 * return the last char '\0' or NULL if no enough
62 * space in dst
63 */
64char *ulltoa(unsigned long long n, char *dst, size_t size)
65{
66 int i = 0;
67 char *res;
68
69 switch(n) {
70 case 1ULL ... 9ULL:
71 i = 0;
72 break;
73
74 case 10ULL ... 99ULL:
75 i = 1;
76 break;
77
78 case 100ULL ... 999ULL:
79 i = 2;
80 break;
81
82 case 1000ULL ... 9999ULL:
83 i = 3;
84 break;
85
86 case 10000ULL ... 99999ULL:
87 i = 4;
88 break;
89
90 case 100000ULL ... 999999ULL:
91 i = 5;
92 break;
93
94 case 1000000ULL ... 9999999ULL:
95 i = 6;
96 break;
97
98 case 10000000ULL ... 99999999ULL:
99 i = 7;
100 break;
101
102 case 100000000ULL ... 999999999ULL:
103 i = 8;
104 break;
105
106 case 1000000000ULL ... 9999999999ULL:
107 i = 9;
108 break;
109
110 case 10000000000ULL ... 99999999999ULL:
111 i = 10;
112 break;
113
114 case 100000000000ULL ... 999999999999ULL:
115 i = 11;
116 break;
117
118 case 1000000000000ULL ... 9999999999999ULL:
119 i = 12;
120 break;
121
122 case 10000000000000ULL ... 99999999999999ULL:
123 i = 13;
124 break;
125
126 case 100000000000000ULL ... 999999999999999ULL:
127 i = 14;
128 break;
129
130 case 1000000000000000ULL ... 9999999999999999ULL:
131 i = 15;
132 break;
133
134 case 10000000000000000ULL ... 99999999999999999ULL:
135 i = 16;
136 break;
137
138 case 100000000000000000ULL ... 999999999999999999ULL:
139 i = 17;
140 break;
141
142 case 1000000000000000000ULL ... 9999999999999999999ULL:
143 i = 18;
144 break;
145
146 case 10000000000000000000ULL ... ULLONG_MAX:
147 i = 19;
148 break;
149 }
150 if (i + 2 > size) // (i + 1) + '\0'
151 return NULL; // too long
152 res = dst + i + 1;
153 *res = '\0';
154 for (; i >= 0; i--) {
155 dst[i] = n % 10ULL + '0';
156 n /= 10ULL;
157 }
158 return res;
159}
160
161/*
162 * unsigned long ASCII representation
163 *
164 * return the last char '\0' or NULL if no enough
165 * space in dst
166 */
167char *ultoa_o(unsigned long n, char *dst, size_t size)
168{
169 int i = 0;
170 char *res;
171
172 switch (n) {
173 case 0U ... 9UL:
174 i = 0;
175 break;
176
177 case 10U ... 99UL:
178 i = 1;
179 break;
180
181 case 100U ... 999UL:
182 i = 2;
183 break;
184
185 case 1000U ... 9999UL:
186 i = 3;
187 break;
188
189 case 10000U ... 99999UL:
190 i = 4;
191 break;
192
193 case 100000U ... 999999UL:
194 i = 5;
195 break;
196
197 case 1000000U ... 9999999UL:
198 i = 6;
199 break;
200
201 case 10000000U ... 99999999UL:
202 i = 7;
203 break;
204
205 case 100000000U ... 999999999UL:
206 i = 8;
207 break;
208#if __WORDSIZE == 32
209
210 case 1000000000ULL ... ULONG_MAX:
211 i = 9;
212 break;
213
214#elif __WORDSIZE == 64
215
216 case 1000000000ULL ... 9999999999UL:
217 i = 9;
218 break;
219
220 case 10000000000ULL ... 99999999999UL:
221 i = 10;
222 break;
223
224 case 100000000000ULL ... 999999999999UL:
225 i = 11;
226 break;
227
228 case 1000000000000ULL ... 9999999999999UL:
229 i = 12;
230 break;
231
232 case 10000000000000ULL ... 99999999999999UL:
233 i = 13;
234 break;
235
236 case 100000000000000ULL ... 999999999999999UL:
237 i = 14;
238 break;
239
240 case 1000000000000000ULL ... 9999999999999999UL:
241 i = 15;
242 break;
243
244 case 10000000000000000ULL ... 99999999999999999UL:
245 i = 16;
246 break;
247
248 case 100000000000000000ULL ... 999999999999999999UL:
249 i = 17;
250 break;
251
252 case 1000000000000000000ULL ... 9999999999999999999UL:
253 i = 18;
254 break;
255
256 case 10000000000000000000ULL ... ULONG_MAX:
257 i = 19;
258 break;
259
260#endif
261 }
262 if (i + 2 > size) // (i + 1) + '\0'
263 return NULL; // too long
264 res = dst + i + 1;
265 *res = '\0';
266 for (; i >= 0; i--) {
267 dst[i] = n % 10U + '0';
268 n /= 10U;
269 }
270 return res;
271}
272
273/*
274 * signed long ASCII representation
275 *
276 * return the last char '\0' or NULL if no enough
277 * space in dst
278 */
279char *ltoa_o(long int n, char *dst, size_t size)
280{
281 char *pos = dst;
282
283 if (n < 0) {
284 if (size < 3)
285 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
286 *pos = '-';
287 pos++;
288 dst = ultoa_o(-n, pos, size - 1);
289 } else {
290 dst = ultoa_o(n, dst, size);
291 }
292 return dst;
293}
294
295/*
296 * signed long long ASCII representation
297 *
298 * return the last char '\0' or NULL if no enough
299 * space in dst
300 */
301char *lltoa(long long n, char *dst, size_t size)
302{
303 char *pos = dst;
304
305 if (n < 0) {
306 if (size < 3)
307 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
308 *pos = '-';
309 pos++;
310 dst = ulltoa(-n, pos, size - 1);
311 } else {
312 dst = ulltoa(n, dst, size);
313 }
314 return dst;
315}
316
317/*
318 * write a ascii representation of a unsigned into dst,
319 * return a pointer to the last character
320 * Pad the ascii representation with '0', using size.
321 */
322char *utoa_pad(unsigned int n, char *dst, size_t size)
323{
324 int i = 0;
325 char *ret;
326
327 switch(n) {
328 case 0U ... 9U:
329 i = 0;
330 break;
331
332 case 10U ... 99U:
333 i = 1;
334 break;
335
336 case 100U ... 999U:
337 i = 2;
338 break;
339
340 case 1000U ... 9999U:
341 i = 3;
342 break;
343
344 case 10000U ... 99999U:
345 i = 4;
346 break;
347
348 case 100000U ... 999999U:
349 i = 5;
350 break;
351
352 case 1000000U ... 9999999U:
353 i = 6;
354 break;
355
356 case 10000000U ... 99999999U:
357 i = 7;
358 break;
359
360 case 100000000U ... 999999999U:
361 i = 8;
362 break;
363
364 case 1000000000U ... 4294967295U:
365 i = 9;
366 break;
367 }
368 if (i + 2 > size) // (i + 1) + '\0'
369 return NULL; // too long
370 if (i < size)
371 i = size - 2; // padding - '\0'
372
373 ret = dst + i + 1;
374 *ret = '\0';
375 for (; i >= 0; i--) {
376 dst[i] = n % 10U + '0';
377 n /= 10U;
378 }
379 return ret;
380}
381
382/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200383 * copies at most <size-1> chars from <src> to <dst>. Last char is always
384 * set to 0, unless <size> is 0. The number of chars copied is returned
385 * (excluding the terminating zero).
386 * This code has been optimized for size and speed : on x86, it's 45 bytes
387 * long, uses only registers, and consumes only 4 cycles per char.
388 */
389int strlcpy2(char *dst, const char *src, int size)
390{
391 char *orig = dst;
392 if (size) {
393 while (--size && (*dst = *src)) {
394 src++; dst++;
395 }
396 *dst = 0;
397 }
398 return dst - orig;
399}
400
401/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200402 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200403 * the ascii representation for number 'n' in decimal.
404 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100405char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200406{
407 char *pos;
408
Willy Tarreau72d759c2007-10-25 12:14:10 +0200409 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200410 *pos-- = '\0';
411
412 do {
413 *pos-- = '0' + n % 10;
414 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200415 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200416 return pos + 1;
417}
418
Willy Tarreau91092e52007-10-25 16:58:42 +0200419/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200420 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200421 * the ascii representation for number 'n' in decimal.
422 */
423char *lltoa_r(long long int in, char *buffer, int size)
424{
425 char *pos;
426 int neg = 0;
427 unsigned long long int n;
428
429 pos = buffer + size - 1;
430 *pos-- = '\0';
431
432 if (in < 0) {
433 neg = 1;
434 n = -in;
435 }
436 else
437 n = in;
438
439 do {
440 *pos-- = '0' + n % 10;
441 n /= 10;
442 } while (n && pos >= buffer);
443 if (neg && pos > buffer)
444 *pos-- = '-';
445 return pos + 1;
446}
447
448/*
449 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200450 * the ascii representation for signed number 'n' in decimal.
451 */
452char *sltoa_r(long n, char *buffer, int size)
453{
454 char *pos;
455
456 if (n >= 0)
457 return ultoa_r(n, buffer, size);
458
459 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
460 *pos = '-';
461 return pos;
462}
463
464/*
465 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200466 * the ascii representation for number 'n' in decimal, formatted for
467 * HTML output with tags to create visual grouping by 3 digits. The
468 * output needs to support at least 171 characters.
469 */
470const char *ulltoh_r(unsigned long long n, char *buffer, int size)
471{
472 char *start;
473 int digit = 0;
474
475 start = buffer + size;
476 *--start = '\0';
477
478 do {
479 if (digit == 3 && start >= buffer + 7)
480 memcpy(start -= 7, "</span>", 7);
481
482 if (start >= buffer + 1) {
483 *--start = '0' + n % 10;
484 n /= 10;
485 }
486
487 if (digit == 3 && start >= buffer + 18)
488 memcpy(start -= 18, "<span class=\"rls\">", 18);
489
490 if (digit++ == 3)
491 digit = 1;
492 } while (n && start > buffer);
493 return start;
494}
495
496/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200497 * This function simply returns a locally allocated string containing the ascii
498 * representation for number 'n' in decimal, unless n is 0 in which case it
499 * returns the alternate string (or an empty string if the alternate string is
500 * NULL). It use is intended for limits reported in reports, where it's
501 * desirable not to display anything if there is no limit. Warning! it shares
502 * the same vector as ultoa_r().
503 */
504const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
505{
506 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
507}
508
Willy Tarreau588297f2014-06-16 15:16:40 +0200509/* returns a locally allocated string containing the quoted encoding of the
510 * input string. The output may be truncated to QSTR_SIZE chars, but it is
511 * guaranteed that the string will always be properly terminated. Quotes are
512 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
513 * always be at least 4 chars.
514 */
515const char *qstr(const char *str)
516{
517 char *ret = quoted_str[quoted_idx];
518 char *p, *end;
519
520 if (++quoted_idx >= NB_QSTR)
521 quoted_idx = 0;
522
523 p = ret;
524 end = ret + QSTR_SIZE;
525
526 *p++ = '"';
527
528 /* always keep 3 chars to support passing "" and the ending " */
529 while (*str && p < end - 3) {
530 if (*str == '"') {
531 *p++ = '"';
532 *p++ = '"';
533 }
534 else
535 *p++ = *str;
536 str++;
537 }
538 *p++ = '"';
539 return ret;
540}
541
Robert Tsai81ae1952007-12-05 10:47:29 +0100542/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200543 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
544 *
545 * It looks like this one would be a good candidate for inlining, but this is
546 * not interesting because it around 35 bytes long and often called multiple
547 * times within the same function.
548 */
549int ishex(char s)
550{
551 s -= '0';
552 if ((unsigned char)s <= 9)
553 return 1;
554 s -= 'A' - '0';
555 if ((unsigned char)s <= 5)
556 return 1;
557 s -= 'a' - 'A';
558 if ((unsigned char)s <= 5)
559 return 1;
560 return 0;
561}
562
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100563/* rounds <i> down to the closest value having max 2 digits */
564unsigned int round_2dig(unsigned int i)
565{
566 unsigned int mul = 1;
567
568 while (i >= 100) {
569 i /= 10;
570 mul *= 10;
571 }
572 return i * mul;
573}
574
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100575/*
576 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
577 * invalid character is found, a pointer to it is returned. If everything is
578 * fine, NULL is returned.
579 */
580const char *invalid_char(const char *name)
581{
582 if (!*name)
583 return name;
584
585 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100586 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100587 *name != '_' && *name != '-')
588 return name;
589 name++;
590 }
591 return NULL;
592}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200593
594/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200595 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
596 * If an invalid character is found, a pointer to it is returned.
597 * If everything is fine, NULL is returned.
598 */
599const char *invalid_domainchar(const char *name) {
600
601 if (!*name)
602 return name;
603
604 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100605 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200606 *name != '_' && *name != '-')
607 return name;
608
609 name++;
610 }
611
612 return NULL;
613}
614
615/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100616 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100617 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
618 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
619 * the function tries to guess the address family from the syntax. If the
620 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100621 * string is assumed to contain only an address, no port. The address can be a
622 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
623 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
624 * The return address will only have the address family and the address set,
625 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100626 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
627 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100628 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200629 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100630struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200631{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100632 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100633 /* max IPv6 length, including brackets and terminating NULL */
634 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100635 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100636
637 /* check IPv6 with square brackets */
638 if (str[0] == '[') {
639 size_t iplength = strlen(str);
640
641 if (iplength < 4) {
642 /* minimal size is 4 when using brackets "[::]" */
643 goto fail;
644 }
645 else if (iplength >= sizeof(tmpip)) {
646 /* IPv6 literal can not be larger than tmpip */
647 goto fail;
648 }
649 else {
650 if (str[iplength - 1] != ']') {
651 /* if address started with bracket, it should end with bracket */
652 goto fail;
653 }
654 else {
655 memcpy(tmpip, str + 1, iplength - 2);
656 tmpip[iplength - 2] = '\0';
657 str = tmpip;
658 }
659 }
660 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100661
Willy Tarreaufab5a432011-03-04 15:31:53 +0100662 /* Any IPv6 address */
663 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100664 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
665 sa->ss_family = AF_INET6;
666 else if (sa->ss_family != AF_INET6)
667 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100668 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100669 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100670 }
671
Willy Tarreau24709282013-03-10 21:32:12 +0100672 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100673 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100674 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
675 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100676 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100677 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100678 }
679
680 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100681 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
682 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100683 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100684 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100685 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100686 }
687
688 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100689 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
690 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100691 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100692 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100693 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100694 }
695
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100696 if (!resolve)
697 return NULL;
698
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200699 if (!dns_hostname_validation(str, NULL))
700 return NULL;
701
David du Colombierd5f43282011-03-17 10:40:16 +0100702#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200703 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100704 struct addrinfo hints, *result;
705
706 memset(&result, 0, sizeof(result));
707 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100708 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100709 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200710 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100711 hints.ai_protocol = 0;
712
713 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100714 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
715 sa->ss_family = result->ai_family;
716 else if (sa->ss_family != result->ai_family)
717 goto fail;
718
David du Colombierd5f43282011-03-17 10:40:16 +0100719 switch (result->ai_family) {
720 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100721 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100722 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100723 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100724 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100726 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100727 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100728 }
729 }
730
Sean Carey58ea0392013-02-15 23:39:18 +0100731 if (result)
732 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100733 }
David du Colombierd5f43282011-03-17 10:40:16 +0100734#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200735 /* try to resolve an IPv4/IPv6 hostname */
736 he = gethostbyname(str);
737 if (he) {
738 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
739 sa->ss_family = he->h_addrtype;
740 else if (sa->ss_family != he->h_addrtype)
741 goto fail;
742
743 switch (sa->ss_family) {
744 case AF_INET:
745 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100746 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200747 return sa;
748 case AF_INET6:
749 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100750 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200751 return sa;
752 }
753 }
754
David du Colombierd5f43282011-03-17 10:40:16 +0100755 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100756 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100757 return NULL;
758}
759
760/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100761 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
762 * range or offset consisting in two integers that the caller will have to
763 * check to find the relevant input format. The following format are supported :
764 *
765 * String format | address | port | low | high
766 * addr | <addr> | 0 | 0 | 0
767 * addr: | <addr> | 0 | 0 | 0
768 * addr:port | <addr> | <port> | <port> | <port>
769 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
770 * addr:+port | <addr> | <port> | 0 | <port>
771 * addr:-port | <addr> |-<port> | <port> | 0
772 *
773 * The detection of a port range or increment by the caller is made by
774 * comparing <low> and <high>. If both are equal, then port 0 means no port
775 * was specified. The caller may pass NULL for <low> and <high> if it is not
776 * interested in retrieving port ranges.
777 *
778 * Note that <addr> above may also be :
779 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
780 * - "*" => family will be AF_INET and address will be INADDR_ANY
781 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
782 * - a host name => family and address will depend on host name resolving.
783 *
Willy Tarreau24709282013-03-10 21:32:12 +0100784 * A prefix may be passed in before the address above to force the family :
785 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
786 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
787 * - "unix@" => force address to be a path to a UNIX socket even if the
788 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200789 * - 'abns@' -> force address to belong to the abstract namespace (Linux
790 * only). These sockets are just like Unix sockets but without
791 * the need for an underlying file system. The address is a
792 * string. Technically it's like a Unix socket with a zero in
793 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100794 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100795 *
mildisff5d5102015-10-26 18:50:08 +0100796 * IPv6 addresses can be declared with or without square brackets. When using
797 * square brackets for IPv6 addresses, the port separator (colon) is optional.
798 * If not using square brackets, and in order to avoid any ambiguity with
799 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
800 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
801 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100802 *
803 * If <pfx> is non-null, it is used as a string prefix before any path-based
804 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100805 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200806 * if <fqdn> is non-null, it will be filled with :
807 * - a pointer to the FQDN of the server name to resolve if there's one, and
808 * that the caller will have to free(),
809 * - NULL if there was an explicit address that doesn't require resolution.
810 *
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200811 * Hostnames are only resolved if <resolve> is non-null.
812 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100813 * When a file descriptor is passed, its value is put into the s_addr part of
814 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100815 */
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200816struct 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 +0100817{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100818 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100819 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100820 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100821 char *port1, *port2;
822 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200823 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100824
825 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200826 if (fqdn)
827 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200828
Willy Tarreaudad36a32013-03-11 01:20:04 +0100829 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100830 if (str2 == NULL) {
831 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100832 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100833 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200834
Willy Tarreau9f69f462015-09-08 16:01:25 +0200835 if (!*str2) {
836 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
837 goto out;
838 }
839
Willy Tarreau24709282013-03-10 21:32:12 +0100840 memset(&ss, 0, sizeof(ss));
841
842 if (strncmp(str2, "unix@", 5) == 0) {
843 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200844 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100845 ss.ss_family = AF_UNIX;
846 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200847 else if (strncmp(str2, "abns@", 5) == 0) {
848 str2 += 5;
849 abstract = 1;
850 ss.ss_family = AF_UNIX;
851 }
Willy Tarreau24709282013-03-10 21:32:12 +0100852 else if (strncmp(str2, "ipv4@", 5) == 0) {
853 str2 += 5;
854 ss.ss_family = AF_INET;
855 }
856 else if (strncmp(str2, "ipv6@", 5) == 0) {
857 str2 += 5;
858 ss.ss_family = AF_INET6;
859 }
860 else if (*str2 == '/') {
861 ss.ss_family = AF_UNIX;
862 }
863 else
864 ss.ss_family = AF_UNSPEC;
865
Willy Tarreau40aa0702013-03-10 23:51:38 +0100866 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
867 char *endptr;
868
869 str2 += 3;
870 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
871
872 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100873 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100874 goto out;
875 }
876
877 /* we return AF_UNSPEC if we use a file descriptor number */
878 ss.ss_family = AF_UNSPEC;
879 }
880 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100881 int prefix_path_len;
882 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200883 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100884
885 /* complete unix socket path name during startup or soft-restart is
886 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
887 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200888 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100889 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
890 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
891
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200892 adr_len = strlen(str2);
893 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100894 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
895 goto out;
896 }
897
Willy Tarreauccfccef2014-05-10 01:49:15 +0200898 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
899 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200900 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100901 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200902 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100903 }
Willy Tarreau24709282013-03-10 21:32:12 +0100904 else { /* IPv4 and IPv6 */
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200905 int use_fqdn = 0;
mildisff5d5102015-10-26 18:50:08 +0100906 char *end = str2 + strlen(str2);
907 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200908
mildisff5d5102015-10-26 18:50:08 +0100909 /* search for : or ] whatever comes first */
910 for (chr = end-1; chr > str2; chr--) {
911 if (*chr == ']' || *chr == ':')
912 break;
913 }
914
915 if (*chr == ':') {
916 /* Found a colon before a closing-bracket, must be a port separator.
917 * This guarantee backward compatibility.
918 */
919 *chr++ = '\0';
920 port1 = chr;
921 }
922 else {
923 /* Either no colon and no closing-bracket
924 * or directly ending with a closing-bracket.
925 * However, no port.
926 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100927 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100928 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200929
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200930 if (str2ip2(str2, &ss, 0) == NULL) {
931 use_fqdn = 1;
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200932 if (!resolve || str2ip2(str2, &ss, 1) == NULL) {
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200933 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
934 goto out;
935 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100936 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100937
Willy Tarreaua39d1992013-04-01 20:37:42 +0200938 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100939 port2 = strchr(port1, '-');
940 if (port2)
941 *port2++ = '\0';
942 else
943 port2 = port1;
944 portl = atoi(port1);
945 porth = atoi(port2);
946 porta = portl;
947 }
948 else if (*port1 == '-') { /* negative offset */
949 portl = atoi(port1 + 1);
950 porta = -portl;
951 }
952 else if (*port1 == '+') { /* positive offset */
953 porth = atoi(port1 + 1);
954 porta = porth;
955 }
956 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100957 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100958 goto out;
959 }
960 set_host_port(&ss, porta);
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200961
962 if (use_fqdn && fqdn) {
963 if (str2 != back)
964 memmove(back, str2, strlen(str2) + 1);
965 *fqdn = back;
966 back = NULL;
967 }
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100968 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100969
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100970 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100971 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100972 if (low)
973 *low = portl;
974 if (high)
975 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100976 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100977 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200978}
979
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100980/* converts <str> to a struct in_addr containing a network mask. It can be
981 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
982 * if the conversion succeeds otherwise non-zero.
983 */
984int str2mask(const char *str, struct in_addr *mask)
985{
986 if (strchr(str, '.') != NULL) { /* dotted notation */
987 if (!inet_pton(AF_INET, str, mask))
988 return 0;
989 }
990 else { /* mask length */
991 char *err;
992 unsigned long len = strtol(str, &err, 10);
993
994 if (!*str || (err && *err) || (unsigned)len > 32)
995 return 0;
996 if (len)
997 mask->s_addr = htonl(~0UL << (32 - len));
998 else
999 mask->s_addr = 0;
1000 }
1001 return 1;
1002}
1003
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001004/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1005 * succeeds otherwise zero.
1006 */
1007int cidr2dotted(int cidr, struct in_addr *mask) {
1008
1009 if (cidr < 0 || cidr > 32)
1010 return 0;
1011
1012 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1013 return 1;
1014}
1015
Thierry Fournier70473a52016-02-17 17:12:14 +01001016/* Convert mask from bit length form to in_addr form.
1017 * This function never fails.
1018 */
1019void len2mask4(int len, struct in_addr *addr)
1020{
1021 if (len >= 32) {
1022 addr->s_addr = 0xffffffff;
1023 return;
1024 }
1025 if (len <= 0) {
1026 addr->s_addr = 0x00000000;
1027 return;
1028 }
1029 addr->s_addr = 0xffffffff << (32 - len);
1030 addr->s_addr = htonl(addr->s_addr);
1031}
1032
1033/* Convert mask from bit length form to in6_addr form.
1034 * This function never fails.
1035 */
1036void len2mask6(int len, struct in6_addr *addr)
1037{
1038 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1039 len -= 32;
1040 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1041 len -= 32;
1042 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1043 len -= 32;
1044 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1045}
1046
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001047/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001048 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001049 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1050 * is optionnal and either in the dotted or CIDR notation.
1051 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1052 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001053int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001054{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001055 __label__ out_free, out_err;
1056 char *c, *s;
1057 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001058
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001059 s = strdup(str);
1060 if (!s)
1061 return 0;
1062
Willy Tarreaubaaee002006-06-26 02:48:02 +02001063 memset(mask, 0, sizeof(*mask));
1064 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001065
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001066 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001067 *c++ = '\0';
1068 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001069 if (!str2mask(c, mask))
1070 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001071 }
1072 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001073 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001074 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001075 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001076 struct hostent *he;
1077
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001078 if (!resolve)
1079 goto out_err;
1080
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001081 if ((he = gethostbyname(s)) == NULL) {
1082 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001083 }
1084 else
1085 *addr = *(struct in_addr *) *(he->h_addr_list);
1086 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001087
1088 ret_val = 1;
1089 out_free:
1090 free(s);
1091 return ret_val;
1092 out_err:
1093 ret_val = 0;
1094 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001095}
1096
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001097
1098/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001099 * converts <str> to two struct in6_addr* which must be pre-allocated.
1100 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1101 * is an optionnal number of bits (128 being the default).
1102 * Returns 1 if OK, 0 if error.
1103 */
1104int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1105{
1106 char *c, *s;
1107 int ret_val = 0;
1108 char *err;
1109 unsigned long len = 128;
1110
1111 s = strdup(str);
1112 if (!s)
1113 return 0;
1114
1115 memset(mask, 0, sizeof(*mask));
1116 memset(addr, 0, sizeof(*addr));
1117
1118 if ((c = strrchr(s, '/')) != NULL) {
1119 *c++ = '\0'; /* c points to the mask */
1120 if (!*c)
1121 goto out_free;
1122
1123 len = strtoul(c, &err, 10);
1124 if ((err && *err) || (unsigned)len > 128)
1125 goto out_free;
1126 }
1127 *mask = len; /* OK we have a valid mask in <len> */
1128
1129 if (!inet_pton(AF_INET6, s, addr))
1130 goto out_free;
1131
1132 ret_val = 1;
1133 out_free:
1134 free(s);
1135 return ret_val;
1136}
1137
1138
1139/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001140 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001141 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001142int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001143{
1144 int saw_digit, octets, ch;
1145 u_char tmp[4], *tp;
1146 const char *cp = addr;
1147
1148 saw_digit = 0;
1149 octets = 0;
1150 *(tp = tmp) = 0;
1151
1152 while (*addr) {
1153 unsigned char digit = (ch = *addr++) - '0';
1154 if (digit > 9 && ch != '.')
1155 break;
1156 if (digit <= 9) {
1157 u_int new = *tp * 10 + digit;
1158 if (new > 255)
1159 return 0;
1160 *tp = new;
1161 if (!saw_digit) {
1162 if (++octets > 4)
1163 return 0;
1164 saw_digit = 1;
1165 }
1166 } else if (ch == '.' && saw_digit) {
1167 if (octets == 4)
1168 return 0;
1169 *++tp = 0;
1170 saw_digit = 0;
1171 } else
1172 return 0;
1173 }
1174
1175 if (octets < 4)
1176 return 0;
1177
1178 memcpy(&dst->s_addr, tmp, 4);
1179 return addr-cp-1;
1180}
1181
1182/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001183 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1184 * <out> contain the code of the dectected scheme, the start and length of
1185 * the hostname. Actually only http and https are supported. <out> can be NULL.
1186 * This function returns the consumed length. It is useful if you parse complete
1187 * url like http://host:port/path, because the consumed length corresponds to
1188 * the first character of the path. If the conversion fails, it returns -1.
1189 *
1190 * This function tries to resolve the DNS name if haproxy is in starting mode.
1191 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001192 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001193int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001194{
1195 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001196 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001197 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001198 unsigned long long int http_code = 0;
1199 int default_port;
1200 struct hostent *he;
1201 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001202
1203 /* Firstly, try to find :// pattern */
1204 while (curr < url+ulen && url_code != 0x3a2f2f) {
1205 url_code = ((url_code & 0xffff) << 8);
1206 url_code += (unsigned char)*curr++;
1207 }
1208
1209 /* Secondly, if :// pattern is found, verify parsed stuff
1210 * before pattern is matching our http pattern.
1211 * If so parse ip address and port in uri.
1212 *
1213 * WARNING: Current code doesn't support dynamic async dns resolver.
1214 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001215 if (url_code != 0x3a2f2f)
1216 return -1;
1217
1218 /* Copy scheme, and utrn to lower case. */
1219 while (cp < curr - 3)
1220 http_code = (http_code << 8) + *cp++;
1221 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001222
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001223 /* HTTP or HTTPS url matching */
1224 if (http_code == 0x2020202068747470ULL) {
1225 default_port = 80;
1226 if (out)
1227 out->scheme = SCH_HTTP;
1228 }
1229 else if (http_code == 0x2020206874747073ULL) {
1230 default_port = 443;
1231 if (out)
1232 out->scheme = SCH_HTTPS;
1233 }
1234 else
1235 return -1;
1236
1237 /* If the next char is '[', the host address is IPv6. */
1238 if (*curr == '[') {
1239 curr++;
1240
1241 /* Check trash size */
1242 if (trash.size < ulen)
1243 return -1;
1244
1245 /* Look for ']' and copy the address in a trash buffer. */
1246 p = trash.str;
1247 for (end = curr;
1248 end < url + ulen && *end != ']';
1249 end++, p++)
1250 *p = *end;
1251 if (*end != ']')
1252 return -1;
1253 *p = '\0';
1254
1255 /* Update out. */
1256 if (out) {
1257 out->host = curr;
1258 out->host_len = end - curr;
1259 }
1260
1261 /* Try IPv6 decoding. */
1262 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1263 return -1;
1264 end++;
1265
1266 /* Decode port. */
1267 if (*end == ':') {
1268 end++;
1269 default_port = read_uint(&end, url + ulen);
1270 }
1271 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1272 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1273 return end - url;
1274 }
1275 else {
1276 /* We are looking for IP address. If you want to parse and
1277 * resolve hostname found in url, you can use str2sa_range(), but
1278 * be warned this can slow down global daemon performances
1279 * while handling lagging dns responses.
1280 */
1281 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1282 if (ret) {
1283 /* Update out. */
1284 if (out) {
1285 out->host = curr;
1286 out->host_len = ret;
1287 }
1288
1289 curr += ret;
1290
1291 /* Decode port. */
1292 if (*curr == ':') {
1293 curr++;
1294 default_port = read_uint(&curr, url + ulen);
1295 }
1296 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1297
1298 /* Set family. */
1299 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1300 return curr - url;
1301 }
1302 else if (global.mode & MODE_STARTING) {
1303 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1304 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001305 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001306
1307 /* look for : or / or end */
1308 for (end = curr;
1309 end < url + ulen && *end != '/' && *end != ':';
1310 end++);
1311 memcpy(trash.str, curr, end - curr);
1312 trash.str[end - curr] = '\0';
1313
1314 /* try to resolve an IPv4/IPv6 hostname */
1315 he = gethostbyname(trash.str);
1316 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001317 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001318
1319 /* Update out. */
1320 if (out) {
1321 out->host = curr;
1322 out->host_len = end - curr;
1323 }
1324
1325 /* Decode port. */
1326 if (*end == ':') {
1327 end++;
1328 default_port = read_uint(&end, url + ulen);
1329 }
1330
1331 /* Copy IP address, set port and family. */
1332 switch (he->h_addrtype) {
1333 case AF_INET:
1334 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1335 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1336 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1337 return end - url;
1338
1339 case AF_INET6:
1340 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1341 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1342 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1343 return end - url;
1344 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001345 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001346 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001347 return -1;
1348}
1349
Willy Tarreau631f01c2011-09-05 00:36:48 +02001350/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1351 * address family is returned so that it's easy for the caller to adapt to the
1352 * output format. Zero is returned if the address family is not supported. -1
1353 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1354 * supported.
1355 */
1356int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1357{
1358
1359 void *ptr;
1360
1361 if (size < 5)
1362 return 0;
1363 *str = '\0';
1364
1365 switch (addr->ss_family) {
1366 case AF_INET:
1367 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1368 break;
1369 case AF_INET6:
1370 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1371 break;
1372 case AF_UNIX:
1373 memcpy(str, "unix", 5);
1374 return addr->ss_family;
1375 default:
1376 return 0;
1377 }
1378
1379 if (inet_ntop(addr->ss_family, ptr, str, size))
1380 return addr->ss_family;
1381
1382 /* failed */
1383 return -1;
1384}
1385
Simon Horman75ab8bd2014-06-16 09:39:41 +09001386/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1387 * address family is returned so that it's easy for the caller to adapt to the
1388 * output format. Zero is returned if the address family is not supported. -1
1389 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1390 * supported.
1391 */
1392int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1393{
1394
1395 uint16_t port;
1396
1397
1398 if (size < 5)
1399 return 0;
1400 *str = '\0';
1401
1402 switch (addr->ss_family) {
1403 case AF_INET:
1404 port = ((struct sockaddr_in *)addr)->sin_port;
1405 break;
1406 case AF_INET6:
1407 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1408 break;
1409 case AF_UNIX:
1410 memcpy(str, "unix", 5);
1411 return addr->ss_family;
1412 default:
1413 return 0;
1414 }
1415
1416 snprintf(str, size, "%u", ntohs(port));
1417 return addr->ss_family;
1418}
1419
Willy Tarreau16e01562016-08-09 16:46:18 +02001420/* check if the given address is local to the system or not. It will return
1421 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1422 * it is. We don't want to iterate over all interfaces for this (and it is not
1423 * portable). So instead we try to bind in UDP to this address on a free non
1424 * privileged port and to connect to the same address, port 0 (connect doesn't
1425 * care). If it succeeds, we own the address. Note that non-inet addresses are
1426 * considered local since they're most likely AF_UNIX.
1427 */
1428int addr_is_local(const struct netns_entry *ns,
1429 const struct sockaddr_storage *orig)
1430{
1431 struct sockaddr_storage addr;
1432 int result;
1433 int fd;
1434
1435 if (!is_inet_addr(orig))
1436 return 1;
1437
1438 memcpy(&addr, orig, sizeof(addr));
1439 set_host_port(&addr, 0);
1440
1441 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1442 if (fd < 0)
1443 return -1;
1444
1445 result = -1;
1446 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1447 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1448 result = 0; // fail, non-local address
1449 else
1450 result = 1; // success, local address
1451 }
1452 else {
1453 if (errno == EADDRNOTAVAIL)
1454 result = 0; // definitely not local :-)
1455 }
1456 close(fd);
1457
1458 return result;
1459}
1460
Willy Tarreaubaaee002006-06-26 02:48:02 +02001461/* will try to encode the string <string> replacing all characters tagged in
1462 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1463 * prefixed by <escape>, and will store the result between <start> (included)
1464 * and <stop> (excluded), and will always terminate the string with a '\0'
1465 * before <stop>. The position of the '\0' is returned if the conversion
1466 * completes. If bytes are missing between <start> and <stop>, then the
1467 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1468 * cannot even be stored so we return <start> without writing the 0.
1469 * The input string must also be zero-terminated.
1470 */
1471const char hextab[16] = "0123456789ABCDEF";
1472char *encode_string(char *start, char *stop,
1473 const char escape, const fd_set *map,
1474 const char *string)
1475{
1476 if (start < stop) {
1477 stop--; /* reserve one byte for the final '\0' */
1478 while (start < stop && *string != '\0') {
1479 if (!FD_ISSET((unsigned char)(*string), map))
1480 *start++ = *string;
1481 else {
1482 if (start + 3 >= stop)
1483 break;
1484 *start++ = escape;
1485 *start++ = hextab[(*string >> 4) & 15];
1486 *start++ = hextab[*string & 15];
1487 }
1488 string++;
1489 }
1490 *start = '\0';
1491 }
1492 return start;
1493}
1494
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001495/*
1496 * Same behavior as encode_string() above, except that it encodes chunk
1497 * <chunk> instead of a string.
1498 */
1499char *encode_chunk(char *start, char *stop,
1500 const char escape, const fd_set *map,
1501 const struct chunk *chunk)
1502{
1503 char *str = chunk->str;
1504 char *end = chunk->str + chunk->len;
1505
1506 if (start < stop) {
1507 stop--; /* reserve one byte for the final '\0' */
1508 while (start < stop && str < end) {
1509 if (!FD_ISSET((unsigned char)(*str), map))
1510 *start++ = *str;
1511 else {
1512 if (start + 3 >= stop)
1513 break;
1514 *start++ = escape;
1515 *start++ = hextab[(*str >> 4) & 15];
1516 *start++ = hextab[*str & 15];
1517 }
1518 str++;
1519 }
1520 *start = '\0';
1521 }
1522 return start;
1523}
1524
Dragan Dosen0edd1092016-02-12 13:23:02 +01001525/*
1526 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001527 * character. The input <string> must be zero-terminated. The result will
1528 * be stored between <start> (included) and <stop> (excluded). This
1529 * function will always try to terminate the resulting string with a '\0'
1530 * before <stop>, and will return its position if the conversion
1531 * completes.
1532 */
1533char *escape_string(char *start, char *stop,
1534 const char escape, const fd_set *map,
1535 const char *string)
1536{
1537 if (start < stop) {
1538 stop--; /* reserve one byte for the final '\0' */
1539 while (start < stop && *string != '\0') {
1540 if (!FD_ISSET((unsigned char)(*string), map))
1541 *start++ = *string;
1542 else {
1543 if (start + 2 >= stop)
1544 break;
1545 *start++ = escape;
1546 *start++ = *string;
1547 }
1548 string++;
1549 }
1550 *start = '\0';
1551 }
1552 return start;
1553}
1554
1555/*
1556 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001557 * character. <chunk> contains the input to be escaped. The result will be
1558 * stored between <start> (included) and <stop> (excluded). The function
1559 * will always try to terminate the resulting string with a '\0' before
1560 * <stop>, and will return its position if the conversion completes.
1561 */
1562char *escape_chunk(char *start, char *stop,
1563 const char escape, const fd_set *map,
1564 const struct chunk *chunk)
1565{
1566 char *str = chunk->str;
1567 char *end = chunk->str + chunk->len;
1568
1569 if (start < stop) {
1570 stop--; /* reserve one byte for the final '\0' */
1571 while (start < stop && str < end) {
1572 if (!FD_ISSET((unsigned char)(*str), map))
1573 *start++ = *str;
1574 else {
1575 if (start + 2 >= stop)
1576 break;
1577 *start++ = escape;
1578 *start++ = *str;
1579 }
1580 str++;
1581 }
1582 *start = '\0';
1583 }
1584 return start;
1585}
1586
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001587/* Check a string for using it in a CSV output format. If the string contains
1588 * one of the following four char <">, <,>, CR or LF, the string is
1589 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1590 * <str> is the input string to be escaped. The function assumes that
1591 * the input string is null-terminated.
1592 *
1593 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001594 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001595 * format.
1596 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001597 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001598 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001599 * If <quote> is 1, the converter puts the quotes only if any reserved character
1600 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001601 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001602 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001603 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001604 * The function returns the converted string on its output. If an error
1605 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001606 * for using the function directly as printf() argument.
1607 *
1608 * If the output buffer is too short to contain the input string, the result
1609 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001610 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001611 * This function appends the encoding to the existing output chunk, and it
1612 * guarantees that it starts immediately at the first available character of
1613 * the chunk. Please use csv_enc() instead if you want to replace the output
1614 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001615 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001616const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001617{
1618 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001619 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001620 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001621
Willy Tarreaub631c292016-01-08 10:04:08 +01001622 if (quote == 1) {
1623 /* automatic quoting: first verify if we'll have to quote the string */
1624 if (!strpbrk(str, "\n\r,\""))
1625 quote = 0;
1626 }
1627
1628 if (quote)
1629 *ptr++ = '"';
1630
Willy Tarreau898529b2016-01-06 18:07:04 +01001631 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1632 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001633 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001634 ptr++;
1635 if (ptr >= end - 2) {
1636 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001637 break;
1638 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001639 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001640 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001641 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001642 str++;
1643 }
1644
Willy Tarreaub631c292016-01-08 10:04:08 +01001645 if (quote)
1646 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001647
Willy Tarreau898529b2016-01-06 18:07:04 +01001648 *ptr = '\0';
1649 output->len = ptr - output->str;
1650 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001651}
1652
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001653/* Decode an URL-encoded string in-place. The resulting string might
1654 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001655 * aborted, the string is truncated before the issue and a negative value is
1656 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001657 */
1658int url_decode(char *string)
1659{
1660 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001661 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001662
1663 in = string;
1664 out = string;
1665 while (*in) {
1666 switch (*in) {
1667 case '+' :
1668 *out++ = ' ';
1669 break;
1670 case '%' :
1671 if (!ishex(in[1]) || !ishex(in[2]))
1672 goto end;
1673 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1674 in += 2;
1675 break;
1676 default:
1677 *out++ = *in;
1678 break;
1679 }
1680 in++;
1681 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001682 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001683 end:
1684 *out = 0;
1685 return ret;
1686}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001687
Willy Tarreau6911fa42007-03-04 18:06:08 +01001688unsigned int str2ui(const char *s)
1689{
1690 return __str2ui(s);
1691}
1692
1693unsigned int str2uic(const char *s)
1694{
1695 return __str2uic(s);
1696}
1697
1698unsigned int strl2ui(const char *s, int len)
1699{
1700 return __strl2ui(s, len);
1701}
1702
1703unsigned int strl2uic(const char *s, int len)
1704{
1705 return __strl2uic(s, len);
1706}
1707
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001708unsigned int read_uint(const char **s, const char *end)
1709{
1710 return __read_uint(s, end);
1711}
1712
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001713/* This function reads an unsigned integer from the string pointed to by <s> and
1714 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1715 * function automatically stops at <end>. If the number overflows, the 2^64-1
1716 * value is returned.
1717 */
1718unsigned long long int read_uint64(const char **s, const char *end)
1719{
1720 const char *ptr = *s;
1721 unsigned long long int i = 0, tmp;
1722 unsigned int j;
1723
1724 while (ptr < end) {
1725
1726 /* read next char */
1727 j = *ptr - '0';
1728 if (j > 9)
1729 goto read_uint64_end;
1730
1731 /* add char to the number and check overflow. */
1732 tmp = i * 10;
1733 if (tmp / 10 != i) {
1734 i = ULLONG_MAX;
1735 goto read_uint64_eat;
1736 }
1737 if (ULLONG_MAX - tmp < j) {
1738 i = ULLONG_MAX;
1739 goto read_uint64_eat;
1740 }
1741 i = tmp + j;
1742 ptr++;
1743 }
1744read_uint64_eat:
1745 /* eat each numeric char */
1746 while (ptr < end) {
1747 if ((unsigned int)(*ptr - '0') > 9)
1748 break;
1749 ptr++;
1750 }
1751read_uint64_end:
1752 *s = ptr;
1753 return i;
1754}
1755
1756/* This function reads an integer from the string pointed to by <s> and returns
1757 * it. The <s> pointer is adjusted to point to the first unread char. The function
1758 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1759 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1760 * returned.
1761 */
1762long long int read_int64(const char **s, const char *end)
1763{
1764 unsigned long long int i = 0;
1765 int neg = 0;
1766
1767 /* Look for minus char. */
1768 if (**s == '-') {
1769 neg = 1;
1770 (*s)++;
1771 }
1772 else if (**s == '+')
1773 (*s)++;
1774
1775 /* convert as positive number. */
1776 i = read_uint64(s, end);
1777
1778 if (neg) {
1779 if (i > 0x8000000000000000ULL)
1780 return LLONG_MIN;
1781 return -i;
1782 }
1783 if (i > 0x7fffffffffffffffULL)
1784 return LLONG_MAX;
1785 return i;
1786}
1787
Willy Tarreau6911fa42007-03-04 18:06:08 +01001788/* This one is 7 times faster than strtol() on athlon with checks.
1789 * It returns the value of the number composed of all valid digits read,
1790 * and can process negative numbers too.
1791 */
1792int strl2ic(const char *s, int len)
1793{
1794 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001795 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001796
1797 if (len > 0) {
1798 if (*s != '-') {
1799 /* positive number */
1800 while (len-- > 0) {
1801 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001802 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001803 if (j > 9)
1804 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001805 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001806 }
1807 } else {
1808 /* negative number */
1809 s++;
1810 while (--len > 0) {
1811 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001812 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001813 if (j > 9)
1814 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001815 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001816 }
1817 }
1818 }
1819 return i;
1820}
1821
1822
1823/* This function reads exactly <len> chars from <s> and converts them to a
1824 * signed integer which it stores into <ret>. It accurately detects any error
1825 * (truncated string, invalid chars, overflows). It is meant to be used in
1826 * applications designed for hostile environments. It returns zero when the
1827 * number has successfully been converted, non-zero otherwise. When an error
1828 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1829 * faster than strtol().
1830 */
1831int strl2irc(const char *s, int len, int *ret)
1832{
1833 int i = 0;
1834 int j;
1835
1836 if (!len)
1837 return 1;
1838
1839 if (*s != '-') {
1840 /* positive number */
1841 while (len-- > 0) {
1842 j = (*s++) - '0';
1843 if (j > 9) return 1; /* invalid char */
1844 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1845 i = i * 10;
1846 if (i + j < i) return 1; /* check for addition overflow */
1847 i = i + j;
1848 }
1849 } else {
1850 /* negative number */
1851 s++;
1852 while (--len > 0) {
1853 j = (*s++) - '0';
1854 if (j > 9) return 1; /* invalid char */
1855 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1856 i = i * 10;
1857 if (i - j > i) return 1; /* check for subtract overflow */
1858 i = i - j;
1859 }
1860 }
1861 *ret = i;
1862 return 0;
1863}
1864
1865
1866/* This function reads exactly <len> chars from <s> and converts them to a
1867 * signed integer which it stores into <ret>. It accurately detects any error
1868 * (truncated string, invalid chars, overflows). It is meant to be used in
1869 * applications designed for hostile environments. It returns zero when the
1870 * number has successfully been converted, non-zero otherwise. When an error
1871 * is returned, the <ret> value is left untouched. It is about 3 times slower
1872 * than str2irc().
1873 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001874
1875int strl2llrc(const char *s, int len, long long *ret)
1876{
1877 long long i = 0;
1878 int j;
1879
1880 if (!len)
1881 return 1;
1882
1883 if (*s != '-') {
1884 /* positive number */
1885 while (len-- > 0) {
1886 j = (*s++) - '0';
1887 if (j > 9) return 1; /* invalid char */
1888 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1889 i = i * 10LL;
1890 if (i + j < i) return 1; /* check for addition overflow */
1891 i = i + j;
1892 }
1893 } else {
1894 /* negative number */
1895 s++;
1896 while (--len > 0) {
1897 j = (*s++) - '0';
1898 if (j > 9) return 1; /* invalid char */
1899 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1900 i = i * 10LL;
1901 if (i - j > i) return 1; /* check for subtract overflow */
1902 i = i - j;
1903 }
1904 }
1905 *ret = i;
1906 return 0;
1907}
1908
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001909/* This function is used with pat_parse_dotted_ver(). It converts a string
1910 * composed by two number separated by a dot. Each part must contain in 16 bits
1911 * because internally they will be represented as a 32-bit quantity stored in
1912 * a 64-bit integer. It returns zero when the number has successfully been
1913 * converted, non-zero otherwise. When an error is returned, the <ret> value
1914 * is left untouched.
1915 *
1916 * "1.3" -> 0x0000000000010003
1917 * "65535.65535" -> 0x00000000ffffffff
1918 */
1919int strl2llrc_dotted(const char *text, int len, long long *ret)
1920{
1921 const char *end = &text[len];
1922 const char *p;
1923 long long major, minor;
1924
1925 /* Look for dot. */
1926 for (p = text; p < end; p++)
1927 if (*p == '.')
1928 break;
1929
1930 /* Convert major. */
1931 if (strl2llrc(text, p - text, &major) != 0)
1932 return 1;
1933
1934 /* Check major. */
1935 if (major >= 65536)
1936 return 1;
1937
1938 /* Convert minor. */
1939 minor = 0;
1940 if (p < end)
1941 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1942 return 1;
1943
1944 /* Check minor. */
1945 if (minor >= 65536)
1946 return 1;
1947
1948 /* Compose value. */
1949 *ret = (major << 16) | (minor & 0xffff);
1950 return 0;
1951}
1952
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001953/* This function parses a time value optionally followed by a unit suffix among
1954 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1955 * expected by the caller. The computation does its best to avoid overflows.
1956 * The value is returned in <ret> if everything is fine, and a NULL is returned
1957 * by the function. In case of error, a pointer to the error is returned and
1958 * <ret> is left untouched. Values are automatically rounded up when needed.
1959 */
1960const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1961{
1962 unsigned imult, idiv;
1963 unsigned omult, odiv;
1964 unsigned value;
1965
1966 omult = odiv = 1;
1967
1968 switch (unit_flags & TIME_UNIT_MASK) {
1969 case TIME_UNIT_US: omult = 1000000; break;
1970 case TIME_UNIT_MS: omult = 1000; break;
1971 case TIME_UNIT_S: break;
1972 case TIME_UNIT_MIN: odiv = 60; break;
1973 case TIME_UNIT_HOUR: odiv = 3600; break;
1974 case TIME_UNIT_DAY: odiv = 86400; break;
1975 default: break;
1976 }
1977
1978 value = 0;
1979
1980 while (1) {
1981 unsigned int j;
1982
1983 j = *text - '0';
1984 if (j > 9)
1985 break;
1986 text++;
1987 value *= 10;
1988 value += j;
1989 }
1990
1991 imult = idiv = 1;
1992 switch (*text) {
1993 case '\0': /* no unit = default unit */
1994 imult = omult = idiv = odiv = 1;
1995 break;
1996 case 's': /* second = unscaled unit */
1997 break;
1998 case 'u': /* microsecond : "us" */
1999 if (text[1] == 's') {
2000 idiv = 1000000;
2001 text++;
2002 }
2003 break;
2004 case 'm': /* millisecond : "ms" or minute: "m" */
2005 if (text[1] == 's') {
2006 idiv = 1000;
2007 text++;
2008 } else
2009 imult = 60;
2010 break;
2011 case 'h': /* hour : "h" */
2012 imult = 3600;
2013 break;
2014 case 'd': /* day : "d" */
2015 imult = 86400;
2016 break;
2017 default:
2018 return text;
2019 break;
2020 }
2021
2022 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2023 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2024 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2025 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2026
2027 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2028 *ret = value;
2029 return NULL;
2030}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002031
Emeric Brun39132b22010-01-04 14:57:24 +01002032/* this function converts the string starting at <text> to an unsigned int
2033 * stored in <ret>. If an error is detected, the pointer to the unexpected
2034 * character is returned. If the conversio is succesful, NULL is returned.
2035 */
2036const char *parse_size_err(const char *text, unsigned *ret) {
2037 unsigned value = 0;
2038
2039 while (1) {
2040 unsigned int j;
2041
2042 j = *text - '0';
2043 if (j > 9)
2044 break;
2045 if (value > ~0U / 10)
2046 return text;
2047 value *= 10;
2048 if (value > (value + j))
2049 return text;
2050 value += j;
2051 text++;
2052 }
2053
2054 switch (*text) {
2055 case '\0':
2056 break;
2057 case 'K':
2058 case 'k':
2059 if (value > ~0U >> 10)
2060 return text;
2061 value = value << 10;
2062 break;
2063 case 'M':
2064 case 'm':
2065 if (value > ~0U >> 20)
2066 return text;
2067 value = value << 20;
2068 break;
2069 case 'G':
2070 case 'g':
2071 if (value > ~0U >> 30)
2072 return text;
2073 value = value << 30;
2074 break;
2075 default:
2076 return text;
2077 }
2078
Godbach58048a22015-01-28 17:36:16 +08002079 if (*text != '\0' && *++text != '\0')
2080 return text;
2081
Emeric Brun39132b22010-01-04 14:57:24 +01002082 *ret = value;
2083 return NULL;
2084}
2085
Willy Tarreau126d4062013-12-03 17:50:47 +01002086/*
2087 * Parse binary string written in hexadecimal (source) and store the decoded
2088 * result into binstr and set binstrlen to the lengh of binstr. Memory for
2089 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002090 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002091 */
2092int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2093{
2094 int len;
2095 const char *p = source;
2096 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002097 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002098
2099 len = strlen(source);
2100 if (len % 2) {
2101 memprintf(err, "an even number of hex digit is expected");
2102 return 0;
2103 }
2104
2105 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002106
Willy Tarreau126d4062013-12-03 17:50:47 +01002107 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002108 *binstr = calloc(len, sizeof(char));
2109 if (!*binstr) {
2110 memprintf(err, "out of memory while loading string pattern");
2111 return 0;
2112 }
2113 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002114 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002115 else {
2116 if (*binstrlen < len) {
2117 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
2118 len, *binstrlen);
2119 return 0;
2120 }
2121 alloc = 0;
2122 }
2123 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002124
2125 i = j = 0;
2126 while (j < len) {
2127 if (!ishex(p[i++]))
2128 goto bad_input;
2129 if (!ishex(p[i++]))
2130 goto bad_input;
2131 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2132 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002133 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002134
2135bad_input:
2136 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002137 if (alloc) {
2138 free(*binstr);
2139 *binstr = NULL;
2140 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002141 return 0;
2142}
2143
Willy Tarreau946ba592009-05-10 15:41:18 +02002144/* copies at most <n> characters from <src> and always terminates with '\0' */
2145char *my_strndup(const char *src, int n)
2146{
2147 int len = 0;
2148 char *ret;
2149
2150 while (len < n && src[len])
2151 len++;
2152
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002153 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002154 if (!ret)
2155 return ret;
2156 memcpy(ret, src, len);
2157 ret[len] = '\0';
2158 return ret;
2159}
2160
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002161/*
2162 * search needle in haystack
2163 * returns the pointer if found, returns NULL otherwise
2164 */
2165const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2166{
2167 const void *c = NULL;
2168 unsigned char f;
2169
2170 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2171 return NULL;
2172
2173 f = *(char *)needle;
2174 c = haystack;
2175 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2176 if ((haystacklen - (c - haystack)) < needlelen)
2177 return NULL;
2178
2179 if (memcmp(c, needle, needlelen) == 0)
2180 return c;
2181 ++c;
2182 }
2183 return NULL;
2184}
2185
Willy Tarreau482b00d2009-10-04 22:48:42 +02002186/* This function returns the first unused key greater than or equal to <key> in
2187 * ID tree <root>. Zero is returned if no place is found.
2188 */
2189unsigned int get_next_id(struct eb_root *root, unsigned int key)
2190{
2191 struct eb32_node *used;
2192
2193 do {
2194 used = eb32_lookup_ge(root, key);
2195 if (!used || used->key > key)
2196 return key; /* key is available */
2197 key++;
2198 } while (key);
2199 return key;
2200}
2201
Willy Tarreau348238b2010-01-18 15:05:57 +01002202/* This function compares a sample word possibly followed by blanks to another
2203 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2204 * otherwise zero. This intends to be used when checking HTTP headers for some
2205 * values. Note that it validates a word followed only by blanks but does not
2206 * validate a word followed by blanks then other chars.
2207 */
2208int word_match(const char *sample, int slen, const char *word, int wlen)
2209{
2210 if (slen < wlen)
2211 return 0;
2212
2213 while (wlen) {
2214 char c = *sample ^ *word;
2215 if (c && c != ('A' ^ 'a'))
2216 return 0;
2217 sample++;
2218 word++;
2219 slen--;
2220 wlen--;
2221 }
2222
2223 while (slen) {
2224 if (*sample != ' ' && *sample != '\t')
2225 return 0;
2226 sample++;
2227 slen--;
2228 }
2229 return 1;
2230}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002231
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002232/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2233 * is particularly fast because it avoids expensive operations such as
2234 * multiplies, which are optimized away at the end. It requires a properly
2235 * formated address though (3 points).
2236 */
2237unsigned int inetaddr_host(const char *text)
2238{
2239 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2240 register unsigned int dig100, dig10, dig1;
2241 int s;
2242 const char *p, *d;
2243
2244 dig1 = dig10 = dig100 = ascii_zero;
2245 s = 24;
2246
2247 p = text;
2248 while (1) {
2249 if (((unsigned)(*p - '0')) <= 9) {
2250 p++;
2251 continue;
2252 }
2253
2254 /* here, we have a complete byte between <text> and <p> (exclusive) */
2255 if (p == text)
2256 goto end;
2257
2258 d = p - 1;
2259 dig1 |= (unsigned int)(*d << s);
2260 if (d == text)
2261 goto end;
2262
2263 d--;
2264 dig10 |= (unsigned int)(*d << s);
2265 if (d == text)
2266 goto end;
2267
2268 d--;
2269 dig100 |= (unsigned int)(*d << s);
2270 end:
2271 if (!s || *p != '.')
2272 break;
2273
2274 s -= 8;
2275 text = ++p;
2276 }
2277
2278 dig100 -= ascii_zero;
2279 dig10 -= ascii_zero;
2280 dig1 -= ascii_zero;
2281 return ((dig100 * 10) + dig10) * 10 + dig1;
2282}
2283
2284/*
2285 * Idem except the first unparsed character has to be passed in <stop>.
2286 */
2287unsigned int inetaddr_host_lim(const char *text, const char *stop)
2288{
2289 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2290 register unsigned int dig100, dig10, dig1;
2291 int s;
2292 const char *p, *d;
2293
2294 dig1 = dig10 = dig100 = ascii_zero;
2295 s = 24;
2296
2297 p = text;
2298 while (1) {
2299 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2300 p++;
2301 continue;
2302 }
2303
2304 /* here, we have a complete byte between <text> and <p> (exclusive) */
2305 if (p == text)
2306 goto end;
2307
2308 d = p - 1;
2309 dig1 |= (unsigned int)(*d << s);
2310 if (d == text)
2311 goto end;
2312
2313 d--;
2314 dig10 |= (unsigned int)(*d << s);
2315 if (d == text)
2316 goto end;
2317
2318 d--;
2319 dig100 |= (unsigned int)(*d << s);
2320 end:
2321 if (!s || p == stop || *p != '.')
2322 break;
2323
2324 s -= 8;
2325 text = ++p;
2326 }
2327
2328 dig100 -= ascii_zero;
2329 dig10 -= ascii_zero;
2330 dig1 -= ascii_zero;
2331 return ((dig100 * 10) + dig10) * 10 + dig1;
2332}
2333
2334/*
2335 * Idem except the pointer to first unparsed byte is returned into <ret> which
2336 * must not be NULL.
2337 */
Willy Tarreau74172752010-10-15 23:21:42 +02002338unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002339{
2340 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2341 register unsigned int dig100, dig10, dig1;
2342 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002343 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002344
2345 dig1 = dig10 = dig100 = ascii_zero;
2346 s = 24;
2347
2348 p = text;
2349 while (1) {
2350 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2351 p++;
2352 continue;
2353 }
2354
2355 /* here, we have a complete byte between <text> and <p> (exclusive) */
2356 if (p == text)
2357 goto end;
2358
2359 d = p - 1;
2360 dig1 |= (unsigned int)(*d << s);
2361 if (d == text)
2362 goto end;
2363
2364 d--;
2365 dig10 |= (unsigned int)(*d << s);
2366 if (d == text)
2367 goto end;
2368
2369 d--;
2370 dig100 |= (unsigned int)(*d << s);
2371 end:
2372 if (!s || p == stop || *p != '.')
2373 break;
2374
2375 s -= 8;
2376 text = ++p;
2377 }
2378
2379 *ret = p;
2380 dig100 -= ascii_zero;
2381 dig10 -= ascii_zero;
2382 dig1 -= ascii_zero;
2383 return ((dig100 * 10) + dig10) * 10 + dig1;
2384}
2385
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002386/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2387 * or the number of chars read in case of success. Maybe this could be replaced
2388 * by one of the functions above. Also, apparently this function does not support
2389 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002390 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002391 */
2392int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2393{
2394 const char *addr;
2395 int saw_digit, octets, ch;
2396 u_char tmp[4], *tp;
2397 const char *cp = buf;
2398
2399 saw_digit = 0;
2400 octets = 0;
2401 *(tp = tmp) = 0;
2402
2403 for (addr = buf; addr - buf < len; addr++) {
2404 unsigned char digit = (ch = *addr) - '0';
2405
2406 if (digit > 9 && ch != '.')
2407 break;
2408
2409 if (digit <= 9) {
2410 u_int new = *tp * 10 + digit;
2411
2412 if (new > 255)
2413 return 0;
2414
2415 *tp = new;
2416
2417 if (!saw_digit) {
2418 if (++octets > 4)
2419 return 0;
2420 saw_digit = 1;
2421 }
2422 } else if (ch == '.' && saw_digit) {
2423 if (octets == 4)
2424 return 0;
2425
2426 *++tp = 0;
2427 saw_digit = 0;
2428 } else
2429 return 0;
2430 }
2431
2432 if (octets < 4)
2433 return 0;
2434
2435 memcpy(&dst->s_addr, tmp, 4);
2436 return addr - cp;
2437}
2438
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002439/* This function converts the string in <buf> of the len <len> to
2440 * struct in6_addr <dst> which must be allocated by the caller.
2441 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002442 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002443 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002444int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2445{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002446 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002447 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002448
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002449 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002450 return 0;
2451
2452 memcpy(null_term_ip6, buf, len);
2453 null_term_ip6[len] = '\0';
2454
Willy Tarreau075415a2013-12-12 11:29:39 +01002455 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002456 return 0;
2457
Willy Tarreau075415a2013-12-12 11:29:39 +01002458 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002459 return 1;
2460}
2461
Willy Tarreauacf95772010-06-14 19:09:21 +02002462/* To be used to quote config arg positions. Returns the short string at <ptr>
2463 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2464 * if ptr is NULL or empty. The string is locally allocated.
2465 */
2466const char *quote_arg(const char *ptr)
2467{
2468 static char val[32];
2469 int i;
2470
2471 if (!ptr || !*ptr)
2472 return "end of line";
2473 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002474 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002475 val[i] = *ptr++;
2476 val[i++] = '\'';
2477 val[i] = '\0';
2478 return val;
2479}
2480
Willy Tarreau5b180202010-07-18 10:40:48 +02002481/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2482int get_std_op(const char *str)
2483{
2484 int ret = -1;
2485
2486 if (*str == 'e' && str[1] == 'q')
2487 ret = STD_OP_EQ;
2488 else if (*str == 'n' && str[1] == 'e')
2489 ret = STD_OP_NE;
2490 else if (*str == 'l') {
2491 if (str[1] == 'e') ret = STD_OP_LE;
2492 else if (str[1] == 't') ret = STD_OP_LT;
2493 }
2494 else if (*str == 'g') {
2495 if (str[1] == 'e') ret = STD_OP_GE;
2496 else if (str[1] == 't') ret = STD_OP_GT;
2497 }
2498
2499 if (ret == -1 || str[2] != '\0')
2500 return -1;
2501 return ret;
2502}
2503
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002504/* hash a 32-bit integer to another 32-bit integer */
2505unsigned int full_hash(unsigned int a)
2506{
2507 return __full_hash(a);
2508}
2509
David du Colombier4f92d322011-03-24 11:09:31 +01002510/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002511 * otherwise zero. Note that <addr> may not necessarily be aligned
2512 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002513 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002514int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002515{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002516 struct in_addr addr_copy;
2517
2518 memcpy(&addr_copy, addr, sizeof(addr_copy));
2519 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002520}
2521
2522/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002523 * otherwise zero. Note that <addr> may not necessarily be aligned
2524 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002525 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002526int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002527{
2528 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002529 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002530
Willy Tarreaueec1d382016-07-13 11:59:39 +02002531 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002532 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002533 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002534 (((int *)net)[i] & ((int *)mask)[i]))
2535 return 0;
2536 return 1;
2537}
2538
2539/* RFC 4291 prefix */
2540const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2541 0x00, 0x00, 0x00, 0x00,
2542 0x00, 0x00, 0xFF, 0xFF };
2543
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002544/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2545 * Input and output may overlap.
2546 */
David du Colombier4f92d322011-03-24 11:09:31 +01002547void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2548{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002549 struct in_addr tmp_addr;
2550
2551 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002552 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002553 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002554}
2555
2556/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2557 * Return true if conversion is possible and false otherwise.
2558 */
2559int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2560{
2561 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2562 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2563 sizeof(struct in_addr));
2564 return 1;
2565 }
2566
2567 return 0;
2568}
2569
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01002570/* compare two struct sockaddr_storage and return:
2571 * 0 (true) if the addr is the same in both
2572 * 1 (false) if the addr is not the same in both
2573 * -1 (unable) if one of the addr is not AF_INET*
2574 */
2575int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
2576{
2577 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
2578 return -1;
2579
2580 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
2581 return -1;
2582
2583 if (ss1->ss_family != ss2->ss_family)
2584 return 1;
2585
2586 switch (ss1->ss_family) {
2587 case AF_INET:
2588 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
2589 &((struct sockaddr_in *)ss2)->sin_addr,
2590 sizeof(struct in_addr)) != 0;
2591 case AF_INET6:
2592 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
2593 &((struct sockaddr_in6 *)ss2)->sin6_addr,
2594 sizeof(struct in6_addr)) != 0;
2595 }
2596
2597 return 1;
2598}
2599
Baptiste Assmann08396c82016-01-31 00:27:17 +01002600/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002601 * The caller must allocate and clear <dest> before calling.
2602 * The source must be in either AF_INET or AF_INET6 family, or the destination
2603 * address will be undefined. If the destination address used to hold a port,
2604 * it is preserved, so that this function can be used to switch to another
2605 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01002606 */
2607struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
2608{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002609 int prev_port;
2610
2611 prev_port = get_net_port(dest);
2612 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01002613 dest->ss_family = source->ss_family;
2614
2615 /* copy new addr and apply it */
2616 switch (source->ss_family) {
2617 case AF_INET:
2618 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002619 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002620 break;
2621 case AF_INET6:
2622 memcpy(((struct sockaddr_in6 *)dest)->sin6_addr.s6_addr, ((struct sockaddr_in6 *)source)->sin6_addr.s6_addr, sizeof(struct in6_addr));
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01002623 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01002624 break;
2625 }
2626
2627 return dest;
2628}
2629
William Lallemand421f5b52012-02-06 18:15:57 +01002630char *human_time(int t, short hz_div) {
2631 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2632 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002633 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002634 int cnt=2; // print two numbers
2635
2636 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002637 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002638 return rv;
2639 }
2640
2641 if (unlikely(hz_div > 1))
2642 t /= hz_div;
2643
2644 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002645 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002646 cnt--;
2647 }
2648
2649 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002650 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002651 cnt--;
2652 }
2653
2654 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002655 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002656 cnt--;
2657 }
2658
2659 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002660 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002661
2662 return rv;
2663}
2664
2665const char *monthname[12] = {
2666 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2667 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2668};
2669
2670/* date2str_log: write a date in the format :
2671 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2672 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2673 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2674 *
2675 * without using sprintf. return a pointer to the last char written (\0) or
2676 * NULL if there isn't enough space.
2677 */
2678char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2679{
2680
2681 if (size < 25) /* the size is fixed: 24 chars + \0 */
2682 return NULL;
2683
2684 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2685 *dst++ = '/';
2686 memcpy(dst, monthname[tm->tm_mon], 3); // month
2687 dst += 3;
2688 *dst++ = '/';
2689 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2690 *dst++ = ':';
2691 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2692 *dst++ = ':';
2693 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2694 *dst++ = ':';
2695 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2696 *dst++ = '.';
2697 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2698 dst += 3; // only the 3 first digits
2699 *dst = '\0';
2700
2701 return dst;
2702}
2703
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002704/* Base year used to compute leap years */
2705#define TM_YEAR_BASE 1900
2706
2707/* Return the difference in seconds between two times (leap seconds are ignored).
2708 * Retrieved from glibc 2.18 source code.
2709 */
2710static int my_tm_diff(const struct tm *a, const struct tm *b)
2711{
2712 /* Compute intervening leap days correctly even if year is negative.
2713 * Take care to avoid int overflow in leap day calculations,
2714 * but it's OK to assume that A and B are close to each other.
2715 */
2716 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2717 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2718 int a100 = a4 / 25 - (a4 % 25 < 0);
2719 int b100 = b4 / 25 - (b4 % 25 < 0);
2720 int a400 = a100 >> 2;
2721 int b400 = b100 >> 2;
2722 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2723 int years = a->tm_year - b->tm_year;
2724 int days = (365 * years + intervening_leap_days
2725 + (a->tm_yday - b->tm_yday));
2726 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2727 + (a->tm_min - b->tm_min))
2728 + (a->tm_sec - b->tm_sec));
2729}
2730
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002731/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002732 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002733 * The string returned has the same format as returned by strftime(... "%z", tm).
2734 * Offsets are kept in an internal cache for better performances.
2735 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002736const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002737{
2738 /* Cache offsets from GMT (depending on whether DST is active or not) */
2739 static char gmt_offsets[2][5+1] = { "", "" };
2740
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002741 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002742 struct tm tm_gmt;
2743 int diff;
2744 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002745
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002746 /* Pretend DST not active if its status is unknown */
2747 if (isdst < 0)
2748 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002749
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002750 /* Fetch the offset and initialize it if needed */
2751 gmt_offset = gmt_offsets[isdst & 0x01];
2752 if (unlikely(!*gmt_offset)) {
2753 get_gmtime(t, &tm_gmt);
2754 diff = my_tm_diff(tm, &tm_gmt);
2755 if (diff < 0) {
2756 diff = -diff;
2757 *gmt_offset = '-';
2758 } else {
2759 *gmt_offset = '+';
2760 }
2761 diff /= 60; /* Convert to minutes */
2762 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2763 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002764
2765 return gmt_offset;
2766}
2767
William Lallemand421f5b52012-02-06 18:15:57 +01002768/* gmt2str_log: write a date in the format :
2769 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2770 * return a pointer to the last char written (\0) or
2771 * NULL if there isn't enough space.
2772 */
2773char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2774{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002775 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002776 return NULL;
2777
2778 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2779 *dst++ = '/';
2780 memcpy(dst, monthname[tm->tm_mon], 3); // month
2781 dst += 3;
2782 *dst++ = '/';
2783 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2784 *dst++ = ':';
2785 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2786 *dst++ = ':';
2787 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2788 *dst++ = ':';
2789 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2790 *dst++ = ' ';
2791 *dst++ = '+';
2792 *dst++ = '0';
2793 *dst++ = '0';
2794 *dst++ = '0';
2795 *dst++ = '0';
2796 *dst = '\0';
2797
2798 return dst;
2799}
2800
Yuxans Yao4e25b012012-10-19 10:36:09 +08002801/* localdate2str_log: write a date in the format :
2802 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002803 * Both t and tm must represent the same time.
2804 * return a pointer to the last char written (\0) or
2805 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002806 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002807char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002808{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002809 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002810 if (size < 27) /* the size is fixed: 26 chars + \0 */
2811 return NULL;
2812
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02002813 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002814
Yuxans Yao4e25b012012-10-19 10:36:09 +08002815 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2816 *dst++ = '/';
2817 memcpy(dst, monthname[tm->tm_mon], 3); // month
2818 dst += 3;
2819 *dst++ = '/';
2820 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2821 *dst++ = ':';
2822 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2823 *dst++ = ':';
2824 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2825 *dst++ = ':';
2826 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2827 *dst++ = ' ';
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02002828 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002829 dst += 5;
2830 *dst = '\0';
2831
2832 return dst;
2833}
2834
Thierry Fournier93127942016-01-20 18:49:45 +01002835/* This function check a char. It returns true and updates
2836 * <date> and <len> pointer to the new position if the
2837 * character is found.
2838 */
2839static inline int parse_expect_char(const char **date, int *len, char c)
2840{
2841 if (*len < 1 || **date != c)
2842 return 0;
2843 (*len)--;
2844 (*date)++;
2845 return 1;
2846}
2847
2848/* This function expects a string <str> of len <l>. It return true and updates.
2849 * <date> and <len> if the string matches, otherwise, it returns false.
2850 */
2851static inline int parse_strcmp(const char **date, int *len, char *str, int l)
2852{
2853 if (*len < l || strncmp(*date, str, l) != 0)
2854 return 0;
2855 (*len) -= l;
2856 (*date) += l;
2857 return 1;
2858}
2859
2860/* This macro converts 3 chars name in integer. */
2861#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
2862
2863/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
2864 * / %x54.75.65 ; "Tue", case-sensitive
2865 * / %x57.65.64 ; "Wed", case-sensitive
2866 * / %x54.68.75 ; "Thu", case-sensitive
2867 * / %x46.72.69 ; "Fri", case-sensitive
2868 * / %x53.61.74 ; "Sat", case-sensitive
2869 * / %x53.75.6E ; "Sun", case-sensitive
2870 *
2871 * This array must be alphabetically sorted
2872 */
2873static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
2874{
2875 if (*len < 3)
2876 return 0;
2877 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2878 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
2879 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
2880 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
2881 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
2882 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
2883 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
2884 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
2885 default: return 0;
2886 }
2887 *len -= 3;
2888 *date += 3;
2889 return 1;
2890}
2891
2892/* month = %x4A.61.6E ; "Jan", case-sensitive
2893 * / %x46.65.62 ; "Feb", case-sensitive
2894 * / %x4D.61.72 ; "Mar", case-sensitive
2895 * / %x41.70.72 ; "Apr", case-sensitive
2896 * / %x4D.61.79 ; "May", case-sensitive
2897 * / %x4A.75.6E ; "Jun", case-sensitive
2898 * / %x4A.75.6C ; "Jul", case-sensitive
2899 * / %x41.75.67 ; "Aug", case-sensitive
2900 * / %x53.65.70 ; "Sep", case-sensitive
2901 * / %x4F.63.74 ; "Oct", case-sensitive
2902 * / %x4E.6F.76 ; "Nov", case-sensitive
2903 * / %x44.65.63 ; "Dec", case-sensitive
2904 *
2905 * This array must be alphabetically sorted
2906 */
2907static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
2908{
2909 if (*len < 3)
2910 return 0;
2911 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2912 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
2913 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
2914 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
2915 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
2916 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
2917 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
2918 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
2919 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
2920 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
2921 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
2922 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
2923 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
2924 default: return 0;
2925 }
2926 *len -= 3;
2927 *date += 3;
2928 return 1;
2929}
2930
2931/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
2932 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
2933 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
2934 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
2935 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
2936 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
2937 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
2938 *
2939 * This array must be alphabetically sorted
2940 */
2941static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
2942{
2943 if (*len < 6) /* Minimum length. */
2944 return 0;
2945 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2946 case STR2I3('M','o','n'):
2947 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
2948 tm->tm_wday = 1;
2949 return 1;
2950 case STR2I3('T','u','e'):
2951 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
2952 tm->tm_wday = 2;
2953 return 1;
2954 case STR2I3('W','e','d'):
2955 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
2956 tm->tm_wday = 3;
2957 return 1;
2958 case STR2I3('T','h','u'):
2959 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
2960 tm->tm_wday = 4;
2961 return 1;
2962 case STR2I3('F','r','i'):
2963 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
2964 tm->tm_wday = 5;
2965 return 1;
2966 case STR2I3('S','a','t'):
2967 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
2968 tm->tm_wday = 6;
2969 return 1;
2970 case STR2I3('S','u','n'):
2971 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
2972 tm->tm_wday = 7;
2973 return 1;
2974 }
2975 return 0;
2976}
2977
2978/* This function parses exactly 1 digit and returns the numeric value in "digit". */
2979static inline int parse_digit(const char **date, int *len, int *digit)
2980{
2981 if (*len < 1 || **date < '0' || **date > '9')
2982 return 0;
2983 *digit = (**date - '0');
2984 (*date)++;
2985 (*len)--;
2986 return 1;
2987}
2988
2989/* This function parses exactly 2 digits and returns the numeric value in "digit". */
2990static inline int parse_2digit(const char **date, int *len, int *digit)
2991{
2992 int value;
2993
2994 RET0_UNLESS(parse_digit(date, len, &value));
2995 (*digit) = value * 10;
2996 RET0_UNLESS(parse_digit(date, len, &value));
2997 (*digit) += value;
2998
2999 return 1;
3000}
3001
3002/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3003static inline int parse_4digit(const char **date, int *len, int *digit)
3004{
3005 int value;
3006
3007 RET0_UNLESS(parse_digit(date, len, &value));
3008 (*digit) = value * 1000;
3009
3010 RET0_UNLESS(parse_digit(date, len, &value));
3011 (*digit) += value * 100;
3012
3013 RET0_UNLESS(parse_digit(date, len, &value));
3014 (*digit) += value * 10;
3015
3016 RET0_UNLESS(parse_digit(date, len, &value));
3017 (*digit) += value;
3018
3019 return 1;
3020}
3021
3022/* time-of-day = hour ":" minute ":" second
3023 * ; 00:00:00 - 23:59:60 (leap second)
3024 *
3025 * hour = 2DIGIT
3026 * minute = 2DIGIT
3027 * second = 2DIGIT
3028 */
3029static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3030{
3031 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3032 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3033 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3034 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3035 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3036 return 1;
3037}
3038
3039/* From RFC7231
3040 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3041 *
3042 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3043 * ; fixed length/zone/capitalization subset of the format
3044 * ; see Section 3.3 of [RFC5322]
3045 *
3046 *
3047 * date1 = day SP month SP year
3048 * ; e.g., 02 Jun 1982
3049 *
3050 * day = 2DIGIT
3051 * year = 4DIGIT
3052 *
3053 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3054 *
3055 * time-of-day = hour ":" minute ":" second
3056 * ; 00:00:00 - 23:59:60 (leap second)
3057 *
3058 * hour = 2DIGIT
3059 * minute = 2DIGIT
3060 * second = 2DIGIT
3061 *
3062 * DIGIT = decimal 0-9
3063 */
3064int parse_imf_date(const char *date, int len, struct tm *tm)
3065{
3066 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3067 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3068 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3069 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3070 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3071 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3072 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3073 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3074 tm->tm_year -= 1900;
3075 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3076 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3077 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3078 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3079 tm->tm_isdst = -1;
3080 tm->tm_gmtoff = 0;
3081 return 1;
3082}
3083
3084/* From RFC7231
3085 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3086 *
3087 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3088 * date2 = day "-" month "-" 2DIGIT
3089 * ; e.g., 02-Jun-82
3090 *
3091 * day = 2DIGIT
3092 */
3093int parse_rfc850_date(const char *date, int len, struct tm *tm)
3094{
3095 int year;
3096
3097 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3098 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3099 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3100 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3101 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3102 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3103 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3104
3105 /* year = 2DIGIT
3106 *
3107 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3108 * two-digit year, MUST interpret a timestamp that appears to be more
3109 * than 50 years in the future as representing the most recent year in
3110 * the past that had the same last two digits.
3111 */
3112 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3113
3114 /* expect SP */
3115 if (!parse_expect_char(&date, &len, ' ')) {
3116 /* Maybe we have the date with 4 digits. */
3117 RET0_UNLESS(parse_2digit(&date, &len, &year));
3118 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3119 /* expect SP */
3120 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3121 } else {
3122 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3123 * tm_year is the number of year since 1900, so for +1900, we
3124 * do nothing, and for +2000, we add 100.
3125 */
3126 if (tm->tm_year <= 60)
3127 tm->tm_year += 100;
3128 }
3129
3130 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3131 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3132 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3133 tm->tm_isdst = -1;
3134 tm->tm_gmtoff = 0;
3135
3136 return 1;
3137}
3138
3139/* From RFC7231
3140 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3141 *
3142 * asctime-date = day-name SP date3 SP time-of-day SP year
3143 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3144 * ; e.g., Jun 2
3145 *
3146 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3147 * whitespace in an HTTP-date beyond that specifically included as SP in
3148 * the grammar.
3149 */
3150int parse_asctime_date(const char *date, int len, struct tm *tm)
3151{
3152 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3153 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3154 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3155 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3156
3157 /* expect SP and 1DIGIT or 2DIGIT */
3158 if (parse_expect_char(&date, &len, ' '))
3159 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3160 else
3161 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3162
3163 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3164 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3165 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3166 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3167 tm->tm_year -= 1900;
3168 tm->tm_isdst = -1;
3169 tm->tm_gmtoff = 0;
3170 return 1;
3171}
3172
3173/* From RFC7231
3174 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3175 *
3176 * HTTP-date = IMF-fixdate / obs-date
3177 * obs-date = rfc850-date / asctime-date
3178 *
3179 * parses an HTTP date in the RFC format and is accepted
3180 * alternatives. <date> is the strinf containing the date,
3181 * len is the len of the string. <tm> is filled with the
3182 * parsed time. We must considers this time as GMT.
3183 */
3184int parse_http_date(const char *date, int len, struct tm *tm)
3185{
3186 if (parse_imf_date(date, len, tm))
3187 return 1;
3188
3189 if (parse_rfc850_date(date, len, tm))
3190 return 1;
3191
3192 if (parse_asctime_date(date, len, tm))
3193 return 1;
3194
3195 return 0;
3196}
3197
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003198/* Dynamically allocates a string of the proper length to hold the formatted
3199 * output. NULL is returned on error. The caller is responsible for freeing the
3200 * memory area using free(). The resulting string is returned in <out> if the
3201 * pointer is not NULL. A previous version of <out> might be used to build the
3202 * new string, and it will be freed before returning if it is not NULL, which
3203 * makes it possible to build complex strings from iterative calls without
3204 * having to care about freeing intermediate values, as in the example below :
3205 *
3206 * memprintf(&err, "invalid argument: '%s'", arg);
3207 * ...
3208 * memprintf(&err, "parser said : <%s>\n", *err);
3209 * ...
3210 * free(*err);
3211 *
3212 * This means that <err> must be initialized to NULL before first invocation.
3213 * The return value also holds the allocated string, which eases error checking
3214 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003215 * passed instead and it will be ignored. The returned message will then also
3216 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003217 *
3218 * It is also convenient to use it without any free except the last one :
3219 * err = NULL;
3220 * if (!fct1(err)) report(*err);
3221 * if (!fct2(err)) report(*err);
3222 * if (!fct3(err)) report(*err);
3223 * free(*err);
3224 */
3225char *memprintf(char **out, const char *format, ...)
3226{
3227 va_list args;
3228 char *ret = NULL;
3229 int allocated = 0;
3230 int needed = 0;
3231
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003232 if (!out)
3233 return NULL;
3234
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003235 do {
3236 /* vsnprintf() will return the required length even when the
3237 * target buffer is NULL. We do this in a loop just in case
3238 * intermediate evaluations get wrong.
3239 */
3240 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003241 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003242 va_end(args);
3243
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003244 if (needed < allocated) {
3245 /* Note: on Solaris 8, the first iteration always
3246 * returns -1 if allocated is zero, so we force a
3247 * retry.
3248 */
3249 if (!allocated)
3250 needed = 0;
3251 else
3252 break;
3253 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003254
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003255 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003256 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003257 } while (ret);
3258
3259 if (needed < 0) {
3260 /* an error was encountered */
3261 free(ret);
3262 ret = NULL;
3263 }
3264
3265 if (out) {
3266 free(*out);
3267 *out = ret;
3268 }
3269
3270 return ret;
3271}
William Lallemand421f5b52012-02-06 18:15:57 +01003272
Willy Tarreau21c705b2012-09-14 11:40:36 +02003273/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3274 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003275 * freed by the caller. It also supports being passed a NULL which results in the same
3276 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003277 * Example of use :
3278 * parse(cmd, &err); (callee: memprintf(&err, ...))
3279 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3280 * free(err);
3281 */
3282char *indent_msg(char **out, int level)
3283{
3284 char *ret, *in, *p;
3285 int needed = 0;
3286 int lf = 0;
3287 int lastlf = 0;
3288 int len;
3289
Willy Tarreau70eec382012-10-10 08:56:47 +02003290 if (!out || !*out)
3291 return NULL;
3292
Willy Tarreau21c705b2012-09-14 11:40:36 +02003293 in = *out - 1;
3294 while ((in = strchr(in + 1, '\n')) != NULL) {
3295 lastlf = in - *out;
3296 lf++;
3297 }
3298
3299 if (!lf) /* single line, no LF, return it as-is */
3300 return *out;
3301
3302 len = strlen(*out);
3303
3304 if (lf == 1 && lastlf == len - 1) {
3305 /* single line, LF at end, strip it and return as-is */
3306 (*out)[lastlf] = 0;
3307 return *out;
3308 }
3309
3310 /* OK now we have at least one LF, we need to process the whole string
3311 * as a multi-line string. What we'll do :
3312 * - prefix with an LF if there is none
3313 * - add <level> spaces before each line
3314 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3315 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3316 */
3317
3318 needed = 1 + level * (lf + 1) + len + 1;
3319 p = ret = malloc(needed);
3320 in = *out;
3321
3322 /* skip initial LFs */
3323 while (*in == '\n')
3324 in++;
3325
3326 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3327 while (*in) {
3328 *p++ = '\n';
3329 memset(p, ' ', level);
3330 p += level;
3331 do {
3332 *p++ = *in++;
3333 } while (*in && *in != '\n');
3334 if (*in)
3335 in++;
3336 }
3337 *p = 0;
3338
3339 free(*out);
3340 *out = ret;
3341
3342 return ret;
3343}
3344
Willy Tarreaudad36a32013-03-11 01:20:04 +01003345/* Convert occurrences of environment variables in the input string to their
3346 * corresponding value. A variable is identified as a series of alphanumeric
3347 * characters or underscores following a '$' sign. The <in> string must be
3348 * free()able. NULL returns NULL. The resulting string might be reallocated if
3349 * some expansion is made. Variable names may also be enclosed into braces if
3350 * needed (eg: to concatenate alphanum characters).
3351 */
3352char *env_expand(char *in)
3353{
3354 char *txt_beg;
3355 char *out;
3356 char *txt_end;
3357 char *var_beg;
3358 char *var_end;
3359 char *value;
3360 char *next;
3361 int out_len;
3362 int val_len;
3363
3364 if (!in)
3365 return in;
3366
3367 value = out = NULL;
3368 out_len = 0;
3369
3370 txt_beg = in;
3371 do {
3372 /* look for next '$' sign in <in> */
3373 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3374
3375 if (!*txt_end && !out) /* end and no expansion performed */
3376 return in;
3377
3378 val_len = 0;
3379 next = txt_end;
3380 if (*txt_end == '$') {
3381 char save;
3382
3383 var_beg = txt_end + 1;
3384 if (*var_beg == '{')
3385 var_beg++;
3386
3387 var_end = var_beg;
3388 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3389 var_end++;
3390 }
3391
3392 next = var_end;
3393 if (*var_end == '}' && (var_beg > txt_end + 1))
3394 next++;
3395
3396 /* get value of the variable name at this location */
3397 save = *var_end;
3398 *var_end = '\0';
3399 value = getenv(var_beg);
3400 *var_end = save;
3401 val_len = value ? strlen(value) : 0;
3402 }
3403
Hubert Verstraete831962e2016-06-28 22:44:26 +02003404 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01003405 if (txt_end > txt_beg) {
3406 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3407 out_len += txt_end - txt_beg;
3408 }
3409 if (val_len) {
3410 memcpy(out + out_len, value, val_len);
3411 out_len += val_len;
3412 }
3413 out[out_len] = 0;
3414 txt_beg = next;
3415 } while (*txt_beg);
3416
3417 /* here we know that <out> was allocated and that we don't need <in> anymore */
3418 free(in);
3419 return out;
3420}
3421
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003422
3423/* same as strstr() but case-insensitive and with limit length */
3424const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3425{
3426 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003427 unsigned int slen, plen;
3428 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003429
3430 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3431 return NULL;
3432
3433 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3434 return str1;
3435
3436 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3437 return NULL;
3438
3439 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3440 while (toupper(*start) != toupper(*str2)) {
3441 start++;
3442 slen--;
3443 tmp1++;
3444
3445 if (tmp1 >= len_str1)
3446 return NULL;
3447
3448 /* if pattern longer than string */
3449 if (slen < plen)
3450 return NULL;
3451 }
3452
3453 sptr = start;
3454 pptr = (char *)str2;
3455
3456 tmp2 = 0;
3457 while (toupper(*sptr) == toupper(*pptr)) {
3458 sptr++;
3459 pptr++;
3460 tmp2++;
3461
3462 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3463 return start;
3464 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3465 return NULL;
3466 }
3467 }
3468 return NULL;
3469}
3470
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003471/* This function read the next valid utf8 char.
3472 * <s> is the byte srray to be decode, <len> is its length.
3473 * The function returns decoded char encoded like this:
3474 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3475 * are the length read. The decoded character is stored in <c>.
3476 */
3477unsigned char utf8_next(const char *s, int len, unsigned int *c)
3478{
3479 const unsigned char *p = (unsigned char *)s;
3480 int dec;
3481 unsigned char code = UTF8_CODE_OK;
3482
3483 if (len < 1)
3484 return UTF8_CODE_OK;
3485
3486 /* Check the type of UTF8 sequence
3487 *
3488 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3489 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3490 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3491 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3492 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3493 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3494 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3495 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3496 */
3497 switch (*p) {
3498 case 0x00 ... 0x7f:
3499 *c = *p;
3500 return UTF8_CODE_OK | 1;
3501
3502 case 0x80 ... 0xbf:
3503 *c = *p;
3504 return UTF8_CODE_BADSEQ | 1;
3505
3506 case 0xc0 ... 0xdf:
3507 if (len < 2) {
3508 *c = *p;
3509 return UTF8_CODE_BADSEQ | 1;
3510 }
3511 *c = *p & 0x1f;
3512 dec = 1;
3513 break;
3514
3515 case 0xe0 ... 0xef:
3516 if (len < 3) {
3517 *c = *p;
3518 return UTF8_CODE_BADSEQ | 1;
3519 }
3520 *c = *p & 0x0f;
3521 dec = 2;
3522 break;
3523
3524 case 0xf0 ... 0xf7:
3525 if (len < 4) {
3526 *c = *p;
3527 return UTF8_CODE_BADSEQ | 1;
3528 }
3529 *c = *p & 0x07;
3530 dec = 3;
3531 break;
3532
3533 case 0xf8 ... 0xfb:
3534 if (len < 5) {
3535 *c = *p;
3536 return UTF8_CODE_BADSEQ | 1;
3537 }
3538 *c = *p & 0x03;
3539 dec = 4;
3540 break;
3541
3542 case 0xfc ... 0xfd:
3543 if (len < 6) {
3544 *c = *p;
3545 return UTF8_CODE_BADSEQ | 1;
3546 }
3547 *c = *p & 0x01;
3548 dec = 5;
3549 break;
3550
3551 case 0xfe ... 0xff:
3552 default:
3553 *c = *p;
3554 return UTF8_CODE_BADSEQ | 1;
3555 }
3556
3557 p++;
3558
3559 while (dec > 0) {
3560
3561 /* need 0x10 for the 2 first bits */
3562 if ( ( *p & 0xc0 ) != 0x80 )
3563 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3564
3565 /* add data at char */
3566 *c = ( *c << 6 ) | ( *p & 0x3f );
3567
3568 dec--;
3569 p++;
3570 }
3571
3572 /* Check ovelong encoding.
3573 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3574 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3575 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3576 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003577 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003578 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3579 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3580 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3581 code |= UTF8_CODE_OVERLONG;
3582
3583 /* Check invalid UTF8 range. */
3584 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3585 (*c >= 0xfffe && *c <= 0xffff))
3586 code |= UTF8_CODE_INVRANGE;
3587
3588 return code | ((p-(unsigned char *)s)&0x0f);
3589}
3590
Maxime de Roucydc887852016-05-13 23:52:54 +02003591/* append a copy of string <str> (in a wordlist) at the end of the list <li>
3592 * On failure : return 0 and <err> filled with an error message.
3593 * The caller is responsible for freeing the <err> and <str> copy
3594 * memory area using free()
3595 */
3596int list_append_word(struct list *li, const char *str, char **err)
3597{
3598 struct wordlist *wl;
3599
3600 wl = calloc(1, sizeof(*wl));
3601 if (!wl) {
3602 memprintf(err, "out of memory");
3603 goto fail_wl;
3604 }
3605
3606 wl->s = strdup(str);
3607 if (!wl->s) {
3608 memprintf(err, "out of memory");
3609 goto fail_wl_s;
3610 }
3611
3612 LIST_ADDQ(li, &wl->list);
3613
3614 return 1;
3615
3616fail_wl_s:
3617 free(wl->s);
3618fail_wl:
3619 free(wl);
3620 return 0;
3621}
3622
Willy Tarreaubaaee002006-06-26 02:48:02 +02003623/*
3624 * Local variables:
3625 * c-indent-level: 8
3626 * c-basic-offset: 8
3627 * End:
3628 */