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