blob: 7964b88ddb46aadd98a0319326205064a3de4a40 [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 Tarreau9f69f462015-09-08 16:01:25 +0200785 if (!*str2) {
786 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
787 goto out;
788 }
789
Willy Tarreau24709282013-03-10 21:32:12 +0100790 memset(&ss, 0, sizeof(ss));
791
792 if (strncmp(str2, "unix@", 5) == 0) {
793 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200794 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100795 ss.ss_family = AF_UNIX;
796 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200797 else if (strncmp(str2, "abns@", 5) == 0) {
798 str2 += 5;
799 abstract = 1;
800 ss.ss_family = AF_UNIX;
801 }
Willy Tarreau24709282013-03-10 21:32:12 +0100802 else if (strncmp(str2, "ipv4@", 5) == 0) {
803 str2 += 5;
804 ss.ss_family = AF_INET;
805 }
806 else if (strncmp(str2, "ipv6@", 5) == 0) {
807 str2 += 5;
808 ss.ss_family = AF_INET6;
809 }
810 else if (*str2 == '/') {
811 ss.ss_family = AF_UNIX;
812 }
813 else
814 ss.ss_family = AF_UNSPEC;
815
Willy Tarreau40aa0702013-03-10 23:51:38 +0100816 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
817 char *endptr;
818
819 str2 += 3;
820 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
821
822 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100823 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100824 goto out;
825 }
826
827 /* we return AF_UNSPEC if we use a file descriptor number */
828 ss.ss_family = AF_UNSPEC;
829 }
830 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100831 int prefix_path_len;
832 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200833 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100834
835 /* complete unix socket path name during startup or soft-restart is
836 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
837 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200838 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100839 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
840 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
841
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200842 adr_len = strlen(str2);
843 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100844 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
845 goto out;
846 }
847
Willy Tarreauccfccef2014-05-10 01:49:15 +0200848 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
849 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200850 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100851 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200852 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100853 }
Willy Tarreau24709282013-03-10 21:32:12 +0100854 else { /* IPv4 and IPv6 */
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200855 int use_fqdn = 0;
856
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100857 port1 = strrchr(str2, ':');
858 if (port1)
859 *port1++ = '\0';
860 else
861 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200862
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200863 if (str2ip2(str2, &ss, 0) == NULL) {
864 use_fqdn = 1;
865 if (str2ip(str2, &ss) == NULL) {
866 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
867 goto out;
868 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100869 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100870
Willy Tarreaua39d1992013-04-01 20:37:42 +0200871 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100872 port2 = strchr(port1, '-');
873 if (port2)
874 *port2++ = '\0';
875 else
876 port2 = port1;
877 portl = atoi(port1);
878 porth = atoi(port2);
879 porta = portl;
880 }
881 else if (*port1 == '-') { /* negative offset */
882 portl = atoi(port1 + 1);
883 porta = -portl;
884 }
885 else if (*port1 == '+') { /* positive offset */
886 porth = atoi(port1 + 1);
887 porta = porth;
888 }
889 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100890 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100891 goto out;
892 }
893 set_host_port(&ss, porta);
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200894
895 if (use_fqdn && fqdn) {
896 if (str2 != back)
897 memmove(back, str2, strlen(str2) + 1);
898 *fqdn = back;
899 back = NULL;
900 }
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100901 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100902
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100903 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100904 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100905 if (low)
906 *low = portl;
907 if (high)
908 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100909 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100910 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200911}
912
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100913/* converts <str> to a struct in_addr containing a network mask. It can be
914 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
915 * if the conversion succeeds otherwise non-zero.
916 */
917int str2mask(const char *str, struct in_addr *mask)
918{
919 if (strchr(str, '.') != NULL) { /* dotted notation */
920 if (!inet_pton(AF_INET, str, mask))
921 return 0;
922 }
923 else { /* mask length */
924 char *err;
925 unsigned long len = strtol(str, &err, 10);
926
927 if (!*str || (err && *err) || (unsigned)len > 32)
928 return 0;
929 if (len)
930 mask->s_addr = htonl(~0UL << (32 - len));
931 else
932 mask->s_addr = 0;
933 }
934 return 1;
935}
936
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100937/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
938 * succeeds otherwise zero.
939 */
940int cidr2dotted(int cidr, struct in_addr *mask) {
941
942 if (cidr < 0 || cidr > 32)
943 return 0;
944
945 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
946 return 1;
947}
948
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200949/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200950 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200951 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
952 * is optionnal and either in the dotted or CIDR notation.
953 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
954 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100955int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200956{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200957 __label__ out_free, out_err;
958 char *c, *s;
959 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200960
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200961 s = strdup(str);
962 if (!s)
963 return 0;
964
Willy Tarreaubaaee002006-06-26 02:48:02 +0200965 memset(mask, 0, sizeof(*mask));
966 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200967
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200968 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200969 *c++ = '\0';
970 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100971 if (!str2mask(c, mask))
972 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200973 }
974 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100975 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200976 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200977 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200978 struct hostent *he;
979
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100980 if (!resolve)
981 goto out_err;
982
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200983 if ((he = gethostbyname(s)) == NULL) {
984 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200985 }
986 else
987 *addr = *(struct in_addr *) *(he->h_addr_list);
988 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200989
990 ret_val = 1;
991 out_free:
992 free(s);
993 return ret_val;
994 out_err:
995 ret_val = 0;
996 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200997}
998
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100999
1000/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001001 * converts <str> to two struct in6_addr* which must be pre-allocated.
1002 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1003 * is an optionnal number of bits (128 being the default).
1004 * Returns 1 if OK, 0 if error.
1005 */
1006int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1007{
1008 char *c, *s;
1009 int ret_val = 0;
1010 char *err;
1011 unsigned long len = 128;
1012
1013 s = strdup(str);
1014 if (!s)
1015 return 0;
1016
1017 memset(mask, 0, sizeof(*mask));
1018 memset(addr, 0, sizeof(*addr));
1019
1020 if ((c = strrchr(s, '/')) != NULL) {
1021 *c++ = '\0'; /* c points to the mask */
1022 if (!*c)
1023 goto out_free;
1024
1025 len = strtoul(c, &err, 10);
1026 if ((err && *err) || (unsigned)len > 128)
1027 goto out_free;
1028 }
1029 *mask = len; /* OK we have a valid mask in <len> */
1030
1031 if (!inet_pton(AF_INET6, s, addr))
1032 goto out_free;
1033
1034 ret_val = 1;
1035 out_free:
1036 free(s);
1037 return ret_val;
1038}
1039
1040
1041/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001042 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001043 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001044int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001045{
1046 int saw_digit, octets, ch;
1047 u_char tmp[4], *tp;
1048 const char *cp = addr;
1049
1050 saw_digit = 0;
1051 octets = 0;
1052 *(tp = tmp) = 0;
1053
1054 while (*addr) {
1055 unsigned char digit = (ch = *addr++) - '0';
1056 if (digit > 9 && ch != '.')
1057 break;
1058 if (digit <= 9) {
1059 u_int new = *tp * 10 + digit;
1060 if (new > 255)
1061 return 0;
1062 *tp = new;
1063 if (!saw_digit) {
1064 if (++octets > 4)
1065 return 0;
1066 saw_digit = 1;
1067 }
1068 } else if (ch == '.' && saw_digit) {
1069 if (octets == 4)
1070 return 0;
1071 *++tp = 0;
1072 saw_digit = 0;
1073 } else
1074 return 0;
1075 }
1076
1077 if (octets < 4)
1078 return 0;
1079
1080 memcpy(&dst->s_addr, tmp, 4);
1081 return addr-cp-1;
1082}
1083
1084/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001085 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1086 * <out> contain the code of the dectected scheme, the start and length of
1087 * the hostname. Actually only http and https are supported. <out> can be NULL.
1088 * This function returns the consumed length. It is useful if you parse complete
1089 * url like http://host:port/path, because the consumed length corresponds to
1090 * the first character of the path. If the conversion fails, it returns -1.
1091 *
1092 * This function tries to resolve the DNS name if haproxy is in starting mode.
1093 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001094 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001095int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001096{
1097 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001098 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001099 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001100 unsigned long long int http_code = 0;
1101 int default_port;
1102 struct hostent *he;
1103 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001104
1105 /* Firstly, try to find :// pattern */
1106 while (curr < url+ulen && url_code != 0x3a2f2f) {
1107 url_code = ((url_code & 0xffff) << 8);
1108 url_code += (unsigned char)*curr++;
1109 }
1110
1111 /* Secondly, if :// pattern is found, verify parsed stuff
1112 * before pattern is matching our http pattern.
1113 * If so parse ip address and port in uri.
1114 *
1115 * WARNING: Current code doesn't support dynamic async dns resolver.
1116 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001117 if (url_code != 0x3a2f2f)
1118 return -1;
1119
1120 /* Copy scheme, and utrn to lower case. */
1121 while (cp < curr - 3)
1122 http_code = (http_code << 8) + *cp++;
1123 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001124
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001125 /* HTTP or HTTPS url matching */
1126 if (http_code == 0x2020202068747470ULL) {
1127 default_port = 80;
1128 if (out)
1129 out->scheme = SCH_HTTP;
1130 }
1131 else if (http_code == 0x2020206874747073ULL) {
1132 default_port = 443;
1133 if (out)
1134 out->scheme = SCH_HTTPS;
1135 }
1136 else
1137 return -1;
1138
1139 /* If the next char is '[', the host address is IPv6. */
1140 if (*curr == '[') {
1141 curr++;
1142
1143 /* Check trash size */
1144 if (trash.size < ulen)
1145 return -1;
1146
1147 /* Look for ']' and copy the address in a trash buffer. */
1148 p = trash.str;
1149 for (end = curr;
1150 end < url + ulen && *end != ']';
1151 end++, p++)
1152 *p = *end;
1153 if (*end != ']')
1154 return -1;
1155 *p = '\0';
1156
1157 /* Update out. */
1158 if (out) {
1159 out->host = curr;
1160 out->host_len = end - curr;
1161 }
1162
1163 /* Try IPv6 decoding. */
1164 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1165 return -1;
1166 end++;
1167
1168 /* Decode port. */
1169 if (*end == ':') {
1170 end++;
1171 default_port = read_uint(&end, url + ulen);
1172 }
1173 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1174 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1175 return end - url;
1176 }
1177 else {
1178 /* We are looking for IP address. If you want to parse and
1179 * resolve hostname found in url, you can use str2sa_range(), but
1180 * be warned this can slow down global daemon performances
1181 * while handling lagging dns responses.
1182 */
1183 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1184 if (ret) {
1185 /* Update out. */
1186 if (out) {
1187 out->host = curr;
1188 out->host_len = ret;
1189 }
1190
1191 curr += ret;
1192
1193 /* Decode port. */
1194 if (*curr == ':') {
1195 curr++;
1196 default_port = read_uint(&curr, url + ulen);
1197 }
1198 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1199
1200 /* Set family. */
1201 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1202 return curr - url;
1203 }
1204 else if (global.mode & MODE_STARTING) {
1205 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1206 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001207 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001208
1209 /* look for : or / or end */
1210 for (end = curr;
1211 end < url + ulen && *end != '/' && *end != ':';
1212 end++);
1213 memcpy(trash.str, curr, end - curr);
1214 trash.str[end - curr] = '\0';
1215
1216 /* try to resolve an IPv4/IPv6 hostname */
1217 he = gethostbyname(trash.str);
1218 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001219 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001220
1221 /* Update out. */
1222 if (out) {
1223 out->host = curr;
1224 out->host_len = end - curr;
1225 }
1226
1227 /* Decode port. */
1228 if (*end == ':') {
1229 end++;
1230 default_port = read_uint(&end, url + ulen);
1231 }
1232
1233 /* Copy IP address, set port and family. */
1234 switch (he->h_addrtype) {
1235 case AF_INET:
1236 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1237 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1238 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1239 return end - url;
1240
1241 case AF_INET6:
1242 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1243 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1244 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1245 return end - url;
1246 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001247 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001248 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001249 return -1;
1250}
1251
Willy Tarreau631f01c2011-09-05 00:36:48 +02001252/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1253 * address family is returned so that it's easy for the caller to adapt to the
1254 * output format. Zero is returned if the address family is not supported. -1
1255 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1256 * supported.
1257 */
1258int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1259{
1260
1261 void *ptr;
1262
1263 if (size < 5)
1264 return 0;
1265 *str = '\0';
1266
1267 switch (addr->ss_family) {
1268 case AF_INET:
1269 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1270 break;
1271 case AF_INET6:
1272 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1273 break;
1274 case AF_UNIX:
1275 memcpy(str, "unix", 5);
1276 return addr->ss_family;
1277 default:
1278 return 0;
1279 }
1280
1281 if (inet_ntop(addr->ss_family, ptr, str, size))
1282 return addr->ss_family;
1283
1284 /* failed */
1285 return -1;
1286}
1287
Simon Horman75ab8bd2014-06-16 09:39:41 +09001288/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1289 * address family is returned so that it's easy for the caller to adapt to the
1290 * output format. Zero is returned if the address family is not supported. -1
1291 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1292 * supported.
1293 */
1294int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1295{
1296
1297 uint16_t port;
1298
1299
1300 if (size < 5)
1301 return 0;
1302 *str = '\0';
1303
1304 switch (addr->ss_family) {
1305 case AF_INET:
1306 port = ((struct sockaddr_in *)addr)->sin_port;
1307 break;
1308 case AF_INET6:
1309 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1310 break;
1311 case AF_UNIX:
1312 memcpy(str, "unix", 5);
1313 return addr->ss_family;
1314 default:
1315 return 0;
1316 }
1317
1318 snprintf(str, size, "%u", ntohs(port));
1319 return addr->ss_family;
1320}
1321
Willy Tarreaubaaee002006-06-26 02:48:02 +02001322/* will try to encode the string <string> replacing all characters tagged in
1323 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1324 * prefixed by <escape>, and will store the result between <start> (included)
1325 * and <stop> (excluded), and will always terminate the string with a '\0'
1326 * before <stop>. The position of the '\0' is returned if the conversion
1327 * completes. If bytes are missing between <start> and <stop>, then the
1328 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1329 * cannot even be stored so we return <start> without writing the 0.
1330 * The input string must also be zero-terminated.
1331 */
1332const char hextab[16] = "0123456789ABCDEF";
1333char *encode_string(char *start, char *stop,
1334 const char escape, const fd_set *map,
1335 const char *string)
1336{
1337 if (start < stop) {
1338 stop--; /* reserve one byte for the final '\0' */
1339 while (start < stop && *string != '\0') {
1340 if (!FD_ISSET((unsigned char)(*string), map))
1341 *start++ = *string;
1342 else {
1343 if (start + 3 >= stop)
1344 break;
1345 *start++ = escape;
1346 *start++ = hextab[(*string >> 4) & 15];
1347 *start++ = hextab[*string & 15];
1348 }
1349 string++;
1350 }
1351 *start = '\0';
1352 }
1353 return start;
1354}
1355
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001356/*
1357 * Same behavior as encode_string() above, except that it encodes chunk
1358 * <chunk> instead of a string.
1359 */
1360char *encode_chunk(char *start, char *stop,
1361 const char escape, const fd_set *map,
1362 const struct chunk *chunk)
1363{
1364 char *str = chunk->str;
1365 char *end = chunk->str + chunk->len;
1366
1367 if (start < stop) {
1368 stop--; /* reserve one byte for the final '\0' */
1369 while (start < stop && str < end) {
1370 if (!FD_ISSET((unsigned char)(*str), map))
1371 *start++ = *str;
1372 else {
1373 if (start + 3 >= stop)
1374 break;
1375 *start++ = escape;
1376 *start++ = hextab[(*str >> 4) & 15];
1377 *start++ = hextab[*str & 15];
1378 }
1379 str++;
1380 }
1381 *start = '\0';
1382 }
1383 return start;
1384}
1385
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001386/* Check a string for using it in a CSV output format. If the string contains
1387 * one of the following four char <">, <,>, CR or LF, the string is
1388 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1389 * <str> is the input string to be escaped. The function assumes that
1390 * the input string is null-terminated.
1391 *
1392 * If <quote> is 0, the result is returned escaped but without double quote.
1393 * Is it useful if the escaped string is used between double quotes in the
1394 * format.
1395 *
1396 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0));
1397 *
1398 * If the <quote> is 1, the converter put the quotes only if any character is
1399 * escaped. If the <quote> is 2, the converter put always the quotes.
1400 *
1401 * <output> is a struct chunk used for storing the output string if any
1402 * change will be done.
1403 *
1404 * The function returns the converted string on this output. If an error
1405 * occurs, the function return an empty string. This type of output is useful
1406 * for using the function directly as printf() argument.
1407 *
1408 * If the output buffer is too short to contain the input string, the result
1409 * is truncated.
1410 */
1411const char *csv_enc(const char *str, int quote, struct chunk *output)
1412{
1413 char *end = output->str + output->size;
1414 char *out = output->str + 1; /* +1 for reserving space for a first <"> */
1415
1416 while (*str && out < end - 2) { /* -2 for reserving space for <"> and \0. */
1417 *out = *str;
1418 if (*str == '"') {
1419 if (quote == 1)
1420 quote = 2;
1421 out++;
1422 if (out >= end - 2) {
1423 out--;
1424 break;
1425 }
1426 *out = '"';
1427 }
1428 if (quote == 1 && ( *str == '\r' || *str == '\n' || *str == ',') )
1429 quote = 2;
1430 out++;
1431 str++;
1432 }
1433
1434 if (quote == 1)
1435 quote = 0;
1436
1437 if (!quote) {
1438 *out = '\0';
1439 return output->str + 1;
1440 }
1441
1442 /* else quote == 2 */
1443 *output->str = '"';
1444 *out = '"';
1445 out++;
1446 *out = '\0';
1447 return output->str;
1448}
1449
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001450/* Decode an URL-encoded string in-place. The resulting string might
1451 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001452 * aborted, the string is truncated before the issue and a negative value is
1453 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001454 */
1455int url_decode(char *string)
1456{
1457 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001458 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001459
1460 in = string;
1461 out = string;
1462 while (*in) {
1463 switch (*in) {
1464 case '+' :
1465 *out++ = ' ';
1466 break;
1467 case '%' :
1468 if (!ishex(in[1]) || !ishex(in[2]))
1469 goto end;
1470 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1471 in += 2;
1472 break;
1473 default:
1474 *out++ = *in;
1475 break;
1476 }
1477 in++;
1478 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001479 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001480 end:
1481 *out = 0;
1482 return ret;
1483}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001484
Willy Tarreau6911fa42007-03-04 18:06:08 +01001485unsigned int str2ui(const char *s)
1486{
1487 return __str2ui(s);
1488}
1489
1490unsigned int str2uic(const char *s)
1491{
1492 return __str2uic(s);
1493}
1494
1495unsigned int strl2ui(const char *s, int len)
1496{
1497 return __strl2ui(s, len);
1498}
1499
1500unsigned int strl2uic(const char *s, int len)
1501{
1502 return __strl2uic(s, len);
1503}
1504
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001505unsigned int read_uint(const char **s, const char *end)
1506{
1507 return __read_uint(s, end);
1508}
1509
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001510/* This function reads an unsigned integer from the string pointed to by <s> and
1511 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1512 * function automatically stops at <end>. If the number overflows, the 2^64-1
1513 * value is returned.
1514 */
1515unsigned long long int read_uint64(const char **s, const char *end)
1516{
1517 const char *ptr = *s;
1518 unsigned long long int i = 0, tmp;
1519 unsigned int j;
1520
1521 while (ptr < end) {
1522
1523 /* read next char */
1524 j = *ptr - '0';
1525 if (j > 9)
1526 goto read_uint64_end;
1527
1528 /* add char to the number and check overflow. */
1529 tmp = i * 10;
1530 if (tmp / 10 != i) {
1531 i = ULLONG_MAX;
1532 goto read_uint64_eat;
1533 }
1534 if (ULLONG_MAX - tmp < j) {
1535 i = ULLONG_MAX;
1536 goto read_uint64_eat;
1537 }
1538 i = tmp + j;
1539 ptr++;
1540 }
1541read_uint64_eat:
1542 /* eat each numeric char */
1543 while (ptr < end) {
1544 if ((unsigned int)(*ptr - '0') > 9)
1545 break;
1546 ptr++;
1547 }
1548read_uint64_end:
1549 *s = ptr;
1550 return i;
1551}
1552
1553/* This function reads an integer from the string pointed to by <s> and returns
1554 * it. The <s> pointer is adjusted to point to the first unread char. The function
1555 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1556 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1557 * returned.
1558 */
1559long long int read_int64(const char **s, const char *end)
1560{
1561 unsigned long long int i = 0;
1562 int neg = 0;
1563
1564 /* Look for minus char. */
1565 if (**s == '-') {
1566 neg = 1;
1567 (*s)++;
1568 }
1569 else if (**s == '+')
1570 (*s)++;
1571
1572 /* convert as positive number. */
1573 i = read_uint64(s, end);
1574
1575 if (neg) {
1576 if (i > 0x8000000000000000ULL)
1577 return LLONG_MIN;
1578 return -i;
1579 }
1580 if (i > 0x7fffffffffffffffULL)
1581 return LLONG_MAX;
1582 return i;
1583}
1584
Willy Tarreau6911fa42007-03-04 18:06:08 +01001585/* This one is 7 times faster than strtol() on athlon with checks.
1586 * It returns the value of the number composed of all valid digits read,
1587 * and can process negative numbers too.
1588 */
1589int strl2ic(const char *s, int len)
1590{
1591 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001592 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001593
1594 if (len > 0) {
1595 if (*s != '-') {
1596 /* positive number */
1597 while (len-- > 0) {
1598 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001599 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001600 if (j > 9)
1601 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001602 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001603 }
1604 } else {
1605 /* negative number */
1606 s++;
1607 while (--len > 0) {
1608 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001609 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001610 if (j > 9)
1611 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001612 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001613 }
1614 }
1615 }
1616 return i;
1617}
1618
1619
1620/* This function reads exactly <len> chars from <s> and converts them to a
1621 * signed integer which it stores into <ret>. It accurately detects any error
1622 * (truncated string, invalid chars, overflows). It is meant to be used in
1623 * applications designed for hostile environments. It returns zero when the
1624 * number has successfully been converted, non-zero otherwise. When an error
1625 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1626 * faster than strtol().
1627 */
1628int strl2irc(const char *s, int len, int *ret)
1629{
1630 int i = 0;
1631 int j;
1632
1633 if (!len)
1634 return 1;
1635
1636 if (*s != '-') {
1637 /* positive number */
1638 while (len-- > 0) {
1639 j = (*s++) - '0';
1640 if (j > 9) return 1; /* invalid char */
1641 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1642 i = i * 10;
1643 if (i + j < i) return 1; /* check for addition overflow */
1644 i = i + j;
1645 }
1646 } else {
1647 /* negative number */
1648 s++;
1649 while (--len > 0) {
1650 j = (*s++) - '0';
1651 if (j > 9) return 1; /* invalid char */
1652 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1653 i = i * 10;
1654 if (i - j > i) return 1; /* check for subtract overflow */
1655 i = i - j;
1656 }
1657 }
1658 *ret = i;
1659 return 0;
1660}
1661
1662
1663/* This function reads exactly <len> chars from <s> and converts them to a
1664 * signed integer which it stores into <ret>. It accurately detects any error
1665 * (truncated string, invalid chars, overflows). It is meant to be used in
1666 * applications designed for hostile environments. It returns zero when the
1667 * number has successfully been converted, non-zero otherwise. When an error
1668 * is returned, the <ret> value is left untouched. It is about 3 times slower
1669 * than str2irc().
1670 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001671
1672int strl2llrc(const char *s, int len, long long *ret)
1673{
1674 long long i = 0;
1675 int j;
1676
1677 if (!len)
1678 return 1;
1679
1680 if (*s != '-') {
1681 /* positive number */
1682 while (len-- > 0) {
1683 j = (*s++) - '0';
1684 if (j > 9) return 1; /* invalid char */
1685 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1686 i = i * 10LL;
1687 if (i + j < i) return 1; /* check for addition overflow */
1688 i = i + j;
1689 }
1690 } else {
1691 /* negative number */
1692 s++;
1693 while (--len > 0) {
1694 j = (*s++) - '0';
1695 if (j > 9) return 1; /* invalid char */
1696 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1697 i = i * 10LL;
1698 if (i - j > i) return 1; /* check for subtract overflow */
1699 i = i - j;
1700 }
1701 }
1702 *ret = i;
1703 return 0;
1704}
1705
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001706/* This function is used with pat_parse_dotted_ver(). It converts a string
1707 * composed by two number separated by a dot. Each part must contain in 16 bits
1708 * because internally they will be represented as a 32-bit quantity stored in
1709 * a 64-bit integer. It returns zero when the number has successfully been
1710 * converted, non-zero otherwise. When an error is returned, the <ret> value
1711 * is left untouched.
1712 *
1713 * "1.3" -> 0x0000000000010003
1714 * "65535.65535" -> 0x00000000ffffffff
1715 */
1716int strl2llrc_dotted(const char *text, int len, long long *ret)
1717{
1718 const char *end = &text[len];
1719 const char *p;
1720 long long major, minor;
1721
1722 /* Look for dot. */
1723 for (p = text; p < end; p++)
1724 if (*p == '.')
1725 break;
1726
1727 /* Convert major. */
1728 if (strl2llrc(text, p - text, &major) != 0)
1729 return 1;
1730
1731 /* Check major. */
1732 if (major >= 65536)
1733 return 1;
1734
1735 /* Convert minor. */
1736 minor = 0;
1737 if (p < end)
1738 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1739 return 1;
1740
1741 /* Check minor. */
1742 if (minor >= 65536)
1743 return 1;
1744
1745 /* Compose value. */
1746 *ret = (major << 16) | (minor & 0xffff);
1747 return 0;
1748}
1749
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001750/* This function parses a time value optionally followed by a unit suffix among
1751 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1752 * expected by the caller. The computation does its best to avoid overflows.
1753 * The value is returned in <ret> if everything is fine, and a NULL is returned
1754 * by the function. In case of error, a pointer to the error is returned and
1755 * <ret> is left untouched. Values are automatically rounded up when needed.
1756 */
1757const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1758{
1759 unsigned imult, idiv;
1760 unsigned omult, odiv;
1761 unsigned value;
1762
1763 omult = odiv = 1;
1764
1765 switch (unit_flags & TIME_UNIT_MASK) {
1766 case TIME_UNIT_US: omult = 1000000; break;
1767 case TIME_UNIT_MS: omult = 1000; break;
1768 case TIME_UNIT_S: break;
1769 case TIME_UNIT_MIN: odiv = 60; break;
1770 case TIME_UNIT_HOUR: odiv = 3600; break;
1771 case TIME_UNIT_DAY: odiv = 86400; break;
1772 default: break;
1773 }
1774
1775 value = 0;
1776
1777 while (1) {
1778 unsigned int j;
1779
1780 j = *text - '0';
1781 if (j > 9)
1782 break;
1783 text++;
1784 value *= 10;
1785 value += j;
1786 }
1787
1788 imult = idiv = 1;
1789 switch (*text) {
1790 case '\0': /* no unit = default unit */
1791 imult = omult = idiv = odiv = 1;
1792 break;
1793 case 's': /* second = unscaled unit */
1794 break;
1795 case 'u': /* microsecond : "us" */
1796 if (text[1] == 's') {
1797 idiv = 1000000;
1798 text++;
1799 }
1800 break;
1801 case 'm': /* millisecond : "ms" or minute: "m" */
1802 if (text[1] == 's') {
1803 idiv = 1000;
1804 text++;
1805 } else
1806 imult = 60;
1807 break;
1808 case 'h': /* hour : "h" */
1809 imult = 3600;
1810 break;
1811 case 'd': /* day : "d" */
1812 imult = 86400;
1813 break;
1814 default:
1815 return text;
1816 break;
1817 }
1818
1819 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1820 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1821 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1822 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1823
1824 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1825 *ret = value;
1826 return NULL;
1827}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001828
Emeric Brun39132b22010-01-04 14:57:24 +01001829/* this function converts the string starting at <text> to an unsigned int
1830 * stored in <ret>. If an error is detected, the pointer to the unexpected
1831 * character is returned. If the conversio is succesful, NULL is returned.
1832 */
1833const char *parse_size_err(const char *text, unsigned *ret) {
1834 unsigned value = 0;
1835
1836 while (1) {
1837 unsigned int j;
1838
1839 j = *text - '0';
1840 if (j > 9)
1841 break;
1842 if (value > ~0U / 10)
1843 return text;
1844 value *= 10;
1845 if (value > (value + j))
1846 return text;
1847 value += j;
1848 text++;
1849 }
1850
1851 switch (*text) {
1852 case '\0':
1853 break;
1854 case 'K':
1855 case 'k':
1856 if (value > ~0U >> 10)
1857 return text;
1858 value = value << 10;
1859 break;
1860 case 'M':
1861 case 'm':
1862 if (value > ~0U >> 20)
1863 return text;
1864 value = value << 20;
1865 break;
1866 case 'G':
1867 case 'g':
1868 if (value > ~0U >> 30)
1869 return text;
1870 value = value << 30;
1871 break;
1872 default:
1873 return text;
1874 }
1875
Godbach58048a22015-01-28 17:36:16 +08001876 if (*text != '\0' && *++text != '\0')
1877 return text;
1878
Emeric Brun39132b22010-01-04 14:57:24 +01001879 *ret = value;
1880 return NULL;
1881}
1882
Willy Tarreau126d4062013-12-03 17:50:47 +01001883/*
1884 * Parse binary string written in hexadecimal (source) and store the decoded
1885 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1886 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001887 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001888 */
1889int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1890{
1891 int len;
1892 const char *p = source;
1893 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001894 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001895
1896 len = strlen(source);
1897 if (len % 2) {
1898 memprintf(err, "an even number of hex digit is expected");
1899 return 0;
1900 }
1901
1902 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001903
Willy Tarreau126d4062013-12-03 17:50:47 +01001904 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001905 *binstr = calloc(len, sizeof(char));
1906 if (!*binstr) {
1907 memprintf(err, "out of memory while loading string pattern");
1908 return 0;
1909 }
1910 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001911 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001912 else {
1913 if (*binstrlen < len) {
1914 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1915 len, *binstrlen);
1916 return 0;
1917 }
1918 alloc = 0;
1919 }
1920 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001921
1922 i = j = 0;
1923 while (j < len) {
1924 if (!ishex(p[i++]))
1925 goto bad_input;
1926 if (!ishex(p[i++]))
1927 goto bad_input;
1928 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1929 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001930 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001931
1932bad_input:
1933 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001934 if (alloc)
1935 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001936 return 0;
1937}
1938
Willy Tarreau946ba592009-05-10 15:41:18 +02001939/* copies at most <n> characters from <src> and always terminates with '\0' */
1940char *my_strndup(const char *src, int n)
1941{
1942 int len = 0;
1943 char *ret;
1944
1945 while (len < n && src[len])
1946 len++;
1947
1948 ret = (char *)malloc(len + 1);
1949 if (!ret)
1950 return ret;
1951 memcpy(ret, src, len);
1952 ret[len] = '\0';
1953 return ret;
1954}
1955
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001956/*
1957 * search needle in haystack
1958 * returns the pointer if found, returns NULL otherwise
1959 */
1960const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1961{
1962 const void *c = NULL;
1963 unsigned char f;
1964
1965 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1966 return NULL;
1967
1968 f = *(char *)needle;
1969 c = haystack;
1970 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1971 if ((haystacklen - (c - haystack)) < needlelen)
1972 return NULL;
1973
1974 if (memcmp(c, needle, needlelen) == 0)
1975 return c;
1976 ++c;
1977 }
1978 return NULL;
1979}
1980
Willy Tarreau482b00d2009-10-04 22:48:42 +02001981/* This function returns the first unused key greater than or equal to <key> in
1982 * ID tree <root>. Zero is returned if no place is found.
1983 */
1984unsigned int get_next_id(struct eb_root *root, unsigned int key)
1985{
1986 struct eb32_node *used;
1987
1988 do {
1989 used = eb32_lookup_ge(root, key);
1990 if (!used || used->key > key)
1991 return key; /* key is available */
1992 key++;
1993 } while (key);
1994 return key;
1995}
1996
Willy Tarreau348238b2010-01-18 15:05:57 +01001997/* This function compares a sample word possibly followed by blanks to another
1998 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1999 * otherwise zero. This intends to be used when checking HTTP headers for some
2000 * values. Note that it validates a word followed only by blanks but does not
2001 * validate a word followed by blanks then other chars.
2002 */
2003int word_match(const char *sample, int slen, const char *word, int wlen)
2004{
2005 if (slen < wlen)
2006 return 0;
2007
2008 while (wlen) {
2009 char c = *sample ^ *word;
2010 if (c && c != ('A' ^ 'a'))
2011 return 0;
2012 sample++;
2013 word++;
2014 slen--;
2015 wlen--;
2016 }
2017
2018 while (slen) {
2019 if (*sample != ' ' && *sample != '\t')
2020 return 0;
2021 sample++;
2022 slen--;
2023 }
2024 return 1;
2025}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002026
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002027/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2028 * is particularly fast because it avoids expensive operations such as
2029 * multiplies, which are optimized away at the end. It requires a properly
2030 * formated address though (3 points).
2031 */
2032unsigned int inetaddr_host(const char *text)
2033{
2034 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2035 register unsigned int dig100, dig10, dig1;
2036 int s;
2037 const char *p, *d;
2038
2039 dig1 = dig10 = dig100 = ascii_zero;
2040 s = 24;
2041
2042 p = text;
2043 while (1) {
2044 if (((unsigned)(*p - '0')) <= 9) {
2045 p++;
2046 continue;
2047 }
2048
2049 /* here, we have a complete byte between <text> and <p> (exclusive) */
2050 if (p == text)
2051 goto end;
2052
2053 d = p - 1;
2054 dig1 |= (unsigned int)(*d << s);
2055 if (d == text)
2056 goto end;
2057
2058 d--;
2059 dig10 |= (unsigned int)(*d << s);
2060 if (d == text)
2061 goto end;
2062
2063 d--;
2064 dig100 |= (unsigned int)(*d << s);
2065 end:
2066 if (!s || *p != '.')
2067 break;
2068
2069 s -= 8;
2070 text = ++p;
2071 }
2072
2073 dig100 -= ascii_zero;
2074 dig10 -= ascii_zero;
2075 dig1 -= ascii_zero;
2076 return ((dig100 * 10) + dig10) * 10 + dig1;
2077}
2078
2079/*
2080 * Idem except the first unparsed character has to be passed in <stop>.
2081 */
2082unsigned int inetaddr_host_lim(const char *text, const char *stop)
2083{
2084 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2085 register unsigned int dig100, dig10, dig1;
2086 int s;
2087 const char *p, *d;
2088
2089 dig1 = dig10 = dig100 = ascii_zero;
2090 s = 24;
2091
2092 p = text;
2093 while (1) {
2094 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2095 p++;
2096 continue;
2097 }
2098
2099 /* here, we have a complete byte between <text> and <p> (exclusive) */
2100 if (p == text)
2101 goto end;
2102
2103 d = p - 1;
2104 dig1 |= (unsigned int)(*d << s);
2105 if (d == text)
2106 goto end;
2107
2108 d--;
2109 dig10 |= (unsigned int)(*d << s);
2110 if (d == text)
2111 goto end;
2112
2113 d--;
2114 dig100 |= (unsigned int)(*d << s);
2115 end:
2116 if (!s || p == stop || *p != '.')
2117 break;
2118
2119 s -= 8;
2120 text = ++p;
2121 }
2122
2123 dig100 -= ascii_zero;
2124 dig10 -= ascii_zero;
2125 dig1 -= ascii_zero;
2126 return ((dig100 * 10) + dig10) * 10 + dig1;
2127}
2128
2129/*
2130 * Idem except the pointer to first unparsed byte is returned into <ret> which
2131 * must not be NULL.
2132 */
Willy Tarreau74172752010-10-15 23:21:42 +02002133unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002134{
2135 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2136 register unsigned int dig100, dig10, dig1;
2137 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002138 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002139
2140 dig1 = dig10 = dig100 = ascii_zero;
2141 s = 24;
2142
2143 p = text;
2144 while (1) {
2145 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2146 p++;
2147 continue;
2148 }
2149
2150 /* here, we have a complete byte between <text> and <p> (exclusive) */
2151 if (p == text)
2152 goto end;
2153
2154 d = p - 1;
2155 dig1 |= (unsigned int)(*d << s);
2156 if (d == text)
2157 goto end;
2158
2159 d--;
2160 dig10 |= (unsigned int)(*d << s);
2161 if (d == text)
2162 goto end;
2163
2164 d--;
2165 dig100 |= (unsigned int)(*d << s);
2166 end:
2167 if (!s || p == stop || *p != '.')
2168 break;
2169
2170 s -= 8;
2171 text = ++p;
2172 }
2173
2174 *ret = p;
2175 dig100 -= ascii_zero;
2176 dig10 -= ascii_zero;
2177 dig1 -= ascii_zero;
2178 return ((dig100 * 10) + dig10) * 10 + dig1;
2179}
2180
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002181/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2182 * or the number of chars read in case of success. Maybe this could be replaced
2183 * by one of the functions above. Also, apparently this function does not support
2184 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002185 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002186 */
2187int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2188{
2189 const char *addr;
2190 int saw_digit, octets, ch;
2191 u_char tmp[4], *tp;
2192 const char *cp = buf;
2193
2194 saw_digit = 0;
2195 octets = 0;
2196 *(tp = tmp) = 0;
2197
2198 for (addr = buf; addr - buf < len; addr++) {
2199 unsigned char digit = (ch = *addr) - '0';
2200
2201 if (digit > 9 && ch != '.')
2202 break;
2203
2204 if (digit <= 9) {
2205 u_int new = *tp * 10 + digit;
2206
2207 if (new > 255)
2208 return 0;
2209
2210 *tp = new;
2211
2212 if (!saw_digit) {
2213 if (++octets > 4)
2214 return 0;
2215 saw_digit = 1;
2216 }
2217 } else if (ch == '.' && saw_digit) {
2218 if (octets == 4)
2219 return 0;
2220
2221 *++tp = 0;
2222 saw_digit = 0;
2223 } else
2224 return 0;
2225 }
2226
2227 if (octets < 4)
2228 return 0;
2229
2230 memcpy(&dst->s_addr, tmp, 4);
2231 return addr - cp;
2232}
2233
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002234/* This function converts the string in <buf> of the len <len> to
2235 * struct in6_addr <dst> which must be allocated by the caller.
2236 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002237 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002238 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002239int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2240{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002241 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002242 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002243
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002244 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002245 return 0;
2246
2247 memcpy(null_term_ip6, buf, len);
2248 null_term_ip6[len] = '\0';
2249
Willy Tarreau075415a2013-12-12 11:29:39 +01002250 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002251 return 0;
2252
Willy Tarreau075415a2013-12-12 11:29:39 +01002253 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002254 return 1;
2255}
2256
Willy Tarreauacf95772010-06-14 19:09:21 +02002257/* To be used to quote config arg positions. Returns the short string at <ptr>
2258 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2259 * if ptr is NULL or empty. The string is locally allocated.
2260 */
2261const char *quote_arg(const char *ptr)
2262{
2263 static char val[32];
2264 int i;
2265
2266 if (!ptr || !*ptr)
2267 return "end of line";
2268 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002269 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002270 val[i] = *ptr++;
2271 val[i++] = '\'';
2272 val[i] = '\0';
2273 return val;
2274}
2275
Willy Tarreau5b180202010-07-18 10:40:48 +02002276/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2277int get_std_op(const char *str)
2278{
2279 int ret = -1;
2280
2281 if (*str == 'e' && str[1] == 'q')
2282 ret = STD_OP_EQ;
2283 else if (*str == 'n' && str[1] == 'e')
2284 ret = STD_OP_NE;
2285 else if (*str == 'l') {
2286 if (str[1] == 'e') ret = STD_OP_LE;
2287 else if (str[1] == 't') ret = STD_OP_LT;
2288 }
2289 else if (*str == 'g') {
2290 if (str[1] == 'e') ret = STD_OP_GE;
2291 else if (str[1] == 't') ret = STD_OP_GT;
2292 }
2293
2294 if (ret == -1 || str[2] != '\0')
2295 return -1;
2296 return ret;
2297}
2298
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002299/* hash a 32-bit integer to another 32-bit integer */
2300unsigned int full_hash(unsigned int a)
2301{
2302 return __full_hash(a);
2303}
2304
David du Colombier4f92d322011-03-24 11:09:31 +01002305/* Return non-zero if IPv4 address is part of the network,
2306 * otherwise zero.
2307 */
2308int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
2309{
2310 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
2311}
2312
2313/* Return non-zero if IPv6 address is part of the network,
2314 * otherwise zero.
2315 */
2316int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
2317{
2318 int i;
2319
2320 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2321 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2322 (((int *)net)[i] & ((int *)mask)[i]))
2323 return 0;
2324 return 1;
2325}
2326
2327/* RFC 4291 prefix */
2328const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2329 0x00, 0x00, 0x00, 0x00,
2330 0x00, 0x00, 0xFF, 0xFF };
2331
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002332/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2333 * Input and output may overlap.
2334 */
David du Colombier4f92d322011-03-24 11:09:31 +01002335void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2336{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002337 struct in_addr tmp_addr;
2338
2339 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002340 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002341 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002342}
2343
2344/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2345 * Return true if conversion is possible and false otherwise.
2346 */
2347int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2348{
2349 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2350 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2351 sizeof(struct in_addr));
2352 return 1;
2353 }
2354
2355 return 0;
2356}
2357
William Lallemand421f5b52012-02-06 18:15:57 +01002358char *human_time(int t, short hz_div) {
2359 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2360 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002361 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002362 int cnt=2; // print two numbers
2363
2364 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002365 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002366 return rv;
2367 }
2368
2369 if (unlikely(hz_div > 1))
2370 t /= hz_div;
2371
2372 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002373 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002374 cnt--;
2375 }
2376
2377 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002378 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002379 cnt--;
2380 }
2381
2382 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002383 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002384 cnt--;
2385 }
2386
2387 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002388 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002389
2390 return rv;
2391}
2392
2393const char *monthname[12] = {
2394 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2395 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2396};
2397
2398/* date2str_log: write a date in the format :
2399 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2400 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2401 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2402 *
2403 * without using sprintf. return a pointer to the last char written (\0) or
2404 * NULL if there isn't enough space.
2405 */
2406char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2407{
2408
2409 if (size < 25) /* the size is fixed: 24 chars + \0 */
2410 return NULL;
2411
2412 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2413 *dst++ = '/';
2414 memcpy(dst, monthname[tm->tm_mon], 3); // month
2415 dst += 3;
2416 *dst++ = '/';
2417 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2418 *dst++ = ':';
2419 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2420 *dst++ = ':';
2421 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2422 *dst++ = ':';
2423 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2424 *dst++ = '.';
2425 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2426 dst += 3; // only the 3 first digits
2427 *dst = '\0';
2428
2429 return dst;
2430}
2431
2432/* gmt2str_log: write a date in the format :
2433 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2434 * return a pointer to the last char written (\0) or
2435 * NULL if there isn't enough space.
2436 */
2437char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2438{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002439 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002440 return NULL;
2441
2442 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2443 *dst++ = '/';
2444 memcpy(dst, monthname[tm->tm_mon], 3); // month
2445 dst += 3;
2446 *dst++ = '/';
2447 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2448 *dst++ = ':';
2449 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2450 *dst++ = ':';
2451 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2452 *dst++ = ':';
2453 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2454 *dst++ = ' ';
2455 *dst++ = '+';
2456 *dst++ = '0';
2457 *dst++ = '0';
2458 *dst++ = '0';
2459 *dst++ = '0';
2460 *dst = '\0';
2461
2462 return dst;
2463}
2464
Yuxans Yao4e25b012012-10-19 10:36:09 +08002465/* localdate2str_log: write a date in the format :
2466 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2467 * * return a pointer to the last char written (\0) or
2468 * * NULL if there isn't enough space.
2469 */
2470char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2471{
2472 if (size < 27) /* the size is fixed: 26 chars + \0 */
2473 return NULL;
2474
2475 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2476 *dst++ = '/';
2477 memcpy(dst, monthname[tm->tm_mon], 3); // month
2478 dst += 3;
2479 *dst++ = '/';
2480 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2481 *dst++ = ':';
2482 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2483 *dst++ = ':';
2484 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2485 *dst++ = ':';
2486 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2487 *dst++ = ' ';
2488 memcpy(dst, localtimezone, 5); // timezone
2489 dst += 5;
2490 *dst = '\0';
2491
2492 return dst;
2493}
2494
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002495/* Dynamically allocates a string of the proper length to hold the formatted
2496 * output. NULL is returned on error. The caller is responsible for freeing the
2497 * memory area using free(). The resulting string is returned in <out> if the
2498 * pointer is not NULL. A previous version of <out> might be used to build the
2499 * new string, and it will be freed before returning if it is not NULL, which
2500 * makes it possible to build complex strings from iterative calls without
2501 * having to care about freeing intermediate values, as in the example below :
2502 *
2503 * memprintf(&err, "invalid argument: '%s'", arg);
2504 * ...
2505 * memprintf(&err, "parser said : <%s>\n", *err);
2506 * ...
2507 * free(*err);
2508 *
2509 * This means that <err> must be initialized to NULL before first invocation.
2510 * The return value also holds the allocated string, which eases error checking
2511 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002512 * passed instead and it will be ignored. The returned message will then also
2513 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002514 *
2515 * It is also convenient to use it without any free except the last one :
2516 * err = NULL;
2517 * if (!fct1(err)) report(*err);
2518 * if (!fct2(err)) report(*err);
2519 * if (!fct3(err)) report(*err);
2520 * free(*err);
2521 */
2522char *memprintf(char **out, const char *format, ...)
2523{
2524 va_list args;
2525 char *ret = NULL;
2526 int allocated = 0;
2527 int needed = 0;
2528
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002529 if (!out)
2530 return NULL;
2531
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002532 do {
2533 /* vsnprintf() will return the required length even when the
2534 * target buffer is NULL. We do this in a loop just in case
2535 * intermediate evaluations get wrong.
2536 */
2537 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002538 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002539 va_end(args);
2540
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002541 if (needed < allocated) {
2542 /* Note: on Solaris 8, the first iteration always
2543 * returns -1 if allocated is zero, so we force a
2544 * retry.
2545 */
2546 if (!allocated)
2547 needed = 0;
2548 else
2549 break;
2550 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002551
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002552 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002553 ret = realloc(ret, allocated);
2554 } while (ret);
2555
2556 if (needed < 0) {
2557 /* an error was encountered */
2558 free(ret);
2559 ret = NULL;
2560 }
2561
2562 if (out) {
2563 free(*out);
2564 *out = ret;
2565 }
2566
2567 return ret;
2568}
William Lallemand421f5b52012-02-06 18:15:57 +01002569
Willy Tarreau21c705b2012-09-14 11:40:36 +02002570/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2571 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002572 * freed by the caller. It also supports being passed a NULL which results in the same
2573 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002574 * Example of use :
2575 * parse(cmd, &err); (callee: memprintf(&err, ...))
2576 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2577 * free(err);
2578 */
2579char *indent_msg(char **out, int level)
2580{
2581 char *ret, *in, *p;
2582 int needed = 0;
2583 int lf = 0;
2584 int lastlf = 0;
2585 int len;
2586
Willy Tarreau70eec382012-10-10 08:56:47 +02002587 if (!out || !*out)
2588 return NULL;
2589
Willy Tarreau21c705b2012-09-14 11:40:36 +02002590 in = *out - 1;
2591 while ((in = strchr(in + 1, '\n')) != NULL) {
2592 lastlf = in - *out;
2593 lf++;
2594 }
2595
2596 if (!lf) /* single line, no LF, return it as-is */
2597 return *out;
2598
2599 len = strlen(*out);
2600
2601 if (lf == 1 && lastlf == len - 1) {
2602 /* single line, LF at end, strip it and return as-is */
2603 (*out)[lastlf] = 0;
2604 return *out;
2605 }
2606
2607 /* OK now we have at least one LF, we need to process the whole string
2608 * as a multi-line string. What we'll do :
2609 * - prefix with an LF if there is none
2610 * - add <level> spaces before each line
2611 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2612 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2613 */
2614
2615 needed = 1 + level * (lf + 1) + len + 1;
2616 p = ret = malloc(needed);
2617 in = *out;
2618
2619 /* skip initial LFs */
2620 while (*in == '\n')
2621 in++;
2622
2623 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2624 while (*in) {
2625 *p++ = '\n';
2626 memset(p, ' ', level);
2627 p += level;
2628 do {
2629 *p++ = *in++;
2630 } while (*in && *in != '\n');
2631 if (*in)
2632 in++;
2633 }
2634 *p = 0;
2635
2636 free(*out);
2637 *out = ret;
2638
2639 return ret;
2640}
2641
Willy Tarreaudad36a32013-03-11 01:20:04 +01002642/* Convert occurrences of environment variables in the input string to their
2643 * corresponding value. A variable is identified as a series of alphanumeric
2644 * characters or underscores following a '$' sign. The <in> string must be
2645 * free()able. NULL returns NULL. The resulting string might be reallocated if
2646 * some expansion is made. Variable names may also be enclosed into braces if
2647 * needed (eg: to concatenate alphanum characters).
2648 */
2649char *env_expand(char *in)
2650{
2651 char *txt_beg;
2652 char *out;
2653 char *txt_end;
2654 char *var_beg;
2655 char *var_end;
2656 char *value;
2657 char *next;
2658 int out_len;
2659 int val_len;
2660
2661 if (!in)
2662 return in;
2663
2664 value = out = NULL;
2665 out_len = 0;
2666
2667 txt_beg = in;
2668 do {
2669 /* look for next '$' sign in <in> */
2670 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2671
2672 if (!*txt_end && !out) /* end and no expansion performed */
2673 return in;
2674
2675 val_len = 0;
2676 next = txt_end;
2677 if (*txt_end == '$') {
2678 char save;
2679
2680 var_beg = txt_end + 1;
2681 if (*var_beg == '{')
2682 var_beg++;
2683
2684 var_end = var_beg;
2685 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2686 var_end++;
2687 }
2688
2689 next = var_end;
2690 if (*var_end == '}' && (var_beg > txt_end + 1))
2691 next++;
2692
2693 /* get value of the variable name at this location */
2694 save = *var_end;
2695 *var_end = '\0';
2696 value = getenv(var_beg);
2697 *var_end = save;
2698 val_len = value ? strlen(value) : 0;
2699 }
2700
2701 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2702 if (txt_end > txt_beg) {
2703 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2704 out_len += txt_end - txt_beg;
2705 }
2706 if (val_len) {
2707 memcpy(out + out_len, value, val_len);
2708 out_len += val_len;
2709 }
2710 out[out_len] = 0;
2711 txt_beg = next;
2712 } while (*txt_beg);
2713
2714 /* here we know that <out> was allocated and that we don't need <in> anymore */
2715 free(in);
2716 return out;
2717}
2718
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002719
2720/* same as strstr() but case-insensitive and with limit length */
2721const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2722{
2723 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02002724 unsigned int slen, plen;
2725 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002726
2727 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2728 return NULL;
2729
2730 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2731 return str1;
2732
2733 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2734 return NULL;
2735
2736 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2737 while (toupper(*start) != toupper(*str2)) {
2738 start++;
2739 slen--;
2740 tmp1++;
2741
2742 if (tmp1 >= len_str1)
2743 return NULL;
2744
2745 /* if pattern longer than string */
2746 if (slen < plen)
2747 return NULL;
2748 }
2749
2750 sptr = start;
2751 pptr = (char *)str2;
2752
2753 tmp2 = 0;
2754 while (toupper(*sptr) == toupper(*pptr)) {
2755 sptr++;
2756 pptr++;
2757 tmp2++;
2758
2759 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2760 return start;
2761 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2762 return NULL;
2763 }
2764 }
2765 return NULL;
2766}
2767
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02002768/* This function read the next valid utf8 char.
2769 * <s> is the byte srray to be decode, <len> is its length.
2770 * The function returns decoded char encoded like this:
2771 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
2772 * are the length read. The decoded character is stored in <c>.
2773 */
2774unsigned char utf8_next(const char *s, int len, unsigned int *c)
2775{
2776 const unsigned char *p = (unsigned char *)s;
2777 int dec;
2778 unsigned char code = UTF8_CODE_OK;
2779
2780 if (len < 1)
2781 return UTF8_CODE_OK;
2782
2783 /* Check the type of UTF8 sequence
2784 *
2785 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
2786 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
2787 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
2788 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
2789 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
2790 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
2791 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
2792 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
2793 */
2794 switch (*p) {
2795 case 0x00 ... 0x7f:
2796 *c = *p;
2797 return UTF8_CODE_OK | 1;
2798
2799 case 0x80 ... 0xbf:
2800 *c = *p;
2801 return UTF8_CODE_BADSEQ | 1;
2802
2803 case 0xc0 ... 0xdf:
2804 if (len < 2) {
2805 *c = *p;
2806 return UTF8_CODE_BADSEQ | 1;
2807 }
2808 *c = *p & 0x1f;
2809 dec = 1;
2810 break;
2811
2812 case 0xe0 ... 0xef:
2813 if (len < 3) {
2814 *c = *p;
2815 return UTF8_CODE_BADSEQ | 1;
2816 }
2817 *c = *p & 0x0f;
2818 dec = 2;
2819 break;
2820
2821 case 0xf0 ... 0xf7:
2822 if (len < 4) {
2823 *c = *p;
2824 return UTF8_CODE_BADSEQ | 1;
2825 }
2826 *c = *p & 0x07;
2827 dec = 3;
2828 break;
2829
2830 case 0xf8 ... 0xfb:
2831 if (len < 5) {
2832 *c = *p;
2833 return UTF8_CODE_BADSEQ | 1;
2834 }
2835 *c = *p & 0x03;
2836 dec = 4;
2837 break;
2838
2839 case 0xfc ... 0xfd:
2840 if (len < 6) {
2841 *c = *p;
2842 return UTF8_CODE_BADSEQ | 1;
2843 }
2844 *c = *p & 0x01;
2845 dec = 5;
2846 break;
2847
2848 case 0xfe ... 0xff:
2849 default:
2850 *c = *p;
2851 return UTF8_CODE_BADSEQ | 1;
2852 }
2853
2854 p++;
2855
2856 while (dec > 0) {
2857
2858 /* need 0x10 for the 2 first bits */
2859 if ( ( *p & 0xc0 ) != 0x80 )
2860 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
2861
2862 /* add data at char */
2863 *c = ( *c << 6 ) | ( *p & 0x3f );
2864
2865 dec--;
2866 p++;
2867 }
2868
2869 /* Check ovelong encoding.
2870 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
2871 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
2872 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
2873 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01002874 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02002875 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
2876 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
2877 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
2878 code |= UTF8_CODE_OVERLONG;
2879
2880 /* Check invalid UTF8 range. */
2881 if ((*c >= 0xd800 && *c <= 0xdfff) ||
2882 (*c >= 0xfffe && *c <= 0xffff))
2883 code |= UTF8_CODE_INVRANGE;
2884
2885 return code | ((p-(unsigned char *)s)&0x0f);
2886}
2887
Willy Tarreaubaaee002006-06-26 02:48:02 +02002888/*
2889 * Local variables:
2890 * c-indent-level: 8
2891 * c-basic-offset: 8
2892 * End:
2893 */