blob: 67c82c7304b460e03fe7dc6761bdd514f283cb98 [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>
Thierry Fournier93127942016-01-20 18:49:45 +010019#include <time.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010020#include <sys/socket.h>
21#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020022#include <netinet/in.h>
23#include <arpa/inet.h>
24
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010025#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020026#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020027#include <common/standard.h>
Thierry Fournier93127942016-01-20 18:49:45 +010028#include <common/tools.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010029#include <types/global.h>
Baptiste Assmanna68ca962015-04-14 01:15:08 +020030#include <proto/dns.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010031#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032
Thierry Fournier93127942016-01-20 18:49:45 +010033/* This macro returns false if the test __x is false. Many
34 * of the following parsing function must be abort the processing
35 * if it returns 0, so this macro is useful for writing light code.
36 */
37#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
38
Willy Tarreau56adcf22012-12-23 18:00:29 +010039/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020040 * 2^64-1 = 18446744073709551615 or
41 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020042 *
43 * The HTML version needs room for adding the 25 characters
44 * '<span class="rls"></span>' around digits at positions 3N+1 in order
45 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020046 */
Willy Tarreau56adcf22012-12-23 18:00:29 +010047char itoa_str[NB_ITOA_STR][171];
48int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020049
Willy Tarreau588297f2014-06-16 15:16:40 +020050/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
51 * to quote strings larger than a max configuration line.
52 */
53char quoted_str[NB_QSTR][QSTR_SIZE + 1];
54int quoted_idx = 0;
55
Willy Tarreaubaaee002006-06-26 02:48:02 +020056/*
William Lallemande7340ec2012-01-24 11:15:39 +010057 * unsigned long long ASCII representation
58 *
59 * return the last char '\0' or NULL if no enough
60 * space in dst
61 */
62char *ulltoa(unsigned long long n, char *dst, size_t size)
63{
64 int i = 0;
65 char *res;
66
67 switch(n) {
68 case 1ULL ... 9ULL:
69 i = 0;
70 break;
71
72 case 10ULL ... 99ULL:
73 i = 1;
74 break;
75
76 case 100ULL ... 999ULL:
77 i = 2;
78 break;
79
80 case 1000ULL ... 9999ULL:
81 i = 3;
82 break;
83
84 case 10000ULL ... 99999ULL:
85 i = 4;
86 break;
87
88 case 100000ULL ... 999999ULL:
89 i = 5;
90 break;
91
92 case 1000000ULL ... 9999999ULL:
93 i = 6;
94 break;
95
96 case 10000000ULL ... 99999999ULL:
97 i = 7;
98 break;
99
100 case 100000000ULL ... 999999999ULL:
101 i = 8;
102 break;
103
104 case 1000000000ULL ... 9999999999ULL:
105 i = 9;
106 break;
107
108 case 10000000000ULL ... 99999999999ULL:
109 i = 10;
110 break;
111
112 case 100000000000ULL ... 999999999999ULL:
113 i = 11;
114 break;
115
116 case 1000000000000ULL ... 9999999999999ULL:
117 i = 12;
118 break;
119
120 case 10000000000000ULL ... 99999999999999ULL:
121 i = 13;
122 break;
123
124 case 100000000000000ULL ... 999999999999999ULL:
125 i = 14;
126 break;
127
128 case 1000000000000000ULL ... 9999999999999999ULL:
129 i = 15;
130 break;
131
132 case 10000000000000000ULL ... 99999999999999999ULL:
133 i = 16;
134 break;
135
136 case 100000000000000000ULL ... 999999999999999999ULL:
137 i = 17;
138 break;
139
140 case 1000000000000000000ULL ... 9999999999999999999ULL:
141 i = 18;
142 break;
143
144 case 10000000000000000000ULL ... ULLONG_MAX:
145 i = 19;
146 break;
147 }
148 if (i + 2 > size) // (i + 1) + '\0'
149 return NULL; // too long
150 res = dst + i + 1;
151 *res = '\0';
152 for (; i >= 0; i--) {
153 dst[i] = n % 10ULL + '0';
154 n /= 10ULL;
155 }
156 return res;
157}
158
159/*
160 * unsigned long ASCII representation
161 *
162 * return the last char '\0' or NULL if no enough
163 * space in dst
164 */
165char *ultoa_o(unsigned long n, char *dst, size_t size)
166{
167 int i = 0;
168 char *res;
169
170 switch (n) {
171 case 0U ... 9UL:
172 i = 0;
173 break;
174
175 case 10U ... 99UL:
176 i = 1;
177 break;
178
179 case 100U ... 999UL:
180 i = 2;
181 break;
182
183 case 1000U ... 9999UL:
184 i = 3;
185 break;
186
187 case 10000U ... 99999UL:
188 i = 4;
189 break;
190
191 case 100000U ... 999999UL:
192 i = 5;
193 break;
194
195 case 1000000U ... 9999999UL:
196 i = 6;
197 break;
198
199 case 10000000U ... 99999999UL:
200 i = 7;
201 break;
202
203 case 100000000U ... 999999999UL:
204 i = 8;
205 break;
206#if __WORDSIZE == 32
207
208 case 1000000000ULL ... ULONG_MAX:
209 i = 9;
210 break;
211
212#elif __WORDSIZE == 64
213
214 case 1000000000ULL ... 9999999999UL:
215 i = 9;
216 break;
217
218 case 10000000000ULL ... 99999999999UL:
219 i = 10;
220 break;
221
222 case 100000000000ULL ... 999999999999UL:
223 i = 11;
224 break;
225
226 case 1000000000000ULL ... 9999999999999UL:
227 i = 12;
228 break;
229
230 case 10000000000000ULL ... 99999999999999UL:
231 i = 13;
232 break;
233
234 case 100000000000000ULL ... 999999999999999UL:
235 i = 14;
236 break;
237
238 case 1000000000000000ULL ... 9999999999999999UL:
239 i = 15;
240 break;
241
242 case 10000000000000000ULL ... 99999999999999999UL:
243 i = 16;
244 break;
245
246 case 100000000000000000ULL ... 999999999999999999UL:
247 i = 17;
248 break;
249
250 case 1000000000000000000ULL ... 9999999999999999999UL:
251 i = 18;
252 break;
253
254 case 10000000000000000000ULL ... ULONG_MAX:
255 i = 19;
256 break;
257
258#endif
259 }
260 if (i + 2 > size) // (i + 1) + '\0'
261 return NULL; // too long
262 res = dst + i + 1;
263 *res = '\0';
264 for (; i >= 0; i--) {
265 dst[i] = n % 10U + '0';
266 n /= 10U;
267 }
268 return res;
269}
270
271/*
272 * signed long ASCII representation
273 *
274 * return the last char '\0' or NULL if no enough
275 * space in dst
276 */
277char *ltoa_o(long int n, char *dst, size_t size)
278{
279 char *pos = dst;
280
281 if (n < 0) {
282 if (size < 3)
283 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
284 *pos = '-';
285 pos++;
286 dst = ultoa_o(-n, pos, size - 1);
287 } else {
288 dst = ultoa_o(n, dst, size);
289 }
290 return dst;
291}
292
293/*
294 * signed long long ASCII representation
295 *
296 * return the last char '\0' or NULL if no enough
297 * space in dst
298 */
299char *lltoa(long long n, char *dst, size_t size)
300{
301 char *pos = dst;
302
303 if (n < 0) {
304 if (size < 3)
305 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
306 *pos = '-';
307 pos++;
308 dst = ulltoa(-n, pos, size - 1);
309 } else {
310 dst = ulltoa(n, dst, size);
311 }
312 return dst;
313}
314
315/*
316 * write a ascii representation of a unsigned into dst,
317 * return a pointer to the last character
318 * Pad the ascii representation with '0', using size.
319 */
320char *utoa_pad(unsigned int n, char *dst, size_t size)
321{
322 int i = 0;
323 char *ret;
324
325 switch(n) {
326 case 0U ... 9U:
327 i = 0;
328 break;
329
330 case 10U ... 99U:
331 i = 1;
332 break;
333
334 case 100U ... 999U:
335 i = 2;
336 break;
337
338 case 1000U ... 9999U:
339 i = 3;
340 break;
341
342 case 10000U ... 99999U:
343 i = 4;
344 break;
345
346 case 100000U ... 999999U:
347 i = 5;
348 break;
349
350 case 1000000U ... 9999999U:
351 i = 6;
352 break;
353
354 case 10000000U ... 99999999U:
355 i = 7;
356 break;
357
358 case 100000000U ... 999999999U:
359 i = 8;
360 break;
361
362 case 1000000000U ... 4294967295U:
363 i = 9;
364 break;
365 }
366 if (i + 2 > size) // (i + 1) + '\0'
367 return NULL; // too long
368 if (i < size)
369 i = size - 2; // padding - '\0'
370
371 ret = dst + i + 1;
372 *ret = '\0';
373 for (; i >= 0; i--) {
374 dst[i] = n % 10U + '0';
375 n /= 10U;
376 }
377 return ret;
378}
379
380/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200381 * copies at most <size-1> chars from <src> to <dst>. Last char is always
382 * set to 0, unless <size> is 0. The number of chars copied is returned
383 * (excluding the terminating zero).
384 * This code has been optimized for size and speed : on x86, it's 45 bytes
385 * long, uses only registers, and consumes only 4 cycles per char.
386 */
387int strlcpy2(char *dst, const char *src, int size)
388{
389 char *orig = dst;
390 if (size) {
391 while (--size && (*dst = *src)) {
392 src++; dst++;
393 }
394 *dst = 0;
395 }
396 return dst - orig;
397}
398
399/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200400 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200401 * the ascii representation for number 'n' in decimal.
402 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100403char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404{
405 char *pos;
406
Willy Tarreau72d759c2007-10-25 12:14:10 +0200407 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200408 *pos-- = '\0';
409
410 do {
411 *pos-- = '0' + n % 10;
412 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200413 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200414 return pos + 1;
415}
416
Willy Tarreau91092e52007-10-25 16:58:42 +0200417/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200418 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200419 * the ascii representation for number 'n' in decimal.
420 */
421char *lltoa_r(long long int in, char *buffer, int size)
422{
423 char *pos;
424 int neg = 0;
425 unsigned long long int n;
426
427 pos = buffer + size - 1;
428 *pos-- = '\0';
429
430 if (in < 0) {
431 neg = 1;
432 n = -in;
433 }
434 else
435 n = in;
436
437 do {
438 *pos-- = '0' + n % 10;
439 n /= 10;
440 } while (n && pos >= buffer);
441 if (neg && pos > buffer)
442 *pos-- = '-';
443 return pos + 1;
444}
445
446/*
447 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200448 * the ascii representation for signed number 'n' in decimal.
449 */
450char *sltoa_r(long n, char *buffer, int size)
451{
452 char *pos;
453
454 if (n >= 0)
455 return ultoa_r(n, buffer, size);
456
457 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
458 *pos = '-';
459 return pos;
460}
461
462/*
463 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200464 * the ascii representation for number 'n' in decimal, formatted for
465 * HTML output with tags to create visual grouping by 3 digits. The
466 * output needs to support at least 171 characters.
467 */
468const char *ulltoh_r(unsigned long long n, char *buffer, int size)
469{
470 char *start;
471 int digit = 0;
472
473 start = buffer + size;
474 *--start = '\0';
475
476 do {
477 if (digit == 3 && start >= buffer + 7)
478 memcpy(start -= 7, "</span>", 7);
479
480 if (start >= buffer + 1) {
481 *--start = '0' + n % 10;
482 n /= 10;
483 }
484
485 if (digit == 3 && start >= buffer + 18)
486 memcpy(start -= 18, "<span class=\"rls\">", 18);
487
488 if (digit++ == 3)
489 digit = 1;
490 } while (n && start > buffer);
491 return start;
492}
493
494/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200495 * This function simply returns a locally allocated string containing the ascii
496 * representation for number 'n' in decimal, unless n is 0 in which case it
497 * returns the alternate string (or an empty string if the alternate string is
498 * NULL). It use is intended for limits reported in reports, where it's
499 * desirable not to display anything if there is no limit. Warning! it shares
500 * the same vector as ultoa_r().
501 */
502const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
503{
504 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
505}
506
Willy Tarreau588297f2014-06-16 15:16:40 +0200507/* returns a locally allocated string containing the quoted encoding of the
508 * input string. The output may be truncated to QSTR_SIZE chars, but it is
509 * guaranteed that the string will always be properly terminated. Quotes are
510 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
511 * always be at least 4 chars.
512 */
513const char *qstr(const char *str)
514{
515 char *ret = quoted_str[quoted_idx];
516 char *p, *end;
517
518 if (++quoted_idx >= NB_QSTR)
519 quoted_idx = 0;
520
521 p = ret;
522 end = ret + QSTR_SIZE;
523
524 *p++ = '"';
525
526 /* always keep 3 chars to support passing "" and the ending " */
527 while (*str && p < end - 3) {
528 if (*str == '"') {
529 *p++ = '"';
530 *p++ = '"';
531 }
532 else
533 *p++ = *str;
534 str++;
535 }
536 *p++ = '"';
537 return ret;
538}
539
Robert Tsai81ae1952007-12-05 10:47:29 +0100540/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200541 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
542 *
543 * It looks like this one would be a good candidate for inlining, but this is
544 * not interesting because it around 35 bytes long and often called multiple
545 * times within the same function.
546 */
547int ishex(char s)
548{
549 s -= '0';
550 if ((unsigned char)s <= 9)
551 return 1;
552 s -= 'A' - '0';
553 if ((unsigned char)s <= 5)
554 return 1;
555 s -= 'a' - 'A';
556 if ((unsigned char)s <= 5)
557 return 1;
558 return 0;
559}
560
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100561/* rounds <i> down to the closest value having max 2 digits */
562unsigned int round_2dig(unsigned int i)
563{
564 unsigned int mul = 1;
565
566 while (i >= 100) {
567 i /= 10;
568 mul *= 10;
569 }
570 return i * mul;
571}
572
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100573/*
574 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
575 * invalid character is found, a pointer to it is returned. If everything is
576 * fine, NULL is returned.
577 */
578const char *invalid_char(const char *name)
579{
580 if (!*name)
581 return name;
582
583 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100584 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100585 *name != '_' && *name != '-')
586 return name;
587 name++;
588 }
589 return NULL;
590}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200591
592/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200593 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
594 * If an invalid character is found, a pointer to it is returned.
595 * If everything is fine, NULL is returned.
596 */
597const char *invalid_domainchar(const char *name) {
598
599 if (!*name)
600 return name;
601
602 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100603 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200604 *name != '_' && *name != '-')
605 return name;
606
607 name++;
608 }
609
610 return NULL;
611}
612
613/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100614 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100615 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
616 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
617 * the function tries to guess the address family from the syntax. If the
618 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100619 * string is assumed to contain only an address, no port. The address can be a
620 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
621 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
622 * The return address will only have the address family and the address set,
623 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100624 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
625 * is resolved, otherwise only IP addresses are resolved, and anything else
626 * returns NULL.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200627 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100628struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200629{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100630 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100631 /* max IPv6 length, including brackets and terminating NULL */
632 char tmpip[48];
633
634 /* check IPv6 with square brackets */
635 if (str[0] == '[') {
636 size_t iplength = strlen(str);
637
638 if (iplength < 4) {
639 /* minimal size is 4 when using brackets "[::]" */
640 goto fail;
641 }
642 else if (iplength >= sizeof(tmpip)) {
643 /* IPv6 literal can not be larger than tmpip */
644 goto fail;
645 }
646 else {
647 if (str[iplength - 1] != ']') {
648 /* if address started with bracket, it should end with bracket */
649 goto fail;
650 }
651 else {
652 memcpy(tmpip, str + 1, iplength - 2);
653 tmpip[iplength - 2] = '\0';
654 str = tmpip;
655 }
656 }
657 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100658
Willy Tarreaufab5a432011-03-04 15:31:53 +0100659 /* Any IPv6 address */
660 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100661 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
662 sa->ss_family = AF_INET6;
663 else if (sa->ss_family != AF_INET6)
664 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100665 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100666 }
667
Willy Tarreau24709282013-03-10 21:32:12 +0100668 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100669 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100670 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
671 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100672 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100673 }
674
675 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100676 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
677 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100678 sa->ss_family = AF_INET6;
679 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100680 }
681
682 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100683 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
684 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100685 sa->ss_family = AF_INET;
686 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100687 }
688
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100689 if (!resolve)
690 return NULL;
691
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200692 if (!dns_hostname_validation(str, NULL))
693 return NULL;
694
David du Colombierd5f43282011-03-17 10:40:16 +0100695#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200696 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100697 struct addrinfo hints, *result;
698
699 memset(&result, 0, sizeof(result));
700 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100701 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100702 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200703 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100704 hints.ai_protocol = 0;
705
706 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100707 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
708 sa->ss_family = result->ai_family;
709 else if (sa->ss_family != result->ai_family)
710 goto fail;
711
David du Colombierd5f43282011-03-17 10:40:16 +0100712 switch (result->ai_family) {
713 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100714 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
715 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100716 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100717 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
718 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100719 }
720 }
721
Sean Carey58ea0392013-02-15 23:39:18 +0100722 if (result)
723 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100724 }
David du Colombierd5f43282011-03-17 10:40:16 +0100725#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200726 /* try to resolve an IPv4/IPv6 hostname */
727 he = gethostbyname(str);
728 if (he) {
729 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
730 sa->ss_family = he->h_addrtype;
731 else if (sa->ss_family != he->h_addrtype)
732 goto fail;
733
734 switch (sa->ss_family) {
735 case AF_INET:
736 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
737 return sa;
738 case AF_INET6:
739 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
740 return sa;
741 }
742 }
743
David du Colombierd5f43282011-03-17 10:40:16 +0100744 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100745 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100746 return NULL;
747}
748
749/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100750 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
751 * range or offset consisting in two integers that the caller will have to
752 * check to find the relevant input format. The following format are supported :
753 *
754 * String format | address | port | low | high
755 * addr | <addr> | 0 | 0 | 0
756 * addr: | <addr> | 0 | 0 | 0
757 * addr:port | <addr> | <port> | <port> | <port>
758 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
759 * addr:+port | <addr> | <port> | 0 | <port>
760 * addr:-port | <addr> |-<port> | <port> | 0
761 *
762 * The detection of a port range or increment by the caller is made by
763 * comparing <low> and <high>. If both are equal, then port 0 means no port
764 * was specified. The caller may pass NULL for <low> and <high> if it is not
765 * interested in retrieving port ranges.
766 *
767 * Note that <addr> above may also be :
768 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
769 * - "*" => family will be AF_INET and address will be INADDR_ANY
770 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
771 * - a host name => family and address will depend on host name resolving.
772 *
Willy Tarreau24709282013-03-10 21:32:12 +0100773 * A prefix may be passed in before the address above to force the family :
774 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
775 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
776 * - "unix@" => force address to be a path to a UNIX socket even if the
777 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200778 * - 'abns@' -> force address to belong to the abstract namespace (Linux
779 * only). These sockets are just like Unix sockets but without
780 * the need for an underlying file system. The address is a
781 * string. Technically it's like a Unix socket with a zero in
782 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100783 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100784 *
mildisff5d5102015-10-26 18:50:08 +0100785 * IPv6 addresses can be declared with or without square brackets. When using
786 * square brackets for IPv6 addresses, the port separator (colon) is optional.
787 * If not using square brackets, and in order to avoid any ambiguity with
788 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
789 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
790 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100791 *
792 * If <pfx> is non-null, it is used as a string prefix before any path-based
793 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100794 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200795 * if <fqdn> is non-null, it will be filled with :
796 * - a pointer to the FQDN of the server name to resolve if there's one, and
797 * that the caller will have to free(),
798 * - NULL if there was an explicit address that doesn't require resolution.
799 *
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200800 * Hostnames are only resolved if <resolve> is non-null.
801 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100802 * When a file descriptor is passed, its value is put into the s_addr part of
803 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100804 */
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200805struct 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 +0100806{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100807 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100808 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100809 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100810 char *port1, *port2;
811 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200812 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100813
814 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200815 if (fqdn)
816 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200817
Willy Tarreaudad36a32013-03-11 01:20:04 +0100818 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100819 if (str2 == NULL) {
820 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100821 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100822 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200823
Willy Tarreau9f69f462015-09-08 16:01:25 +0200824 if (!*str2) {
825 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
826 goto out;
827 }
828
Willy Tarreau24709282013-03-10 21:32:12 +0100829 memset(&ss, 0, sizeof(ss));
830
831 if (strncmp(str2, "unix@", 5) == 0) {
832 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200833 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100834 ss.ss_family = AF_UNIX;
835 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200836 else if (strncmp(str2, "abns@", 5) == 0) {
837 str2 += 5;
838 abstract = 1;
839 ss.ss_family = AF_UNIX;
840 }
Willy Tarreau24709282013-03-10 21:32:12 +0100841 else if (strncmp(str2, "ipv4@", 5) == 0) {
842 str2 += 5;
843 ss.ss_family = AF_INET;
844 }
845 else if (strncmp(str2, "ipv6@", 5) == 0) {
846 str2 += 5;
847 ss.ss_family = AF_INET6;
848 }
849 else if (*str2 == '/') {
850 ss.ss_family = AF_UNIX;
851 }
852 else
853 ss.ss_family = AF_UNSPEC;
854
Willy Tarreau40aa0702013-03-10 23:51:38 +0100855 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
856 char *endptr;
857
858 str2 += 3;
859 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
860
861 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100862 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100863 goto out;
864 }
865
866 /* we return AF_UNSPEC if we use a file descriptor number */
867 ss.ss_family = AF_UNSPEC;
868 }
869 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100870 int prefix_path_len;
871 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200872 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100873
874 /* complete unix socket path name during startup or soft-restart is
875 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
876 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200877 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100878 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
879 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
880
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200881 adr_len = strlen(str2);
882 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100883 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
884 goto out;
885 }
886
Willy Tarreauccfccef2014-05-10 01:49:15 +0200887 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
888 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200889 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100890 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200891 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100892 }
Willy Tarreau24709282013-03-10 21:32:12 +0100893 else { /* IPv4 and IPv6 */
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200894 int use_fqdn = 0;
mildisff5d5102015-10-26 18:50:08 +0100895 char *end = str2 + strlen(str2);
896 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200897
mildisff5d5102015-10-26 18:50:08 +0100898 /* search for : or ] whatever comes first */
899 for (chr = end-1; chr > str2; chr--) {
900 if (*chr == ']' || *chr == ':')
901 break;
902 }
903
904 if (*chr == ':') {
905 /* Found a colon before a closing-bracket, must be a port separator.
906 * This guarantee backward compatibility.
907 */
908 *chr++ = '\0';
909 port1 = chr;
910 }
911 else {
912 /* Either no colon and no closing-bracket
913 * or directly ending with a closing-bracket.
914 * However, no port.
915 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100916 port1 = "";
mildisff5d5102015-10-26 18:50:08 +0100917 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200918
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200919 if (str2ip2(str2, &ss, 0) == NULL) {
920 use_fqdn = 1;
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200921 if (!resolve || str2ip2(str2, &ss, 1) == NULL) {
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200922 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
923 goto out;
924 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100925 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100926
Willy Tarreaua39d1992013-04-01 20:37:42 +0200927 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100928 port2 = strchr(port1, '-');
929 if (port2)
930 *port2++ = '\0';
931 else
932 port2 = port1;
933 portl = atoi(port1);
934 porth = atoi(port2);
935 porta = portl;
936 }
937 else if (*port1 == '-') { /* negative offset */
938 portl = atoi(port1 + 1);
939 porta = -portl;
940 }
941 else if (*port1 == '+') { /* positive offset */
942 porth = atoi(port1 + 1);
943 porta = porth;
944 }
945 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100946 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100947 goto out;
948 }
949 set_host_port(&ss, porta);
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200950
951 if (use_fqdn && fqdn) {
952 if (str2 != back)
953 memmove(back, str2, strlen(str2) + 1);
954 *fqdn = back;
955 back = NULL;
956 }
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100957 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100958
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100959 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100960 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100961 if (low)
962 *low = portl;
963 if (high)
964 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100965 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100966 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200967}
968
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100969/* converts <str> to a struct in_addr containing a network mask. It can be
970 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
971 * if the conversion succeeds otherwise non-zero.
972 */
973int str2mask(const char *str, struct in_addr *mask)
974{
975 if (strchr(str, '.') != NULL) { /* dotted notation */
976 if (!inet_pton(AF_INET, str, mask))
977 return 0;
978 }
979 else { /* mask length */
980 char *err;
981 unsigned long len = strtol(str, &err, 10);
982
983 if (!*str || (err && *err) || (unsigned)len > 32)
984 return 0;
985 if (len)
986 mask->s_addr = htonl(~0UL << (32 - len));
987 else
988 mask->s_addr = 0;
989 }
990 return 1;
991}
992
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100993/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
994 * succeeds otherwise zero.
995 */
996int cidr2dotted(int cidr, struct in_addr *mask) {
997
998 if (cidr < 0 || cidr > 32)
999 return 0;
1000
1001 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1002 return 1;
1003}
1004
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001005/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001006 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001007 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1008 * is optionnal and either in the dotted or CIDR notation.
1009 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1010 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001011int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001012{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001013 __label__ out_free, out_err;
1014 char *c, *s;
1015 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001016
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001017 s = strdup(str);
1018 if (!s)
1019 return 0;
1020
Willy Tarreaubaaee002006-06-26 02:48:02 +02001021 memset(mask, 0, sizeof(*mask));
1022 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001023
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001024 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001025 *c++ = '\0';
1026 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001027 if (!str2mask(c, mask))
1028 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001029 }
1030 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001031 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001032 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001033 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001034 struct hostent *he;
1035
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001036 if (!resolve)
1037 goto out_err;
1038
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001039 if ((he = gethostbyname(s)) == NULL) {
1040 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001041 }
1042 else
1043 *addr = *(struct in_addr *) *(he->h_addr_list);
1044 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001045
1046 ret_val = 1;
1047 out_free:
1048 free(s);
1049 return ret_val;
1050 out_err:
1051 ret_val = 0;
1052 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001053}
1054
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001055
1056/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001057 * converts <str> to two struct in6_addr* which must be pre-allocated.
1058 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
1059 * is an optionnal number of bits (128 being the default).
1060 * Returns 1 if OK, 0 if error.
1061 */
1062int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1063{
1064 char *c, *s;
1065 int ret_val = 0;
1066 char *err;
1067 unsigned long len = 128;
1068
1069 s = strdup(str);
1070 if (!s)
1071 return 0;
1072
1073 memset(mask, 0, sizeof(*mask));
1074 memset(addr, 0, sizeof(*addr));
1075
1076 if ((c = strrchr(s, '/')) != NULL) {
1077 *c++ = '\0'; /* c points to the mask */
1078 if (!*c)
1079 goto out_free;
1080
1081 len = strtoul(c, &err, 10);
1082 if ((err && *err) || (unsigned)len > 128)
1083 goto out_free;
1084 }
1085 *mask = len; /* OK we have a valid mask in <len> */
1086
1087 if (!inet_pton(AF_INET6, s, addr))
1088 goto out_free;
1089
1090 ret_val = 1;
1091 out_free:
1092 free(s);
1093 return ret_val;
1094}
1095
1096
1097/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001098 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001099 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001100int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001101{
1102 int saw_digit, octets, ch;
1103 u_char tmp[4], *tp;
1104 const char *cp = addr;
1105
1106 saw_digit = 0;
1107 octets = 0;
1108 *(tp = tmp) = 0;
1109
1110 while (*addr) {
1111 unsigned char digit = (ch = *addr++) - '0';
1112 if (digit > 9 && ch != '.')
1113 break;
1114 if (digit <= 9) {
1115 u_int new = *tp * 10 + digit;
1116 if (new > 255)
1117 return 0;
1118 *tp = new;
1119 if (!saw_digit) {
1120 if (++octets > 4)
1121 return 0;
1122 saw_digit = 1;
1123 }
1124 } else if (ch == '.' && saw_digit) {
1125 if (octets == 4)
1126 return 0;
1127 *++tp = 0;
1128 saw_digit = 0;
1129 } else
1130 return 0;
1131 }
1132
1133 if (octets < 4)
1134 return 0;
1135
1136 memcpy(&dst->s_addr, tmp, 4);
1137 return addr-cp-1;
1138}
1139
1140/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001141 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1142 * <out> contain the code of the dectected scheme, the start and length of
1143 * the hostname. Actually only http and https are supported. <out> can be NULL.
1144 * This function returns the consumed length. It is useful if you parse complete
1145 * url like http://host:port/path, because the consumed length corresponds to
1146 * the first character of the path. If the conversion fails, it returns -1.
1147 *
1148 * This function tries to resolve the DNS name if haproxy is in starting mode.
1149 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001150 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001151int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001152{
1153 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001154 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001155 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001156 unsigned long long int http_code = 0;
1157 int default_port;
1158 struct hostent *he;
1159 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001160
1161 /* Firstly, try to find :// pattern */
1162 while (curr < url+ulen && url_code != 0x3a2f2f) {
1163 url_code = ((url_code & 0xffff) << 8);
1164 url_code += (unsigned char)*curr++;
1165 }
1166
1167 /* Secondly, if :// pattern is found, verify parsed stuff
1168 * before pattern is matching our http pattern.
1169 * If so parse ip address and port in uri.
1170 *
1171 * WARNING: Current code doesn't support dynamic async dns resolver.
1172 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001173 if (url_code != 0x3a2f2f)
1174 return -1;
1175
1176 /* Copy scheme, and utrn to lower case. */
1177 while (cp < curr - 3)
1178 http_code = (http_code << 8) + *cp++;
1179 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001180
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001181 /* HTTP or HTTPS url matching */
1182 if (http_code == 0x2020202068747470ULL) {
1183 default_port = 80;
1184 if (out)
1185 out->scheme = SCH_HTTP;
1186 }
1187 else if (http_code == 0x2020206874747073ULL) {
1188 default_port = 443;
1189 if (out)
1190 out->scheme = SCH_HTTPS;
1191 }
1192 else
1193 return -1;
1194
1195 /* If the next char is '[', the host address is IPv6. */
1196 if (*curr == '[') {
1197 curr++;
1198
1199 /* Check trash size */
1200 if (trash.size < ulen)
1201 return -1;
1202
1203 /* Look for ']' and copy the address in a trash buffer. */
1204 p = trash.str;
1205 for (end = curr;
1206 end < url + ulen && *end != ']';
1207 end++, p++)
1208 *p = *end;
1209 if (*end != ']')
1210 return -1;
1211 *p = '\0';
1212
1213 /* Update out. */
1214 if (out) {
1215 out->host = curr;
1216 out->host_len = end - curr;
1217 }
1218
1219 /* Try IPv6 decoding. */
1220 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1221 return -1;
1222 end++;
1223
1224 /* Decode port. */
1225 if (*end == ':') {
1226 end++;
1227 default_port = read_uint(&end, url + ulen);
1228 }
1229 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1230 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1231 return end - url;
1232 }
1233 else {
1234 /* We are looking for IP address. If you want to parse and
1235 * resolve hostname found in url, you can use str2sa_range(), but
1236 * be warned this can slow down global daemon performances
1237 * while handling lagging dns responses.
1238 */
1239 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1240 if (ret) {
1241 /* Update out. */
1242 if (out) {
1243 out->host = curr;
1244 out->host_len = ret;
1245 }
1246
1247 curr += ret;
1248
1249 /* Decode port. */
1250 if (*curr == ':') {
1251 curr++;
1252 default_port = read_uint(&curr, url + ulen);
1253 }
1254 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1255
1256 /* Set family. */
1257 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1258 return curr - url;
1259 }
1260 else if (global.mode & MODE_STARTING) {
1261 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1262 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001263 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001264
1265 /* look for : or / or end */
1266 for (end = curr;
1267 end < url + ulen && *end != '/' && *end != ':';
1268 end++);
1269 memcpy(trash.str, curr, end - curr);
1270 trash.str[end - curr] = '\0';
1271
1272 /* try to resolve an IPv4/IPv6 hostname */
1273 he = gethostbyname(trash.str);
1274 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001275 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001276
1277 /* Update out. */
1278 if (out) {
1279 out->host = curr;
1280 out->host_len = end - curr;
1281 }
1282
1283 /* Decode port. */
1284 if (*end == ':') {
1285 end++;
1286 default_port = read_uint(&end, url + ulen);
1287 }
1288
1289 /* Copy IP address, set port and family. */
1290 switch (he->h_addrtype) {
1291 case AF_INET:
1292 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1293 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1294 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1295 return end - url;
1296
1297 case AF_INET6:
1298 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1299 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1300 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1301 return end - url;
1302 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001303 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001304 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001305 return -1;
1306}
1307
Willy Tarreau631f01c2011-09-05 00:36:48 +02001308/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1309 * address family is returned so that it's easy for the caller to adapt to the
1310 * output format. Zero is returned if the address family is not supported. -1
1311 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1312 * supported.
1313 */
1314int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1315{
1316
1317 void *ptr;
1318
1319 if (size < 5)
1320 return 0;
1321 *str = '\0';
1322
1323 switch (addr->ss_family) {
1324 case AF_INET:
1325 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1326 break;
1327 case AF_INET6:
1328 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1329 break;
1330 case AF_UNIX:
1331 memcpy(str, "unix", 5);
1332 return addr->ss_family;
1333 default:
1334 return 0;
1335 }
1336
1337 if (inet_ntop(addr->ss_family, ptr, str, size))
1338 return addr->ss_family;
1339
1340 /* failed */
1341 return -1;
1342}
1343
Simon Horman75ab8bd2014-06-16 09:39:41 +09001344/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1345 * address family is returned so that it's easy for the caller to adapt to the
1346 * output format. Zero is returned if the address family is not supported. -1
1347 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1348 * supported.
1349 */
1350int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1351{
1352
1353 uint16_t port;
1354
1355
1356 if (size < 5)
1357 return 0;
1358 *str = '\0';
1359
1360 switch (addr->ss_family) {
1361 case AF_INET:
1362 port = ((struct sockaddr_in *)addr)->sin_port;
1363 break;
1364 case AF_INET6:
1365 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1366 break;
1367 case AF_UNIX:
1368 memcpy(str, "unix", 5);
1369 return addr->ss_family;
1370 default:
1371 return 0;
1372 }
1373
1374 snprintf(str, size, "%u", ntohs(port));
1375 return addr->ss_family;
1376}
1377
Willy Tarreaubaaee002006-06-26 02:48:02 +02001378/* will try to encode the string <string> replacing all characters tagged in
1379 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1380 * prefixed by <escape>, and will store the result between <start> (included)
1381 * and <stop> (excluded), and will always terminate the string with a '\0'
1382 * before <stop>. The position of the '\0' is returned if the conversion
1383 * completes. If bytes are missing between <start> and <stop>, then the
1384 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1385 * cannot even be stored so we return <start> without writing the 0.
1386 * The input string must also be zero-terminated.
1387 */
1388const char hextab[16] = "0123456789ABCDEF";
1389char *encode_string(char *start, char *stop,
1390 const char escape, const fd_set *map,
1391 const char *string)
1392{
1393 if (start < stop) {
1394 stop--; /* reserve one byte for the final '\0' */
1395 while (start < stop && *string != '\0') {
1396 if (!FD_ISSET((unsigned char)(*string), map))
1397 *start++ = *string;
1398 else {
1399 if (start + 3 >= stop)
1400 break;
1401 *start++ = escape;
1402 *start++ = hextab[(*string >> 4) & 15];
1403 *start++ = hextab[*string & 15];
1404 }
1405 string++;
1406 }
1407 *start = '\0';
1408 }
1409 return start;
1410}
1411
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001412/*
1413 * Same behavior as encode_string() above, except that it encodes chunk
1414 * <chunk> instead of a string.
1415 */
1416char *encode_chunk(char *start, char *stop,
1417 const char escape, const fd_set *map,
1418 const struct chunk *chunk)
1419{
1420 char *str = chunk->str;
1421 char *end = chunk->str + chunk->len;
1422
1423 if (start < stop) {
1424 stop--; /* reserve one byte for the final '\0' */
1425 while (start < stop && str < end) {
1426 if (!FD_ISSET((unsigned char)(*str), map))
1427 *start++ = *str;
1428 else {
1429 if (start + 3 >= stop)
1430 break;
1431 *start++ = escape;
1432 *start++ = hextab[(*str >> 4) & 15];
1433 *start++ = hextab[*str & 15];
1434 }
1435 str++;
1436 }
1437 *start = '\0';
1438 }
1439 return start;
1440}
1441
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001442/* Check a string for using it in a CSV output format. If the string contains
1443 * one of the following four char <">, <,>, CR or LF, the string is
1444 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1445 * <str> is the input string to be escaped. The function assumes that
1446 * the input string is null-terminated.
1447 *
1448 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001449 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001450 * format.
1451 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001452 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001453 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001454 * If <quote> is 1, the converter puts the quotes only if any reserved character
1455 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001456 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001457 * <output> is a struct chunk used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001458 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001459 * The function returns the converted string on its output. If an error
1460 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001461 * for using the function directly as printf() argument.
1462 *
1463 * If the output buffer is too short to contain the input string, the result
1464 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001465 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001466 * This function appends the encoding to the existing output chunk, and it
1467 * guarantees that it starts immediately at the first available character of
1468 * the chunk. Please use csv_enc() instead if you want to replace the output
1469 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001470 */
Willy Tarreau898529b2016-01-06 18:07:04 +01001471const char *csv_enc_append(const char *str, int quote, struct chunk *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001472{
1473 char *end = output->str + output->size;
Willy Tarreaub631c292016-01-08 10:04:08 +01001474 char *out = output->str + output->len;
Willy Tarreau898529b2016-01-06 18:07:04 +01001475 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001476
Willy Tarreaub631c292016-01-08 10:04:08 +01001477 if (quote == 1) {
1478 /* automatic quoting: first verify if we'll have to quote the string */
1479 if (!strpbrk(str, "\n\r,\""))
1480 quote = 0;
1481 }
1482
1483 if (quote)
1484 *ptr++ = '"';
1485
Willy Tarreau898529b2016-01-06 18:07:04 +01001486 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1487 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001488 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001489 ptr++;
1490 if (ptr >= end - 2) {
1491 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001492 break;
1493 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001494 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001495 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001496 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001497 str++;
1498 }
1499
Willy Tarreaub631c292016-01-08 10:04:08 +01001500 if (quote)
1501 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001502
Willy Tarreau898529b2016-01-06 18:07:04 +01001503 *ptr = '\0';
1504 output->len = ptr - output->str;
1505 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001506}
1507
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001508/* Decode an URL-encoded string in-place. The resulting string might
1509 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001510 * aborted, the string is truncated before the issue and a negative value is
1511 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001512 */
1513int url_decode(char *string)
1514{
1515 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001516 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001517
1518 in = string;
1519 out = string;
1520 while (*in) {
1521 switch (*in) {
1522 case '+' :
1523 *out++ = ' ';
1524 break;
1525 case '%' :
1526 if (!ishex(in[1]) || !ishex(in[2]))
1527 goto end;
1528 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1529 in += 2;
1530 break;
1531 default:
1532 *out++ = *in;
1533 break;
1534 }
1535 in++;
1536 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001537 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001538 end:
1539 *out = 0;
1540 return ret;
1541}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001542
Willy Tarreau6911fa42007-03-04 18:06:08 +01001543unsigned int str2ui(const char *s)
1544{
1545 return __str2ui(s);
1546}
1547
1548unsigned int str2uic(const char *s)
1549{
1550 return __str2uic(s);
1551}
1552
1553unsigned int strl2ui(const char *s, int len)
1554{
1555 return __strl2ui(s, len);
1556}
1557
1558unsigned int strl2uic(const char *s, int len)
1559{
1560 return __strl2uic(s, len);
1561}
1562
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001563unsigned int read_uint(const char **s, const char *end)
1564{
1565 return __read_uint(s, end);
1566}
1567
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001568/* This function reads an unsigned integer from the string pointed to by <s> and
1569 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1570 * function automatically stops at <end>. If the number overflows, the 2^64-1
1571 * value is returned.
1572 */
1573unsigned long long int read_uint64(const char **s, const char *end)
1574{
1575 const char *ptr = *s;
1576 unsigned long long int i = 0, tmp;
1577 unsigned int j;
1578
1579 while (ptr < end) {
1580
1581 /* read next char */
1582 j = *ptr - '0';
1583 if (j > 9)
1584 goto read_uint64_end;
1585
1586 /* add char to the number and check overflow. */
1587 tmp = i * 10;
1588 if (tmp / 10 != i) {
1589 i = ULLONG_MAX;
1590 goto read_uint64_eat;
1591 }
1592 if (ULLONG_MAX - tmp < j) {
1593 i = ULLONG_MAX;
1594 goto read_uint64_eat;
1595 }
1596 i = tmp + j;
1597 ptr++;
1598 }
1599read_uint64_eat:
1600 /* eat each numeric char */
1601 while (ptr < end) {
1602 if ((unsigned int)(*ptr - '0') > 9)
1603 break;
1604 ptr++;
1605 }
1606read_uint64_end:
1607 *s = ptr;
1608 return i;
1609}
1610
1611/* This function reads an integer from the string pointed to by <s> and returns
1612 * it. The <s> pointer is adjusted to point to the first unread char. The function
1613 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
1614 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
1615 * returned.
1616 */
1617long long int read_int64(const char **s, const char *end)
1618{
1619 unsigned long long int i = 0;
1620 int neg = 0;
1621
1622 /* Look for minus char. */
1623 if (**s == '-') {
1624 neg = 1;
1625 (*s)++;
1626 }
1627 else if (**s == '+')
1628 (*s)++;
1629
1630 /* convert as positive number. */
1631 i = read_uint64(s, end);
1632
1633 if (neg) {
1634 if (i > 0x8000000000000000ULL)
1635 return LLONG_MIN;
1636 return -i;
1637 }
1638 if (i > 0x7fffffffffffffffULL)
1639 return LLONG_MAX;
1640 return i;
1641}
1642
Willy Tarreau6911fa42007-03-04 18:06:08 +01001643/* This one is 7 times faster than strtol() on athlon with checks.
1644 * It returns the value of the number composed of all valid digits read,
1645 * and can process negative numbers too.
1646 */
1647int strl2ic(const char *s, int len)
1648{
1649 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001650 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001651
1652 if (len > 0) {
1653 if (*s != '-') {
1654 /* positive number */
1655 while (len-- > 0) {
1656 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001657 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001658 if (j > 9)
1659 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001660 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001661 }
1662 } else {
1663 /* negative number */
1664 s++;
1665 while (--len > 0) {
1666 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001667 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001668 if (j > 9)
1669 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001670 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001671 }
1672 }
1673 }
1674 return i;
1675}
1676
1677
1678/* This function reads exactly <len> chars from <s> and converts them to a
1679 * signed integer which it stores into <ret>. It accurately detects any error
1680 * (truncated string, invalid chars, overflows). It is meant to be used in
1681 * applications designed for hostile environments. It returns zero when the
1682 * number has successfully been converted, non-zero otherwise. When an error
1683 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1684 * faster than strtol().
1685 */
1686int strl2irc(const char *s, int len, int *ret)
1687{
1688 int i = 0;
1689 int j;
1690
1691 if (!len)
1692 return 1;
1693
1694 if (*s != '-') {
1695 /* positive number */
1696 while (len-- > 0) {
1697 j = (*s++) - '0';
1698 if (j > 9) return 1; /* invalid char */
1699 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1700 i = i * 10;
1701 if (i + j < i) return 1; /* check for addition overflow */
1702 i = i + j;
1703 }
1704 } else {
1705 /* negative number */
1706 s++;
1707 while (--len > 0) {
1708 j = (*s++) - '0';
1709 if (j > 9) return 1; /* invalid char */
1710 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1711 i = i * 10;
1712 if (i - j > i) return 1; /* check for subtract overflow */
1713 i = i - j;
1714 }
1715 }
1716 *ret = i;
1717 return 0;
1718}
1719
1720
1721/* This function reads exactly <len> chars from <s> and converts them to a
1722 * signed integer which it stores into <ret>. It accurately detects any error
1723 * (truncated string, invalid chars, overflows). It is meant to be used in
1724 * applications designed for hostile environments. It returns zero when the
1725 * number has successfully been converted, non-zero otherwise. When an error
1726 * is returned, the <ret> value is left untouched. It is about 3 times slower
1727 * than str2irc().
1728 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001729
1730int strl2llrc(const char *s, int len, long long *ret)
1731{
1732 long long i = 0;
1733 int j;
1734
1735 if (!len)
1736 return 1;
1737
1738 if (*s != '-') {
1739 /* positive number */
1740 while (len-- > 0) {
1741 j = (*s++) - '0';
1742 if (j > 9) return 1; /* invalid char */
1743 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1744 i = i * 10LL;
1745 if (i + j < i) return 1; /* check for addition overflow */
1746 i = i + j;
1747 }
1748 } else {
1749 /* negative number */
1750 s++;
1751 while (--len > 0) {
1752 j = (*s++) - '0';
1753 if (j > 9) return 1; /* invalid char */
1754 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1755 i = i * 10LL;
1756 if (i - j > i) return 1; /* check for subtract overflow */
1757 i = i - j;
1758 }
1759 }
1760 *ret = i;
1761 return 0;
1762}
1763
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001764/* This function is used with pat_parse_dotted_ver(). It converts a string
1765 * composed by two number separated by a dot. Each part must contain in 16 bits
1766 * because internally they will be represented as a 32-bit quantity stored in
1767 * a 64-bit integer. It returns zero when the number has successfully been
1768 * converted, non-zero otherwise. When an error is returned, the <ret> value
1769 * is left untouched.
1770 *
1771 * "1.3" -> 0x0000000000010003
1772 * "65535.65535" -> 0x00000000ffffffff
1773 */
1774int strl2llrc_dotted(const char *text, int len, long long *ret)
1775{
1776 const char *end = &text[len];
1777 const char *p;
1778 long long major, minor;
1779
1780 /* Look for dot. */
1781 for (p = text; p < end; p++)
1782 if (*p == '.')
1783 break;
1784
1785 /* Convert major. */
1786 if (strl2llrc(text, p - text, &major) != 0)
1787 return 1;
1788
1789 /* Check major. */
1790 if (major >= 65536)
1791 return 1;
1792
1793 /* Convert minor. */
1794 minor = 0;
1795 if (p < end)
1796 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1797 return 1;
1798
1799 /* Check minor. */
1800 if (minor >= 65536)
1801 return 1;
1802
1803 /* Compose value. */
1804 *ret = (major << 16) | (minor & 0xffff);
1805 return 0;
1806}
1807
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001808/* This function parses a time value optionally followed by a unit suffix among
1809 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1810 * expected by the caller. The computation does its best to avoid overflows.
1811 * The value is returned in <ret> if everything is fine, and a NULL is returned
1812 * by the function. In case of error, a pointer to the error is returned and
1813 * <ret> is left untouched. Values are automatically rounded up when needed.
1814 */
1815const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1816{
1817 unsigned imult, idiv;
1818 unsigned omult, odiv;
1819 unsigned value;
1820
1821 omult = odiv = 1;
1822
1823 switch (unit_flags & TIME_UNIT_MASK) {
1824 case TIME_UNIT_US: omult = 1000000; break;
1825 case TIME_UNIT_MS: omult = 1000; break;
1826 case TIME_UNIT_S: break;
1827 case TIME_UNIT_MIN: odiv = 60; break;
1828 case TIME_UNIT_HOUR: odiv = 3600; break;
1829 case TIME_UNIT_DAY: odiv = 86400; break;
1830 default: break;
1831 }
1832
1833 value = 0;
1834
1835 while (1) {
1836 unsigned int j;
1837
1838 j = *text - '0';
1839 if (j > 9)
1840 break;
1841 text++;
1842 value *= 10;
1843 value += j;
1844 }
1845
1846 imult = idiv = 1;
1847 switch (*text) {
1848 case '\0': /* no unit = default unit */
1849 imult = omult = idiv = odiv = 1;
1850 break;
1851 case 's': /* second = unscaled unit */
1852 break;
1853 case 'u': /* microsecond : "us" */
1854 if (text[1] == 's') {
1855 idiv = 1000000;
1856 text++;
1857 }
1858 break;
1859 case 'm': /* millisecond : "ms" or minute: "m" */
1860 if (text[1] == 's') {
1861 idiv = 1000;
1862 text++;
1863 } else
1864 imult = 60;
1865 break;
1866 case 'h': /* hour : "h" */
1867 imult = 3600;
1868 break;
1869 case 'd': /* day : "d" */
1870 imult = 86400;
1871 break;
1872 default:
1873 return text;
1874 break;
1875 }
1876
1877 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1878 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1879 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1880 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1881
1882 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1883 *ret = value;
1884 return NULL;
1885}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001886
Emeric Brun39132b22010-01-04 14:57:24 +01001887/* this function converts the string starting at <text> to an unsigned int
1888 * stored in <ret>. If an error is detected, the pointer to the unexpected
1889 * character is returned. If the conversio is succesful, NULL is returned.
1890 */
1891const char *parse_size_err(const char *text, unsigned *ret) {
1892 unsigned value = 0;
1893
1894 while (1) {
1895 unsigned int j;
1896
1897 j = *text - '0';
1898 if (j > 9)
1899 break;
1900 if (value > ~0U / 10)
1901 return text;
1902 value *= 10;
1903 if (value > (value + j))
1904 return text;
1905 value += j;
1906 text++;
1907 }
1908
1909 switch (*text) {
1910 case '\0':
1911 break;
1912 case 'K':
1913 case 'k':
1914 if (value > ~0U >> 10)
1915 return text;
1916 value = value << 10;
1917 break;
1918 case 'M':
1919 case 'm':
1920 if (value > ~0U >> 20)
1921 return text;
1922 value = value << 20;
1923 break;
1924 case 'G':
1925 case 'g':
1926 if (value > ~0U >> 30)
1927 return text;
1928 value = value << 30;
1929 break;
1930 default:
1931 return text;
1932 }
1933
Godbach58048a22015-01-28 17:36:16 +08001934 if (*text != '\0' && *++text != '\0')
1935 return text;
1936
Emeric Brun39132b22010-01-04 14:57:24 +01001937 *ret = value;
1938 return NULL;
1939}
1940
Willy Tarreau126d4062013-12-03 17:50:47 +01001941/*
1942 * Parse binary string written in hexadecimal (source) and store the decoded
1943 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1944 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001945 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001946 */
1947int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1948{
1949 int len;
1950 const char *p = source;
1951 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001952 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001953
1954 len = strlen(source);
1955 if (len % 2) {
1956 memprintf(err, "an even number of hex digit is expected");
1957 return 0;
1958 }
1959
1960 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001961
Willy Tarreau126d4062013-12-03 17:50:47 +01001962 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001963 *binstr = calloc(len, sizeof(char));
1964 if (!*binstr) {
1965 memprintf(err, "out of memory while loading string pattern");
1966 return 0;
1967 }
1968 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001969 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001970 else {
1971 if (*binstrlen < len) {
1972 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1973 len, *binstrlen);
1974 return 0;
1975 }
1976 alloc = 0;
1977 }
1978 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001979
1980 i = j = 0;
1981 while (j < len) {
1982 if (!ishex(p[i++]))
1983 goto bad_input;
1984 if (!ishex(p[i++]))
1985 goto bad_input;
1986 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1987 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001988 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001989
1990bad_input:
1991 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001992 if (alloc)
1993 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001994 return 0;
1995}
1996
Willy Tarreau946ba592009-05-10 15:41:18 +02001997/* copies at most <n> characters from <src> and always terminates with '\0' */
1998char *my_strndup(const char *src, int n)
1999{
2000 int len = 0;
2001 char *ret;
2002
2003 while (len < n && src[len])
2004 len++;
2005
2006 ret = (char *)malloc(len + 1);
2007 if (!ret)
2008 return ret;
2009 memcpy(ret, src, len);
2010 ret[len] = '\0';
2011 return ret;
2012}
2013
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002014/*
2015 * search needle in haystack
2016 * returns the pointer if found, returns NULL otherwise
2017 */
2018const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2019{
2020 const void *c = NULL;
2021 unsigned char f;
2022
2023 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2024 return NULL;
2025
2026 f = *(char *)needle;
2027 c = haystack;
2028 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2029 if ((haystacklen - (c - haystack)) < needlelen)
2030 return NULL;
2031
2032 if (memcmp(c, needle, needlelen) == 0)
2033 return c;
2034 ++c;
2035 }
2036 return NULL;
2037}
2038
Willy Tarreau482b00d2009-10-04 22:48:42 +02002039/* This function returns the first unused key greater than or equal to <key> in
2040 * ID tree <root>. Zero is returned if no place is found.
2041 */
2042unsigned int get_next_id(struct eb_root *root, unsigned int key)
2043{
2044 struct eb32_node *used;
2045
2046 do {
2047 used = eb32_lookup_ge(root, key);
2048 if (!used || used->key > key)
2049 return key; /* key is available */
2050 key++;
2051 } while (key);
2052 return key;
2053}
2054
Willy Tarreau348238b2010-01-18 15:05:57 +01002055/* This function compares a sample word possibly followed by blanks to another
2056 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2057 * otherwise zero. This intends to be used when checking HTTP headers for some
2058 * values. Note that it validates a word followed only by blanks but does not
2059 * validate a word followed by blanks then other chars.
2060 */
2061int word_match(const char *sample, int slen, const char *word, int wlen)
2062{
2063 if (slen < wlen)
2064 return 0;
2065
2066 while (wlen) {
2067 char c = *sample ^ *word;
2068 if (c && c != ('A' ^ 'a'))
2069 return 0;
2070 sample++;
2071 word++;
2072 slen--;
2073 wlen--;
2074 }
2075
2076 while (slen) {
2077 if (*sample != ' ' && *sample != '\t')
2078 return 0;
2079 sample++;
2080 slen--;
2081 }
2082 return 1;
2083}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002084
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002085/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2086 * is particularly fast because it avoids expensive operations such as
2087 * multiplies, which are optimized away at the end. It requires a properly
2088 * formated address though (3 points).
2089 */
2090unsigned int inetaddr_host(const char *text)
2091{
2092 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2093 register unsigned int dig100, dig10, dig1;
2094 int s;
2095 const char *p, *d;
2096
2097 dig1 = dig10 = dig100 = ascii_zero;
2098 s = 24;
2099
2100 p = text;
2101 while (1) {
2102 if (((unsigned)(*p - '0')) <= 9) {
2103 p++;
2104 continue;
2105 }
2106
2107 /* here, we have a complete byte between <text> and <p> (exclusive) */
2108 if (p == text)
2109 goto end;
2110
2111 d = p - 1;
2112 dig1 |= (unsigned int)(*d << s);
2113 if (d == text)
2114 goto end;
2115
2116 d--;
2117 dig10 |= (unsigned int)(*d << s);
2118 if (d == text)
2119 goto end;
2120
2121 d--;
2122 dig100 |= (unsigned int)(*d << s);
2123 end:
2124 if (!s || *p != '.')
2125 break;
2126
2127 s -= 8;
2128 text = ++p;
2129 }
2130
2131 dig100 -= ascii_zero;
2132 dig10 -= ascii_zero;
2133 dig1 -= ascii_zero;
2134 return ((dig100 * 10) + dig10) * 10 + dig1;
2135}
2136
2137/*
2138 * Idem except the first unparsed character has to be passed in <stop>.
2139 */
2140unsigned int inetaddr_host_lim(const char *text, const char *stop)
2141{
2142 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2143 register unsigned int dig100, dig10, dig1;
2144 int s;
2145 const char *p, *d;
2146
2147 dig1 = dig10 = dig100 = ascii_zero;
2148 s = 24;
2149
2150 p = text;
2151 while (1) {
2152 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2153 p++;
2154 continue;
2155 }
2156
2157 /* here, we have a complete byte between <text> and <p> (exclusive) */
2158 if (p == text)
2159 goto end;
2160
2161 d = p - 1;
2162 dig1 |= (unsigned int)(*d << s);
2163 if (d == text)
2164 goto end;
2165
2166 d--;
2167 dig10 |= (unsigned int)(*d << s);
2168 if (d == text)
2169 goto end;
2170
2171 d--;
2172 dig100 |= (unsigned int)(*d << s);
2173 end:
2174 if (!s || p == stop || *p != '.')
2175 break;
2176
2177 s -= 8;
2178 text = ++p;
2179 }
2180
2181 dig100 -= ascii_zero;
2182 dig10 -= ascii_zero;
2183 dig1 -= ascii_zero;
2184 return ((dig100 * 10) + dig10) * 10 + dig1;
2185}
2186
2187/*
2188 * Idem except the pointer to first unparsed byte is returned into <ret> which
2189 * must not be NULL.
2190 */
Willy Tarreau74172752010-10-15 23:21:42 +02002191unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002192{
2193 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2194 register unsigned int dig100, dig10, dig1;
2195 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002196 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002197
2198 dig1 = dig10 = dig100 = ascii_zero;
2199 s = 24;
2200
2201 p = text;
2202 while (1) {
2203 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2204 p++;
2205 continue;
2206 }
2207
2208 /* here, we have a complete byte between <text> and <p> (exclusive) */
2209 if (p == text)
2210 goto end;
2211
2212 d = p - 1;
2213 dig1 |= (unsigned int)(*d << s);
2214 if (d == text)
2215 goto end;
2216
2217 d--;
2218 dig10 |= (unsigned int)(*d << s);
2219 if (d == text)
2220 goto end;
2221
2222 d--;
2223 dig100 |= (unsigned int)(*d << s);
2224 end:
2225 if (!s || p == stop || *p != '.')
2226 break;
2227
2228 s -= 8;
2229 text = ++p;
2230 }
2231
2232 *ret = p;
2233 dig100 -= ascii_zero;
2234 dig10 -= ascii_zero;
2235 dig1 -= ascii_zero;
2236 return ((dig100 * 10) + dig10) * 10 + dig1;
2237}
2238
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002239/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2240 * or the number of chars read in case of success. Maybe this could be replaced
2241 * by one of the functions above. Also, apparently this function does not support
2242 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002243 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002244 */
2245int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2246{
2247 const char *addr;
2248 int saw_digit, octets, ch;
2249 u_char tmp[4], *tp;
2250 const char *cp = buf;
2251
2252 saw_digit = 0;
2253 octets = 0;
2254 *(tp = tmp) = 0;
2255
2256 for (addr = buf; addr - buf < len; addr++) {
2257 unsigned char digit = (ch = *addr) - '0';
2258
2259 if (digit > 9 && ch != '.')
2260 break;
2261
2262 if (digit <= 9) {
2263 u_int new = *tp * 10 + digit;
2264
2265 if (new > 255)
2266 return 0;
2267
2268 *tp = new;
2269
2270 if (!saw_digit) {
2271 if (++octets > 4)
2272 return 0;
2273 saw_digit = 1;
2274 }
2275 } else if (ch == '.' && saw_digit) {
2276 if (octets == 4)
2277 return 0;
2278
2279 *++tp = 0;
2280 saw_digit = 0;
2281 } else
2282 return 0;
2283 }
2284
2285 if (octets < 4)
2286 return 0;
2287
2288 memcpy(&dst->s_addr, tmp, 4);
2289 return addr - cp;
2290}
2291
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002292/* This function converts the string in <buf> of the len <len> to
2293 * struct in6_addr <dst> which must be allocated by the caller.
2294 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002295 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002296 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002297int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2298{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002299 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002300 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002301
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002302 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002303 return 0;
2304
2305 memcpy(null_term_ip6, buf, len);
2306 null_term_ip6[len] = '\0';
2307
Willy Tarreau075415a2013-12-12 11:29:39 +01002308 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002309 return 0;
2310
Willy Tarreau075415a2013-12-12 11:29:39 +01002311 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002312 return 1;
2313}
2314
Willy Tarreauacf95772010-06-14 19:09:21 +02002315/* To be used to quote config arg positions. Returns the short string at <ptr>
2316 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2317 * if ptr is NULL or empty. The string is locally allocated.
2318 */
2319const char *quote_arg(const char *ptr)
2320{
2321 static char val[32];
2322 int i;
2323
2324 if (!ptr || !*ptr)
2325 return "end of line";
2326 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002327 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002328 val[i] = *ptr++;
2329 val[i++] = '\'';
2330 val[i] = '\0';
2331 return val;
2332}
2333
Willy Tarreau5b180202010-07-18 10:40:48 +02002334/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2335int get_std_op(const char *str)
2336{
2337 int ret = -1;
2338
2339 if (*str == 'e' && str[1] == 'q')
2340 ret = STD_OP_EQ;
2341 else if (*str == 'n' && str[1] == 'e')
2342 ret = STD_OP_NE;
2343 else if (*str == 'l') {
2344 if (str[1] == 'e') ret = STD_OP_LE;
2345 else if (str[1] == 't') ret = STD_OP_LT;
2346 }
2347 else if (*str == 'g') {
2348 if (str[1] == 'e') ret = STD_OP_GE;
2349 else if (str[1] == 't') ret = STD_OP_GT;
2350 }
2351
2352 if (ret == -1 || str[2] != '\0')
2353 return -1;
2354 return ret;
2355}
2356
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002357/* hash a 32-bit integer to another 32-bit integer */
2358unsigned int full_hash(unsigned int a)
2359{
2360 return __full_hash(a);
2361}
2362
David du Colombier4f92d322011-03-24 11:09:31 +01002363/* Return non-zero if IPv4 address is part of the network,
2364 * otherwise zero.
2365 */
2366int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
2367{
2368 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
2369}
2370
2371/* Return non-zero if IPv6 address is part of the network,
2372 * otherwise zero.
2373 */
2374int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
2375{
2376 int i;
2377
2378 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2379 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2380 (((int *)net)[i] & ((int *)mask)[i]))
2381 return 0;
2382 return 1;
2383}
2384
2385/* RFC 4291 prefix */
2386const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2387 0x00, 0x00, 0x00, 0x00,
2388 0x00, 0x00, 0xFF, 0xFF };
2389
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002390/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2391 * Input and output may overlap.
2392 */
David du Colombier4f92d322011-03-24 11:09:31 +01002393void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2394{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002395 struct in_addr tmp_addr;
2396
2397 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002398 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002399 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002400}
2401
2402/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2403 * Return true if conversion is possible and false otherwise.
2404 */
2405int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2406{
2407 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2408 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2409 sizeof(struct in_addr));
2410 return 1;
2411 }
2412
2413 return 0;
2414}
2415
William Lallemand421f5b52012-02-06 18:15:57 +01002416char *human_time(int t, short hz_div) {
2417 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2418 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002419 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002420 int cnt=2; // print two numbers
2421
2422 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002423 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002424 return rv;
2425 }
2426
2427 if (unlikely(hz_div > 1))
2428 t /= hz_div;
2429
2430 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002431 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002432 cnt--;
2433 }
2434
2435 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002436 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002437 cnt--;
2438 }
2439
2440 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002441 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002442 cnt--;
2443 }
2444
2445 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002446 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002447
2448 return rv;
2449}
2450
2451const char *monthname[12] = {
2452 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2453 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2454};
2455
2456/* date2str_log: write a date in the format :
2457 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2458 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2459 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2460 *
2461 * without using sprintf. return a pointer to the last char written (\0) or
2462 * NULL if there isn't enough space.
2463 */
2464char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2465{
2466
2467 if (size < 25) /* the size is fixed: 24 chars + \0 */
2468 return NULL;
2469
2470 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2471 *dst++ = '/';
2472 memcpy(dst, monthname[tm->tm_mon], 3); // month
2473 dst += 3;
2474 *dst++ = '/';
2475 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2476 *dst++ = ':';
2477 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2478 *dst++ = ':';
2479 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2480 *dst++ = ':';
2481 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2482 *dst++ = '.';
2483 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2484 dst += 3; // only the 3 first digits
2485 *dst = '\0';
2486
2487 return dst;
2488}
2489
2490/* gmt2str_log: write a date in the format :
2491 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2492 * return a pointer to the last char written (\0) or
2493 * NULL if there isn't enough space.
2494 */
2495char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2496{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002497 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002498 return NULL;
2499
2500 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2501 *dst++ = '/';
2502 memcpy(dst, monthname[tm->tm_mon], 3); // month
2503 dst += 3;
2504 *dst++ = '/';
2505 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2506 *dst++ = ':';
2507 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2508 *dst++ = ':';
2509 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2510 *dst++ = ':';
2511 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2512 *dst++ = ' ';
2513 *dst++ = '+';
2514 *dst++ = '0';
2515 *dst++ = '0';
2516 *dst++ = '0';
2517 *dst++ = '0';
2518 *dst = '\0';
2519
2520 return dst;
2521}
2522
Yuxans Yao4e25b012012-10-19 10:36:09 +08002523/* localdate2str_log: write a date in the format :
2524 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2525 * * return a pointer to the last char written (\0) or
2526 * * NULL if there isn't enough space.
2527 */
2528char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2529{
2530 if (size < 27) /* the size is fixed: 26 chars + \0 */
2531 return NULL;
2532
2533 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2534 *dst++ = '/';
2535 memcpy(dst, monthname[tm->tm_mon], 3); // month
2536 dst += 3;
2537 *dst++ = '/';
2538 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2539 *dst++ = ':';
2540 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2541 *dst++ = ':';
2542 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2543 *dst++ = ':';
2544 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2545 *dst++ = ' ';
2546 memcpy(dst, localtimezone, 5); // timezone
2547 dst += 5;
2548 *dst = '\0';
2549
2550 return dst;
2551}
2552
Thierry Fournier93127942016-01-20 18:49:45 +01002553/* This function check a char. It returns true and updates
2554 * <date> and <len> pointer to the new position if the
2555 * character is found.
2556 */
2557static inline int parse_expect_char(const char **date, int *len, char c)
2558{
2559 if (*len < 1 || **date != c)
2560 return 0;
2561 (*len)--;
2562 (*date)++;
2563 return 1;
2564}
2565
2566/* This function expects a string <str> of len <l>. It return true and updates.
2567 * <date> and <len> if the string matches, otherwise, it returns false.
2568 */
2569static inline int parse_strcmp(const char **date, int *len, char *str, int l)
2570{
2571 if (*len < l || strncmp(*date, str, l) != 0)
2572 return 0;
2573 (*len) -= l;
2574 (*date) += l;
2575 return 1;
2576}
2577
2578/* This macro converts 3 chars name in integer. */
2579#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
2580
2581/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
2582 * / %x54.75.65 ; "Tue", case-sensitive
2583 * / %x57.65.64 ; "Wed", case-sensitive
2584 * / %x54.68.75 ; "Thu", case-sensitive
2585 * / %x46.72.69 ; "Fri", case-sensitive
2586 * / %x53.61.74 ; "Sat", case-sensitive
2587 * / %x53.75.6E ; "Sun", case-sensitive
2588 *
2589 * This array must be alphabetically sorted
2590 */
2591static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
2592{
2593 if (*len < 3)
2594 return 0;
2595 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2596 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
2597 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
2598 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
2599 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
2600 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
2601 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
2602 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
2603 default: return 0;
2604 }
2605 *len -= 3;
2606 *date += 3;
2607 return 1;
2608}
2609
2610/* month = %x4A.61.6E ; "Jan", case-sensitive
2611 * / %x46.65.62 ; "Feb", case-sensitive
2612 * / %x4D.61.72 ; "Mar", case-sensitive
2613 * / %x41.70.72 ; "Apr", case-sensitive
2614 * / %x4D.61.79 ; "May", case-sensitive
2615 * / %x4A.75.6E ; "Jun", case-sensitive
2616 * / %x4A.75.6C ; "Jul", case-sensitive
2617 * / %x41.75.67 ; "Aug", case-sensitive
2618 * / %x53.65.70 ; "Sep", case-sensitive
2619 * / %x4F.63.74 ; "Oct", case-sensitive
2620 * / %x4E.6F.76 ; "Nov", case-sensitive
2621 * / %x44.65.63 ; "Dec", case-sensitive
2622 *
2623 * This array must be alphabetically sorted
2624 */
2625static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
2626{
2627 if (*len < 3)
2628 return 0;
2629 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2630 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
2631 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
2632 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
2633 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
2634 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
2635 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
2636 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
2637 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
2638 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
2639 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
2640 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
2641 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
2642 default: return 0;
2643 }
2644 *len -= 3;
2645 *date += 3;
2646 return 1;
2647}
2648
2649/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
2650 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
2651 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
2652 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
2653 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
2654 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
2655 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
2656 *
2657 * This array must be alphabetically sorted
2658 */
2659static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
2660{
2661 if (*len < 6) /* Minimum length. */
2662 return 0;
2663 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
2664 case STR2I3('M','o','n'):
2665 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
2666 tm->tm_wday = 1;
2667 return 1;
2668 case STR2I3('T','u','e'):
2669 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
2670 tm->tm_wday = 2;
2671 return 1;
2672 case STR2I3('W','e','d'):
2673 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
2674 tm->tm_wday = 3;
2675 return 1;
2676 case STR2I3('T','h','u'):
2677 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
2678 tm->tm_wday = 4;
2679 return 1;
2680 case STR2I3('F','r','i'):
2681 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
2682 tm->tm_wday = 5;
2683 return 1;
2684 case STR2I3('S','a','t'):
2685 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
2686 tm->tm_wday = 6;
2687 return 1;
2688 case STR2I3('S','u','n'):
2689 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
2690 tm->tm_wday = 7;
2691 return 1;
2692 }
2693 return 0;
2694}
2695
2696/* This function parses exactly 1 digit and returns the numeric value in "digit". */
2697static inline int parse_digit(const char **date, int *len, int *digit)
2698{
2699 if (*len < 1 || **date < '0' || **date > '9')
2700 return 0;
2701 *digit = (**date - '0');
2702 (*date)++;
2703 (*len)--;
2704 return 1;
2705}
2706
2707/* This function parses exactly 2 digits and returns the numeric value in "digit". */
2708static inline int parse_2digit(const char **date, int *len, int *digit)
2709{
2710 int value;
2711
2712 RET0_UNLESS(parse_digit(date, len, &value));
2713 (*digit) = value * 10;
2714 RET0_UNLESS(parse_digit(date, len, &value));
2715 (*digit) += value;
2716
2717 return 1;
2718}
2719
2720/* This function parses exactly 4 digits and returns the numeric value in "digit". */
2721static inline int parse_4digit(const char **date, int *len, int *digit)
2722{
2723 int value;
2724
2725 RET0_UNLESS(parse_digit(date, len, &value));
2726 (*digit) = value * 1000;
2727
2728 RET0_UNLESS(parse_digit(date, len, &value));
2729 (*digit) += value * 100;
2730
2731 RET0_UNLESS(parse_digit(date, len, &value));
2732 (*digit) += value * 10;
2733
2734 RET0_UNLESS(parse_digit(date, len, &value));
2735 (*digit) += value;
2736
2737 return 1;
2738}
2739
2740/* time-of-day = hour ":" minute ":" second
2741 * ; 00:00:00 - 23:59:60 (leap second)
2742 *
2743 * hour = 2DIGIT
2744 * minute = 2DIGIT
2745 * second = 2DIGIT
2746 */
2747static inline int parse_http_time(const char **date, int *len, struct tm *tm)
2748{
2749 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
2750 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
2751 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
2752 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
2753 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
2754 return 1;
2755}
2756
2757/* From RFC7231
2758 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
2759 *
2760 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
2761 * ; fixed length/zone/capitalization subset of the format
2762 * ; see Section 3.3 of [RFC5322]
2763 *
2764 *
2765 * date1 = day SP month SP year
2766 * ; e.g., 02 Jun 1982
2767 *
2768 * day = 2DIGIT
2769 * year = 4DIGIT
2770 *
2771 * GMT = %x47.4D.54 ; "GMT", case-sensitive
2772 *
2773 * time-of-day = hour ":" minute ":" second
2774 * ; 00:00:00 - 23:59:60 (leap second)
2775 *
2776 * hour = 2DIGIT
2777 * minute = 2DIGIT
2778 * second = 2DIGIT
2779 *
2780 * DIGIT = decimal 0-9
2781 */
2782int parse_imf_date(const char *date, int len, struct tm *tm)
2783{
2784 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
2785 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
2786 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2787 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
2788 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2789 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
2790 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2791 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
2792 tm->tm_year -= 1900;
2793 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2794 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
2795 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2796 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
2797 tm->tm_isdst = -1;
2798 tm->tm_gmtoff = 0;
2799 return 1;
2800}
2801
2802/* From RFC7231
2803 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
2804 *
2805 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
2806 * date2 = day "-" month "-" 2DIGIT
2807 * ; e.g., 02-Jun-82
2808 *
2809 * day = 2DIGIT
2810 */
2811int parse_rfc850_date(const char *date, int len, struct tm *tm)
2812{
2813 int year;
2814
2815 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
2816 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
2817 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2818 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
2819 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
2820 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
2821 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
2822
2823 /* year = 2DIGIT
2824 *
2825 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
2826 * two-digit year, MUST interpret a timestamp that appears to be more
2827 * than 50 years in the future as representing the most recent year in
2828 * the past that had the same last two digits.
2829 */
2830 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
2831
2832 /* expect SP */
2833 if (!parse_expect_char(&date, &len, ' ')) {
2834 /* Maybe we have the date with 4 digits. */
2835 RET0_UNLESS(parse_2digit(&date, &len, &year));
2836 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
2837 /* expect SP */
2838 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
2839 } else {
2840 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
2841 * tm_year is the number of year since 1900, so for +1900, we
2842 * do nothing, and for +2000, we add 100.
2843 */
2844 if (tm->tm_year <= 60)
2845 tm->tm_year += 100;
2846 }
2847
2848 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
2849 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2850 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
2851 tm->tm_isdst = -1;
2852 tm->tm_gmtoff = 0;
2853
2854 return 1;
2855}
2856
2857/* From RFC7231
2858 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
2859 *
2860 * asctime-date = day-name SP date3 SP time-of-day SP year
2861 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
2862 * ; e.g., Jun 2
2863 *
2864 * HTTP-date is case sensitive. A sender MUST NOT generate additional
2865 * whitespace in an HTTP-date beyond that specifically included as SP in
2866 * the grammar.
2867 */
2868int parse_asctime_date(const char *date, int len, struct tm *tm)
2869{
2870 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
2871 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2872 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
2873 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2874
2875 /* expect SP and 1DIGIT or 2DIGIT */
2876 if (parse_expect_char(&date, &len, ' '))
2877 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
2878 else
2879 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
2880
2881 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2882 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
2883 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
2884 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
2885 tm->tm_year -= 1900;
2886 tm->tm_isdst = -1;
2887 tm->tm_gmtoff = 0;
2888 return 1;
2889}
2890
2891/* From RFC7231
2892 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
2893 *
2894 * HTTP-date = IMF-fixdate / obs-date
2895 * obs-date = rfc850-date / asctime-date
2896 *
2897 * parses an HTTP date in the RFC format and is accepted
2898 * alternatives. <date> is the strinf containing the date,
2899 * len is the len of the string. <tm> is filled with the
2900 * parsed time. We must considers this time as GMT.
2901 */
2902int parse_http_date(const char *date, int len, struct tm *tm)
2903{
2904 if (parse_imf_date(date, len, tm))
2905 return 1;
2906
2907 if (parse_rfc850_date(date, len, tm))
2908 return 1;
2909
2910 if (parse_asctime_date(date, len, tm))
2911 return 1;
2912
2913 return 0;
2914}
2915
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002916/* Dynamically allocates a string of the proper length to hold the formatted
2917 * output. NULL is returned on error. The caller is responsible for freeing the
2918 * memory area using free(). The resulting string is returned in <out> if the
2919 * pointer is not NULL. A previous version of <out> might be used to build the
2920 * new string, and it will be freed before returning if it is not NULL, which
2921 * makes it possible to build complex strings from iterative calls without
2922 * having to care about freeing intermediate values, as in the example below :
2923 *
2924 * memprintf(&err, "invalid argument: '%s'", arg);
2925 * ...
2926 * memprintf(&err, "parser said : <%s>\n", *err);
2927 * ...
2928 * free(*err);
2929 *
2930 * This means that <err> must be initialized to NULL before first invocation.
2931 * The return value also holds the allocated string, which eases error checking
2932 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002933 * passed instead and it will be ignored. The returned message will then also
2934 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002935 *
2936 * It is also convenient to use it without any free except the last one :
2937 * err = NULL;
2938 * if (!fct1(err)) report(*err);
2939 * if (!fct2(err)) report(*err);
2940 * if (!fct3(err)) report(*err);
2941 * free(*err);
2942 */
2943char *memprintf(char **out, const char *format, ...)
2944{
2945 va_list args;
2946 char *ret = NULL;
2947 int allocated = 0;
2948 int needed = 0;
2949
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002950 if (!out)
2951 return NULL;
2952
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002953 do {
2954 /* vsnprintf() will return the required length even when the
2955 * target buffer is NULL. We do this in a loop just in case
2956 * intermediate evaluations get wrong.
2957 */
2958 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002959 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002960 va_end(args);
2961
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002962 if (needed < allocated) {
2963 /* Note: on Solaris 8, the first iteration always
2964 * returns -1 if allocated is zero, so we force a
2965 * retry.
2966 */
2967 if (!allocated)
2968 needed = 0;
2969 else
2970 break;
2971 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002972
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002973 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002974 ret = realloc(ret, allocated);
2975 } while (ret);
2976
2977 if (needed < 0) {
2978 /* an error was encountered */
2979 free(ret);
2980 ret = NULL;
2981 }
2982
2983 if (out) {
2984 free(*out);
2985 *out = ret;
2986 }
2987
2988 return ret;
2989}
William Lallemand421f5b52012-02-06 18:15:57 +01002990
Willy Tarreau21c705b2012-09-14 11:40:36 +02002991/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2992 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002993 * freed by the caller. It also supports being passed a NULL which results in the same
2994 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002995 * Example of use :
2996 * parse(cmd, &err); (callee: memprintf(&err, ...))
2997 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2998 * free(err);
2999 */
3000char *indent_msg(char **out, int level)
3001{
3002 char *ret, *in, *p;
3003 int needed = 0;
3004 int lf = 0;
3005 int lastlf = 0;
3006 int len;
3007
Willy Tarreau70eec382012-10-10 08:56:47 +02003008 if (!out || !*out)
3009 return NULL;
3010
Willy Tarreau21c705b2012-09-14 11:40:36 +02003011 in = *out - 1;
3012 while ((in = strchr(in + 1, '\n')) != NULL) {
3013 lastlf = in - *out;
3014 lf++;
3015 }
3016
3017 if (!lf) /* single line, no LF, return it as-is */
3018 return *out;
3019
3020 len = strlen(*out);
3021
3022 if (lf == 1 && lastlf == len - 1) {
3023 /* single line, LF at end, strip it and return as-is */
3024 (*out)[lastlf] = 0;
3025 return *out;
3026 }
3027
3028 /* OK now we have at least one LF, we need to process the whole string
3029 * as a multi-line string. What we'll do :
3030 * - prefix with an LF if there is none
3031 * - add <level> spaces before each line
3032 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3033 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3034 */
3035
3036 needed = 1 + level * (lf + 1) + len + 1;
3037 p = ret = malloc(needed);
3038 in = *out;
3039
3040 /* skip initial LFs */
3041 while (*in == '\n')
3042 in++;
3043
3044 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3045 while (*in) {
3046 *p++ = '\n';
3047 memset(p, ' ', level);
3048 p += level;
3049 do {
3050 *p++ = *in++;
3051 } while (*in && *in != '\n');
3052 if (*in)
3053 in++;
3054 }
3055 *p = 0;
3056
3057 free(*out);
3058 *out = ret;
3059
3060 return ret;
3061}
3062
Willy Tarreaudad36a32013-03-11 01:20:04 +01003063/* Convert occurrences of environment variables in the input string to their
3064 * corresponding value. A variable is identified as a series of alphanumeric
3065 * characters or underscores following a '$' sign. The <in> string must be
3066 * free()able. NULL returns NULL. The resulting string might be reallocated if
3067 * some expansion is made. Variable names may also be enclosed into braces if
3068 * needed (eg: to concatenate alphanum characters).
3069 */
3070char *env_expand(char *in)
3071{
3072 char *txt_beg;
3073 char *out;
3074 char *txt_end;
3075 char *var_beg;
3076 char *var_end;
3077 char *value;
3078 char *next;
3079 int out_len;
3080 int val_len;
3081
3082 if (!in)
3083 return in;
3084
3085 value = out = NULL;
3086 out_len = 0;
3087
3088 txt_beg = in;
3089 do {
3090 /* look for next '$' sign in <in> */
3091 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
3092
3093 if (!*txt_end && !out) /* end and no expansion performed */
3094 return in;
3095
3096 val_len = 0;
3097 next = txt_end;
3098 if (*txt_end == '$') {
3099 char save;
3100
3101 var_beg = txt_end + 1;
3102 if (*var_beg == '{')
3103 var_beg++;
3104
3105 var_end = var_beg;
3106 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
3107 var_end++;
3108 }
3109
3110 next = var_end;
3111 if (*var_end == '}' && (var_beg > txt_end + 1))
3112 next++;
3113
3114 /* get value of the variable name at this location */
3115 save = *var_end;
3116 *var_end = '\0';
3117 value = getenv(var_beg);
3118 *var_end = save;
3119 val_len = value ? strlen(value) : 0;
3120 }
3121
3122 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
3123 if (txt_end > txt_beg) {
3124 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
3125 out_len += txt_end - txt_beg;
3126 }
3127 if (val_len) {
3128 memcpy(out + out_len, value, val_len);
3129 out_len += val_len;
3130 }
3131 out[out_len] = 0;
3132 txt_beg = next;
3133 } while (*txt_beg);
3134
3135 /* here we know that <out> was allocated and that we don't need <in> anymore */
3136 free(in);
3137 return out;
3138}
3139
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003140
3141/* same as strstr() but case-insensitive and with limit length */
3142const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
3143{
3144 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02003145 unsigned int slen, plen;
3146 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02003147
3148 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
3149 return NULL;
3150
3151 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
3152 return str1;
3153
3154 if (len_str1 < len_str2) // pattern is longer than string => search is not found
3155 return NULL;
3156
3157 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
3158 while (toupper(*start) != toupper(*str2)) {
3159 start++;
3160 slen--;
3161 tmp1++;
3162
3163 if (tmp1 >= len_str1)
3164 return NULL;
3165
3166 /* if pattern longer than string */
3167 if (slen < plen)
3168 return NULL;
3169 }
3170
3171 sptr = start;
3172 pptr = (char *)str2;
3173
3174 tmp2 = 0;
3175 while (toupper(*sptr) == toupper(*pptr)) {
3176 sptr++;
3177 pptr++;
3178 tmp2++;
3179
3180 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
3181 return start;
3182 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
3183 return NULL;
3184 }
3185 }
3186 return NULL;
3187}
3188
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003189/* This function read the next valid utf8 char.
3190 * <s> is the byte srray to be decode, <len> is its length.
3191 * The function returns decoded char encoded like this:
3192 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
3193 * are the length read. The decoded character is stored in <c>.
3194 */
3195unsigned char utf8_next(const char *s, int len, unsigned int *c)
3196{
3197 const unsigned char *p = (unsigned char *)s;
3198 int dec;
3199 unsigned char code = UTF8_CODE_OK;
3200
3201 if (len < 1)
3202 return UTF8_CODE_OK;
3203
3204 /* Check the type of UTF8 sequence
3205 *
3206 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
3207 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
3208 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
3209 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
3210 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
3211 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
3212 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
3213 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
3214 */
3215 switch (*p) {
3216 case 0x00 ... 0x7f:
3217 *c = *p;
3218 return UTF8_CODE_OK | 1;
3219
3220 case 0x80 ... 0xbf:
3221 *c = *p;
3222 return UTF8_CODE_BADSEQ | 1;
3223
3224 case 0xc0 ... 0xdf:
3225 if (len < 2) {
3226 *c = *p;
3227 return UTF8_CODE_BADSEQ | 1;
3228 }
3229 *c = *p & 0x1f;
3230 dec = 1;
3231 break;
3232
3233 case 0xe0 ... 0xef:
3234 if (len < 3) {
3235 *c = *p;
3236 return UTF8_CODE_BADSEQ | 1;
3237 }
3238 *c = *p & 0x0f;
3239 dec = 2;
3240 break;
3241
3242 case 0xf0 ... 0xf7:
3243 if (len < 4) {
3244 *c = *p;
3245 return UTF8_CODE_BADSEQ | 1;
3246 }
3247 *c = *p & 0x07;
3248 dec = 3;
3249 break;
3250
3251 case 0xf8 ... 0xfb:
3252 if (len < 5) {
3253 *c = *p;
3254 return UTF8_CODE_BADSEQ | 1;
3255 }
3256 *c = *p & 0x03;
3257 dec = 4;
3258 break;
3259
3260 case 0xfc ... 0xfd:
3261 if (len < 6) {
3262 *c = *p;
3263 return UTF8_CODE_BADSEQ | 1;
3264 }
3265 *c = *p & 0x01;
3266 dec = 5;
3267 break;
3268
3269 case 0xfe ... 0xff:
3270 default:
3271 *c = *p;
3272 return UTF8_CODE_BADSEQ | 1;
3273 }
3274
3275 p++;
3276
3277 while (dec > 0) {
3278
3279 /* need 0x10 for the 2 first bits */
3280 if ( ( *p & 0xc0 ) != 0x80 )
3281 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
3282
3283 /* add data at char */
3284 *c = ( *c << 6 ) | ( *p & 0x3f );
3285
3286 dec--;
3287 p++;
3288 }
3289
3290 /* Check ovelong encoding.
3291 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
3292 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
3293 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
3294 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01003295 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02003296 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
3297 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
3298 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
3299 code |= UTF8_CODE_OVERLONG;
3300
3301 /* Check invalid UTF8 range. */
3302 if ((*c >= 0xd800 && *c <= 0xdfff) ||
3303 (*c >= 0xfffe && *c <= 0xffff))
3304 code |= UTF8_CODE_INVRANGE;
3305
3306 return code | ((p-(unsigned char *)s)&0x0f);
3307}
3308
Willy Tarreaubaaee002006-06-26 02:48:02 +02003309/*
3310 * Local variables:
3311 * c-indent-level: 8
3312 * c-basic-offset: 8
3313 * End:
3314 */