blob: 58cc5deb4329ebed035527bc42d3f709e3c48b59 [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 Tarreaubaaee002006-06-26 02:48:02 +020014#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020015#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020016#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020017#include <stdlib.h>
18#include <string.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010019#include <sys/socket.h>
20#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netinet/in.h>
22#include <arpa/inet.h>
23
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010024#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020025#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020026#include <common/standard.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010027#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020028#include <proto/dns.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010029#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020030
Willy Tarreau56adcf22012-12-23 18:00:29 +010031/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020032 * 2^64-1 = 18446744073709551615 or
33 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020034 *
35 * The HTML version needs room for adding the 25 characters
36 * '<span class="rls"></span>' around digits at positions 3N+1 in order
37 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020038 */
Willy Tarreau56adcf22012-12-23 18:00:29 +010039char itoa_str[NB_ITOA_STR][171];
40int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020041
Willy Tarreau588297f2014-06-16 15:16:40 +020042/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
43 * to quote strings larger than a max configuration line.
44 */
45char quoted_str[NB_QSTR][QSTR_SIZE + 1];
46int quoted_idx = 0;
47
Willy Tarreaubaaee002006-06-26 02:48:02 +020048/*
William Lallemande7340ec2012-01-24 11:15:39 +010049 * unsigned long long ASCII representation
50 *
51 * return the last char '\0' or NULL if no enough
52 * space in dst
53 */
54char *ulltoa(unsigned long long n, char *dst, size_t size)
55{
56 int i = 0;
57 char *res;
58
59 switch(n) {
60 case 1ULL ... 9ULL:
61 i = 0;
62 break;
63
64 case 10ULL ... 99ULL:
65 i = 1;
66 break;
67
68 case 100ULL ... 999ULL:
69 i = 2;
70 break;
71
72 case 1000ULL ... 9999ULL:
73 i = 3;
74 break;
75
76 case 10000ULL ... 99999ULL:
77 i = 4;
78 break;
79
80 case 100000ULL ... 999999ULL:
81 i = 5;
82 break;
83
84 case 1000000ULL ... 9999999ULL:
85 i = 6;
86 break;
87
88 case 10000000ULL ... 99999999ULL:
89 i = 7;
90 break;
91
92 case 100000000ULL ... 999999999ULL:
93 i = 8;
94 break;
95
96 case 1000000000ULL ... 9999999999ULL:
97 i = 9;
98 break;
99
100 case 10000000000ULL ... 99999999999ULL:
101 i = 10;
102 break;
103
104 case 100000000000ULL ... 999999999999ULL:
105 i = 11;
106 break;
107
108 case 1000000000000ULL ... 9999999999999ULL:
109 i = 12;
110 break;
111
112 case 10000000000000ULL ... 99999999999999ULL:
113 i = 13;
114 break;
115
116 case 100000000000000ULL ... 999999999999999ULL:
117 i = 14;
118 break;
119
120 case 1000000000000000ULL ... 9999999999999999ULL:
121 i = 15;
122 break;
123
124 case 10000000000000000ULL ... 99999999999999999ULL:
125 i = 16;
126 break;
127
128 case 100000000000000000ULL ... 999999999999999999ULL:
129 i = 17;
130 break;
131
132 case 1000000000000000000ULL ... 9999999999999999999ULL:
133 i = 18;
134 break;
135
136 case 10000000000000000000ULL ... ULLONG_MAX:
137 i = 19;
138 break;
139 }
140 if (i + 2 > size) // (i + 1) + '\0'
141 return NULL; // too long
142 res = dst + i + 1;
143 *res = '\0';
144 for (; i >= 0; i--) {
145 dst[i] = n % 10ULL + '0';
146 n /= 10ULL;
147 }
148 return res;
149}
150
151/*
152 * unsigned long ASCII representation
153 *
154 * return the last char '\0' or NULL if no enough
155 * space in dst
156 */
157char *ultoa_o(unsigned long n, char *dst, size_t size)
158{
159 int i = 0;
160 char *res;
161
162 switch (n) {
163 case 0U ... 9UL:
164 i = 0;
165 break;
166
167 case 10U ... 99UL:
168 i = 1;
169 break;
170
171 case 100U ... 999UL:
172 i = 2;
173 break;
174
175 case 1000U ... 9999UL:
176 i = 3;
177 break;
178
179 case 10000U ... 99999UL:
180 i = 4;
181 break;
182
183 case 100000U ... 999999UL:
184 i = 5;
185 break;
186
187 case 1000000U ... 9999999UL:
188 i = 6;
189 break;
190
191 case 10000000U ... 99999999UL:
192 i = 7;
193 break;
194
195 case 100000000U ... 999999999UL:
196 i = 8;
197 break;
198#if __WORDSIZE == 32
199
200 case 1000000000ULL ... ULONG_MAX:
201 i = 9;
202 break;
203
204#elif __WORDSIZE == 64
205
206 case 1000000000ULL ... 9999999999UL:
207 i = 9;
208 break;
209
210 case 10000000000ULL ... 99999999999UL:
211 i = 10;
212 break;
213
214 case 100000000000ULL ... 999999999999UL:
215 i = 11;
216 break;
217
218 case 1000000000000ULL ... 9999999999999UL:
219 i = 12;
220 break;
221
222 case 10000000000000ULL ... 99999999999999UL:
223 i = 13;
224 break;
225
226 case 100000000000000ULL ... 999999999999999UL:
227 i = 14;
228 break;
229
230 case 1000000000000000ULL ... 9999999999999999UL:
231 i = 15;
232 break;
233
234 case 10000000000000000ULL ... 99999999999999999UL:
235 i = 16;
236 break;
237
238 case 100000000000000000ULL ... 999999999999999999UL:
239 i = 17;
240 break;
241
242 case 1000000000000000000ULL ... 9999999999999999999UL:
243 i = 18;
244 break;
245
246 case 10000000000000000000ULL ... ULONG_MAX:
247 i = 19;
248 break;
249
250#endif
251 }
252 if (i + 2 > size) // (i + 1) + '\0'
253 return NULL; // too long
254 res = dst + i + 1;
255 *res = '\0';
256 for (; i >= 0; i--) {
257 dst[i] = n % 10U + '0';
258 n /= 10U;
259 }
260 return res;
261}
262
263/*
264 * signed long ASCII representation
265 *
266 * return the last char '\0' or NULL if no enough
267 * space in dst
268 */
269char *ltoa_o(long int n, char *dst, size_t size)
270{
271 char *pos = dst;
272
273 if (n < 0) {
274 if (size < 3)
275 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
276 *pos = '-';
277 pos++;
278 dst = ultoa_o(-n, pos, size - 1);
279 } else {
280 dst = ultoa_o(n, dst, size);
281 }
282 return dst;
283}
284
285/*
286 * signed long long ASCII representation
287 *
288 * return the last char '\0' or NULL if no enough
289 * space in dst
290 */
291char *lltoa(long long n, char *dst, size_t size)
292{
293 char *pos = dst;
294
295 if (n < 0) {
296 if (size < 3)
297 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
298 *pos = '-';
299 pos++;
300 dst = ulltoa(-n, pos, size - 1);
301 } else {
302 dst = ulltoa(n, dst, size);
303 }
304 return dst;
305}
306
307/*
308 * write a ascii representation of a unsigned into dst,
309 * return a pointer to the last character
310 * Pad the ascii representation with '0', using size.
311 */
312char *utoa_pad(unsigned int n, char *dst, size_t size)
313{
314 int i = 0;
315 char *ret;
316
317 switch(n) {
318 case 0U ... 9U:
319 i = 0;
320 break;
321
322 case 10U ... 99U:
323 i = 1;
324 break;
325
326 case 100U ... 999U:
327 i = 2;
328 break;
329
330 case 1000U ... 9999U:
331 i = 3;
332 break;
333
334 case 10000U ... 99999U:
335 i = 4;
336 break;
337
338 case 100000U ... 999999U:
339 i = 5;
340 break;
341
342 case 1000000U ... 9999999U:
343 i = 6;
344 break;
345
346 case 10000000U ... 99999999U:
347 i = 7;
348 break;
349
350 case 100000000U ... 999999999U:
351 i = 8;
352 break;
353
354 case 1000000000U ... 4294967295U:
355 i = 9;
356 break;
357 }
358 if (i + 2 > size) // (i + 1) + '\0'
359 return NULL; // too long
360 if (i < size)
361 i = size - 2; // padding - '\0'
362
363 ret = dst + i + 1;
364 *ret = '\0';
365 for (; i >= 0; i--) {
366 dst[i] = n % 10U + '0';
367 n /= 10U;
368 }
369 return ret;
370}
371
372/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200373 * copies at most <size-1> chars from <src> to <dst>. Last char is always
374 * set to 0, unless <size> is 0. The number of chars copied is returned
375 * (excluding the terminating zero).
376 * This code has been optimized for size and speed : on x86, it's 45 bytes
377 * long, uses only registers, and consumes only 4 cycles per char.
378 */
379int strlcpy2(char *dst, const char *src, int size)
380{
381 char *orig = dst;
382 if (size) {
383 while (--size && (*dst = *src)) {
384 src++; dst++;
385 }
386 *dst = 0;
387 }
388 return dst - orig;
389}
390
391/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200392 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200393 * the ascii representation for number 'n' in decimal.
394 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100395char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200396{
397 char *pos;
398
Willy Tarreau72d759c2007-10-25 12:14:10 +0200399 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200400 *pos-- = '\0';
401
402 do {
403 *pos-- = '0' + n % 10;
404 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200405 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200406 return pos + 1;
407}
408
Willy Tarreau91092e52007-10-25 16:58:42 +0200409/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200410 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200411 * the ascii representation for number 'n' in decimal.
412 */
413char *lltoa_r(long long int in, char *buffer, int size)
414{
415 char *pos;
416 int neg = 0;
417 unsigned long long int n;
418
419 pos = buffer + size - 1;
420 *pos-- = '\0';
421
422 if (in < 0) {
423 neg = 1;
424 n = -in;
425 }
426 else
427 n = in;
428
429 do {
430 *pos-- = '0' + n % 10;
431 n /= 10;
432 } while (n && pos >= buffer);
433 if (neg && pos > buffer)
434 *pos-- = '-';
435 return pos + 1;
436}
437
438/*
439 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200440 * the ascii representation for signed number 'n' in decimal.
441 */
442char *sltoa_r(long n, char *buffer, int size)
443{
444 char *pos;
445
446 if (n >= 0)
447 return ultoa_r(n, buffer, size);
448
449 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
450 *pos = '-';
451 return pos;
452}
453
454/*
455 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200456 * the ascii representation for number 'n' in decimal, formatted for
457 * HTML output with tags to create visual grouping by 3 digits. The
458 * output needs to support at least 171 characters.
459 */
460const char *ulltoh_r(unsigned long long n, char *buffer, int size)
461{
462 char *start;
463 int digit = 0;
464
465 start = buffer + size;
466 *--start = '\0';
467
468 do {
469 if (digit == 3 && start >= buffer + 7)
470 memcpy(start -= 7, "</span>", 7);
471
472 if (start >= buffer + 1) {
473 *--start = '0' + n % 10;
474 n /= 10;
475 }
476
477 if (digit == 3 && start >= buffer + 18)
478 memcpy(start -= 18, "<span class=\"rls\">", 18);
479
480 if (digit++ == 3)
481 digit = 1;
482 } while (n && start > buffer);
483 return start;
484}
485
486/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200487 * This function simply returns a locally allocated string containing the ascii
488 * representation for number 'n' in decimal, unless n is 0 in which case it
489 * returns the alternate string (or an empty string if the alternate string is
490 * NULL). It use is intended for limits reported in reports, where it's
491 * desirable not to display anything if there is no limit. Warning! it shares
492 * the same vector as ultoa_r().
493 */
494const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
495{
496 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
497}
498
Willy Tarreau588297f2014-06-16 15:16:40 +0200499/* returns a locally allocated string containing the quoted encoding of the
500 * input string. The output may be truncated to QSTR_SIZE chars, but it is
501 * guaranteed that the string will always be properly terminated. Quotes are
502 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
503 * always be at least 4 chars.
504 */
505const char *qstr(const char *str)
506{
507 char *ret = quoted_str[quoted_idx];
508 char *p, *end;
509
510 if (++quoted_idx >= NB_QSTR)
511 quoted_idx = 0;
512
513 p = ret;
514 end = ret + QSTR_SIZE;
515
516 *p++ = '"';
517
518 /* always keep 3 chars to support passing "" and the ending " */
519 while (*str && p < end - 3) {
520 if (*str == '"') {
521 *p++ = '"';
522 *p++ = '"';
523 }
524 else
525 *p++ = *str;
526 str++;
527 }
528 *p++ = '"';
529 return ret;
530}
531
Robert Tsai81ae1952007-12-05 10:47:29 +0100532/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200533 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
534 *
535 * It looks like this one would be a good candidate for inlining, but this is
536 * not interesting because it around 35 bytes long and often called multiple
537 * times within the same function.
538 */
539int ishex(char s)
540{
541 s -= '0';
542 if ((unsigned char)s <= 9)
543 return 1;
544 s -= 'A' - '0';
545 if ((unsigned char)s <= 5)
546 return 1;
547 s -= 'a' - 'A';
548 if ((unsigned char)s <= 5)
549 return 1;
550 return 0;
551}
552
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100553/* rounds <i> down to the closest value having max 2 digits */
554unsigned int round_2dig(unsigned int i)
555{
556 unsigned int mul = 1;
557
558 while (i >= 100) {
559 i /= 10;
560 mul *= 10;
561 }
562 return i * mul;
563}
564
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100565/*
566 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
567 * invalid character is found, a pointer to it is returned. If everything is
568 * fine, NULL is returned.
569 */
570const char *invalid_char(const char *name)
571{
572 if (!*name)
573 return name;
574
575 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100576 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100577 *name != '_' && *name != '-')
578 return name;
579 name++;
580 }
581 return NULL;
582}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200583
584/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200585 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
586 * If an invalid character is found, a pointer to it is returned.
587 * If everything is fine, NULL is returned.
588 */
589const char *invalid_domainchar(const char *name) {
590
591 if (!*name)
592 return name;
593
594 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100595 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200596 *name != '_' && *name != '-')
597 return name;
598
599 name++;
600 }
601
602 return NULL;
603}
604
605/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100606 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100607 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
608 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
609 * the function tries to guess the address family from the syntax. If the
610 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100611 * string is assumed to contain only an address, no port. The address can be a
612 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
613 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
614 * The return address will only have the address family and the address set,
615 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100616 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
617 * is resolved, otherwise only IP addresses are resolved, and anything else
618 * returns NULL.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200619 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100620struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200621{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100622 struct hostent *he;
623
Willy Tarreaufab5a432011-03-04 15:31:53 +0100624 /* Any IPv6 address */
625 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100626 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
627 sa->ss_family = AF_INET6;
628 else if (sa->ss_family != AF_INET6)
629 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100630 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100631 }
632
Willy Tarreau24709282013-03-10 21:32:12 +0100633 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100634 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100635 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
636 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100637 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100638 }
639
640 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100641 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
642 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100643 sa->ss_family = AF_INET6;
644 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100645 }
646
647 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100648 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
649 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100650 sa->ss_family = AF_INET;
651 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100652 }
653
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100654 if (!resolve)
655 return NULL;
656
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200657 if (!dns_hostname_validation(str, NULL))
658 return NULL;
659
David du Colombierd5f43282011-03-17 10:40:16 +0100660#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200661 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100662 struct addrinfo hints, *result;
663
664 memset(&result, 0, sizeof(result));
665 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100666 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100667 hints.ai_socktype = SOCK_DGRAM;
668 hints.ai_flags = AI_PASSIVE;
669 hints.ai_protocol = 0;
670
671 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100672 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
673 sa->ss_family = result->ai_family;
674 else if (sa->ss_family != result->ai_family)
675 goto fail;
676
David du Colombierd5f43282011-03-17 10:40:16 +0100677 switch (result->ai_family) {
678 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100679 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
680 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100681 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100682 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
683 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100684 }
685 }
686
Sean Carey58ea0392013-02-15 23:39:18 +0100687 if (result)
688 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100689 }
David du Colombierd5f43282011-03-17 10:40:16 +0100690#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200691 /* try to resolve an IPv4/IPv6 hostname */
692 he = gethostbyname(str);
693 if (he) {
694 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
695 sa->ss_family = he->h_addrtype;
696 else if (sa->ss_family != he->h_addrtype)
697 goto fail;
698
699 switch (sa->ss_family) {
700 case AF_INET:
701 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
702 return sa;
703 case AF_INET6:
704 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
705 return sa;
706 }
707 }
708
David du Colombierd5f43282011-03-17 10:40:16 +0100709 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100710 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100711 return NULL;
712}
713
714/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100715 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
716 * range or offset consisting in two integers that the caller will have to
717 * check to find the relevant input format. The following format are supported :
718 *
719 * String format | address | port | low | high
720 * addr | <addr> | 0 | 0 | 0
721 * addr: | <addr> | 0 | 0 | 0
722 * addr:port | <addr> | <port> | <port> | <port>
723 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
724 * addr:+port | <addr> | <port> | 0 | <port>
725 * addr:-port | <addr> |-<port> | <port> | 0
726 *
727 * The detection of a port range or increment by the caller is made by
728 * comparing <low> and <high>. If both are equal, then port 0 means no port
729 * was specified. The caller may pass NULL for <low> and <high> if it is not
730 * interested in retrieving port ranges.
731 *
732 * Note that <addr> above may also be :
733 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
734 * - "*" => family will be AF_INET and address will be INADDR_ANY
735 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
736 * - a host name => family and address will depend on host name resolving.
737 *
Willy Tarreau24709282013-03-10 21:32:12 +0100738 * A prefix may be passed in before the address above to force the family :
739 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
740 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
741 * - "unix@" => force address to be a path to a UNIX socket even if the
742 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200743 * - 'abns@' -> force address to belong to the abstract namespace (Linux
744 * only). These sockets are just like Unix sockets but without
745 * the need for an underlying file system. The address is a
746 * string. Technically it's like a Unix socket with a zero in
747 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100748 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100749 *
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100750 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
751 * is mandatory after the IP address even when no port is specified. NULL is
752 * returned if the address cannot be parsed. The <low> and <high> ports are
Willy Tarreau24709282013-03-10 21:32:12 +0100753 * always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100754 *
755 * If <pfx> is non-null, it is used as a string prefix before any path-based
756 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100757 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200758 * if <fqdn> is non-null, it will be filled with :
759 * - a pointer to the FQDN of the server name to resolve if there's one, and
760 * that the caller will have to free(),
761 * - NULL if there was an explicit address that doesn't require resolution.
762 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100763 * When a file descriptor is passed, its value is put into the s_addr part of
764 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100765 */
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200766struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx, char **fqdn)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100767{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100768 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100769 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100770 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100771 char *port1, *port2;
772 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200773 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100774
775 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200776 if (fqdn)
777 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200778
Willy Tarreaudad36a32013-03-11 01:20:04 +0100779 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100780 if (str2 == NULL) {
781 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100782 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100783 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200784
Willy Tarreau24709282013-03-10 21:32:12 +0100785 memset(&ss, 0, sizeof(ss));
786
787 if (strncmp(str2, "unix@", 5) == 0) {
788 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200789 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100790 ss.ss_family = AF_UNIX;
791 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200792 else if (strncmp(str2, "abns@", 5) == 0) {
793 str2 += 5;
794 abstract = 1;
795 ss.ss_family = AF_UNIX;
796 }
Willy Tarreau24709282013-03-10 21:32:12 +0100797 else if (strncmp(str2, "ipv4@", 5) == 0) {
798 str2 += 5;
799 ss.ss_family = AF_INET;
800 }
801 else if (strncmp(str2, "ipv6@", 5) == 0) {
802 str2 += 5;
803 ss.ss_family = AF_INET6;
804 }
805 else if (*str2 == '/') {
806 ss.ss_family = AF_UNIX;
807 }
808 else
809 ss.ss_family = AF_UNSPEC;
810
Willy Tarreau40aa0702013-03-10 23:51:38 +0100811 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
812 char *endptr;
813
814 str2 += 3;
815 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
816
817 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100818 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100819 goto out;
820 }
821
822 /* we return AF_UNSPEC if we use a file descriptor number */
823 ss.ss_family = AF_UNSPEC;
824 }
825 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100826 int prefix_path_len;
827 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200828 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100829
830 /* complete unix socket path name during startup or soft-restart is
831 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
832 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200833 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100834 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
835 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
836
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200837 adr_len = strlen(str2);
838 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100839 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
840 goto out;
841 }
842
Willy Tarreauccfccef2014-05-10 01:49:15 +0200843 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
844 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200845 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100846 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200847 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100848 }
Willy Tarreau24709282013-03-10 21:32:12 +0100849 else { /* IPv4 and IPv6 */
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200850 int use_fqdn = 0;
851
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100852 port1 = strrchr(str2, ':');
853 if (port1)
854 *port1++ = '\0';
855 else
856 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200857
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200858 if (str2ip2(str2, &ss, 0) == NULL) {
859 use_fqdn = 1;
860 if (str2ip(str2, &ss) == NULL) {
861 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
862 goto out;
863 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100864 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100865
Willy Tarreaua39d1992013-04-01 20:37:42 +0200866 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100867 port2 = strchr(port1, '-');
868 if (port2)
869 *port2++ = '\0';
870 else
871 port2 = port1;
872 portl = atoi(port1);
873 porth = atoi(port2);
874 porta = portl;
875 }
876 else if (*port1 == '-') { /* negative offset */
877 portl = atoi(port1 + 1);
878 porta = -portl;
879 }
880 else if (*port1 == '+') { /* positive offset */
881 porth = atoi(port1 + 1);
882 porta = porth;
883 }
884 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100885 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100886 goto out;
887 }
888 set_host_port(&ss, porta);
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200889
890 if (use_fqdn && fqdn) {
891 if (str2 != back)
892 memmove(back, str2, strlen(str2) + 1);
893 *fqdn = back;
894 back = NULL;
895 }
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100896 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100897
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100898 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100899 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100900 if (low)
901 *low = portl;
902 if (high)
903 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100904 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100905 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200906}
907
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100908/* converts <str> to a struct in_addr containing a network mask. It can be
909 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
910 * if the conversion succeeds otherwise non-zero.
911 */
912int str2mask(const char *str, struct in_addr *mask)
913{
914 if (strchr(str, '.') != NULL) { /* dotted notation */
915 if (!inet_pton(AF_INET, str, mask))
916 return 0;
917 }
918 else { /* mask length */
919 char *err;
920 unsigned long len = strtol(str, &err, 10);
921
922 if (!*str || (err && *err) || (unsigned)len > 32)
923 return 0;
924 if (len)
925 mask->s_addr = htonl(~0UL << (32 - len));
926 else
927 mask->s_addr = 0;
928 }
929 return 1;
930}
931
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100932/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
933 * succeeds otherwise zero.
934 */
935int cidr2dotted(int cidr, struct in_addr *mask) {
936
937 if (cidr < 0 || cidr > 32)
938 return 0;
939
940 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
941 return 1;
942}
943
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200944/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200945 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200946 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
947 * is optionnal and either in the dotted or CIDR notation.
948 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
949 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100950int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200951{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200952 __label__ out_free, out_err;
953 char *c, *s;
954 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200955
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200956 s = strdup(str);
957 if (!s)
958 return 0;
959
Willy Tarreaubaaee002006-06-26 02:48:02 +0200960 memset(mask, 0, sizeof(*mask));
961 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200962
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200963 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200964 *c++ = '\0';
965 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100966 if (!str2mask(c, mask))
967 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200968 }
969 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100970 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200971 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200972 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200973 struct hostent *he;
974
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100975 if (!resolve)
976 goto out_err;
977
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200978 if ((he = gethostbyname(s)) == NULL) {
979 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200980 }
981 else
982 *addr = *(struct in_addr *) *(he->h_addr_list);
983 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200984
985 ret_val = 1;
986 out_free:
987 free(s);
988 return ret_val;
989 out_err:
990 ret_val = 0;
991 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200992}
993
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100994
995/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200996 * converts <str> to two struct in6_addr* which must be pre-allocated.
997 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
998 * is an optionnal number of bits (128 being the default).
999 * Returns 1 if OK, 0 if error.
1000 */
1001int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1002{
1003 char *c, *s;
1004 int ret_val = 0;
1005 char *err;
1006 unsigned long len = 128;
1007
1008 s = strdup(str);
1009 if (!s)
1010 return 0;
1011
1012 memset(mask, 0, sizeof(*mask));
1013 memset(addr, 0, sizeof(*addr));
1014
1015 if ((c = strrchr(s, '/')) != NULL) {
1016 *c++ = '\0'; /* c points to the mask */
1017 if (!*c)
1018 goto out_free;
1019
1020 len = strtoul(c, &err, 10);
1021 if ((err && *err) || (unsigned)len > 128)
1022 goto out_free;
1023 }
1024 *mask = len; /* OK we have a valid mask in <len> */
1025
1026 if (!inet_pton(AF_INET6, s, addr))
1027 goto out_free;
1028
1029 ret_val = 1;
1030 out_free:
1031 free(s);
1032 return ret_val;
1033}
1034
1035
1036/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001037 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001038 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001039int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001040{
1041 int saw_digit, octets, ch;
1042 u_char tmp[4], *tp;
1043 const char *cp = addr;
1044
1045 saw_digit = 0;
1046 octets = 0;
1047 *(tp = tmp) = 0;
1048
1049 while (*addr) {
1050 unsigned char digit = (ch = *addr++) - '0';
1051 if (digit > 9 && ch != '.')
1052 break;
1053 if (digit <= 9) {
1054 u_int new = *tp * 10 + digit;
1055 if (new > 255)
1056 return 0;
1057 *tp = new;
1058 if (!saw_digit) {
1059 if (++octets > 4)
1060 return 0;
1061 saw_digit = 1;
1062 }
1063 } else if (ch == '.' && saw_digit) {
1064 if (octets == 4)
1065 return 0;
1066 *++tp = 0;
1067 saw_digit = 0;
1068 } else
1069 return 0;
1070 }
1071
1072 if (octets < 4)
1073 return 0;
1074
1075 memcpy(&dst->s_addr, tmp, 4);
1076 return addr-cp-1;
1077}
1078
1079/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001080 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1081 * <out> contain the code of the dectected scheme, the start and length of
1082 * the hostname. Actually only http and https are supported. <out> can be NULL.
1083 * This function returns the consumed length. It is useful if you parse complete
1084 * url like http://host:port/path, because the consumed length corresponds to
1085 * the first character of the path. If the conversion fails, it returns -1.
1086 *
1087 * This function tries to resolve the DNS name if haproxy is in starting mode.
1088 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001089 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001090int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001091{
1092 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001093 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001094 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001095 unsigned long long int http_code = 0;
1096 int default_port;
1097 struct hostent *he;
1098 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001099
1100 /* Firstly, try to find :// pattern */
1101 while (curr < url+ulen && url_code != 0x3a2f2f) {
1102 url_code = ((url_code & 0xffff) << 8);
1103 url_code += (unsigned char)*curr++;
1104 }
1105
1106 /* Secondly, if :// pattern is found, verify parsed stuff
1107 * before pattern is matching our http pattern.
1108 * If so parse ip address and port in uri.
1109 *
1110 * WARNING: Current code doesn't support dynamic async dns resolver.
1111 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001112 if (url_code != 0x3a2f2f)
1113 return -1;
1114
1115 /* Copy scheme, and utrn to lower case. */
1116 while (cp < curr - 3)
1117 http_code = (http_code << 8) + *cp++;
1118 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001119
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001120 /* HTTP or HTTPS url matching */
1121 if (http_code == 0x2020202068747470ULL) {
1122 default_port = 80;
1123 if (out)
1124 out->scheme = SCH_HTTP;
1125 }
1126 else if (http_code == 0x2020206874747073ULL) {
1127 default_port = 443;
1128 if (out)
1129 out->scheme = SCH_HTTPS;
1130 }
1131 else
1132 return -1;
1133
1134 /* If the next char is '[', the host address is IPv6. */
1135 if (*curr == '[') {
1136 curr++;
1137
1138 /* Check trash size */
1139 if (trash.size < ulen)
1140 return -1;
1141
1142 /* Look for ']' and copy the address in a trash buffer. */
1143 p = trash.str;
1144 for (end = curr;
1145 end < url + ulen && *end != ']';
1146 end++, p++)
1147 *p = *end;
1148 if (*end != ']')
1149 return -1;
1150 *p = '\0';
1151
1152 /* Update out. */
1153 if (out) {
1154 out->host = curr;
1155 out->host_len = end - curr;
1156 }
1157
1158 /* Try IPv6 decoding. */
1159 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1160 return -1;
1161 end++;
1162
1163 /* Decode port. */
1164 if (*end == ':') {
1165 end++;
1166 default_port = read_uint(&end, url + ulen);
1167 }
1168 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1169 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1170 return end - url;
1171 }
1172 else {
1173 /* We are looking for IP address. If you want to parse and
1174 * resolve hostname found in url, you can use str2sa_range(), but
1175 * be warned this can slow down global daemon performances
1176 * while handling lagging dns responses.
1177 */
1178 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1179 if (ret) {
1180 /* Update out. */
1181 if (out) {
1182 out->host = curr;
1183 out->host_len = ret;
1184 }
1185
1186 curr += ret;
1187
1188 /* Decode port. */
1189 if (*curr == ':') {
1190 curr++;
1191 default_port = read_uint(&curr, url + ulen);
1192 }
1193 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1194
1195 /* Set family. */
1196 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1197 return curr - url;
1198 }
1199 else if (global.mode & MODE_STARTING) {
1200 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1201 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001202 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001203
1204 /* look for : or / or end */
1205 for (end = curr;
1206 end < url + ulen && *end != '/' && *end != ':';
1207 end++);
1208 memcpy(trash.str, curr, end - curr);
1209 trash.str[end - curr] = '\0';
1210
1211 /* try to resolve an IPv4/IPv6 hostname */
1212 he = gethostbyname(trash.str);
1213 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001214 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001215
1216 /* Update out. */
1217 if (out) {
1218 out->host = curr;
1219 out->host_len = end - curr;
1220 }
1221
1222 /* Decode port. */
1223 if (*end == ':') {
1224 end++;
1225 default_port = read_uint(&end, url + ulen);
1226 }
1227
1228 /* Copy IP address, set port and family. */
1229 switch (he->h_addrtype) {
1230 case AF_INET:
1231 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1232 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1233 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1234 return end - url;
1235
1236 case AF_INET6:
1237 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1238 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1239 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1240 return end - url;
1241 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001242 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001243 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001244 return -1;
1245}
1246
Willy Tarreau631f01c2011-09-05 00:36:48 +02001247/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1248 * address family is returned so that it's easy for the caller to adapt to the
1249 * output format. Zero is returned if the address family is not supported. -1
1250 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1251 * supported.
1252 */
1253int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1254{
1255
1256 void *ptr;
1257
1258 if (size < 5)
1259 return 0;
1260 *str = '\0';
1261
1262 switch (addr->ss_family) {
1263 case AF_INET:
1264 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1265 break;
1266 case AF_INET6:
1267 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1268 break;
1269 case AF_UNIX:
1270 memcpy(str, "unix", 5);
1271 return addr->ss_family;
1272 default:
1273 return 0;
1274 }
1275
1276 if (inet_ntop(addr->ss_family, ptr, str, size))
1277 return addr->ss_family;
1278
1279 /* failed */
1280 return -1;
1281}
1282
Simon Horman75ab8bd2014-06-16 09:39:41 +09001283/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1284 * address family is returned so that it's easy for the caller to adapt to the
1285 * output format. Zero is returned if the address family is not supported. -1
1286 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1287 * supported.
1288 */
1289int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1290{
1291
1292 uint16_t port;
1293
1294
1295 if (size < 5)
1296 return 0;
1297 *str = '\0';
1298
1299 switch (addr->ss_family) {
1300 case AF_INET:
1301 port = ((struct sockaddr_in *)addr)->sin_port;
1302 break;
1303 case AF_INET6:
1304 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1305 break;
1306 case AF_UNIX:
1307 memcpy(str, "unix", 5);
1308 return addr->ss_family;
1309 default:
1310 return 0;
1311 }
1312
1313 snprintf(str, size, "%u", ntohs(port));
1314 return addr->ss_family;
1315}
1316
Willy Tarreaubaaee002006-06-26 02:48:02 +02001317/* will try to encode the string <string> replacing all characters tagged in
1318 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1319 * prefixed by <escape>, and will store the result between <start> (included)
1320 * and <stop> (excluded), and will always terminate the string with a '\0'
1321 * before <stop>. The position of the '\0' is returned if the conversion
1322 * completes. If bytes are missing between <start> and <stop>, then the
1323 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1324 * cannot even be stored so we return <start> without writing the 0.
1325 * The input string must also be zero-terminated.
1326 */
1327const char hextab[16] = "0123456789ABCDEF";
1328char *encode_string(char *start, char *stop,
1329 const char escape, const fd_set *map,
1330 const char *string)
1331{
1332 if (start < stop) {
1333 stop--; /* reserve one byte for the final '\0' */
1334 while (start < stop && *string != '\0') {
1335 if (!FD_ISSET((unsigned char)(*string), map))
1336 *start++ = *string;
1337 else {
1338 if (start + 3 >= stop)
1339 break;
1340 *start++ = escape;
1341 *start++ = hextab[(*string >> 4) & 15];
1342 *start++ = hextab[*string & 15];
1343 }
1344 string++;
1345 }
1346 *start = '\0';
1347 }
1348 return start;
1349}
1350
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001351/*
1352 * Same behavior as encode_string() above, except that it encodes chunk
1353 * <chunk> instead of a string.
1354 */
1355char *encode_chunk(char *start, char *stop,
1356 const char escape, const fd_set *map,
1357 const struct chunk *chunk)
1358{
1359 char *str = chunk->str;
1360 char *end = chunk->str + chunk->len;
1361
1362 if (start < stop) {
1363 stop--; /* reserve one byte for the final '\0' */
1364 while (start < stop && str < end) {
1365 if (!FD_ISSET((unsigned char)(*str), map))
1366 *start++ = *str;
1367 else {
1368 if (start + 3 >= stop)
1369 break;
1370 *start++ = escape;
1371 *start++ = hextab[(*str >> 4) & 15];
1372 *start++ = hextab[*str & 15];
1373 }
1374 str++;
1375 }
1376 *start = '\0';
1377 }
1378 return start;
1379}
1380
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001381/* Check a string for using it in a CSV output format. If the string contains
1382 * one of the following four char <">, <,>, CR or LF, the string is
1383 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1384 * <str> is the input string to be escaped. The function assumes that
1385 * the input string is null-terminated.
1386 *
1387 * If <quote> is 0, the result is returned escaped but without double quote.
1388 * Is it useful if the escaped string is used between double quotes in the
1389 * format.
1390 *
1391 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0));
1392 *
1393 * If the <quote> is 1, the converter put the quotes only if any character is
1394 * escaped. If the <quote> is 2, the converter put always the quotes.
1395 *
1396 * <output> is a struct chunk used for storing the output string if any
1397 * change will be done.
1398 *
1399 * The function returns the converted string on this output. If an error
1400 * occurs, the function return an empty string. This type of output is useful
1401 * for using the function directly as printf() argument.
1402 *
1403 * If the output buffer is too short to contain the input string, the result
1404 * is truncated.
1405 */
1406const char *csv_enc(const char *str, int quote, struct chunk *output)
1407{
1408 char *end = output->str + output->size;
1409 char *out = output->str + 1; /* +1 for reserving space for a first <"> */
1410
1411 while (*str && out < end - 2) { /* -2 for reserving space for <"> and \0. */
1412 *out = *str;
1413 if (*str == '"') {
1414 if (quote == 1)
1415 quote = 2;
1416 out++;
1417 if (out >= end - 2) {
1418 out--;
1419 break;
1420 }
1421 *out = '"';
1422 }
1423 if (quote == 1 && ( *str == '\r' || *str == '\n' || *str == ',') )
1424 quote = 2;
1425 out++;
1426 str++;
1427 }
1428
1429 if (quote == 1)
1430 quote = 0;
1431
1432 if (!quote) {
1433 *out = '\0';
1434 return output->str + 1;
1435 }
1436
1437 /* else quote == 2 */
1438 *output->str = '"';
1439 *out = '"';
1440 out++;
1441 *out = '\0';
1442 return output->str;
1443}
1444
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001445/* Decode an URL-encoded string in-place. The resulting string might
1446 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001447 * aborted, the string is truncated before the issue and a negative value is
1448 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001449 */
1450int url_decode(char *string)
1451{
1452 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001453 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001454
1455 in = string;
1456 out = string;
1457 while (*in) {
1458 switch (*in) {
1459 case '+' :
1460 *out++ = ' ';
1461 break;
1462 case '%' :
1463 if (!ishex(in[1]) || !ishex(in[2]))
1464 goto end;
1465 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1466 in += 2;
1467 break;
1468 default:
1469 *out++ = *in;
1470 break;
1471 }
1472 in++;
1473 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001474 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001475 end:
1476 *out = 0;
1477 return ret;
1478}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001479
Willy Tarreau6911fa42007-03-04 18:06:08 +01001480unsigned int str2ui(const char *s)
1481{
1482 return __str2ui(s);
1483}
1484
1485unsigned int str2uic(const char *s)
1486{
1487 return __str2uic(s);
1488}
1489
1490unsigned int strl2ui(const char *s, int len)
1491{
1492 return __strl2ui(s, len);
1493}
1494
1495unsigned int strl2uic(const char *s, int len)
1496{
1497 return __strl2uic(s, len);
1498}
1499
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001500unsigned int read_uint(const char **s, const char *end)
1501{
1502 return __read_uint(s, end);
1503}
1504
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001505/* This function reads an unsigned integer from the string pointed to by <s> and
1506 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1507 * function automatically stops at <end>. If the number overflows, the 2^64-1
1508 * value is returned.
1509 */
1510unsigned long long int read_uint64(const char **s, const char *end)
1511{
1512 const char *ptr = *s;
1513 unsigned long long int i = 0, tmp;
1514 unsigned int j;
1515
1516 while (ptr < end) {
1517
1518 /* read next char */
1519 j = *ptr - '0';
1520 if (j > 9)
1521 goto read_uint64_end;
1522
1523 /* add char to the number and check overflow. */
1524 tmp = i * 10;
1525 if (tmp / 10 != i) {
1526 i = ULLONG_MAX;
1527 goto read_uint64_eat;
1528 }
1529 if (ULLONG_MAX - tmp < j) {
1530 i = ULLONG_MAX;
1531 goto read_uint64_eat;
1532 }
1533 i = tmp + j;
1534 ptr++;
1535 }
1536read_uint64_eat:
1537 /* eat each numeric char */
1538 while (ptr < end) {
1539 if ((unsigned int)(*ptr - '0') > 9)
1540 break;
1541 ptr++;
1542 }
1543read_uint64_end:
1544 *s = ptr;
1545 return i;
1546}
1547
1548/* This function reads an integer from the string pointed to by <s> and returns
1549 * it. The <s> pointer is adjusted to point to the first unread char. The function
1550 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1551 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1552 * returned.
1553 */
1554long long int read_int64(const char **s, const char *end)
1555{
1556 unsigned long long int i = 0;
1557 int neg = 0;
1558
1559 /* Look for minus char. */
1560 if (**s == '-') {
1561 neg = 1;
1562 (*s)++;
1563 }
1564 else if (**s == '+')
1565 (*s)++;
1566
1567 /* convert as positive number. */
1568 i = read_uint64(s, end);
1569
1570 if (neg) {
1571 if (i > 0x8000000000000000ULL)
1572 return LLONG_MIN;
1573 return -i;
1574 }
1575 if (i > 0x7fffffffffffffffULL)
1576 return LLONG_MAX;
1577 return i;
1578}
1579
Willy Tarreau6911fa42007-03-04 18:06:08 +01001580/* This one is 7 times faster than strtol() on athlon with checks.
1581 * It returns the value of the number composed of all valid digits read,
1582 * and can process negative numbers too.
1583 */
1584int strl2ic(const char *s, int len)
1585{
1586 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001587 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001588
1589 if (len > 0) {
1590 if (*s != '-') {
1591 /* positive number */
1592 while (len-- > 0) {
1593 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001594 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001595 if (j > 9)
1596 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001597 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001598 }
1599 } else {
1600 /* negative number */
1601 s++;
1602 while (--len > 0) {
1603 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001604 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001605 if (j > 9)
1606 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001607 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001608 }
1609 }
1610 }
1611 return i;
1612}
1613
1614
1615/* This function reads exactly <len> chars from <s> and converts them to a
1616 * signed integer which it stores into <ret>. It accurately detects any error
1617 * (truncated string, invalid chars, overflows). It is meant to be used in
1618 * applications designed for hostile environments. It returns zero when the
1619 * number has successfully been converted, non-zero otherwise. When an error
1620 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1621 * faster than strtol().
1622 */
1623int strl2irc(const char *s, int len, int *ret)
1624{
1625 int i = 0;
1626 int j;
1627
1628 if (!len)
1629 return 1;
1630
1631 if (*s != '-') {
1632 /* positive number */
1633 while (len-- > 0) {
1634 j = (*s++) - '0';
1635 if (j > 9) return 1; /* invalid char */
1636 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1637 i = i * 10;
1638 if (i + j < i) return 1; /* check for addition overflow */
1639 i = i + j;
1640 }
1641 } else {
1642 /* negative number */
1643 s++;
1644 while (--len > 0) {
1645 j = (*s++) - '0';
1646 if (j > 9) return 1; /* invalid char */
1647 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1648 i = i * 10;
1649 if (i - j > i) return 1; /* check for subtract overflow */
1650 i = i - j;
1651 }
1652 }
1653 *ret = i;
1654 return 0;
1655}
1656
1657
1658/* This function reads exactly <len> chars from <s> and converts them to a
1659 * signed integer which it stores into <ret>. It accurately detects any error
1660 * (truncated string, invalid chars, overflows). It is meant to be used in
1661 * applications designed for hostile environments. It returns zero when the
1662 * number has successfully been converted, non-zero otherwise. When an error
1663 * is returned, the <ret> value is left untouched. It is about 3 times slower
1664 * than str2irc().
1665 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001666
1667int strl2llrc(const char *s, int len, long long *ret)
1668{
1669 long long i = 0;
1670 int j;
1671
1672 if (!len)
1673 return 1;
1674
1675 if (*s != '-') {
1676 /* positive number */
1677 while (len-- > 0) {
1678 j = (*s++) - '0';
1679 if (j > 9) return 1; /* invalid char */
1680 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1681 i = i * 10LL;
1682 if (i + j < i) return 1; /* check for addition overflow */
1683 i = i + j;
1684 }
1685 } else {
1686 /* negative number */
1687 s++;
1688 while (--len > 0) {
1689 j = (*s++) - '0';
1690 if (j > 9) return 1; /* invalid char */
1691 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1692 i = i * 10LL;
1693 if (i - j > i) return 1; /* check for subtract overflow */
1694 i = i - j;
1695 }
1696 }
1697 *ret = i;
1698 return 0;
1699}
1700
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001701/* This function is used with pat_parse_dotted_ver(). It converts a string
1702 * composed by two number separated by a dot. Each part must contain in 16 bits
1703 * because internally they will be represented as a 32-bit quantity stored in
1704 * a 64-bit integer. It returns zero when the number has successfully been
1705 * converted, non-zero otherwise. When an error is returned, the <ret> value
1706 * is left untouched.
1707 *
1708 * "1.3" -> 0x0000000000010003
1709 * "65535.65535" -> 0x00000000ffffffff
1710 */
1711int strl2llrc_dotted(const char *text, int len, long long *ret)
1712{
1713 const char *end = &text[len];
1714 const char *p;
1715 long long major, minor;
1716
1717 /* Look for dot. */
1718 for (p = text; p < end; p++)
1719 if (*p == '.')
1720 break;
1721
1722 /* Convert major. */
1723 if (strl2llrc(text, p - text, &major) != 0)
1724 return 1;
1725
1726 /* Check major. */
1727 if (major >= 65536)
1728 return 1;
1729
1730 /* Convert minor. */
1731 minor = 0;
1732 if (p < end)
1733 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1734 return 1;
1735
1736 /* Check minor. */
1737 if (minor >= 65536)
1738 return 1;
1739
1740 /* Compose value. */
1741 *ret = (major << 16) | (minor & 0xffff);
1742 return 0;
1743}
1744
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001745/* This function parses a time value optionally followed by a unit suffix among
1746 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1747 * expected by the caller. The computation does its best to avoid overflows.
1748 * The value is returned in <ret> if everything is fine, and a NULL is returned
1749 * by the function. In case of error, a pointer to the error is returned and
1750 * <ret> is left untouched. Values are automatically rounded up when needed.
1751 */
1752const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1753{
1754 unsigned imult, idiv;
1755 unsigned omult, odiv;
1756 unsigned value;
1757
1758 omult = odiv = 1;
1759
1760 switch (unit_flags & TIME_UNIT_MASK) {
1761 case TIME_UNIT_US: omult = 1000000; break;
1762 case TIME_UNIT_MS: omult = 1000; break;
1763 case TIME_UNIT_S: break;
1764 case TIME_UNIT_MIN: odiv = 60; break;
1765 case TIME_UNIT_HOUR: odiv = 3600; break;
1766 case TIME_UNIT_DAY: odiv = 86400; break;
1767 default: break;
1768 }
1769
1770 value = 0;
1771
1772 while (1) {
1773 unsigned int j;
1774
1775 j = *text - '0';
1776 if (j > 9)
1777 break;
1778 text++;
1779 value *= 10;
1780 value += j;
1781 }
1782
1783 imult = idiv = 1;
1784 switch (*text) {
1785 case '\0': /* no unit = default unit */
1786 imult = omult = idiv = odiv = 1;
1787 break;
1788 case 's': /* second = unscaled unit */
1789 break;
1790 case 'u': /* microsecond : "us" */
1791 if (text[1] == 's') {
1792 idiv = 1000000;
1793 text++;
1794 }
1795 break;
1796 case 'm': /* millisecond : "ms" or minute: "m" */
1797 if (text[1] == 's') {
1798 idiv = 1000;
1799 text++;
1800 } else
1801 imult = 60;
1802 break;
1803 case 'h': /* hour : "h" */
1804 imult = 3600;
1805 break;
1806 case 'd': /* day : "d" */
1807 imult = 86400;
1808 break;
1809 default:
1810 return text;
1811 break;
1812 }
1813
1814 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1815 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1816 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1817 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1818
1819 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1820 *ret = value;
1821 return NULL;
1822}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001823
Emeric Brun39132b22010-01-04 14:57:24 +01001824/* this function converts the string starting at <text> to an unsigned int
1825 * stored in <ret>. If an error is detected, the pointer to the unexpected
1826 * character is returned. If the conversio is succesful, NULL is returned.
1827 */
1828const char *parse_size_err(const char *text, unsigned *ret) {
1829 unsigned value = 0;
1830
1831 while (1) {
1832 unsigned int j;
1833
1834 j = *text - '0';
1835 if (j > 9)
1836 break;
1837 if (value > ~0U / 10)
1838 return text;
1839 value *= 10;
1840 if (value > (value + j))
1841 return text;
1842 value += j;
1843 text++;
1844 }
1845
1846 switch (*text) {
1847 case '\0':
1848 break;
1849 case 'K':
1850 case 'k':
1851 if (value > ~0U >> 10)
1852 return text;
1853 value = value << 10;
1854 break;
1855 case 'M':
1856 case 'm':
1857 if (value > ~0U >> 20)
1858 return text;
1859 value = value << 20;
1860 break;
1861 case 'G':
1862 case 'g':
1863 if (value > ~0U >> 30)
1864 return text;
1865 value = value << 30;
1866 break;
1867 default:
1868 return text;
1869 }
1870
Godbach58048a22015-01-28 17:36:16 +08001871 if (*text != '\0' && *++text != '\0')
1872 return text;
1873
Emeric Brun39132b22010-01-04 14:57:24 +01001874 *ret = value;
1875 return NULL;
1876}
1877
Willy Tarreau126d4062013-12-03 17:50:47 +01001878/*
1879 * Parse binary string written in hexadecimal (source) and store the decoded
1880 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1881 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001882 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001883 */
1884int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1885{
1886 int len;
1887 const char *p = source;
1888 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001889 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001890
1891 len = strlen(source);
1892 if (len % 2) {
1893 memprintf(err, "an even number of hex digit is expected");
1894 return 0;
1895 }
1896
1897 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001898
Willy Tarreau126d4062013-12-03 17:50:47 +01001899 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001900 *binstr = calloc(len, sizeof(char));
1901 if (!*binstr) {
1902 memprintf(err, "out of memory while loading string pattern");
1903 return 0;
1904 }
1905 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001906 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001907 else {
1908 if (*binstrlen < len) {
1909 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1910 len, *binstrlen);
1911 return 0;
1912 }
1913 alloc = 0;
1914 }
1915 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001916
1917 i = j = 0;
1918 while (j < len) {
1919 if (!ishex(p[i++]))
1920 goto bad_input;
1921 if (!ishex(p[i++]))
1922 goto bad_input;
1923 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1924 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001925 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001926
1927bad_input:
1928 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001929 if (alloc)
1930 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001931 return 0;
1932}
1933
Willy Tarreau946ba592009-05-10 15:41:18 +02001934/* copies at most <n> characters from <src> and always terminates with '\0' */
1935char *my_strndup(const char *src, int n)
1936{
1937 int len = 0;
1938 char *ret;
1939
1940 while (len < n && src[len])
1941 len++;
1942
1943 ret = (char *)malloc(len + 1);
1944 if (!ret)
1945 return ret;
1946 memcpy(ret, src, len);
1947 ret[len] = '\0';
1948 return ret;
1949}
1950
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001951/*
1952 * search needle in haystack
1953 * returns the pointer if found, returns NULL otherwise
1954 */
1955const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1956{
1957 const void *c = NULL;
1958 unsigned char f;
1959
1960 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1961 return NULL;
1962
1963 f = *(char *)needle;
1964 c = haystack;
1965 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1966 if ((haystacklen - (c - haystack)) < needlelen)
1967 return NULL;
1968
1969 if (memcmp(c, needle, needlelen) == 0)
1970 return c;
1971 ++c;
1972 }
1973 return NULL;
1974}
1975
Willy Tarreau482b00d2009-10-04 22:48:42 +02001976/* This function returns the first unused key greater than or equal to <key> in
1977 * ID tree <root>. Zero is returned if no place is found.
1978 */
1979unsigned int get_next_id(struct eb_root *root, unsigned int key)
1980{
1981 struct eb32_node *used;
1982
1983 do {
1984 used = eb32_lookup_ge(root, key);
1985 if (!used || used->key > key)
1986 return key; /* key is available */
1987 key++;
1988 } while (key);
1989 return key;
1990}
1991
Willy Tarreau348238b2010-01-18 15:05:57 +01001992/* This function compares a sample word possibly followed by blanks to another
1993 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1994 * otherwise zero. This intends to be used when checking HTTP headers for some
1995 * values. Note that it validates a word followed only by blanks but does not
1996 * validate a word followed by blanks then other chars.
1997 */
1998int word_match(const char *sample, int slen, const char *word, int wlen)
1999{
2000 if (slen < wlen)
2001 return 0;
2002
2003 while (wlen) {
2004 char c = *sample ^ *word;
2005 if (c && c != ('A' ^ 'a'))
2006 return 0;
2007 sample++;
2008 word++;
2009 slen--;
2010 wlen--;
2011 }
2012
2013 while (slen) {
2014 if (*sample != ' ' && *sample != '\t')
2015 return 0;
2016 sample++;
2017 slen--;
2018 }
2019 return 1;
2020}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002021
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002022/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2023 * is particularly fast because it avoids expensive operations such as
2024 * multiplies, which are optimized away at the end. It requires a properly
2025 * formated address though (3 points).
2026 */
2027unsigned int inetaddr_host(const char *text)
2028{
2029 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2030 register unsigned int dig100, dig10, dig1;
2031 int s;
2032 const char *p, *d;
2033
2034 dig1 = dig10 = dig100 = ascii_zero;
2035 s = 24;
2036
2037 p = text;
2038 while (1) {
2039 if (((unsigned)(*p - '0')) <= 9) {
2040 p++;
2041 continue;
2042 }
2043
2044 /* here, we have a complete byte between <text> and <p> (exclusive) */
2045 if (p == text)
2046 goto end;
2047
2048 d = p - 1;
2049 dig1 |= (unsigned int)(*d << s);
2050 if (d == text)
2051 goto end;
2052
2053 d--;
2054 dig10 |= (unsigned int)(*d << s);
2055 if (d == text)
2056 goto end;
2057
2058 d--;
2059 dig100 |= (unsigned int)(*d << s);
2060 end:
2061 if (!s || *p != '.')
2062 break;
2063
2064 s -= 8;
2065 text = ++p;
2066 }
2067
2068 dig100 -= ascii_zero;
2069 dig10 -= ascii_zero;
2070 dig1 -= ascii_zero;
2071 return ((dig100 * 10) + dig10) * 10 + dig1;
2072}
2073
2074/*
2075 * Idem except the first unparsed character has to be passed in <stop>.
2076 */
2077unsigned int inetaddr_host_lim(const char *text, const char *stop)
2078{
2079 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2080 register unsigned int dig100, dig10, dig1;
2081 int s;
2082 const char *p, *d;
2083
2084 dig1 = dig10 = dig100 = ascii_zero;
2085 s = 24;
2086
2087 p = text;
2088 while (1) {
2089 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2090 p++;
2091 continue;
2092 }
2093
2094 /* here, we have a complete byte between <text> and <p> (exclusive) */
2095 if (p == text)
2096 goto end;
2097
2098 d = p - 1;
2099 dig1 |= (unsigned int)(*d << s);
2100 if (d == text)
2101 goto end;
2102
2103 d--;
2104 dig10 |= (unsigned int)(*d << s);
2105 if (d == text)
2106 goto end;
2107
2108 d--;
2109 dig100 |= (unsigned int)(*d << s);
2110 end:
2111 if (!s || p == stop || *p != '.')
2112 break;
2113
2114 s -= 8;
2115 text = ++p;
2116 }
2117
2118 dig100 -= ascii_zero;
2119 dig10 -= ascii_zero;
2120 dig1 -= ascii_zero;
2121 return ((dig100 * 10) + dig10) * 10 + dig1;
2122}
2123
2124/*
2125 * Idem except the pointer to first unparsed byte is returned into <ret> which
2126 * must not be NULL.
2127 */
Willy Tarreau74172752010-10-15 23:21:42 +02002128unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002129{
2130 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2131 register unsigned int dig100, dig10, dig1;
2132 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002133 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002134
2135 dig1 = dig10 = dig100 = ascii_zero;
2136 s = 24;
2137
2138 p = text;
2139 while (1) {
2140 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2141 p++;
2142 continue;
2143 }
2144
2145 /* here, we have a complete byte between <text> and <p> (exclusive) */
2146 if (p == text)
2147 goto end;
2148
2149 d = p - 1;
2150 dig1 |= (unsigned int)(*d << s);
2151 if (d == text)
2152 goto end;
2153
2154 d--;
2155 dig10 |= (unsigned int)(*d << s);
2156 if (d == text)
2157 goto end;
2158
2159 d--;
2160 dig100 |= (unsigned int)(*d << s);
2161 end:
2162 if (!s || p == stop || *p != '.')
2163 break;
2164
2165 s -= 8;
2166 text = ++p;
2167 }
2168
2169 *ret = p;
2170 dig100 -= ascii_zero;
2171 dig10 -= ascii_zero;
2172 dig1 -= ascii_zero;
2173 return ((dig100 * 10) + dig10) * 10 + dig1;
2174}
2175
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002176/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2177 * or the number of chars read in case of success. Maybe this could be replaced
2178 * by one of the functions above. Also, apparently this function does not support
2179 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002180 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002181 */
2182int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2183{
2184 const char *addr;
2185 int saw_digit, octets, ch;
2186 u_char tmp[4], *tp;
2187 const char *cp = buf;
2188
2189 saw_digit = 0;
2190 octets = 0;
2191 *(tp = tmp) = 0;
2192
2193 for (addr = buf; addr - buf < len; addr++) {
2194 unsigned char digit = (ch = *addr) - '0';
2195
2196 if (digit > 9 && ch != '.')
2197 break;
2198
2199 if (digit <= 9) {
2200 u_int new = *tp * 10 + digit;
2201
2202 if (new > 255)
2203 return 0;
2204
2205 *tp = new;
2206
2207 if (!saw_digit) {
2208 if (++octets > 4)
2209 return 0;
2210 saw_digit = 1;
2211 }
2212 } else if (ch == '.' && saw_digit) {
2213 if (octets == 4)
2214 return 0;
2215
2216 *++tp = 0;
2217 saw_digit = 0;
2218 } else
2219 return 0;
2220 }
2221
2222 if (octets < 4)
2223 return 0;
2224
2225 memcpy(&dst->s_addr, tmp, 4);
2226 return addr - cp;
2227}
2228
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002229/* This function converts the string in <buf> of the len <len> to
2230 * struct in6_addr <dst> which must be allocated by the caller.
2231 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002232 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002233 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002234int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2235{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002236 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002237 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002238
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002239 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002240 return 0;
2241
2242 memcpy(null_term_ip6, buf, len);
2243 null_term_ip6[len] = '\0';
2244
Willy Tarreau075415a2013-12-12 11:29:39 +01002245 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002246 return 0;
2247
Willy Tarreau075415a2013-12-12 11:29:39 +01002248 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002249 return 1;
2250}
2251
Willy Tarreauacf95772010-06-14 19:09:21 +02002252/* To be used to quote config arg positions. Returns the short string at <ptr>
2253 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2254 * if ptr is NULL or empty. The string is locally allocated.
2255 */
2256const char *quote_arg(const char *ptr)
2257{
2258 static char val[32];
2259 int i;
2260
2261 if (!ptr || !*ptr)
2262 return "end of line";
2263 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002264 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002265 val[i] = *ptr++;
2266 val[i++] = '\'';
2267 val[i] = '\0';
2268 return val;
2269}
2270
Willy Tarreau5b180202010-07-18 10:40:48 +02002271/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2272int get_std_op(const char *str)
2273{
2274 int ret = -1;
2275
2276 if (*str == 'e' && str[1] == 'q')
2277 ret = STD_OP_EQ;
2278 else if (*str == 'n' && str[1] == 'e')
2279 ret = STD_OP_NE;
2280 else if (*str == 'l') {
2281 if (str[1] == 'e') ret = STD_OP_LE;
2282 else if (str[1] == 't') ret = STD_OP_LT;
2283 }
2284 else if (*str == 'g') {
2285 if (str[1] == 'e') ret = STD_OP_GE;
2286 else if (str[1] == 't') ret = STD_OP_GT;
2287 }
2288
2289 if (ret == -1 || str[2] != '\0')
2290 return -1;
2291 return ret;
2292}
2293
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002294/* hash a 32-bit integer to another 32-bit integer */
2295unsigned int full_hash(unsigned int a)
2296{
2297 return __full_hash(a);
2298}
2299
David du Colombier4f92d322011-03-24 11:09:31 +01002300/* Return non-zero if IPv4 address is part of the network,
2301 * otherwise zero.
2302 */
2303int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
2304{
2305 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
2306}
2307
2308/* Return non-zero if IPv6 address is part of the network,
2309 * otherwise zero.
2310 */
2311int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
2312{
2313 int i;
2314
2315 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2316 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2317 (((int *)net)[i] & ((int *)mask)[i]))
2318 return 0;
2319 return 1;
2320}
2321
2322/* RFC 4291 prefix */
2323const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2324 0x00, 0x00, 0x00, 0x00,
2325 0x00, 0x00, 0xFF, 0xFF };
2326
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002327/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2328 * Input and output may overlap.
2329 */
David du Colombier4f92d322011-03-24 11:09:31 +01002330void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2331{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002332 struct in_addr tmp_addr;
2333
2334 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002335 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002336 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002337}
2338
2339/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2340 * Return true if conversion is possible and false otherwise.
2341 */
2342int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2343{
2344 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2345 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2346 sizeof(struct in_addr));
2347 return 1;
2348 }
2349
2350 return 0;
2351}
2352
William Lallemand421f5b52012-02-06 18:15:57 +01002353char *human_time(int t, short hz_div) {
2354 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2355 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002356 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002357 int cnt=2; // print two numbers
2358
2359 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002360 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002361 return rv;
2362 }
2363
2364 if (unlikely(hz_div > 1))
2365 t /= hz_div;
2366
2367 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002368 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002369 cnt--;
2370 }
2371
2372 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002373 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002374 cnt--;
2375 }
2376
2377 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002378 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002379 cnt--;
2380 }
2381
2382 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002383 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002384
2385 return rv;
2386}
2387
2388const char *monthname[12] = {
2389 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2390 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2391};
2392
2393/* date2str_log: write a date in the format :
2394 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2395 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2396 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2397 *
2398 * without using sprintf. return a pointer to the last char written (\0) or
2399 * NULL if there isn't enough space.
2400 */
2401char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2402{
2403
2404 if (size < 25) /* the size is fixed: 24 chars + \0 */
2405 return NULL;
2406
2407 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2408 *dst++ = '/';
2409 memcpy(dst, monthname[tm->tm_mon], 3); // month
2410 dst += 3;
2411 *dst++ = '/';
2412 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2413 *dst++ = ':';
2414 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2415 *dst++ = ':';
2416 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2417 *dst++ = ':';
2418 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2419 *dst++ = '.';
2420 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2421 dst += 3; // only the 3 first digits
2422 *dst = '\0';
2423
2424 return dst;
2425}
2426
2427/* gmt2str_log: write a date in the format :
2428 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2429 * return a pointer to the last char written (\0) or
2430 * NULL if there isn't enough space.
2431 */
2432char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2433{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002434 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002435 return NULL;
2436
2437 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2438 *dst++ = '/';
2439 memcpy(dst, monthname[tm->tm_mon], 3); // month
2440 dst += 3;
2441 *dst++ = '/';
2442 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2443 *dst++ = ':';
2444 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2445 *dst++ = ':';
2446 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2447 *dst++ = ':';
2448 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2449 *dst++ = ' ';
2450 *dst++ = '+';
2451 *dst++ = '0';
2452 *dst++ = '0';
2453 *dst++ = '0';
2454 *dst++ = '0';
2455 *dst = '\0';
2456
2457 return dst;
2458}
2459
Yuxans Yao4e25b012012-10-19 10:36:09 +08002460/* localdate2str_log: write a date in the format :
2461 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2462 * * return a pointer to the last char written (\0) or
2463 * * NULL if there isn't enough space.
2464 */
2465char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2466{
2467 if (size < 27) /* the size is fixed: 26 chars + \0 */
2468 return NULL;
2469
2470 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2471 *dst++ = '/';
2472 memcpy(dst, monthname[tm->tm_mon], 3); // month
2473 dst += 3;
2474 *dst++ = '/';
2475 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2476 *dst++ = ':';
2477 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2478 *dst++ = ':';
2479 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2480 *dst++ = ':';
2481 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2482 *dst++ = ' ';
2483 memcpy(dst, localtimezone, 5); // timezone
2484 dst += 5;
2485 *dst = '\0';
2486
2487 return dst;
2488}
2489
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002490/* Dynamically allocates a string of the proper length to hold the formatted
2491 * output. NULL is returned on error. The caller is responsible for freeing the
2492 * memory area using free(). The resulting string is returned in <out> if the
2493 * pointer is not NULL. A previous version of <out> might be used to build the
2494 * new string, and it will be freed before returning if it is not NULL, which
2495 * makes it possible to build complex strings from iterative calls without
2496 * having to care about freeing intermediate values, as in the example below :
2497 *
2498 * memprintf(&err, "invalid argument: '%s'", arg);
2499 * ...
2500 * memprintf(&err, "parser said : <%s>\n", *err);
2501 * ...
2502 * free(*err);
2503 *
2504 * This means that <err> must be initialized to NULL before first invocation.
2505 * The return value also holds the allocated string, which eases error checking
2506 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002507 * passed instead and it will be ignored. The returned message will then also
2508 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002509 *
2510 * It is also convenient to use it without any free except the last one :
2511 * err = NULL;
2512 * if (!fct1(err)) report(*err);
2513 * if (!fct2(err)) report(*err);
2514 * if (!fct3(err)) report(*err);
2515 * free(*err);
2516 */
2517char *memprintf(char **out, const char *format, ...)
2518{
2519 va_list args;
2520 char *ret = NULL;
2521 int allocated = 0;
2522 int needed = 0;
2523
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002524 if (!out)
2525 return NULL;
2526
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002527 do {
2528 /* vsnprintf() will return the required length even when the
2529 * target buffer is NULL. We do this in a loop just in case
2530 * intermediate evaluations get wrong.
2531 */
2532 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002533 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002534 va_end(args);
2535
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002536 if (needed < allocated) {
2537 /* Note: on Solaris 8, the first iteration always
2538 * returns -1 if allocated is zero, so we force a
2539 * retry.
2540 */
2541 if (!allocated)
2542 needed = 0;
2543 else
2544 break;
2545 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002546
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002547 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002548 ret = realloc(ret, allocated);
2549 } while (ret);
2550
2551 if (needed < 0) {
2552 /* an error was encountered */
2553 free(ret);
2554 ret = NULL;
2555 }
2556
2557 if (out) {
2558 free(*out);
2559 *out = ret;
2560 }
2561
2562 return ret;
2563}
William Lallemand421f5b52012-02-06 18:15:57 +01002564
Willy Tarreau21c705b2012-09-14 11:40:36 +02002565/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2566 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002567 * freed by the caller. It also supports being passed a NULL which results in the same
2568 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002569 * Example of use :
2570 * parse(cmd, &err); (callee: memprintf(&err, ...))
2571 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2572 * free(err);
2573 */
2574char *indent_msg(char **out, int level)
2575{
2576 char *ret, *in, *p;
2577 int needed = 0;
2578 int lf = 0;
2579 int lastlf = 0;
2580 int len;
2581
Willy Tarreau70eec382012-10-10 08:56:47 +02002582 if (!out || !*out)
2583 return NULL;
2584
Willy Tarreau21c705b2012-09-14 11:40:36 +02002585 in = *out - 1;
2586 while ((in = strchr(in + 1, '\n')) != NULL) {
2587 lastlf = in - *out;
2588 lf++;
2589 }
2590
2591 if (!lf) /* single line, no LF, return it as-is */
2592 return *out;
2593
2594 len = strlen(*out);
2595
2596 if (lf == 1 && lastlf == len - 1) {
2597 /* single line, LF at end, strip it and return as-is */
2598 (*out)[lastlf] = 0;
2599 return *out;
2600 }
2601
2602 /* OK now we have at least one LF, we need to process the whole string
2603 * as a multi-line string. What we'll do :
2604 * - prefix with an LF if there is none
2605 * - add <level> spaces before each line
2606 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2607 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2608 */
2609
2610 needed = 1 + level * (lf + 1) + len + 1;
2611 p = ret = malloc(needed);
2612 in = *out;
2613
2614 /* skip initial LFs */
2615 while (*in == '\n')
2616 in++;
2617
2618 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2619 while (*in) {
2620 *p++ = '\n';
2621 memset(p, ' ', level);
2622 p += level;
2623 do {
2624 *p++ = *in++;
2625 } while (*in && *in != '\n');
2626 if (*in)
2627 in++;
2628 }
2629 *p = 0;
2630
2631 free(*out);
2632 *out = ret;
2633
2634 return ret;
2635}
2636
Willy Tarreaudad36a32013-03-11 01:20:04 +01002637/* Convert occurrences of environment variables in the input string to their
2638 * corresponding value. A variable is identified as a series of alphanumeric
2639 * characters or underscores following a '$' sign. The <in> string must be
2640 * free()able. NULL returns NULL. The resulting string might be reallocated if
2641 * some expansion is made. Variable names may also be enclosed into braces if
2642 * needed (eg: to concatenate alphanum characters).
2643 */
2644char *env_expand(char *in)
2645{
2646 char *txt_beg;
2647 char *out;
2648 char *txt_end;
2649 char *var_beg;
2650 char *var_end;
2651 char *value;
2652 char *next;
2653 int out_len;
2654 int val_len;
2655
2656 if (!in)
2657 return in;
2658
2659 value = out = NULL;
2660 out_len = 0;
2661
2662 txt_beg = in;
2663 do {
2664 /* look for next '$' sign in <in> */
2665 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2666
2667 if (!*txt_end && !out) /* end and no expansion performed */
2668 return in;
2669
2670 val_len = 0;
2671 next = txt_end;
2672 if (*txt_end == '$') {
2673 char save;
2674
2675 var_beg = txt_end + 1;
2676 if (*var_beg == '{')
2677 var_beg++;
2678
2679 var_end = var_beg;
2680 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2681 var_end++;
2682 }
2683
2684 next = var_end;
2685 if (*var_end == '}' && (var_beg > txt_end + 1))
2686 next++;
2687
2688 /* get value of the variable name at this location */
2689 save = *var_end;
2690 *var_end = '\0';
2691 value = getenv(var_beg);
2692 *var_end = save;
2693 val_len = value ? strlen(value) : 0;
2694 }
2695
2696 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2697 if (txt_end > txt_beg) {
2698 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2699 out_len += txt_end - txt_beg;
2700 }
2701 if (val_len) {
2702 memcpy(out + out_len, value, val_len);
2703 out_len += val_len;
2704 }
2705 out[out_len] = 0;
2706 txt_beg = next;
2707 } while (*txt_beg);
2708
2709 /* here we know that <out> was allocated and that we don't need <in> anymore */
2710 free(in);
2711 return out;
2712}
2713
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002714
2715/* same as strstr() but case-insensitive and with limit length */
2716const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2717{
2718 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02002719 unsigned int slen, plen;
2720 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002721
2722 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2723 return NULL;
2724
2725 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2726 return str1;
2727
2728 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2729 return NULL;
2730
2731 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2732 while (toupper(*start) != toupper(*str2)) {
2733 start++;
2734 slen--;
2735 tmp1++;
2736
2737 if (tmp1 >= len_str1)
2738 return NULL;
2739
2740 /* if pattern longer than string */
2741 if (slen < plen)
2742 return NULL;
2743 }
2744
2745 sptr = start;
2746 pptr = (char *)str2;
2747
2748 tmp2 = 0;
2749 while (toupper(*sptr) == toupper(*pptr)) {
2750 sptr++;
2751 pptr++;
2752 tmp2++;
2753
2754 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2755 return start;
2756 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2757 return NULL;
2758 }
2759 }
2760 return NULL;
2761}
2762
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02002763/* This function read the next valid utf8 char.
2764 * <s> is the byte srray to be decode, <len> is its length.
2765 * The function returns decoded char encoded like this:
2766 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
2767 * are the length read. The decoded character is stored in <c>.
2768 */
2769unsigned char utf8_next(const char *s, int len, unsigned int *c)
2770{
2771 const unsigned char *p = (unsigned char *)s;
2772 int dec;
2773 unsigned char code = UTF8_CODE_OK;
2774
2775 if (len < 1)
2776 return UTF8_CODE_OK;
2777
2778 /* Check the type of UTF8 sequence
2779 *
2780 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
2781 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
2782 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
2783 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
2784 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
2785 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
2786 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
2787 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
2788 */
2789 switch (*p) {
2790 case 0x00 ... 0x7f:
2791 *c = *p;
2792 return UTF8_CODE_OK | 1;
2793
2794 case 0x80 ... 0xbf:
2795 *c = *p;
2796 return UTF8_CODE_BADSEQ | 1;
2797
2798 case 0xc0 ... 0xdf:
2799 if (len < 2) {
2800 *c = *p;
2801 return UTF8_CODE_BADSEQ | 1;
2802 }
2803 *c = *p & 0x1f;
2804 dec = 1;
2805 break;
2806
2807 case 0xe0 ... 0xef:
2808 if (len < 3) {
2809 *c = *p;
2810 return UTF8_CODE_BADSEQ | 1;
2811 }
2812 *c = *p & 0x0f;
2813 dec = 2;
2814 break;
2815
2816 case 0xf0 ... 0xf7:
2817 if (len < 4) {
2818 *c = *p;
2819 return UTF8_CODE_BADSEQ | 1;
2820 }
2821 *c = *p & 0x07;
2822 dec = 3;
2823 break;
2824
2825 case 0xf8 ... 0xfb:
2826 if (len < 5) {
2827 *c = *p;
2828 return UTF8_CODE_BADSEQ | 1;
2829 }
2830 *c = *p & 0x03;
2831 dec = 4;
2832 break;
2833
2834 case 0xfc ... 0xfd:
2835 if (len < 6) {
2836 *c = *p;
2837 return UTF8_CODE_BADSEQ | 1;
2838 }
2839 *c = *p & 0x01;
2840 dec = 5;
2841 break;
2842
2843 case 0xfe ... 0xff:
2844 default:
2845 *c = *p;
2846 return UTF8_CODE_BADSEQ | 1;
2847 }
2848
2849 p++;
2850
2851 while (dec > 0) {
2852
2853 /* need 0x10 for the 2 first bits */
2854 if ( ( *p & 0xc0 ) != 0x80 )
2855 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
2856
2857 /* add data at char */
2858 *c = ( *c << 6 ) | ( *p & 0x3f );
2859
2860 dec--;
2861 p++;
2862 }
2863
2864 /* Check ovelong encoding.
2865 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
2866 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
2867 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
2868 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01002869 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02002870 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
2871 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
2872 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
2873 code |= UTF8_CODE_OVERLONG;
2874
2875 /* Check invalid UTF8 range. */
2876 if ((*c >= 0xd800 && *c <= 0xdfff) ||
2877 (*c >= 0xfffe && *c <= 0xffff))
2878 code |= UTF8_CODE_INVRANGE;
2879
2880 return code | ((p-(unsigned char *)s)&0x0f);
2881}
2882
Willy Tarreaubaaee002006-06-26 02:48:02 +02002883/*
2884 * Local variables:
2885 * c-indent-level: 8
2886 * c-basic-offset: 8
2887 * End:
2888 */