blob: 92998823c57945cc891a3a63f7ca22d34f16b3a1 [file] [log] [blame]
Willy Tarreaubaaee002006-06-26 02:48:02 +02001/*
2 * General purpose functions.
3 *
Willy Tarreau348238b2010-01-18 15:05:57 +01004 * Copyright 2000-2010 Willy Tarreau <w@1wt.eu>
Willy Tarreaubaaee002006-06-26 02:48:02 +02005 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
12
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010013#include <ctype.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020014#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020015#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020016#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020017#include <stdlib.h>
18#include <string.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010019#include <sys/socket.h>
20#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netinet/in.h>
22#include <arpa/inet.h>
23
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010024#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020025#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020026#include <common/standard.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010027#include <types/global.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010028#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020029
Willy Tarreau56adcf22012-12-23 18:00:29 +010030/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020031 * 2^64-1 = 18446744073709551615 or
32 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020033 *
34 * The HTML version needs room for adding the 25 characters
35 * '<span class="rls"></span>' around digits at positions 3N+1 in order
36 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020037 */
Willy Tarreau56adcf22012-12-23 18:00:29 +010038char itoa_str[NB_ITOA_STR][171];
39int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020040
Willy Tarreau588297f2014-06-16 15:16:40 +020041/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
42 * to quote strings larger than a max configuration line.
43 */
44char quoted_str[NB_QSTR][QSTR_SIZE + 1];
45int quoted_idx = 0;
46
Willy Tarreaubaaee002006-06-26 02:48:02 +020047/*
William Lallemande7340ec2012-01-24 11:15:39 +010048 * unsigned long long ASCII representation
49 *
50 * return the last char '\0' or NULL if no enough
51 * space in dst
52 */
53char *ulltoa(unsigned long long n, char *dst, size_t size)
54{
55 int i = 0;
56 char *res;
57
58 switch(n) {
59 case 1ULL ... 9ULL:
60 i = 0;
61 break;
62
63 case 10ULL ... 99ULL:
64 i = 1;
65 break;
66
67 case 100ULL ... 999ULL:
68 i = 2;
69 break;
70
71 case 1000ULL ... 9999ULL:
72 i = 3;
73 break;
74
75 case 10000ULL ... 99999ULL:
76 i = 4;
77 break;
78
79 case 100000ULL ... 999999ULL:
80 i = 5;
81 break;
82
83 case 1000000ULL ... 9999999ULL:
84 i = 6;
85 break;
86
87 case 10000000ULL ... 99999999ULL:
88 i = 7;
89 break;
90
91 case 100000000ULL ... 999999999ULL:
92 i = 8;
93 break;
94
95 case 1000000000ULL ... 9999999999ULL:
96 i = 9;
97 break;
98
99 case 10000000000ULL ... 99999999999ULL:
100 i = 10;
101 break;
102
103 case 100000000000ULL ... 999999999999ULL:
104 i = 11;
105 break;
106
107 case 1000000000000ULL ... 9999999999999ULL:
108 i = 12;
109 break;
110
111 case 10000000000000ULL ... 99999999999999ULL:
112 i = 13;
113 break;
114
115 case 100000000000000ULL ... 999999999999999ULL:
116 i = 14;
117 break;
118
119 case 1000000000000000ULL ... 9999999999999999ULL:
120 i = 15;
121 break;
122
123 case 10000000000000000ULL ... 99999999999999999ULL:
124 i = 16;
125 break;
126
127 case 100000000000000000ULL ... 999999999999999999ULL:
128 i = 17;
129 break;
130
131 case 1000000000000000000ULL ... 9999999999999999999ULL:
132 i = 18;
133 break;
134
135 case 10000000000000000000ULL ... ULLONG_MAX:
136 i = 19;
137 break;
138 }
139 if (i + 2 > size) // (i + 1) + '\0'
140 return NULL; // too long
141 res = dst + i + 1;
142 *res = '\0';
143 for (; i >= 0; i--) {
144 dst[i] = n % 10ULL + '0';
145 n /= 10ULL;
146 }
147 return res;
148}
149
150/*
151 * unsigned long ASCII representation
152 *
153 * return the last char '\0' or NULL if no enough
154 * space in dst
155 */
156char *ultoa_o(unsigned long n, char *dst, size_t size)
157{
158 int i = 0;
159 char *res;
160
161 switch (n) {
162 case 0U ... 9UL:
163 i = 0;
164 break;
165
166 case 10U ... 99UL:
167 i = 1;
168 break;
169
170 case 100U ... 999UL:
171 i = 2;
172 break;
173
174 case 1000U ... 9999UL:
175 i = 3;
176 break;
177
178 case 10000U ... 99999UL:
179 i = 4;
180 break;
181
182 case 100000U ... 999999UL:
183 i = 5;
184 break;
185
186 case 1000000U ... 9999999UL:
187 i = 6;
188 break;
189
190 case 10000000U ... 99999999UL:
191 i = 7;
192 break;
193
194 case 100000000U ... 999999999UL:
195 i = 8;
196 break;
197#if __WORDSIZE == 32
198
199 case 1000000000ULL ... ULONG_MAX:
200 i = 9;
201 break;
202
203#elif __WORDSIZE == 64
204
205 case 1000000000ULL ... 9999999999UL:
206 i = 9;
207 break;
208
209 case 10000000000ULL ... 99999999999UL:
210 i = 10;
211 break;
212
213 case 100000000000ULL ... 999999999999UL:
214 i = 11;
215 break;
216
217 case 1000000000000ULL ... 9999999999999UL:
218 i = 12;
219 break;
220
221 case 10000000000000ULL ... 99999999999999UL:
222 i = 13;
223 break;
224
225 case 100000000000000ULL ... 999999999999999UL:
226 i = 14;
227 break;
228
229 case 1000000000000000ULL ... 9999999999999999UL:
230 i = 15;
231 break;
232
233 case 10000000000000000ULL ... 99999999999999999UL:
234 i = 16;
235 break;
236
237 case 100000000000000000ULL ... 999999999999999999UL:
238 i = 17;
239 break;
240
241 case 1000000000000000000ULL ... 9999999999999999999UL:
242 i = 18;
243 break;
244
245 case 10000000000000000000ULL ... ULONG_MAX:
246 i = 19;
247 break;
248
249#endif
250 }
251 if (i + 2 > size) // (i + 1) + '\0'
252 return NULL; // too long
253 res = dst + i + 1;
254 *res = '\0';
255 for (; i >= 0; i--) {
256 dst[i] = n % 10U + '0';
257 n /= 10U;
258 }
259 return res;
260}
261
262/*
263 * signed long ASCII representation
264 *
265 * return the last char '\0' or NULL if no enough
266 * space in dst
267 */
268char *ltoa_o(long int n, char *dst, size_t size)
269{
270 char *pos = dst;
271
272 if (n < 0) {
273 if (size < 3)
274 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
275 *pos = '-';
276 pos++;
277 dst = ultoa_o(-n, pos, size - 1);
278 } else {
279 dst = ultoa_o(n, dst, size);
280 }
281 return dst;
282}
283
284/*
285 * signed long long ASCII representation
286 *
287 * return the last char '\0' or NULL if no enough
288 * space in dst
289 */
290char *lltoa(long long n, char *dst, size_t size)
291{
292 char *pos = dst;
293
294 if (n < 0) {
295 if (size < 3)
296 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
297 *pos = '-';
298 pos++;
299 dst = ulltoa(-n, pos, size - 1);
300 } else {
301 dst = ulltoa(n, dst, size);
302 }
303 return dst;
304}
305
306/*
307 * write a ascii representation of a unsigned into dst,
308 * return a pointer to the last character
309 * Pad the ascii representation with '0', using size.
310 */
311char *utoa_pad(unsigned int n, char *dst, size_t size)
312{
313 int i = 0;
314 char *ret;
315
316 switch(n) {
317 case 0U ... 9U:
318 i = 0;
319 break;
320
321 case 10U ... 99U:
322 i = 1;
323 break;
324
325 case 100U ... 999U:
326 i = 2;
327 break;
328
329 case 1000U ... 9999U:
330 i = 3;
331 break;
332
333 case 10000U ... 99999U:
334 i = 4;
335 break;
336
337 case 100000U ... 999999U:
338 i = 5;
339 break;
340
341 case 1000000U ... 9999999U:
342 i = 6;
343 break;
344
345 case 10000000U ... 99999999U:
346 i = 7;
347 break;
348
349 case 100000000U ... 999999999U:
350 i = 8;
351 break;
352
353 case 1000000000U ... 4294967295U:
354 i = 9;
355 break;
356 }
357 if (i + 2 > size) // (i + 1) + '\0'
358 return NULL; // too long
359 if (i < size)
360 i = size - 2; // padding - '\0'
361
362 ret = dst + i + 1;
363 *ret = '\0';
364 for (; i >= 0; i--) {
365 dst[i] = n % 10U + '0';
366 n /= 10U;
367 }
368 return ret;
369}
370
371/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200372 * copies at most <size-1> chars from <src> to <dst>. Last char is always
373 * set to 0, unless <size> is 0. The number of chars copied is returned
374 * (excluding the terminating zero).
375 * This code has been optimized for size and speed : on x86, it's 45 bytes
376 * long, uses only registers, and consumes only 4 cycles per char.
377 */
378int strlcpy2(char *dst, const char *src, int size)
379{
380 char *orig = dst;
381 if (size) {
382 while (--size && (*dst = *src)) {
383 src++; dst++;
384 }
385 *dst = 0;
386 }
387 return dst - orig;
388}
389
390/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200391 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200392 * the ascii representation for number 'n' in decimal.
393 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100394char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200395{
396 char *pos;
397
Willy Tarreau72d759c2007-10-25 12:14:10 +0200398 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200399 *pos-- = '\0';
400
401 do {
402 *pos-- = '0' + n % 10;
403 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200404 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200405 return pos + 1;
406}
407
Willy Tarreau91092e52007-10-25 16:58:42 +0200408/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200409 * This function simply returns a locally allocated string containing
410 * the ascii representation for number 'n' in decimal, formatted for
411 * HTML output with tags to create visual grouping by 3 digits. The
412 * output needs to support at least 171 characters.
413 */
414const char *ulltoh_r(unsigned long long n, char *buffer, int size)
415{
416 char *start;
417 int digit = 0;
418
419 start = buffer + size;
420 *--start = '\0';
421
422 do {
423 if (digit == 3 && start >= buffer + 7)
424 memcpy(start -= 7, "</span>", 7);
425
426 if (start >= buffer + 1) {
427 *--start = '0' + n % 10;
428 n /= 10;
429 }
430
431 if (digit == 3 && start >= buffer + 18)
432 memcpy(start -= 18, "<span class=\"rls\">", 18);
433
434 if (digit++ == 3)
435 digit = 1;
436 } while (n && start > buffer);
437 return start;
438}
439
440/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200441 * This function simply returns a locally allocated string containing the ascii
442 * representation for number 'n' in decimal, unless n is 0 in which case it
443 * returns the alternate string (or an empty string if the alternate string is
444 * NULL). It use is intended for limits reported in reports, where it's
445 * desirable not to display anything if there is no limit. Warning! it shares
446 * the same vector as ultoa_r().
447 */
448const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
449{
450 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
451}
452
Willy Tarreau588297f2014-06-16 15:16:40 +0200453/* returns a locally allocated string containing the quoted encoding of the
454 * input string. The output may be truncated to QSTR_SIZE chars, but it is
455 * guaranteed that the string will always be properly terminated. Quotes are
456 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
457 * always be at least 4 chars.
458 */
459const char *qstr(const char *str)
460{
461 char *ret = quoted_str[quoted_idx];
462 char *p, *end;
463
464 if (++quoted_idx >= NB_QSTR)
465 quoted_idx = 0;
466
467 p = ret;
468 end = ret + QSTR_SIZE;
469
470 *p++ = '"';
471
472 /* always keep 3 chars to support passing "" and the ending " */
473 while (*str && p < end - 3) {
474 if (*str == '"') {
475 *p++ = '"';
476 *p++ = '"';
477 }
478 else
479 *p++ = *str;
480 str++;
481 }
482 *p++ = '"';
483 return ret;
484}
485
Robert Tsai81ae1952007-12-05 10:47:29 +0100486/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200487 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
488 *
489 * It looks like this one would be a good candidate for inlining, but this is
490 * not interesting because it around 35 bytes long and often called multiple
491 * times within the same function.
492 */
493int ishex(char s)
494{
495 s -= '0';
496 if ((unsigned char)s <= 9)
497 return 1;
498 s -= 'A' - '0';
499 if ((unsigned char)s <= 5)
500 return 1;
501 s -= 'a' - 'A';
502 if ((unsigned char)s <= 5)
503 return 1;
504 return 0;
505}
506
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100507/*
508 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
509 * invalid character is found, a pointer to it is returned. If everything is
510 * fine, NULL is returned.
511 */
512const char *invalid_char(const char *name)
513{
514 if (!*name)
515 return name;
516
517 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100518 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100519 *name != '_' && *name != '-')
520 return name;
521 name++;
522 }
523 return NULL;
524}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200525
526/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200527 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
528 * If an invalid character is found, a pointer to it is returned.
529 * If everything is fine, NULL is returned.
530 */
531const char *invalid_domainchar(const char *name) {
532
533 if (!*name)
534 return name;
535
536 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100537 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200538 *name != '_' && *name != '-')
539 return name;
540
541 name++;
542 }
543
544 return NULL;
545}
546
547/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100548 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100549 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
550 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
551 * the function tries to guess the address family from the syntax. If the
552 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100553 * string is assumed to contain only an address, no port. The address can be a
554 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
555 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
556 * The return address will only have the address family and the address set,
557 * all other fields remain zero. The string is not supposed to be modified.
558 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200559 */
Willy Tarreau24709282013-03-10 21:32:12 +0100560static struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200561{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100562 struct hostent *he;
563
Willy Tarreaufab5a432011-03-04 15:31:53 +0100564 /* Any IPv6 address */
565 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100566 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
567 sa->ss_family = AF_INET6;
568 else if (sa->ss_family != AF_INET6)
569 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100570 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100571 }
572
Willy Tarreau24709282013-03-10 21:32:12 +0100573 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100574 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100575 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
576 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100577 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100578 }
579
580 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100581 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
582 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100583 sa->ss_family = AF_INET6;
584 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100585 }
586
587 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100588 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
589 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100590 sa->ss_family = AF_INET;
591 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100592 }
593
David du Colombierd5f43282011-03-17 10:40:16 +0100594#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200595 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100596 struct addrinfo hints, *result;
597
598 memset(&result, 0, sizeof(result));
599 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100600 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100601 hints.ai_socktype = SOCK_DGRAM;
602 hints.ai_flags = AI_PASSIVE;
603 hints.ai_protocol = 0;
604
605 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100606 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
607 sa->ss_family = result->ai_family;
608 else if (sa->ss_family != result->ai_family)
609 goto fail;
610
David du Colombierd5f43282011-03-17 10:40:16 +0100611 switch (result->ai_family) {
612 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100613 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
614 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100615 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100616 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
617 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100618 }
619 }
620
Sean Carey58ea0392013-02-15 23:39:18 +0100621 if (result)
622 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100623 }
David du Colombierd5f43282011-03-17 10:40:16 +0100624#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200625 /* try to resolve an IPv4/IPv6 hostname */
626 he = gethostbyname(str);
627 if (he) {
628 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
629 sa->ss_family = he->h_addrtype;
630 else if (sa->ss_family != he->h_addrtype)
631 goto fail;
632
633 switch (sa->ss_family) {
634 case AF_INET:
635 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
636 return sa;
637 case AF_INET6:
638 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
639 return sa;
640 }
641 }
642
David du Colombierd5f43282011-03-17 10:40:16 +0100643 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100644 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100645 return NULL;
646}
647
648/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100649 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
650 * range or offset consisting in two integers that the caller will have to
651 * check to find the relevant input format. The following format are supported :
652 *
653 * String format | address | port | low | high
654 * addr | <addr> | 0 | 0 | 0
655 * addr: | <addr> | 0 | 0 | 0
656 * addr:port | <addr> | <port> | <port> | <port>
657 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
658 * addr:+port | <addr> | <port> | 0 | <port>
659 * addr:-port | <addr> |-<port> | <port> | 0
660 *
661 * The detection of a port range or increment by the caller is made by
662 * comparing <low> and <high>. If both are equal, then port 0 means no port
663 * was specified. The caller may pass NULL for <low> and <high> if it is not
664 * interested in retrieving port ranges.
665 *
666 * Note that <addr> above may also be :
667 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
668 * - "*" => family will be AF_INET and address will be INADDR_ANY
669 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
670 * - a host name => family and address will depend on host name resolving.
671 *
Willy Tarreau24709282013-03-10 21:32:12 +0100672 * A prefix may be passed in before the address above to force the family :
673 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
674 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
675 * - "unix@" => force address to be a path to a UNIX socket even if the
676 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200677 * - 'abns@' -> force address to belong to the abstract namespace (Linux
678 * only). These sockets are just like Unix sockets but without
679 * the need for an underlying file system. The address is a
680 * string. Technically it's like a Unix socket with a zero in
681 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100682 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100683 *
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100684 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
685 * is mandatory after the IP address even when no port is specified. NULL is
686 * returned if the address cannot be parsed. The <low> and <high> ports are
Willy Tarreau24709282013-03-10 21:32:12 +0100687 * always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100688 *
689 * If <pfx> is non-null, it is used as a string prefix before any path-based
690 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100691 *
692 * When a file descriptor is passed, its value is put into the s_addr part of
693 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100694 */
Willy Tarreaud393a622013-03-04 18:22:00 +0100695struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100696{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100697 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100698 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100699 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100700 char *port1, *port2;
701 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200702 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100703
704 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200705
Willy Tarreaudad36a32013-03-11 01:20:04 +0100706 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100707 if (str2 == NULL) {
708 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100709 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100710 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200711
Willy Tarreau36456072015-09-08 16:01:25 +0200712 if (!*str2) {
713 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
714 goto out;
715 }
716
Willy Tarreau24709282013-03-10 21:32:12 +0100717 memset(&ss, 0, sizeof(ss));
718
719 if (strncmp(str2, "unix@", 5) == 0) {
720 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200721 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100722 ss.ss_family = AF_UNIX;
723 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200724 else if (strncmp(str2, "abns@", 5) == 0) {
725 str2 += 5;
726 abstract = 1;
727 ss.ss_family = AF_UNIX;
728 }
Willy Tarreau24709282013-03-10 21:32:12 +0100729 else if (strncmp(str2, "ipv4@", 5) == 0) {
730 str2 += 5;
731 ss.ss_family = AF_INET;
732 }
733 else if (strncmp(str2, "ipv6@", 5) == 0) {
734 str2 += 5;
735 ss.ss_family = AF_INET6;
736 }
737 else if (*str2 == '/') {
738 ss.ss_family = AF_UNIX;
739 }
740 else
741 ss.ss_family = AF_UNSPEC;
742
Willy Tarreau40aa0702013-03-10 23:51:38 +0100743 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
744 char *endptr;
745
746 str2 += 3;
747 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
748
749 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100750 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100751 goto out;
752 }
753
754 /* we return AF_UNSPEC if we use a file descriptor number */
755 ss.ss_family = AF_UNSPEC;
756 }
757 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100758 int prefix_path_len;
759 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200760 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100761
762 /* complete unix socket path name during startup or soft-restart is
763 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
764 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200765 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100766 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
767 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
768
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200769 adr_len = strlen(str2);
770 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100771 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
772 goto out;
773 }
774
Willy Tarreauccfccef2014-05-10 01:49:15 +0200775 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
776 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200777 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100778 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200779 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100780 }
Willy Tarreau24709282013-03-10 21:32:12 +0100781 else { /* IPv4 and IPv6 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100782 port1 = strrchr(str2, ':');
783 if (port1)
784 *port1++ = '\0';
785 else
786 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200787
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100788 if (str2ip(str2, &ss) == NULL) {
789 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
790 goto out;
791 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100792
Willy Tarreaua39d1992013-04-01 20:37:42 +0200793 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100794 port2 = strchr(port1, '-');
795 if (port2)
796 *port2++ = '\0';
797 else
798 port2 = port1;
799 portl = atoi(port1);
800 porth = atoi(port2);
801 porta = portl;
802 }
803 else if (*port1 == '-') { /* negative offset */
804 portl = atoi(port1 + 1);
805 porta = -portl;
806 }
807 else if (*port1 == '+') { /* positive offset */
808 porth = atoi(port1 + 1);
809 porta = porth;
810 }
811 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100812 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100813 goto out;
814 }
815 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100816 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100817
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100818 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100819 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100820 if (low)
821 *low = portl;
822 if (high)
823 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100824 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100825 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200826}
827
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100828/* converts <str> to a struct in_addr containing a network mask. It can be
829 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
830 * if the conversion succeeds otherwise non-zero.
831 */
832int str2mask(const char *str, struct in_addr *mask)
833{
834 if (strchr(str, '.') != NULL) { /* dotted notation */
835 if (!inet_pton(AF_INET, str, mask))
836 return 0;
837 }
838 else { /* mask length */
839 char *err;
840 unsigned long len = strtol(str, &err, 10);
841
842 if (!*str || (err && *err) || (unsigned)len > 32)
843 return 0;
844 if (len)
845 mask->s_addr = htonl(~0UL << (32 - len));
846 else
847 mask->s_addr = 0;
848 }
849 return 1;
850}
851
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100852/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
853 * succeeds otherwise zero.
854 */
855int cidr2dotted(int cidr, struct in_addr *mask) {
856
857 if (cidr < 0 || cidr > 32)
858 return 0;
859
860 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
861 return 1;
862}
863
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200864/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200865 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200866 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
867 * is optionnal and either in the dotted or CIDR notation.
868 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
869 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100870int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200871{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200872 __label__ out_free, out_err;
873 char *c, *s;
874 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200875
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200876 s = strdup(str);
877 if (!s)
878 return 0;
879
Willy Tarreaubaaee002006-06-26 02:48:02 +0200880 memset(mask, 0, sizeof(*mask));
881 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200882
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200883 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200884 *c++ = '\0';
885 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100886 if (!str2mask(c, mask))
887 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200888 }
889 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100890 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200891 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200892 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200893 struct hostent *he;
894
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100895 if (!resolve)
896 goto out_err;
897
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200898 if ((he = gethostbyname(s)) == NULL) {
899 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200900 }
901 else
902 *addr = *(struct in_addr *) *(he->h_addr_list);
903 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200904
905 ret_val = 1;
906 out_free:
907 free(s);
908 return ret_val;
909 out_err:
910 ret_val = 0;
911 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200912}
913
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100914
915/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200916 * converts <str> to two struct in6_addr* which must be pre-allocated.
917 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
918 * is an optionnal number of bits (128 being the default).
919 * Returns 1 if OK, 0 if error.
920 */
921int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
922{
923 char *c, *s;
924 int ret_val = 0;
925 char *err;
926 unsigned long len = 128;
927
928 s = strdup(str);
929 if (!s)
930 return 0;
931
932 memset(mask, 0, sizeof(*mask));
933 memset(addr, 0, sizeof(*addr));
934
935 if ((c = strrchr(s, '/')) != NULL) {
936 *c++ = '\0'; /* c points to the mask */
937 if (!*c)
938 goto out_free;
939
940 len = strtoul(c, &err, 10);
941 if ((err && *err) || (unsigned)len > 128)
942 goto out_free;
943 }
944 *mask = len; /* OK we have a valid mask in <len> */
945
946 if (!inet_pton(AF_INET6, s, addr))
947 goto out_free;
948
949 ret_val = 1;
950 out_free:
951 free(s);
952 return ret_val;
953}
954
955
956/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100957 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100958 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100959int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100960{
961 int saw_digit, octets, ch;
962 u_char tmp[4], *tp;
963 const char *cp = addr;
964
965 saw_digit = 0;
966 octets = 0;
967 *(tp = tmp) = 0;
968
969 while (*addr) {
970 unsigned char digit = (ch = *addr++) - '0';
971 if (digit > 9 && ch != '.')
972 break;
973 if (digit <= 9) {
974 u_int new = *tp * 10 + digit;
975 if (new > 255)
976 return 0;
977 *tp = new;
978 if (!saw_digit) {
979 if (++octets > 4)
980 return 0;
981 saw_digit = 1;
982 }
983 } else if (ch == '.' && saw_digit) {
984 if (octets == 4)
985 return 0;
986 *++tp = 0;
987 saw_digit = 0;
988 } else
989 return 0;
990 }
991
992 if (octets < 4)
993 return 0;
994
995 memcpy(&dst->s_addr, tmp, 4);
996 return addr-cp-1;
997}
998
999/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001000 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1001 * <out> contain the code of the dectected scheme, the start and length of
1002 * the hostname. Actually only http and https are supported. <out> can be NULL.
1003 * This function returns the consumed length. It is useful if you parse complete
1004 * url like http://host:port/path, because the consumed length corresponds to
1005 * the first character of the path. If the conversion fails, it returns -1.
1006 *
1007 * This function tries to resolve the DNS name if haproxy is in starting mode.
1008 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001009 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001010int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001011{
1012 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001013 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001014 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001015 unsigned long long int http_code = 0;
1016 int default_port;
1017 struct hostent *he;
1018 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001019
1020 /* Firstly, try to find :// pattern */
1021 while (curr < url+ulen && url_code != 0x3a2f2f) {
1022 url_code = ((url_code & 0xffff) << 8);
1023 url_code += (unsigned char)*curr++;
1024 }
1025
1026 /* Secondly, if :// pattern is found, verify parsed stuff
1027 * before pattern is matching our http pattern.
1028 * If so parse ip address and port in uri.
1029 *
1030 * WARNING: Current code doesn't support dynamic async dns resolver.
1031 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001032 if (url_code != 0x3a2f2f)
1033 return -1;
1034
1035 /* Copy scheme, and utrn to lower case. */
1036 while (cp < curr - 3)
1037 http_code = (http_code << 8) + *cp++;
1038 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001039
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001040 /* HTTP or HTTPS url matching */
1041 if (http_code == 0x2020202068747470ULL) {
1042 default_port = 80;
1043 if (out)
1044 out->scheme = SCH_HTTP;
1045 }
1046 else if (http_code == 0x2020206874747073ULL) {
1047 default_port = 443;
1048 if (out)
1049 out->scheme = SCH_HTTPS;
1050 }
1051 else
1052 return -1;
1053
1054 /* If the next char is '[', the host address is IPv6. */
1055 if (*curr == '[') {
1056 curr++;
1057
1058 /* Check trash size */
1059 if (trash.size < ulen)
1060 return -1;
1061
1062 /* Look for ']' and copy the address in a trash buffer. */
1063 p = trash.str;
1064 for (end = curr;
1065 end < url + ulen && *end != ']';
1066 end++, p++)
1067 *p = *end;
1068 if (*end != ']')
1069 return -1;
1070 *p = '\0';
1071
1072 /* Update out. */
1073 if (out) {
1074 out->host = curr;
1075 out->host_len = end - curr;
1076 }
1077
1078 /* Try IPv6 decoding. */
1079 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1080 return -1;
1081 end++;
1082
1083 /* Decode port. */
1084 if (*end == ':') {
1085 end++;
1086 default_port = read_uint(&end, url + ulen);
1087 }
1088 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1089 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1090 return end - url;
1091 }
1092 else {
1093 /* We are looking for IP address. If you want to parse and
1094 * resolve hostname found in url, you can use str2sa_range(), but
1095 * be warned this can slow down global daemon performances
1096 * while handling lagging dns responses.
1097 */
1098 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1099 if (ret) {
1100 /* Update out. */
1101 if (out) {
1102 out->host = curr;
1103 out->host_len = ret;
1104 }
1105
1106 curr += ret;
1107
1108 /* Decode port. */
1109 if (*curr == ':') {
1110 curr++;
1111 default_port = read_uint(&curr, url + ulen);
1112 }
1113 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1114
1115 /* Set family. */
1116 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1117 return curr - url;
1118 }
1119 else if (global.mode & MODE_STARTING) {
1120 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1121 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001122 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001123
1124 /* look for : or / or end */
1125 for (end = curr;
1126 end < url + ulen && *end != '/' && *end != ':';
1127 end++);
1128 memcpy(trash.str, curr, end - curr);
1129 trash.str[end - curr] = '\0';
1130
1131 /* try to resolve an IPv4/IPv6 hostname */
1132 he = gethostbyname(trash.str);
1133 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001134 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001135
1136 /* Update out. */
1137 if (out) {
1138 out->host = curr;
1139 out->host_len = end - curr;
1140 }
1141
1142 /* Decode port. */
1143 if (*end == ':') {
1144 end++;
1145 default_port = read_uint(&end, url + ulen);
1146 }
1147
1148 /* Copy IP address, set port and family. */
1149 switch (he->h_addrtype) {
1150 case AF_INET:
1151 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1152 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1153 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1154 return end - url;
1155
1156 case AF_INET6:
1157 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1158 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1159 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1160 return end - url;
1161 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001162 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001163 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001164 return -1;
1165}
1166
Willy Tarreau631f01c2011-09-05 00:36:48 +02001167/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1168 * address family is returned so that it's easy for the caller to adapt to the
1169 * output format. Zero is returned if the address family is not supported. -1
1170 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1171 * supported.
1172 */
1173int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1174{
1175
1176 void *ptr;
1177
1178 if (size < 5)
1179 return 0;
1180 *str = '\0';
1181
1182 switch (addr->ss_family) {
1183 case AF_INET:
1184 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1185 break;
1186 case AF_INET6:
1187 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1188 break;
1189 case AF_UNIX:
1190 memcpy(str, "unix", 5);
1191 return addr->ss_family;
1192 default:
1193 return 0;
1194 }
1195
1196 if (inet_ntop(addr->ss_family, ptr, str, size))
1197 return addr->ss_family;
1198
1199 /* failed */
1200 return -1;
1201}
1202
Simon Horman75ab8bd2014-06-16 09:39:41 +09001203/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1204 * address family is returned so that it's easy for the caller to adapt to the
1205 * output format. Zero is returned if the address family is not supported. -1
1206 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1207 * supported.
1208 */
1209int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1210{
1211
1212 uint16_t port;
1213
1214
1215 if (size < 5)
1216 return 0;
1217 *str = '\0';
1218
1219 switch (addr->ss_family) {
1220 case AF_INET:
1221 port = ((struct sockaddr_in *)addr)->sin_port;
1222 break;
1223 case AF_INET6:
1224 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1225 break;
1226 case AF_UNIX:
1227 memcpy(str, "unix", 5);
1228 return addr->ss_family;
1229 default:
1230 return 0;
1231 }
1232
1233 snprintf(str, size, "%u", ntohs(port));
1234 return addr->ss_family;
1235}
1236
Willy Tarreaubaaee002006-06-26 02:48:02 +02001237/* will try to encode the string <string> replacing all characters tagged in
1238 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1239 * prefixed by <escape>, and will store the result between <start> (included)
1240 * and <stop> (excluded), and will always terminate the string with a '\0'
1241 * before <stop>. The position of the '\0' is returned if the conversion
1242 * completes. If bytes are missing between <start> and <stop>, then the
1243 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1244 * cannot even be stored so we return <start> without writing the 0.
1245 * The input string must also be zero-terminated.
1246 */
1247const char hextab[16] = "0123456789ABCDEF";
1248char *encode_string(char *start, char *stop,
1249 const char escape, const fd_set *map,
1250 const char *string)
1251{
1252 if (start < stop) {
1253 stop--; /* reserve one byte for the final '\0' */
1254 while (start < stop && *string != '\0') {
1255 if (!FD_ISSET((unsigned char)(*string), map))
1256 *start++ = *string;
1257 else {
1258 if (start + 3 >= stop)
1259 break;
1260 *start++ = escape;
1261 *start++ = hextab[(*string >> 4) & 15];
1262 *start++ = hextab[*string & 15];
1263 }
1264 string++;
1265 }
1266 *start = '\0';
1267 }
1268 return start;
1269}
1270
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001271/*
1272 * Same behavior as encode_string() above, except that it encodes chunk
1273 * <chunk> instead of a string.
1274 */
1275char *encode_chunk(char *start, char *stop,
1276 const char escape, const fd_set *map,
1277 const struct chunk *chunk)
1278{
1279 char *str = chunk->str;
1280 char *end = chunk->str + chunk->len;
1281
1282 if (start < stop) {
1283 stop--; /* reserve one byte for the final '\0' */
1284 while (start < stop && str < end) {
1285 if (!FD_ISSET((unsigned char)(*str), map))
1286 *start++ = *str;
1287 else {
1288 if (start + 3 >= stop)
1289 break;
1290 *start++ = escape;
1291 *start++ = hextab[(*str >> 4) & 15];
1292 *start++ = hextab[*str & 15];
1293 }
1294 str++;
1295 }
1296 *start = '\0';
1297 }
1298 return start;
1299}
1300
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001301/* Decode an URL-encoded string in-place. The resulting string might
1302 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001303 * aborted, the string is truncated before the issue and a negative value is
1304 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001305 */
1306int url_decode(char *string)
1307{
1308 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001309 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001310
1311 in = string;
1312 out = string;
1313 while (*in) {
1314 switch (*in) {
1315 case '+' :
1316 *out++ = ' ';
1317 break;
1318 case '%' :
1319 if (!ishex(in[1]) || !ishex(in[2]))
1320 goto end;
1321 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1322 in += 2;
1323 break;
1324 default:
1325 *out++ = *in;
1326 break;
1327 }
1328 in++;
1329 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001330 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001331 end:
1332 *out = 0;
1333 return ret;
1334}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001335
Willy Tarreau6911fa42007-03-04 18:06:08 +01001336unsigned int str2ui(const char *s)
1337{
1338 return __str2ui(s);
1339}
1340
1341unsigned int str2uic(const char *s)
1342{
1343 return __str2uic(s);
1344}
1345
1346unsigned int strl2ui(const char *s, int len)
1347{
1348 return __strl2ui(s, len);
1349}
1350
1351unsigned int strl2uic(const char *s, int len)
1352{
1353 return __strl2uic(s, len);
1354}
1355
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001356unsigned int read_uint(const char **s, const char *end)
1357{
1358 return __read_uint(s, end);
1359}
1360
Willy Tarreau6911fa42007-03-04 18:06:08 +01001361/* This one is 7 times faster than strtol() on athlon with checks.
1362 * It returns the value of the number composed of all valid digits read,
1363 * and can process negative numbers too.
1364 */
1365int strl2ic(const char *s, int len)
1366{
1367 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001368 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001369
1370 if (len > 0) {
1371 if (*s != '-') {
1372 /* positive number */
1373 while (len-- > 0) {
1374 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001375 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001376 if (j > 9)
1377 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001378 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001379 }
1380 } else {
1381 /* negative number */
1382 s++;
1383 while (--len > 0) {
1384 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001385 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001386 if (j > 9)
1387 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001388 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001389 }
1390 }
1391 }
1392 return i;
1393}
1394
1395
1396/* This function reads exactly <len> chars from <s> and converts them to a
1397 * signed integer which it stores into <ret>. It accurately detects any error
1398 * (truncated string, invalid chars, overflows). It is meant to be used in
1399 * applications designed for hostile environments. It returns zero when the
1400 * number has successfully been converted, non-zero otherwise. When an error
1401 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1402 * faster than strtol().
1403 */
1404int strl2irc(const char *s, int len, int *ret)
1405{
1406 int i = 0;
1407 int j;
1408
1409 if (!len)
1410 return 1;
1411
1412 if (*s != '-') {
1413 /* positive number */
1414 while (len-- > 0) {
1415 j = (*s++) - '0';
1416 if (j > 9) return 1; /* invalid char */
1417 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1418 i = i * 10;
1419 if (i + j < i) return 1; /* check for addition overflow */
1420 i = i + j;
1421 }
1422 } else {
1423 /* negative number */
1424 s++;
1425 while (--len > 0) {
1426 j = (*s++) - '0';
1427 if (j > 9) return 1; /* invalid char */
1428 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1429 i = i * 10;
1430 if (i - j > i) return 1; /* check for subtract overflow */
1431 i = i - j;
1432 }
1433 }
1434 *ret = i;
1435 return 0;
1436}
1437
1438
1439/* This function reads exactly <len> chars from <s> and converts them to a
1440 * signed integer which it stores into <ret>. It accurately detects any error
1441 * (truncated string, invalid chars, overflows). It is meant to be used in
1442 * applications designed for hostile environments. It returns zero when the
1443 * number has successfully been converted, non-zero otherwise. When an error
1444 * is returned, the <ret> value is left untouched. It is about 3 times slower
1445 * than str2irc().
1446 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001447
1448int strl2llrc(const char *s, int len, long long *ret)
1449{
1450 long long i = 0;
1451 int j;
1452
1453 if (!len)
1454 return 1;
1455
1456 if (*s != '-') {
1457 /* positive number */
1458 while (len-- > 0) {
1459 j = (*s++) - '0';
1460 if (j > 9) return 1; /* invalid char */
1461 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1462 i = i * 10LL;
1463 if (i + j < i) return 1; /* check for addition overflow */
1464 i = i + j;
1465 }
1466 } else {
1467 /* negative number */
1468 s++;
1469 while (--len > 0) {
1470 j = (*s++) - '0';
1471 if (j > 9) return 1; /* invalid char */
1472 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1473 i = i * 10LL;
1474 if (i - j > i) return 1; /* check for subtract overflow */
1475 i = i - j;
1476 }
1477 }
1478 *ret = i;
1479 return 0;
1480}
1481
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001482/* This function is used with pat_parse_dotted_ver(). It converts a string
1483 * composed by two number separated by a dot. Each part must contain in 16 bits
1484 * because internally they will be represented as a 32-bit quantity stored in
1485 * a 64-bit integer. It returns zero when the number has successfully been
1486 * converted, non-zero otherwise. When an error is returned, the <ret> value
1487 * is left untouched.
1488 *
1489 * "1.3" -> 0x0000000000010003
1490 * "65535.65535" -> 0x00000000ffffffff
1491 */
1492int strl2llrc_dotted(const char *text, int len, long long *ret)
1493{
1494 const char *end = &text[len];
1495 const char *p;
1496 long long major, minor;
1497
1498 /* Look for dot. */
1499 for (p = text; p < end; p++)
1500 if (*p == '.')
1501 break;
1502
1503 /* Convert major. */
1504 if (strl2llrc(text, p - text, &major) != 0)
1505 return 1;
1506
1507 /* Check major. */
1508 if (major >= 65536)
1509 return 1;
1510
1511 /* Convert minor. */
1512 minor = 0;
1513 if (p < end)
1514 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1515 return 1;
1516
1517 /* Check minor. */
1518 if (minor >= 65536)
1519 return 1;
1520
1521 /* Compose value. */
1522 *ret = (major << 16) | (minor & 0xffff);
1523 return 0;
1524}
1525
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001526/* This function parses a time value optionally followed by a unit suffix among
1527 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1528 * expected by the caller. The computation does its best to avoid overflows.
1529 * The value is returned in <ret> if everything is fine, and a NULL is returned
1530 * by the function. In case of error, a pointer to the error is returned and
1531 * <ret> is left untouched. Values are automatically rounded up when needed.
1532 */
1533const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1534{
1535 unsigned imult, idiv;
1536 unsigned omult, odiv;
1537 unsigned value;
1538
1539 omult = odiv = 1;
1540
1541 switch (unit_flags & TIME_UNIT_MASK) {
1542 case TIME_UNIT_US: omult = 1000000; break;
1543 case TIME_UNIT_MS: omult = 1000; break;
1544 case TIME_UNIT_S: break;
1545 case TIME_UNIT_MIN: odiv = 60; break;
1546 case TIME_UNIT_HOUR: odiv = 3600; break;
1547 case TIME_UNIT_DAY: odiv = 86400; break;
1548 default: break;
1549 }
1550
1551 value = 0;
1552
1553 while (1) {
1554 unsigned int j;
1555
1556 j = *text - '0';
1557 if (j > 9)
1558 break;
1559 text++;
1560 value *= 10;
1561 value += j;
1562 }
1563
1564 imult = idiv = 1;
1565 switch (*text) {
1566 case '\0': /* no unit = default unit */
1567 imult = omult = idiv = odiv = 1;
1568 break;
1569 case 's': /* second = unscaled unit */
1570 break;
1571 case 'u': /* microsecond : "us" */
1572 if (text[1] == 's') {
1573 idiv = 1000000;
1574 text++;
1575 }
1576 break;
1577 case 'm': /* millisecond : "ms" or minute: "m" */
1578 if (text[1] == 's') {
1579 idiv = 1000;
1580 text++;
1581 } else
1582 imult = 60;
1583 break;
1584 case 'h': /* hour : "h" */
1585 imult = 3600;
1586 break;
1587 case 'd': /* day : "d" */
1588 imult = 86400;
1589 break;
1590 default:
1591 return text;
1592 break;
1593 }
1594
1595 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1596 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1597 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1598 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1599
1600 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1601 *ret = value;
1602 return NULL;
1603}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001604
Emeric Brun39132b22010-01-04 14:57:24 +01001605/* this function converts the string starting at <text> to an unsigned int
1606 * stored in <ret>. If an error is detected, the pointer to the unexpected
1607 * character is returned. If the conversio is succesful, NULL is returned.
1608 */
1609const char *parse_size_err(const char *text, unsigned *ret) {
1610 unsigned value = 0;
1611
1612 while (1) {
1613 unsigned int j;
1614
1615 j = *text - '0';
1616 if (j > 9)
1617 break;
1618 if (value > ~0U / 10)
1619 return text;
1620 value *= 10;
1621 if (value > (value + j))
1622 return text;
1623 value += j;
1624 text++;
1625 }
1626
1627 switch (*text) {
1628 case '\0':
1629 break;
1630 case 'K':
1631 case 'k':
1632 if (value > ~0U >> 10)
1633 return text;
1634 value = value << 10;
1635 break;
1636 case 'M':
1637 case 'm':
1638 if (value > ~0U >> 20)
1639 return text;
1640 value = value << 20;
1641 break;
1642 case 'G':
1643 case 'g':
1644 if (value > ~0U >> 30)
1645 return text;
1646 value = value << 30;
1647 break;
1648 default:
1649 return text;
1650 }
1651
1652 *ret = value;
1653 return NULL;
1654}
1655
Willy Tarreau126d4062013-12-03 17:50:47 +01001656/*
1657 * Parse binary string written in hexadecimal (source) and store the decoded
1658 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1659 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001660 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001661 */
1662int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1663{
1664 int len;
1665 const char *p = source;
1666 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001667 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001668
1669 len = strlen(source);
1670 if (len % 2) {
1671 memprintf(err, "an even number of hex digit is expected");
1672 return 0;
1673 }
1674
1675 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001676
Willy Tarreau126d4062013-12-03 17:50:47 +01001677 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001678 *binstr = calloc(len, sizeof(char));
1679 if (!*binstr) {
1680 memprintf(err, "out of memory while loading string pattern");
1681 return 0;
1682 }
1683 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001684 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001685 else {
1686 if (*binstrlen < len) {
1687 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1688 len, *binstrlen);
1689 return 0;
1690 }
1691 alloc = 0;
1692 }
1693 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001694
1695 i = j = 0;
1696 while (j < len) {
1697 if (!ishex(p[i++]))
1698 goto bad_input;
1699 if (!ishex(p[i++]))
1700 goto bad_input;
1701 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1702 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001703 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001704
1705bad_input:
1706 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001707 if (alloc)
1708 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001709 return 0;
1710}
1711
Willy Tarreau946ba592009-05-10 15:41:18 +02001712/* copies at most <n> characters from <src> and always terminates with '\0' */
1713char *my_strndup(const char *src, int n)
1714{
1715 int len = 0;
1716 char *ret;
1717
1718 while (len < n && src[len])
1719 len++;
1720
1721 ret = (char *)malloc(len + 1);
1722 if (!ret)
1723 return ret;
1724 memcpy(ret, src, len);
1725 ret[len] = '\0';
1726 return ret;
1727}
1728
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001729/*
1730 * search needle in haystack
1731 * returns the pointer if found, returns NULL otherwise
1732 */
1733const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1734{
1735 const void *c = NULL;
1736 unsigned char f;
1737
1738 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1739 return NULL;
1740
1741 f = *(char *)needle;
1742 c = haystack;
1743 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1744 if ((haystacklen - (c - haystack)) < needlelen)
1745 return NULL;
1746
1747 if (memcmp(c, needle, needlelen) == 0)
1748 return c;
1749 ++c;
1750 }
1751 return NULL;
1752}
1753
Willy Tarreau482b00d2009-10-04 22:48:42 +02001754/* This function returns the first unused key greater than or equal to <key> in
1755 * ID tree <root>. Zero is returned if no place is found.
1756 */
1757unsigned int get_next_id(struct eb_root *root, unsigned int key)
1758{
1759 struct eb32_node *used;
1760
1761 do {
1762 used = eb32_lookup_ge(root, key);
1763 if (!used || used->key > key)
1764 return key; /* key is available */
1765 key++;
1766 } while (key);
1767 return key;
1768}
1769
Willy Tarreau348238b2010-01-18 15:05:57 +01001770/* This function compares a sample word possibly followed by blanks to another
1771 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1772 * otherwise zero. This intends to be used when checking HTTP headers for some
1773 * values. Note that it validates a word followed only by blanks but does not
1774 * validate a word followed by blanks then other chars.
1775 */
1776int word_match(const char *sample, int slen, const char *word, int wlen)
1777{
1778 if (slen < wlen)
1779 return 0;
1780
1781 while (wlen) {
1782 char c = *sample ^ *word;
1783 if (c && c != ('A' ^ 'a'))
1784 return 0;
1785 sample++;
1786 word++;
1787 slen--;
1788 wlen--;
1789 }
1790
1791 while (slen) {
1792 if (*sample != ' ' && *sample != '\t')
1793 return 0;
1794 sample++;
1795 slen--;
1796 }
1797 return 1;
1798}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001799
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001800/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1801 * is particularly fast because it avoids expensive operations such as
1802 * multiplies, which are optimized away at the end. It requires a properly
1803 * formated address though (3 points).
1804 */
1805unsigned int inetaddr_host(const char *text)
1806{
1807 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1808 register unsigned int dig100, dig10, dig1;
1809 int s;
1810 const char *p, *d;
1811
1812 dig1 = dig10 = dig100 = ascii_zero;
1813 s = 24;
1814
1815 p = text;
1816 while (1) {
1817 if (((unsigned)(*p - '0')) <= 9) {
1818 p++;
1819 continue;
1820 }
1821
1822 /* here, we have a complete byte between <text> and <p> (exclusive) */
1823 if (p == text)
1824 goto end;
1825
1826 d = p - 1;
1827 dig1 |= (unsigned int)(*d << s);
1828 if (d == text)
1829 goto end;
1830
1831 d--;
1832 dig10 |= (unsigned int)(*d << s);
1833 if (d == text)
1834 goto end;
1835
1836 d--;
1837 dig100 |= (unsigned int)(*d << s);
1838 end:
1839 if (!s || *p != '.')
1840 break;
1841
1842 s -= 8;
1843 text = ++p;
1844 }
1845
1846 dig100 -= ascii_zero;
1847 dig10 -= ascii_zero;
1848 dig1 -= ascii_zero;
1849 return ((dig100 * 10) + dig10) * 10 + dig1;
1850}
1851
1852/*
1853 * Idem except the first unparsed character has to be passed in <stop>.
1854 */
1855unsigned int inetaddr_host_lim(const char *text, const char *stop)
1856{
1857 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1858 register unsigned int dig100, dig10, dig1;
1859 int s;
1860 const char *p, *d;
1861
1862 dig1 = dig10 = dig100 = ascii_zero;
1863 s = 24;
1864
1865 p = text;
1866 while (1) {
1867 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1868 p++;
1869 continue;
1870 }
1871
1872 /* here, we have a complete byte between <text> and <p> (exclusive) */
1873 if (p == text)
1874 goto end;
1875
1876 d = p - 1;
1877 dig1 |= (unsigned int)(*d << s);
1878 if (d == text)
1879 goto end;
1880
1881 d--;
1882 dig10 |= (unsigned int)(*d << s);
1883 if (d == text)
1884 goto end;
1885
1886 d--;
1887 dig100 |= (unsigned int)(*d << s);
1888 end:
1889 if (!s || p == stop || *p != '.')
1890 break;
1891
1892 s -= 8;
1893 text = ++p;
1894 }
1895
1896 dig100 -= ascii_zero;
1897 dig10 -= ascii_zero;
1898 dig1 -= ascii_zero;
1899 return ((dig100 * 10) + dig10) * 10 + dig1;
1900}
1901
1902/*
1903 * Idem except the pointer to first unparsed byte is returned into <ret> which
1904 * must not be NULL.
1905 */
Willy Tarreau74172752010-10-15 23:21:42 +02001906unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001907{
1908 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1909 register unsigned int dig100, dig10, dig1;
1910 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001911 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001912
1913 dig1 = dig10 = dig100 = ascii_zero;
1914 s = 24;
1915
1916 p = text;
1917 while (1) {
1918 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1919 p++;
1920 continue;
1921 }
1922
1923 /* here, we have a complete byte between <text> and <p> (exclusive) */
1924 if (p == text)
1925 goto end;
1926
1927 d = p - 1;
1928 dig1 |= (unsigned int)(*d << s);
1929 if (d == text)
1930 goto end;
1931
1932 d--;
1933 dig10 |= (unsigned int)(*d << s);
1934 if (d == text)
1935 goto end;
1936
1937 d--;
1938 dig100 |= (unsigned int)(*d << s);
1939 end:
1940 if (!s || p == stop || *p != '.')
1941 break;
1942
1943 s -= 8;
1944 text = ++p;
1945 }
1946
1947 *ret = p;
1948 dig100 -= ascii_zero;
1949 dig10 -= ascii_zero;
1950 dig1 -= ascii_zero;
1951 return ((dig100 * 10) + dig10) * 10 + dig1;
1952}
1953
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001954/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1955 * or the number of chars read in case of success. Maybe this could be replaced
1956 * by one of the functions above. Also, apparently this function does not support
1957 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001958 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001959 */
1960int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1961{
1962 const char *addr;
1963 int saw_digit, octets, ch;
1964 u_char tmp[4], *tp;
1965 const char *cp = buf;
1966
1967 saw_digit = 0;
1968 octets = 0;
1969 *(tp = tmp) = 0;
1970
1971 for (addr = buf; addr - buf < len; addr++) {
1972 unsigned char digit = (ch = *addr) - '0';
1973
1974 if (digit > 9 && ch != '.')
1975 break;
1976
1977 if (digit <= 9) {
1978 u_int new = *tp * 10 + digit;
1979
1980 if (new > 255)
1981 return 0;
1982
1983 *tp = new;
1984
1985 if (!saw_digit) {
1986 if (++octets > 4)
1987 return 0;
1988 saw_digit = 1;
1989 }
1990 } else if (ch == '.' && saw_digit) {
1991 if (octets == 4)
1992 return 0;
1993
1994 *++tp = 0;
1995 saw_digit = 0;
1996 } else
1997 return 0;
1998 }
1999
2000 if (octets < 4)
2001 return 0;
2002
2003 memcpy(&dst->s_addr, tmp, 4);
2004 return addr - cp;
2005}
2006
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002007/* This function converts the string in <buf> of the len <len> to
2008 * struct in6_addr <dst> which must be allocated by the caller.
2009 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002010 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002011 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002012int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2013{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002014 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002015 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002016
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002017 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002018 return 0;
2019
2020 memcpy(null_term_ip6, buf, len);
2021 null_term_ip6[len] = '\0';
2022
Willy Tarreau075415a2013-12-12 11:29:39 +01002023 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002024 return 0;
2025
Willy Tarreau075415a2013-12-12 11:29:39 +01002026 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002027 return 1;
2028}
2029
Willy Tarreauacf95772010-06-14 19:09:21 +02002030/* To be used to quote config arg positions. Returns the short string at <ptr>
2031 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2032 * if ptr is NULL or empty. The string is locally allocated.
2033 */
2034const char *quote_arg(const char *ptr)
2035{
2036 static char val[32];
2037 int i;
2038
2039 if (!ptr || !*ptr)
2040 return "end of line";
2041 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002042 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002043 val[i] = *ptr++;
2044 val[i++] = '\'';
2045 val[i] = '\0';
2046 return val;
2047}
2048
Willy Tarreau5b180202010-07-18 10:40:48 +02002049/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2050int get_std_op(const char *str)
2051{
2052 int ret = -1;
2053
2054 if (*str == 'e' && str[1] == 'q')
2055 ret = STD_OP_EQ;
2056 else if (*str == 'n' && str[1] == 'e')
2057 ret = STD_OP_NE;
2058 else if (*str == 'l') {
2059 if (str[1] == 'e') ret = STD_OP_LE;
2060 else if (str[1] == 't') ret = STD_OP_LT;
2061 }
2062 else if (*str == 'g') {
2063 if (str[1] == 'e') ret = STD_OP_GE;
2064 else if (str[1] == 't') ret = STD_OP_GT;
2065 }
2066
2067 if (ret == -1 || str[2] != '\0')
2068 return -1;
2069 return ret;
2070}
2071
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002072/* hash a 32-bit integer to another 32-bit integer */
2073unsigned int full_hash(unsigned int a)
2074{
2075 return __full_hash(a);
2076}
2077
David du Colombier4f92d322011-03-24 11:09:31 +01002078/* Return non-zero if IPv4 address is part of the network,
2079 * otherwise zero.
2080 */
2081int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
2082{
2083 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
2084}
2085
2086/* Return non-zero if IPv6 address is part of the network,
2087 * otherwise zero.
2088 */
2089int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
2090{
2091 int i;
2092
2093 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2094 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2095 (((int *)net)[i] & ((int *)mask)[i]))
2096 return 0;
2097 return 1;
2098}
2099
2100/* RFC 4291 prefix */
2101const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2102 0x00, 0x00, 0x00, 0x00,
2103 0x00, 0x00, 0xFF, 0xFF };
2104
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002105/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2106 * Input and output may overlap.
2107 */
David du Colombier4f92d322011-03-24 11:09:31 +01002108void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2109{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002110 struct in_addr tmp_addr;
2111
2112 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002113 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002114 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002115}
2116
2117/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2118 * Return true if conversion is possible and false otherwise.
2119 */
2120int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2121{
2122 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2123 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2124 sizeof(struct in_addr));
2125 return 1;
2126 }
2127
2128 return 0;
2129}
2130
William Lallemand421f5b52012-02-06 18:15:57 +01002131char *human_time(int t, short hz_div) {
2132 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2133 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002134 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002135 int cnt=2; // print two numbers
2136
2137 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002138 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002139 return rv;
2140 }
2141
2142 if (unlikely(hz_div > 1))
2143 t /= hz_div;
2144
2145 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002146 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002147 cnt--;
2148 }
2149
2150 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002151 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002152 cnt--;
2153 }
2154
2155 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002156 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002157 cnt--;
2158 }
2159
2160 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002161 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002162
2163 return rv;
2164}
2165
2166const char *monthname[12] = {
2167 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2168 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2169};
2170
2171/* date2str_log: write a date in the format :
2172 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2173 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2174 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2175 *
2176 * without using sprintf. return a pointer to the last char written (\0) or
2177 * NULL if there isn't enough space.
2178 */
2179char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2180{
2181
2182 if (size < 25) /* the size is fixed: 24 chars + \0 */
2183 return NULL;
2184
2185 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2186 *dst++ = '/';
2187 memcpy(dst, monthname[tm->tm_mon], 3); // month
2188 dst += 3;
2189 *dst++ = '/';
2190 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2191 *dst++ = ':';
2192 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2193 *dst++ = ':';
2194 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2195 *dst++ = ':';
2196 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2197 *dst++ = '.';
2198 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2199 dst += 3; // only the 3 first digits
2200 *dst = '\0';
2201
2202 return dst;
2203}
2204
2205/* gmt2str_log: write a date in the format :
2206 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2207 * return a pointer to the last char written (\0) or
2208 * NULL if there isn't enough space.
2209 */
2210char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2211{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002212 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002213 return NULL;
2214
2215 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2216 *dst++ = '/';
2217 memcpy(dst, monthname[tm->tm_mon], 3); // month
2218 dst += 3;
2219 *dst++ = '/';
2220 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2221 *dst++ = ':';
2222 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2223 *dst++ = ':';
2224 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2225 *dst++ = ':';
2226 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2227 *dst++ = ' ';
2228 *dst++ = '+';
2229 *dst++ = '0';
2230 *dst++ = '0';
2231 *dst++ = '0';
2232 *dst++ = '0';
2233 *dst = '\0';
2234
2235 return dst;
2236}
2237
Yuxans Yao4e25b012012-10-19 10:36:09 +08002238/* localdate2str_log: write a date in the format :
2239 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2240 * * return a pointer to the last char written (\0) or
2241 * * NULL if there isn't enough space.
2242 */
2243char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2244{
2245 if (size < 27) /* the size is fixed: 26 chars + \0 */
2246 return NULL;
2247
2248 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2249 *dst++ = '/';
2250 memcpy(dst, monthname[tm->tm_mon], 3); // month
2251 dst += 3;
2252 *dst++ = '/';
2253 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2254 *dst++ = ':';
2255 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2256 *dst++ = ':';
2257 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2258 *dst++ = ':';
2259 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2260 *dst++ = ' ';
2261 memcpy(dst, localtimezone, 5); // timezone
2262 dst += 5;
2263 *dst = '\0';
2264
2265 return dst;
2266}
2267
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002268/* Dynamically allocates a string of the proper length to hold the formatted
2269 * output. NULL is returned on error. The caller is responsible for freeing the
2270 * memory area using free(). The resulting string is returned in <out> if the
2271 * pointer is not NULL. A previous version of <out> might be used to build the
2272 * new string, and it will be freed before returning if it is not NULL, which
2273 * makes it possible to build complex strings from iterative calls without
2274 * having to care about freeing intermediate values, as in the example below :
2275 *
2276 * memprintf(&err, "invalid argument: '%s'", arg);
2277 * ...
2278 * memprintf(&err, "parser said : <%s>\n", *err);
2279 * ...
2280 * free(*err);
2281 *
2282 * This means that <err> must be initialized to NULL before first invocation.
2283 * The return value also holds the allocated string, which eases error checking
2284 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002285 * passed instead and it will be ignored. The returned message will then also
2286 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002287 *
2288 * It is also convenient to use it without any free except the last one :
2289 * err = NULL;
2290 * if (!fct1(err)) report(*err);
2291 * if (!fct2(err)) report(*err);
2292 * if (!fct3(err)) report(*err);
2293 * free(*err);
2294 */
2295char *memprintf(char **out, const char *format, ...)
2296{
2297 va_list args;
2298 char *ret = NULL;
2299 int allocated = 0;
2300 int needed = 0;
2301
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002302 if (!out)
2303 return NULL;
2304
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002305 do {
2306 /* vsnprintf() will return the required length even when the
2307 * target buffer is NULL. We do this in a loop just in case
2308 * intermediate evaluations get wrong.
2309 */
2310 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002311 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002312 va_end(args);
2313
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002314 if (needed < allocated) {
2315 /* Note: on Solaris 8, the first iteration always
2316 * returns -1 if allocated is zero, so we force a
2317 * retry.
2318 */
2319 if (!allocated)
2320 needed = 0;
2321 else
2322 break;
2323 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002324
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002325 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002326 ret = realloc(ret, allocated);
2327 } while (ret);
2328
2329 if (needed < 0) {
2330 /* an error was encountered */
2331 free(ret);
2332 ret = NULL;
2333 }
2334
2335 if (out) {
2336 free(*out);
2337 *out = ret;
2338 }
2339
2340 return ret;
2341}
William Lallemand421f5b52012-02-06 18:15:57 +01002342
Willy Tarreau21c705b2012-09-14 11:40:36 +02002343/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2344 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002345 * freed by the caller. It also supports being passed a NULL which results in the same
2346 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002347 * Example of use :
2348 * parse(cmd, &err); (callee: memprintf(&err, ...))
2349 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2350 * free(err);
2351 */
2352char *indent_msg(char **out, int level)
2353{
2354 char *ret, *in, *p;
2355 int needed = 0;
2356 int lf = 0;
2357 int lastlf = 0;
2358 int len;
2359
Willy Tarreau70eec382012-10-10 08:56:47 +02002360 if (!out || !*out)
2361 return NULL;
2362
Willy Tarreau21c705b2012-09-14 11:40:36 +02002363 in = *out - 1;
2364 while ((in = strchr(in + 1, '\n')) != NULL) {
2365 lastlf = in - *out;
2366 lf++;
2367 }
2368
2369 if (!lf) /* single line, no LF, return it as-is */
2370 return *out;
2371
2372 len = strlen(*out);
2373
2374 if (lf == 1 && lastlf == len - 1) {
2375 /* single line, LF at end, strip it and return as-is */
2376 (*out)[lastlf] = 0;
2377 return *out;
2378 }
2379
2380 /* OK now we have at least one LF, we need to process the whole string
2381 * as a multi-line string. What we'll do :
2382 * - prefix with an LF if there is none
2383 * - add <level> spaces before each line
2384 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2385 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2386 */
2387
2388 needed = 1 + level * (lf + 1) + len + 1;
2389 p = ret = malloc(needed);
2390 in = *out;
2391
2392 /* skip initial LFs */
2393 while (*in == '\n')
2394 in++;
2395
2396 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2397 while (*in) {
2398 *p++ = '\n';
2399 memset(p, ' ', level);
2400 p += level;
2401 do {
2402 *p++ = *in++;
2403 } while (*in && *in != '\n');
2404 if (*in)
2405 in++;
2406 }
2407 *p = 0;
2408
2409 free(*out);
2410 *out = ret;
2411
2412 return ret;
2413}
2414
Willy Tarreaudad36a32013-03-11 01:20:04 +01002415/* Convert occurrences of environment variables in the input string to their
2416 * corresponding value. A variable is identified as a series of alphanumeric
2417 * characters or underscores following a '$' sign. The <in> string must be
2418 * free()able. NULL returns NULL. The resulting string might be reallocated if
2419 * some expansion is made. Variable names may also be enclosed into braces if
2420 * needed (eg: to concatenate alphanum characters).
2421 */
2422char *env_expand(char *in)
2423{
2424 char *txt_beg;
2425 char *out;
2426 char *txt_end;
2427 char *var_beg;
2428 char *var_end;
2429 char *value;
2430 char *next;
2431 int out_len;
2432 int val_len;
2433
2434 if (!in)
2435 return in;
2436
2437 value = out = NULL;
2438 out_len = 0;
2439
2440 txt_beg = in;
2441 do {
2442 /* look for next '$' sign in <in> */
2443 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2444
2445 if (!*txt_end && !out) /* end and no expansion performed */
2446 return in;
2447
2448 val_len = 0;
2449 next = txt_end;
2450 if (*txt_end == '$') {
2451 char save;
2452
2453 var_beg = txt_end + 1;
2454 if (*var_beg == '{')
2455 var_beg++;
2456
2457 var_end = var_beg;
2458 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2459 var_end++;
2460 }
2461
2462 next = var_end;
2463 if (*var_end == '}' && (var_beg > txt_end + 1))
2464 next++;
2465
2466 /* get value of the variable name at this location */
2467 save = *var_end;
2468 *var_end = '\0';
2469 value = getenv(var_beg);
2470 *var_end = save;
2471 val_len = value ? strlen(value) : 0;
2472 }
2473
2474 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2475 if (txt_end > txt_beg) {
2476 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2477 out_len += txt_end - txt_beg;
2478 }
2479 if (val_len) {
2480 memcpy(out + out_len, value, val_len);
2481 out_len += val_len;
2482 }
2483 out[out_len] = 0;
2484 txt_beg = next;
2485 } while (*txt_beg);
2486
2487 /* here we know that <out> was allocated and that we don't need <in> anymore */
2488 free(in);
2489 return out;
2490}
2491
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002492
2493/* same as strstr() but case-insensitive and with limit length */
2494const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2495{
2496 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02002497 unsigned int slen, plen;
2498 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002499
2500 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2501 return NULL;
2502
2503 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2504 return str1;
2505
2506 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2507 return NULL;
2508
2509 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2510 while (toupper(*start) != toupper(*str2)) {
2511 start++;
2512 slen--;
2513 tmp1++;
2514
2515 if (tmp1 >= len_str1)
2516 return NULL;
2517
2518 /* if pattern longer than string */
2519 if (slen < plen)
2520 return NULL;
2521 }
2522
2523 sptr = start;
2524 pptr = (char *)str2;
2525
2526 tmp2 = 0;
2527 while (toupper(*sptr) == toupper(*pptr)) {
2528 sptr++;
2529 pptr++;
2530 tmp2++;
2531
2532 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2533 return start;
2534 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2535 return NULL;
2536 }
2537 }
2538 return NULL;
2539}
2540
Willy Tarreaubaaee002006-06-26 02:48:02 +02002541/*
2542 * Local variables:
2543 * c-indent-level: 8
2544 * c-basic-offset: 8
2545 * End:
2546 */