blob: 75a0389b8c64a315bc39f6f168b8fecb5d219adc [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
41/*
William Lallemande7340ec2012-01-24 11:15:39 +010042 * unsigned long long ASCII representation
43 *
44 * return the last char '\0' or NULL if no enough
45 * space in dst
46 */
47char *ulltoa(unsigned long long n, char *dst, size_t size)
48{
49 int i = 0;
50 char *res;
51
52 switch(n) {
53 case 1ULL ... 9ULL:
54 i = 0;
55 break;
56
57 case 10ULL ... 99ULL:
58 i = 1;
59 break;
60
61 case 100ULL ... 999ULL:
62 i = 2;
63 break;
64
65 case 1000ULL ... 9999ULL:
66 i = 3;
67 break;
68
69 case 10000ULL ... 99999ULL:
70 i = 4;
71 break;
72
73 case 100000ULL ... 999999ULL:
74 i = 5;
75 break;
76
77 case 1000000ULL ... 9999999ULL:
78 i = 6;
79 break;
80
81 case 10000000ULL ... 99999999ULL:
82 i = 7;
83 break;
84
85 case 100000000ULL ... 999999999ULL:
86 i = 8;
87 break;
88
89 case 1000000000ULL ... 9999999999ULL:
90 i = 9;
91 break;
92
93 case 10000000000ULL ... 99999999999ULL:
94 i = 10;
95 break;
96
97 case 100000000000ULL ... 999999999999ULL:
98 i = 11;
99 break;
100
101 case 1000000000000ULL ... 9999999999999ULL:
102 i = 12;
103 break;
104
105 case 10000000000000ULL ... 99999999999999ULL:
106 i = 13;
107 break;
108
109 case 100000000000000ULL ... 999999999999999ULL:
110 i = 14;
111 break;
112
113 case 1000000000000000ULL ... 9999999999999999ULL:
114 i = 15;
115 break;
116
117 case 10000000000000000ULL ... 99999999999999999ULL:
118 i = 16;
119 break;
120
121 case 100000000000000000ULL ... 999999999999999999ULL:
122 i = 17;
123 break;
124
125 case 1000000000000000000ULL ... 9999999999999999999ULL:
126 i = 18;
127 break;
128
129 case 10000000000000000000ULL ... ULLONG_MAX:
130 i = 19;
131 break;
132 }
133 if (i + 2 > size) // (i + 1) + '\0'
134 return NULL; // too long
135 res = dst + i + 1;
136 *res = '\0';
137 for (; i >= 0; i--) {
138 dst[i] = n % 10ULL + '0';
139 n /= 10ULL;
140 }
141 return res;
142}
143
144/*
145 * unsigned long ASCII representation
146 *
147 * return the last char '\0' or NULL if no enough
148 * space in dst
149 */
150char *ultoa_o(unsigned long n, char *dst, size_t size)
151{
152 int i = 0;
153 char *res;
154
155 switch (n) {
156 case 0U ... 9UL:
157 i = 0;
158 break;
159
160 case 10U ... 99UL:
161 i = 1;
162 break;
163
164 case 100U ... 999UL:
165 i = 2;
166 break;
167
168 case 1000U ... 9999UL:
169 i = 3;
170 break;
171
172 case 10000U ... 99999UL:
173 i = 4;
174 break;
175
176 case 100000U ... 999999UL:
177 i = 5;
178 break;
179
180 case 1000000U ... 9999999UL:
181 i = 6;
182 break;
183
184 case 10000000U ... 99999999UL:
185 i = 7;
186 break;
187
188 case 100000000U ... 999999999UL:
189 i = 8;
190 break;
191#if __WORDSIZE == 32
192
193 case 1000000000ULL ... ULONG_MAX:
194 i = 9;
195 break;
196
197#elif __WORDSIZE == 64
198
199 case 1000000000ULL ... 9999999999UL:
200 i = 9;
201 break;
202
203 case 10000000000ULL ... 99999999999UL:
204 i = 10;
205 break;
206
207 case 100000000000ULL ... 999999999999UL:
208 i = 11;
209 break;
210
211 case 1000000000000ULL ... 9999999999999UL:
212 i = 12;
213 break;
214
215 case 10000000000000ULL ... 99999999999999UL:
216 i = 13;
217 break;
218
219 case 100000000000000ULL ... 999999999999999UL:
220 i = 14;
221 break;
222
223 case 1000000000000000ULL ... 9999999999999999UL:
224 i = 15;
225 break;
226
227 case 10000000000000000ULL ... 99999999999999999UL:
228 i = 16;
229 break;
230
231 case 100000000000000000ULL ... 999999999999999999UL:
232 i = 17;
233 break;
234
235 case 1000000000000000000ULL ... 9999999999999999999UL:
236 i = 18;
237 break;
238
239 case 10000000000000000000ULL ... ULONG_MAX:
240 i = 19;
241 break;
242
243#endif
244 }
245 if (i + 2 > size) // (i + 1) + '\0'
246 return NULL; // too long
247 res = dst + i + 1;
248 *res = '\0';
249 for (; i >= 0; i--) {
250 dst[i] = n % 10U + '0';
251 n /= 10U;
252 }
253 return res;
254}
255
256/*
257 * signed long ASCII representation
258 *
259 * return the last char '\0' or NULL if no enough
260 * space in dst
261 */
262char *ltoa_o(long int n, char *dst, size_t size)
263{
264 char *pos = dst;
265
266 if (n < 0) {
267 if (size < 3)
268 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
269 *pos = '-';
270 pos++;
271 dst = ultoa_o(-n, pos, size - 1);
272 } else {
273 dst = ultoa_o(n, dst, size);
274 }
275 return dst;
276}
277
278/*
279 * signed long long ASCII representation
280 *
281 * return the last char '\0' or NULL if no enough
282 * space in dst
283 */
284char *lltoa(long long n, char *dst, size_t size)
285{
286 char *pos = dst;
287
288 if (n < 0) {
289 if (size < 3)
290 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
291 *pos = '-';
292 pos++;
293 dst = ulltoa(-n, pos, size - 1);
294 } else {
295 dst = ulltoa(n, dst, size);
296 }
297 return dst;
298}
299
300/*
301 * write a ascii representation of a unsigned into dst,
302 * return a pointer to the last character
303 * Pad the ascii representation with '0', using size.
304 */
305char *utoa_pad(unsigned int n, char *dst, size_t size)
306{
307 int i = 0;
308 char *ret;
309
310 switch(n) {
311 case 0U ... 9U:
312 i = 0;
313 break;
314
315 case 10U ... 99U:
316 i = 1;
317 break;
318
319 case 100U ... 999U:
320 i = 2;
321 break;
322
323 case 1000U ... 9999U:
324 i = 3;
325 break;
326
327 case 10000U ... 99999U:
328 i = 4;
329 break;
330
331 case 100000U ... 999999U:
332 i = 5;
333 break;
334
335 case 1000000U ... 9999999U:
336 i = 6;
337 break;
338
339 case 10000000U ... 99999999U:
340 i = 7;
341 break;
342
343 case 100000000U ... 999999999U:
344 i = 8;
345 break;
346
347 case 1000000000U ... 4294967295U:
348 i = 9;
349 break;
350 }
351 if (i + 2 > size) // (i + 1) + '\0'
352 return NULL; // too long
353 if (i < size)
354 i = size - 2; // padding - '\0'
355
356 ret = dst + i + 1;
357 *ret = '\0';
358 for (; i >= 0; i--) {
359 dst[i] = n % 10U + '0';
360 n /= 10U;
361 }
362 return ret;
363}
364
365/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200366 * copies at most <size-1> chars from <src> to <dst>. Last char is always
367 * set to 0, unless <size> is 0. The number of chars copied is returned
368 * (excluding the terminating zero).
369 * This code has been optimized for size and speed : on x86, it's 45 bytes
370 * long, uses only registers, and consumes only 4 cycles per char.
371 */
372int strlcpy2(char *dst, const char *src, int size)
373{
374 char *orig = dst;
375 if (size) {
376 while (--size && (*dst = *src)) {
377 src++; dst++;
378 }
379 *dst = 0;
380 }
381 return dst - orig;
382}
383
384/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200385 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200386 * the ascii representation for number 'n' in decimal.
387 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100388char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200389{
390 char *pos;
391
Willy Tarreau72d759c2007-10-25 12:14:10 +0200392 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200393 *pos-- = '\0';
394
395 do {
396 *pos-- = '0' + n % 10;
397 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200398 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200399 return pos + 1;
400}
401
Willy Tarreau91092e52007-10-25 16:58:42 +0200402/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200403 * This function simply returns a locally allocated string containing
404 * the ascii representation for number 'n' in decimal, formatted for
405 * HTML output with tags to create visual grouping by 3 digits. The
406 * output needs to support at least 171 characters.
407 */
408const char *ulltoh_r(unsigned long long n, char *buffer, int size)
409{
410 char *start;
411 int digit = 0;
412
413 start = buffer + size;
414 *--start = '\0';
415
416 do {
417 if (digit == 3 && start >= buffer + 7)
418 memcpy(start -= 7, "</span>", 7);
419
420 if (start >= buffer + 1) {
421 *--start = '0' + n % 10;
422 n /= 10;
423 }
424
425 if (digit == 3 && start >= buffer + 18)
426 memcpy(start -= 18, "<span class=\"rls\">", 18);
427
428 if (digit++ == 3)
429 digit = 1;
430 } while (n && start > buffer);
431 return start;
432}
433
434/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200435 * This function simply returns a locally allocated string containing the ascii
436 * representation for number 'n' in decimal, unless n is 0 in which case it
437 * returns the alternate string (or an empty string if the alternate string is
438 * NULL). It use is intended for limits reported in reports, where it's
439 * desirable not to display anything if there is no limit. Warning! it shares
440 * the same vector as ultoa_r().
441 */
442const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
443{
444 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
445}
446
Robert Tsai81ae1952007-12-05 10:47:29 +0100447/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200448 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
449 *
450 * It looks like this one would be a good candidate for inlining, but this is
451 * not interesting because it around 35 bytes long and often called multiple
452 * times within the same function.
453 */
454int ishex(char s)
455{
456 s -= '0';
457 if ((unsigned char)s <= 9)
458 return 1;
459 s -= 'A' - '0';
460 if ((unsigned char)s <= 5)
461 return 1;
462 s -= 'a' - 'A';
463 if ((unsigned char)s <= 5)
464 return 1;
465 return 0;
466}
467
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100468/*
469 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
470 * invalid character is found, a pointer to it is returned. If everything is
471 * fine, NULL is returned.
472 */
473const char *invalid_char(const char *name)
474{
475 if (!*name)
476 return name;
477
478 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100479 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100480 *name != '_' && *name != '-')
481 return name;
482 name++;
483 }
484 return NULL;
485}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200486
487/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200488 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
489 * If an invalid character is found, a pointer to it is returned.
490 * If everything is fine, NULL is returned.
491 */
492const char *invalid_domainchar(const char *name) {
493
494 if (!*name)
495 return name;
496
497 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100498 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200499 *name != '_' && *name != '-')
500 return name;
501
502 name++;
503 }
504
505 return NULL;
506}
507
508/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100509 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100510 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
511 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
512 * the function tries to guess the address family from the syntax. If the
513 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100514 * string is assumed to contain only an address, no port. The address can be a
515 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
516 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
517 * The return address will only have the address family and the address set,
518 * all other fields remain zero. The string is not supposed to be modified.
519 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200520 */
Willy Tarreau24709282013-03-10 21:32:12 +0100521static struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200522{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100523 struct hostent *he;
524
Willy Tarreaufab5a432011-03-04 15:31:53 +0100525 /* Any IPv6 address */
526 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100527 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
528 sa->ss_family = AF_INET6;
529 else if (sa->ss_family != AF_INET6)
530 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100531 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100532 }
533
Willy Tarreau24709282013-03-10 21:32:12 +0100534 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100535 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100536 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
537 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100538 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100539 }
540
541 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100542 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
543 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100544 sa->ss_family = AF_INET6;
545 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100546 }
547
548 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100549 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
550 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100551 sa->ss_family = AF_INET;
552 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100553 }
554
555 /* try to resolve an IPv4/IPv6 hostname */
556 he = gethostbyname(str);
557 if (he) {
Willy Tarreau24709282013-03-10 21:32:12 +0100558 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
559 sa->ss_family = he->h_addrtype;
560 else if (sa->ss_family != he->h_addrtype)
561 goto fail;
562
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100563 switch (sa->ss_family) {
Willy Tarreaufab5a432011-03-04 15:31:53 +0100564 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100565 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
566 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100567 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100568 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
569 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100570 }
David du Colombierd5f43282011-03-17 10:40:16 +0100571 }
572#ifdef USE_GETADDRINFO
573 else {
574 struct addrinfo hints, *result;
575
576 memset(&result, 0, sizeof(result));
577 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100578 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100579 hints.ai_socktype = SOCK_DGRAM;
580 hints.ai_flags = AI_PASSIVE;
581 hints.ai_protocol = 0;
582
583 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100584 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
585 sa->ss_family = result->ai_family;
586 else if (sa->ss_family != result->ai_family)
587 goto fail;
588
David du Colombierd5f43282011-03-17 10:40:16 +0100589 switch (result->ai_family) {
590 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100591 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
592 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100593 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100594 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
595 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100596 }
597 }
598
Sean Carey58ea0392013-02-15 23:39:18 +0100599 if (result)
600 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100601 }
David du Colombierd5f43282011-03-17 10:40:16 +0100602#endif
603 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100604 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100605 return NULL;
606}
607
608/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100609 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
610 * range or offset consisting in two integers that the caller will have to
611 * check to find the relevant input format. The following format are supported :
612 *
613 * String format | address | port | low | high
614 * addr | <addr> | 0 | 0 | 0
615 * addr: | <addr> | 0 | 0 | 0
616 * addr:port | <addr> | <port> | <port> | <port>
617 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
618 * addr:+port | <addr> | <port> | 0 | <port>
619 * addr:-port | <addr> |-<port> | <port> | 0
620 *
621 * The detection of a port range or increment by the caller is made by
622 * comparing <low> and <high>. If both are equal, then port 0 means no port
623 * was specified. The caller may pass NULL for <low> and <high> if it is not
624 * interested in retrieving port ranges.
625 *
626 * Note that <addr> above may also be :
627 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
628 * - "*" => family will be AF_INET and address will be INADDR_ANY
629 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
630 * - a host name => family and address will depend on host name resolving.
631 *
Willy Tarreau24709282013-03-10 21:32:12 +0100632 * A prefix may be passed in before the address above to force the family :
633 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
634 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
635 * - "unix@" => force address to be a path to a UNIX socket even if the
636 * path does not start with a '/'
Willy Tarreau40aa0702013-03-10 23:51:38 +0100637 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100638 *
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100639 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
640 * is mandatory after the IP address even when no port is specified. NULL is
641 * returned if the address cannot be parsed. The <low> and <high> ports are
Willy Tarreau24709282013-03-10 21:32:12 +0100642 * always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100643 *
644 * If <pfx> is non-null, it is used as a string prefix before any path-based
645 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100646 *
647 * When a file descriptor is passed, its value is put into the s_addr part of
648 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100649 */
Willy Tarreaud393a622013-03-04 18:22:00 +0100650struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100651{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100652 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100653 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100654 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100655 char *port1, *port2;
656 int portl, porth, porta;
657
658 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200659
Willy Tarreaudad36a32013-03-11 01:20:04 +0100660 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100661 if (str2 == NULL) {
662 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100663 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100664 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200665
Willy Tarreau24709282013-03-10 21:32:12 +0100666 memset(&ss, 0, sizeof(ss));
667
668 if (strncmp(str2, "unix@", 5) == 0) {
669 str2 += 5;
670 ss.ss_family = AF_UNIX;
671 }
672 else if (strncmp(str2, "ipv4@", 5) == 0) {
673 str2 += 5;
674 ss.ss_family = AF_INET;
675 }
676 else if (strncmp(str2, "ipv6@", 5) == 0) {
677 str2 += 5;
678 ss.ss_family = AF_INET6;
679 }
680 else if (*str2 == '/') {
681 ss.ss_family = AF_UNIX;
682 }
683 else
684 ss.ss_family = AF_UNSPEC;
685
Willy Tarreau40aa0702013-03-10 23:51:38 +0100686 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
687 char *endptr;
688
689 str2 += 3;
690 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
691
692 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100693 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100694 goto out;
695 }
696
697 /* we return AF_UNSPEC if we use a file descriptor number */
698 ss.ss_family = AF_UNSPEC;
699 }
700 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100701 int prefix_path_len;
702 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200703 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100704
705 /* complete unix socket path name during startup or soft-restart is
706 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
707 */
708 prefix_path_len = pfx ? strlen(pfx) : 0;
709 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
710 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
711
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200712 adr_len = strlen(str2);
713 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100714 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
715 goto out;
716 }
717
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200718 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100719 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200720 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len, str2, adr_len + 1);
Willy Tarreau15586382013-03-04 19:48:14 +0100721 }
Willy Tarreau24709282013-03-10 21:32:12 +0100722 else { /* IPv4 and IPv6 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100723 port1 = strrchr(str2, ':');
724 if (port1)
725 *port1++ = '\0';
726 else
727 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200728
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100729 if (str2ip(str2, &ss) == NULL) {
730 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
731 goto out;
732 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100733
Willy Tarreaua39d1992013-04-01 20:37:42 +0200734 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100735 port2 = strchr(port1, '-');
736 if (port2)
737 *port2++ = '\0';
738 else
739 port2 = port1;
740 portl = atoi(port1);
741 porth = atoi(port2);
742 porta = portl;
743 }
744 else if (*port1 == '-') { /* negative offset */
745 portl = atoi(port1 + 1);
746 porta = -portl;
747 }
748 else if (*port1 == '+') { /* positive offset */
749 porth = atoi(port1 + 1);
750 porta = porth;
751 }
752 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100753 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100754 goto out;
755 }
756 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100757 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100758
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100759 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100760 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100761 if (low)
762 *low = portl;
763 if (high)
764 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100765 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100766 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200767}
768
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100769/* converts <str> to a struct in_addr containing a network mask. It can be
770 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
771 * if the conversion succeeds otherwise non-zero.
772 */
773int str2mask(const char *str, struct in_addr *mask)
774{
775 if (strchr(str, '.') != NULL) { /* dotted notation */
776 if (!inet_pton(AF_INET, str, mask))
777 return 0;
778 }
779 else { /* mask length */
780 char *err;
781 unsigned long len = strtol(str, &err, 10);
782
783 if (!*str || (err && *err) || (unsigned)len > 32)
784 return 0;
785 if (len)
786 mask->s_addr = htonl(~0UL << (32 - len));
787 else
788 mask->s_addr = 0;
789 }
790 return 1;
791}
792
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100793/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
794 * succeeds otherwise zero.
795 */
796int cidr2dotted(int cidr, struct in_addr *mask) {
797
798 if (cidr < 0 || cidr > 32)
799 return 0;
800
801 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
802 return 1;
803}
804
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200805/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200806 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200807 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
808 * is optionnal and either in the dotted or CIDR notation.
809 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
810 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100811int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200812{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200813 __label__ out_free, out_err;
814 char *c, *s;
815 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200816
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200817 s = strdup(str);
818 if (!s)
819 return 0;
820
Willy Tarreaubaaee002006-06-26 02:48:02 +0200821 memset(mask, 0, sizeof(*mask));
822 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200823
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200824 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200825 *c++ = '\0';
826 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100827 if (!str2mask(c, mask))
828 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200829 }
830 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100831 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200832 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200833 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200834 struct hostent *he;
835
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100836 if (!resolve)
837 goto out_err;
838
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200839 if ((he = gethostbyname(s)) == NULL) {
840 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200841 }
842 else
843 *addr = *(struct in_addr *) *(he->h_addr_list);
844 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200845
846 ret_val = 1;
847 out_free:
848 free(s);
849 return ret_val;
850 out_err:
851 ret_val = 0;
852 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200853}
854
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100855
856/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200857 * converts <str> to two struct in6_addr* which must be pre-allocated.
858 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
859 * is an optionnal number of bits (128 being the default).
860 * Returns 1 if OK, 0 if error.
861 */
862int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
863{
864 char *c, *s;
865 int ret_val = 0;
866 char *err;
867 unsigned long len = 128;
868
869 s = strdup(str);
870 if (!s)
871 return 0;
872
873 memset(mask, 0, sizeof(*mask));
874 memset(addr, 0, sizeof(*addr));
875
876 if ((c = strrchr(s, '/')) != NULL) {
877 *c++ = '\0'; /* c points to the mask */
878 if (!*c)
879 goto out_free;
880
881 len = strtoul(c, &err, 10);
882 if ((err && *err) || (unsigned)len > 128)
883 goto out_free;
884 }
885 *mask = len; /* OK we have a valid mask in <len> */
886
887 if (!inet_pton(AF_INET6, s, addr))
888 goto out_free;
889
890 ret_val = 1;
891 out_free:
892 free(s);
893 return ret_val;
894}
895
896
897/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100898 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100899 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100900int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100901{
902 int saw_digit, octets, ch;
903 u_char tmp[4], *tp;
904 const char *cp = addr;
905
906 saw_digit = 0;
907 octets = 0;
908 *(tp = tmp) = 0;
909
910 while (*addr) {
911 unsigned char digit = (ch = *addr++) - '0';
912 if (digit > 9 && ch != '.')
913 break;
914 if (digit <= 9) {
915 u_int new = *tp * 10 + digit;
916 if (new > 255)
917 return 0;
918 *tp = new;
919 if (!saw_digit) {
920 if (++octets > 4)
921 return 0;
922 saw_digit = 1;
923 }
924 } else if (ch == '.' && saw_digit) {
925 if (octets == 4)
926 return 0;
927 *++tp = 0;
928 saw_digit = 0;
929 } else
930 return 0;
931 }
932
933 if (octets < 4)
934 return 0;
935
936 memcpy(&dst->s_addr, tmp, 4);
937 return addr-cp-1;
938}
939
940/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100941 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
942 * <out> contain the code of the dectected scheme, the start and length of
943 * the hostname. Actually only http and https are supported. <out> can be NULL.
944 * This function returns the consumed length. It is useful if you parse complete
945 * url like http://host:port/path, because the consumed length corresponds to
946 * the first character of the path. If the conversion fails, it returns -1.
947 *
948 * This function tries to resolve the DNS name if haproxy is in starting mode.
949 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100950 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100951int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100952{
953 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100954 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100955 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100956 unsigned long long int http_code = 0;
957 int default_port;
958 struct hostent *he;
959 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100960
961 /* Firstly, try to find :// pattern */
962 while (curr < url+ulen && url_code != 0x3a2f2f) {
963 url_code = ((url_code & 0xffff) << 8);
964 url_code += (unsigned char)*curr++;
965 }
966
967 /* Secondly, if :// pattern is found, verify parsed stuff
968 * before pattern is matching our http pattern.
969 * If so parse ip address and port in uri.
970 *
971 * WARNING: Current code doesn't support dynamic async dns resolver.
972 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100973 if (url_code != 0x3a2f2f)
974 return -1;
975
976 /* Copy scheme, and utrn to lower case. */
977 while (cp < curr - 3)
978 http_code = (http_code << 8) + *cp++;
979 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100980
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100981 /* HTTP or HTTPS url matching */
982 if (http_code == 0x2020202068747470ULL) {
983 default_port = 80;
984 if (out)
985 out->scheme = SCH_HTTP;
986 }
987 else if (http_code == 0x2020206874747073ULL) {
988 default_port = 443;
989 if (out)
990 out->scheme = SCH_HTTPS;
991 }
992 else
993 return -1;
994
995 /* If the next char is '[', the host address is IPv6. */
996 if (*curr == '[') {
997 curr++;
998
999 /* Check trash size */
1000 if (trash.size < ulen)
1001 return -1;
1002
1003 /* Look for ']' and copy the address in a trash buffer. */
1004 p = trash.str;
1005 for (end = curr;
1006 end < url + ulen && *end != ']';
1007 end++, p++)
1008 *p = *end;
1009 if (*end != ']')
1010 return -1;
1011 *p = '\0';
1012
1013 /* Update out. */
1014 if (out) {
1015 out->host = curr;
1016 out->host_len = end - curr;
1017 }
1018
1019 /* Try IPv6 decoding. */
1020 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1021 return -1;
1022 end++;
1023
1024 /* Decode port. */
1025 if (*end == ':') {
1026 end++;
1027 default_port = read_uint(&end, url + ulen);
1028 }
1029 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1030 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1031 return end - url;
1032 }
1033 else {
1034 /* We are looking for IP address. If you want to parse and
1035 * resolve hostname found in url, you can use str2sa_range(), but
1036 * be warned this can slow down global daemon performances
1037 * while handling lagging dns responses.
1038 */
1039 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1040 if (ret) {
1041 /* Update out. */
1042 if (out) {
1043 out->host = curr;
1044 out->host_len = ret;
1045 }
1046
1047 curr += ret;
1048
1049 /* Decode port. */
1050 if (*curr == ':') {
1051 curr++;
1052 default_port = read_uint(&curr, url + ulen);
1053 }
1054 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1055
1056 /* Set family. */
1057 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1058 return curr - url;
1059 }
1060 else if (global.mode & MODE_STARTING) {
1061 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1062 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001063 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001064
1065 /* look for : or / or end */
1066 for (end = curr;
1067 end < url + ulen && *end != '/' && *end != ':';
1068 end++);
1069 memcpy(trash.str, curr, end - curr);
1070 trash.str[end - curr] = '\0';
1071
1072 /* try to resolve an IPv4/IPv6 hostname */
1073 he = gethostbyname(trash.str);
1074 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001075 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001076
1077 /* Update out. */
1078 if (out) {
1079 out->host = curr;
1080 out->host_len = end - curr;
1081 }
1082
1083 /* Decode port. */
1084 if (*end == ':') {
1085 end++;
1086 default_port = read_uint(&end, url + ulen);
1087 }
1088
1089 /* Copy IP address, set port and family. */
1090 switch (he->h_addrtype) {
1091 case AF_INET:
1092 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1093 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1094 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1095 return end - url;
1096
1097 case AF_INET6:
1098 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1099 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1100 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1101 return end - url;
1102 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001103 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001104 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001105 return -1;
1106}
1107
Willy Tarreau631f01c2011-09-05 00:36:48 +02001108/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1109 * address family is returned so that it's easy for the caller to adapt to the
1110 * output format. Zero is returned if the address family is not supported. -1
1111 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1112 * supported.
1113 */
1114int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1115{
1116
1117 void *ptr;
1118
1119 if (size < 5)
1120 return 0;
1121 *str = '\0';
1122
1123 switch (addr->ss_family) {
1124 case AF_INET:
1125 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1126 break;
1127 case AF_INET6:
1128 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1129 break;
1130 case AF_UNIX:
1131 memcpy(str, "unix", 5);
1132 return addr->ss_family;
1133 default:
1134 return 0;
1135 }
1136
1137 if (inet_ntop(addr->ss_family, ptr, str, size))
1138 return addr->ss_family;
1139
1140 /* failed */
1141 return -1;
1142}
1143
Willy Tarreaubaaee002006-06-26 02:48:02 +02001144/* will try to encode the string <string> replacing all characters tagged in
1145 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1146 * prefixed by <escape>, and will store the result between <start> (included)
1147 * and <stop> (excluded), and will always terminate the string with a '\0'
1148 * before <stop>. The position of the '\0' is returned if the conversion
1149 * completes. If bytes are missing between <start> and <stop>, then the
1150 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1151 * cannot even be stored so we return <start> without writing the 0.
1152 * The input string must also be zero-terminated.
1153 */
1154const char hextab[16] = "0123456789ABCDEF";
1155char *encode_string(char *start, char *stop,
1156 const char escape, const fd_set *map,
1157 const char *string)
1158{
1159 if (start < stop) {
1160 stop--; /* reserve one byte for the final '\0' */
1161 while (start < stop && *string != '\0') {
1162 if (!FD_ISSET((unsigned char)(*string), map))
1163 *start++ = *string;
1164 else {
1165 if (start + 3 >= stop)
1166 break;
1167 *start++ = escape;
1168 *start++ = hextab[(*string >> 4) & 15];
1169 *start++ = hextab[*string & 15];
1170 }
1171 string++;
1172 }
1173 *start = '\0';
1174 }
1175 return start;
1176}
1177
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001178/*
1179 * Same behavior as encode_string() above, except that it encodes chunk
1180 * <chunk> instead of a string.
1181 */
1182char *encode_chunk(char *start, char *stop,
1183 const char escape, const fd_set *map,
1184 const struct chunk *chunk)
1185{
1186 char *str = chunk->str;
1187 char *end = chunk->str + chunk->len;
1188
1189 if (start < stop) {
1190 stop--; /* reserve one byte for the final '\0' */
1191 while (start < stop && str < end) {
1192 if (!FD_ISSET((unsigned char)(*str), map))
1193 *start++ = *str;
1194 else {
1195 if (start + 3 >= stop)
1196 break;
1197 *start++ = escape;
1198 *start++ = hextab[(*str >> 4) & 15];
1199 *start++ = hextab[*str & 15];
1200 }
1201 str++;
1202 }
1203 *start = '\0';
1204 }
1205 return start;
1206}
1207
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001208/* Decode an URL-encoded string in-place. The resulting string might
1209 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001210 * aborted, the string is truncated before the issue and a negative value is
1211 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001212 */
1213int url_decode(char *string)
1214{
1215 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001216 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001217
1218 in = string;
1219 out = string;
1220 while (*in) {
1221 switch (*in) {
1222 case '+' :
1223 *out++ = ' ';
1224 break;
1225 case '%' :
1226 if (!ishex(in[1]) || !ishex(in[2]))
1227 goto end;
1228 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1229 in += 2;
1230 break;
1231 default:
1232 *out++ = *in;
1233 break;
1234 }
1235 in++;
1236 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001237 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001238 end:
1239 *out = 0;
1240 return ret;
1241}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001242
Willy Tarreau6911fa42007-03-04 18:06:08 +01001243unsigned int str2ui(const char *s)
1244{
1245 return __str2ui(s);
1246}
1247
1248unsigned int str2uic(const char *s)
1249{
1250 return __str2uic(s);
1251}
1252
1253unsigned int strl2ui(const char *s, int len)
1254{
1255 return __strl2ui(s, len);
1256}
1257
1258unsigned int strl2uic(const char *s, int len)
1259{
1260 return __strl2uic(s, len);
1261}
1262
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001263unsigned int read_uint(const char **s, const char *end)
1264{
1265 return __read_uint(s, end);
1266}
1267
Willy Tarreau6911fa42007-03-04 18:06:08 +01001268/* This one is 7 times faster than strtol() on athlon with checks.
1269 * It returns the value of the number composed of all valid digits read,
1270 * and can process negative numbers too.
1271 */
1272int strl2ic(const char *s, int len)
1273{
1274 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001275 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001276
1277 if (len > 0) {
1278 if (*s != '-') {
1279 /* positive number */
1280 while (len-- > 0) {
1281 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001282 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001283 if (j > 9)
1284 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001285 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001286 }
1287 } else {
1288 /* negative number */
1289 s++;
1290 while (--len > 0) {
1291 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001292 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001293 if (j > 9)
1294 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001295 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001296 }
1297 }
1298 }
1299 return i;
1300}
1301
1302
1303/* This function reads exactly <len> chars from <s> and converts them to a
1304 * signed integer which it stores into <ret>. It accurately detects any error
1305 * (truncated string, invalid chars, overflows). It is meant to be used in
1306 * applications designed for hostile environments. It returns zero when the
1307 * number has successfully been converted, non-zero otherwise. When an error
1308 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1309 * faster than strtol().
1310 */
1311int strl2irc(const char *s, int len, int *ret)
1312{
1313 int i = 0;
1314 int j;
1315
1316 if (!len)
1317 return 1;
1318
1319 if (*s != '-') {
1320 /* positive number */
1321 while (len-- > 0) {
1322 j = (*s++) - '0';
1323 if (j > 9) return 1; /* invalid char */
1324 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1325 i = i * 10;
1326 if (i + j < i) return 1; /* check for addition overflow */
1327 i = i + j;
1328 }
1329 } else {
1330 /* negative number */
1331 s++;
1332 while (--len > 0) {
1333 j = (*s++) - '0';
1334 if (j > 9) return 1; /* invalid char */
1335 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1336 i = i * 10;
1337 if (i - j > i) return 1; /* check for subtract overflow */
1338 i = i - j;
1339 }
1340 }
1341 *ret = i;
1342 return 0;
1343}
1344
1345
1346/* This function reads exactly <len> chars from <s> and converts them to a
1347 * signed integer which it stores into <ret>. It accurately detects any error
1348 * (truncated string, invalid chars, overflows). It is meant to be used in
1349 * applications designed for hostile environments. It returns zero when the
1350 * number has successfully been converted, non-zero otherwise. When an error
1351 * is returned, the <ret> value is left untouched. It is about 3 times slower
1352 * than str2irc().
1353 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001354
1355int strl2llrc(const char *s, int len, long long *ret)
1356{
1357 long long i = 0;
1358 int j;
1359
1360 if (!len)
1361 return 1;
1362
1363 if (*s != '-') {
1364 /* positive number */
1365 while (len-- > 0) {
1366 j = (*s++) - '0';
1367 if (j > 9) return 1; /* invalid char */
1368 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1369 i = i * 10LL;
1370 if (i + j < i) return 1; /* check for addition overflow */
1371 i = i + j;
1372 }
1373 } else {
1374 /* negative number */
1375 s++;
1376 while (--len > 0) {
1377 j = (*s++) - '0';
1378 if (j > 9) return 1; /* invalid char */
1379 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1380 i = i * 10LL;
1381 if (i - j > i) return 1; /* check for subtract overflow */
1382 i = i - j;
1383 }
1384 }
1385 *ret = i;
1386 return 0;
1387}
1388
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001389/* This function is used with pat_parse_dotted_ver(). It converts a string
1390 * composed by two number separated by a dot. Each part must contain in 16 bits
1391 * because internally they will be represented as a 32-bit quantity stored in
1392 * a 64-bit integer. It returns zero when the number has successfully been
1393 * converted, non-zero otherwise. When an error is returned, the <ret> value
1394 * is left untouched.
1395 *
1396 * "1.3" -> 0x0000000000010003
1397 * "65535.65535" -> 0x00000000ffffffff
1398 */
1399int strl2llrc_dotted(const char *text, int len, long long *ret)
1400{
1401 const char *end = &text[len];
1402 const char *p;
1403 long long major, minor;
1404
1405 /* Look for dot. */
1406 for (p = text; p < end; p++)
1407 if (*p == '.')
1408 break;
1409
1410 /* Convert major. */
1411 if (strl2llrc(text, p - text, &major) != 0)
1412 return 1;
1413
1414 /* Check major. */
1415 if (major >= 65536)
1416 return 1;
1417
1418 /* Convert minor. */
1419 minor = 0;
1420 if (p < end)
1421 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1422 return 1;
1423
1424 /* Check minor. */
1425 if (minor >= 65536)
1426 return 1;
1427
1428 /* Compose value. */
1429 *ret = (major << 16) | (minor & 0xffff);
1430 return 0;
1431}
1432
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001433/* This function parses a time value optionally followed by a unit suffix among
1434 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1435 * expected by the caller. The computation does its best to avoid overflows.
1436 * The value is returned in <ret> if everything is fine, and a NULL is returned
1437 * by the function. In case of error, a pointer to the error is returned and
1438 * <ret> is left untouched. Values are automatically rounded up when needed.
1439 */
1440const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1441{
1442 unsigned imult, idiv;
1443 unsigned omult, odiv;
1444 unsigned value;
1445
1446 omult = odiv = 1;
1447
1448 switch (unit_flags & TIME_UNIT_MASK) {
1449 case TIME_UNIT_US: omult = 1000000; break;
1450 case TIME_UNIT_MS: omult = 1000; break;
1451 case TIME_UNIT_S: break;
1452 case TIME_UNIT_MIN: odiv = 60; break;
1453 case TIME_UNIT_HOUR: odiv = 3600; break;
1454 case TIME_UNIT_DAY: odiv = 86400; break;
1455 default: break;
1456 }
1457
1458 value = 0;
1459
1460 while (1) {
1461 unsigned int j;
1462
1463 j = *text - '0';
1464 if (j > 9)
1465 break;
1466 text++;
1467 value *= 10;
1468 value += j;
1469 }
1470
1471 imult = idiv = 1;
1472 switch (*text) {
1473 case '\0': /* no unit = default unit */
1474 imult = omult = idiv = odiv = 1;
1475 break;
1476 case 's': /* second = unscaled unit */
1477 break;
1478 case 'u': /* microsecond : "us" */
1479 if (text[1] == 's') {
1480 idiv = 1000000;
1481 text++;
1482 }
1483 break;
1484 case 'm': /* millisecond : "ms" or minute: "m" */
1485 if (text[1] == 's') {
1486 idiv = 1000;
1487 text++;
1488 } else
1489 imult = 60;
1490 break;
1491 case 'h': /* hour : "h" */
1492 imult = 3600;
1493 break;
1494 case 'd': /* day : "d" */
1495 imult = 86400;
1496 break;
1497 default:
1498 return text;
1499 break;
1500 }
1501
1502 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1503 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1504 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1505 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1506
1507 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1508 *ret = value;
1509 return NULL;
1510}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001511
Emeric Brun39132b22010-01-04 14:57:24 +01001512/* this function converts the string starting at <text> to an unsigned int
1513 * stored in <ret>. If an error is detected, the pointer to the unexpected
1514 * character is returned. If the conversio is succesful, NULL is returned.
1515 */
1516const char *parse_size_err(const char *text, unsigned *ret) {
1517 unsigned value = 0;
1518
1519 while (1) {
1520 unsigned int j;
1521
1522 j = *text - '0';
1523 if (j > 9)
1524 break;
1525 if (value > ~0U / 10)
1526 return text;
1527 value *= 10;
1528 if (value > (value + j))
1529 return text;
1530 value += j;
1531 text++;
1532 }
1533
1534 switch (*text) {
1535 case '\0':
1536 break;
1537 case 'K':
1538 case 'k':
1539 if (value > ~0U >> 10)
1540 return text;
1541 value = value << 10;
1542 break;
1543 case 'M':
1544 case 'm':
1545 if (value > ~0U >> 20)
1546 return text;
1547 value = value << 20;
1548 break;
1549 case 'G':
1550 case 'g':
1551 if (value > ~0U >> 30)
1552 return text;
1553 value = value << 30;
1554 break;
1555 default:
1556 return text;
1557 }
1558
1559 *ret = value;
1560 return NULL;
1561}
1562
Willy Tarreau126d4062013-12-03 17:50:47 +01001563/*
1564 * Parse binary string written in hexadecimal (source) and store the decoded
1565 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1566 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001567 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001568 */
1569int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1570{
1571 int len;
1572 const char *p = source;
1573 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001574 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001575
1576 len = strlen(source);
1577 if (len % 2) {
1578 memprintf(err, "an even number of hex digit is expected");
1579 return 0;
1580 }
1581
1582 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001583
Willy Tarreau126d4062013-12-03 17:50:47 +01001584 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001585 *binstr = calloc(len, sizeof(char));
1586 if (!*binstr) {
1587 memprintf(err, "out of memory while loading string pattern");
1588 return 0;
1589 }
1590 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001591 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001592 else {
1593 if (*binstrlen < len) {
1594 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1595 len, *binstrlen);
1596 return 0;
1597 }
1598 alloc = 0;
1599 }
1600 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001601
1602 i = j = 0;
1603 while (j < len) {
1604 if (!ishex(p[i++]))
1605 goto bad_input;
1606 if (!ishex(p[i++]))
1607 goto bad_input;
1608 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1609 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001610 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001611
1612bad_input:
1613 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001614 if (alloc)
1615 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001616 return 0;
1617}
1618
Willy Tarreau946ba592009-05-10 15:41:18 +02001619/* copies at most <n> characters from <src> and always terminates with '\0' */
1620char *my_strndup(const char *src, int n)
1621{
1622 int len = 0;
1623 char *ret;
1624
1625 while (len < n && src[len])
1626 len++;
1627
1628 ret = (char *)malloc(len + 1);
1629 if (!ret)
1630 return ret;
1631 memcpy(ret, src, len);
1632 ret[len] = '\0';
1633 return ret;
1634}
1635
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001636/*
1637 * search needle in haystack
1638 * returns the pointer if found, returns NULL otherwise
1639 */
1640const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1641{
1642 const void *c = NULL;
1643 unsigned char f;
1644
1645 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1646 return NULL;
1647
1648 f = *(char *)needle;
1649 c = haystack;
1650 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1651 if ((haystacklen - (c - haystack)) < needlelen)
1652 return NULL;
1653
1654 if (memcmp(c, needle, needlelen) == 0)
1655 return c;
1656 ++c;
1657 }
1658 return NULL;
1659}
1660
Willy Tarreau482b00d2009-10-04 22:48:42 +02001661/* This function returns the first unused key greater than or equal to <key> in
1662 * ID tree <root>. Zero is returned if no place is found.
1663 */
1664unsigned int get_next_id(struct eb_root *root, unsigned int key)
1665{
1666 struct eb32_node *used;
1667
1668 do {
1669 used = eb32_lookup_ge(root, key);
1670 if (!used || used->key > key)
1671 return key; /* key is available */
1672 key++;
1673 } while (key);
1674 return key;
1675}
1676
Willy Tarreau348238b2010-01-18 15:05:57 +01001677/* This function compares a sample word possibly followed by blanks to another
1678 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1679 * otherwise zero. This intends to be used when checking HTTP headers for some
1680 * values. Note that it validates a word followed only by blanks but does not
1681 * validate a word followed by blanks then other chars.
1682 */
1683int word_match(const char *sample, int slen, const char *word, int wlen)
1684{
1685 if (slen < wlen)
1686 return 0;
1687
1688 while (wlen) {
1689 char c = *sample ^ *word;
1690 if (c && c != ('A' ^ 'a'))
1691 return 0;
1692 sample++;
1693 word++;
1694 slen--;
1695 wlen--;
1696 }
1697
1698 while (slen) {
1699 if (*sample != ' ' && *sample != '\t')
1700 return 0;
1701 sample++;
1702 slen--;
1703 }
1704 return 1;
1705}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001706
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001707/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1708 * is particularly fast because it avoids expensive operations such as
1709 * multiplies, which are optimized away at the end. It requires a properly
1710 * formated address though (3 points).
1711 */
1712unsigned int inetaddr_host(const char *text)
1713{
1714 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1715 register unsigned int dig100, dig10, dig1;
1716 int s;
1717 const char *p, *d;
1718
1719 dig1 = dig10 = dig100 = ascii_zero;
1720 s = 24;
1721
1722 p = text;
1723 while (1) {
1724 if (((unsigned)(*p - '0')) <= 9) {
1725 p++;
1726 continue;
1727 }
1728
1729 /* here, we have a complete byte between <text> and <p> (exclusive) */
1730 if (p == text)
1731 goto end;
1732
1733 d = p - 1;
1734 dig1 |= (unsigned int)(*d << s);
1735 if (d == text)
1736 goto end;
1737
1738 d--;
1739 dig10 |= (unsigned int)(*d << s);
1740 if (d == text)
1741 goto end;
1742
1743 d--;
1744 dig100 |= (unsigned int)(*d << s);
1745 end:
1746 if (!s || *p != '.')
1747 break;
1748
1749 s -= 8;
1750 text = ++p;
1751 }
1752
1753 dig100 -= ascii_zero;
1754 dig10 -= ascii_zero;
1755 dig1 -= ascii_zero;
1756 return ((dig100 * 10) + dig10) * 10 + dig1;
1757}
1758
1759/*
1760 * Idem except the first unparsed character has to be passed in <stop>.
1761 */
1762unsigned int inetaddr_host_lim(const char *text, const char *stop)
1763{
1764 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1765 register unsigned int dig100, dig10, dig1;
1766 int s;
1767 const char *p, *d;
1768
1769 dig1 = dig10 = dig100 = ascii_zero;
1770 s = 24;
1771
1772 p = text;
1773 while (1) {
1774 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1775 p++;
1776 continue;
1777 }
1778
1779 /* here, we have a complete byte between <text> and <p> (exclusive) */
1780 if (p == text)
1781 goto end;
1782
1783 d = p - 1;
1784 dig1 |= (unsigned int)(*d << s);
1785 if (d == text)
1786 goto end;
1787
1788 d--;
1789 dig10 |= (unsigned int)(*d << s);
1790 if (d == text)
1791 goto end;
1792
1793 d--;
1794 dig100 |= (unsigned int)(*d << s);
1795 end:
1796 if (!s || p == stop || *p != '.')
1797 break;
1798
1799 s -= 8;
1800 text = ++p;
1801 }
1802
1803 dig100 -= ascii_zero;
1804 dig10 -= ascii_zero;
1805 dig1 -= ascii_zero;
1806 return ((dig100 * 10) + dig10) * 10 + dig1;
1807}
1808
1809/*
1810 * Idem except the pointer to first unparsed byte is returned into <ret> which
1811 * must not be NULL.
1812 */
Willy Tarreau74172752010-10-15 23:21:42 +02001813unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001814{
1815 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1816 register unsigned int dig100, dig10, dig1;
1817 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001818 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001819
1820 dig1 = dig10 = dig100 = ascii_zero;
1821 s = 24;
1822
1823 p = text;
1824 while (1) {
1825 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1826 p++;
1827 continue;
1828 }
1829
1830 /* here, we have a complete byte between <text> and <p> (exclusive) */
1831 if (p == text)
1832 goto end;
1833
1834 d = p - 1;
1835 dig1 |= (unsigned int)(*d << s);
1836 if (d == text)
1837 goto end;
1838
1839 d--;
1840 dig10 |= (unsigned int)(*d << s);
1841 if (d == text)
1842 goto end;
1843
1844 d--;
1845 dig100 |= (unsigned int)(*d << s);
1846 end:
1847 if (!s || p == stop || *p != '.')
1848 break;
1849
1850 s -= 8;
1851 text = ++p;
1852 }
1853
1854 *ret = p;
1855 dig100 -= ascii_zero;
1856 dig10 -= ascii_zero;
1857 dig1 -= ascii_zero;
1858 return ((dig100 * 10) + dig10) * 10 + dig1;
1859}
1860
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001861/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1862 * or the number of chars read in case of success. Maybe this could be replaced
1863 * by one of the functions above. Also, apparently this function does not support
1864 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001865 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001866 */
1867int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1868{
1869 const char *addr;
1870 int saw_digit, octets, ch;
1871 u_char tmp[4], *tp;
1872 const char *cp = buf;
1873
1874 saw_digit = 0;
1875 octets = 0;
1876 *(tp = tmp) = 0;
1877
1878 for (addr = buf; addr - buf < len; addr++) {
1879 unsigned char digit = (ch = *addr) - '0';
1880
1881 if (digit > 9 && ch != '.')
1882 break;
1883
1884 if (digit <= 9) {
1885 u_int new = *tp * 10 + digit;
1886
1887 if (new > 255)
1888 return 0;
1889
1890 *tp = new;
1891
1892 if (!saw_digit) {
1893 if (++octets > 4)
1894 return 0;
1895 saw_digit = 1;
1896 }
1897 } else if (ch == '.' && saw_digit) {
1898 if (octets == 4)
1899 return 0;
1900
1901 *++tp = 0;
1902 saw_digit = 0;
1903 } else
1904 return 0;
1905 }
1906
1907 if (octets < 4)
1908 return 0;
1909
1910 memcpy(&dst->s_addr, tmp, 4);
1911 return addr - cp;
1912}
1913
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001914/* This function converts the string in <buf> of the len <len> to
1915 * struct in6_addr <dst> which must be allocated by the caller.
1916 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01001917 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001918 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001919int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
1920{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001921 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01001922 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001923
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001924 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001925 return 0;
1926
1927 memcpy(null_term_ip6, buf, len);
1928 null_term_ip6[len] = '\0';
1929
Willy Tarreau075415a2013-12-12 11:29:39 +01001930 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001931 return 0;
1932
Willy Tarreau075415a2013-12-12 11:29:39 +01001933 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001934 return 1;
1935}
1936
Willy Tarreauacf95772010-06-14 19:09:21 +02001937/* To be used to quote config arg positions. Returns the short string at <ptr>
1938 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1939 * if ptr is NULL or empty. The string is locally allocated.
1940 */
1941const char *quote_arg(const char *ptr)
1942{
1943 static char val[32];
1944 int i;
1945
1946 if (!ptr || !*ptr)
1947 return "end of line";
1948 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001949 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001950 val[i] = *ptr++;
1951 val[i++] = '\'';
1952 val[i] = '\0';
1953 return val;
1954}
1955
Willy Tarreau5b180202010-07-18 10:40:48 +02001956/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1957int get_std_op(const char *str)
1958{
1959 int ret = -1;
1960
1961 if (*str == 'e' && str[1] == 'q')
1962 ret = STD_OP_EQ;
1963 else if (*str == 'n' && str[1] == 'e')
1964 ret = STD_OP_NE;
1965 else if (*str == 'l') {
1966 if (str[1] == 'e') ret = STD_OP_LE;
1967 else if (str[1] == 't') ret = STD_OP_LT;
1968 }
1969 else if (*str == 'g') {
1970 if (str[1] == 'e') ret = STD_OP_GE;
1971 else if (str[1] == 't') ret = STD_OP_GT;
1972 }
1973
1974 if (ret == -1 || str[2] != '\0')
1975 return -1;
1976 return ret;
1977}
1978
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001979/* hash a 32-bit integer to another 32-bit integer */
1980unsigned int full_hash(unsigned int a)
1981{
1982 return __full_hash(a);
1983}
1984
David du Colombier4f92d322011-03-24 11:09:31 +01001985/* Return non-zero if IPv4 address is part of the network,
1986 * otherwise zero.
1987 */
1988int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1989{
1990 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1991}
1992
1993/* Return non-zero if IPv6 address is part of the network,
1994 * otherwise zero.
1995 */
1996int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1997{
1998 int i;
1999
2000 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2001 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2002 (((int *)net)[i] & ((int *)mask)[i]))
2003 return 0;
2004 return 1;
2005}
2006
2007/* RFC 4291 prefix */
2008const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2009 0x00, 0x00, 0x00, 0x00,
2010 0x00, 0x00, 0xFF, 0xFF };
2011
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002012/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2013 * Input and output may overlap.
2014 */
David du Colombier4f92d322011-03-24 11:09:31 +01002015void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2016{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002017 struct in_addr tmp_addr;
2018
2019 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002020 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002021 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002022}
2023
2024/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2025 * Return true if conversion is possible and false otherwise.
2026 */
2027int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2028{
2029 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2030 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2031 sizeof(struct in_addr));
2032 return 1;
2033 }
2034
2035 return 0;
2036}
2037
William Lallemand421f5b52012-02-06 18:15:57 +01002038char *human_time(int t, short hz_div) {
2039 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2040 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002041 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002042 int cnt=2; // print two numbers
2043
2044 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002045 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002046 return rv;
2047 }
2048
2049 if (unlikely(hz_div > 1))
2050 t /= hz_div;
2051
2052 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002053 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002054 cnt--;
2055 }
2056
2057 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002058 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002059 cnt--;
2060 }
2061
2062 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002063 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002064 cnt--;
2065 }
2066
2067 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002068 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002069
2070 return rv;
2071}
2072
2073const char *monthname[12] = {
2074 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2075 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2076};
2077
2078/* date2str_log: write a date in the format :
2079 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2080 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2081 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2082 *
2083 * without using sprintf. return a pointer to the last char written (\0) or
2084 * NULL if there isn't enough space.
2085 */
2086char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2087{
2088
2089 if (size < 25) /* the size is fixed: 24 chars + \0 */
2090 return NULL;
2091
2092 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2093 *dst++ = '/';
2094 memcpy(dst, monthname[tm->tm_mon], 3); // month
2095 dst += 3;
2096 *dst++ = '/';
2097 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2098 *dst++ = ':';
2099 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2100 *dst++ = ':';
2101 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2102 *dst++ = ':';
2103 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2104 *dst++ = '.';
2105 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2106 dst += 3; // only the 3 first digits
2107 *dst = '\0';
2108
2109 return dst;
2110}
2111
2112/* gmt2str_log: write a date in the format :
2113 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2114 * return a pointer to the last char written (\0) or
2115 * NULL if there isn't enough space.
2116 */
2117char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2118{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002119 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002120 return NULL;
2121
2122 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2123 *dst++ = '/';
2124 memcpy(dst, monthname[tm->tm_mon], 3); // month
2125 dst += 3;
2126 *dst++ = '/';
2127 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2128 *dst++ = ':';
2129 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2130 *dst++ = ':';
2131 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2132 *dst++ = ':';
2133 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2134 *dst++ = ' ';
2135 *dst++ = '+';
2136 *dst++ = '0';
2137 *dst++ = '0';
2138 *dst++ = '0';
2139 *dst++ = '0';
2140 *dst = '\0';
2141
2142 return dst;
2143}
2144
Yuxans Yao4e25b012012-10-19 10:36:09 +08002145/* localdate2str_log: write a date in the format :
2146 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2147 * * return a pointer to the last char written (\0) or
2148 * * NULL if there isn't enough space.
2149 */
2150char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2151{
2152 if (size < 27) /* the size is fixed: 26 chars + \0 */
2153 return NULL;
2154
2155 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2156 *dst++ = '/';
2157 memcpy(dst, monthname[tm->tm_mon], 3); // month
2158 dst += 3;
2159 *dst++ = '/';
2160 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2161 *dst++ = ':';
2162 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2163 *dst++ = ':';
2164 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2165 *dst++ = ':';
2166 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2167 *dst++ = ' ';
2168 memcpy(dst, localtimezone, 5); // timezone
2169 dst += 5;
2170 *dst = '\0';
2171
2172 return dst;
2173}
2174
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002175/* Dynamically allocates a string of the proper length to hold the formatted
2176 * output. NULL is returned on error. The caller is responsible for freeing the
2177 * memory area using free(). The resulting string is returned in <out> if the
2178 * pointer is not NULL. A previous version of <out> might be used to build the
2179 * new string, and it will be freed before returning if it is not NULL, which
2180 * makes it possible to build complex strings from iterative calls without
2181 * having to care about freeing intermediate values, as in the example below :
2182 *
2183 * memprintf(&err, "invalid argument: '%s'", arg);
2184 * ...
2185 * memprintf(&err, "parser said : <%s>\n", *err);
2186 * ...
2187 * free(*err);
2188 *
2189 * This means that <err> must be initialized to NULL before first invocation.
2190 * The return value also holds the allocated string, which eases error checking
2191 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002192 * passed instead and it will be ignored. The returned message will then also
2193 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002194 *
2195 * It is also convenient to use it without any free except the last one :
2196 * err = NULL;
2197 * if (!fct1(err)) report(*err);
2198 * if (!fct2(err)) report(*err);
2199 * if (!fct3(err)) report(*err);
2200 * free(*err);
2201 */
2202char *memprintf(char **out, const char *format, ...)
2203{
2204 va_list args;
2205 char *ret = NULL;
2206 int allocated = 0;
2207 int needed = 0;
2208
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002209 if (!out)
2210 return NULL;
2211
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002212 do {
2213 /* vsnprintf() will return the required length even when the
2214 * target buffer is NULL. We do this in a loop just in case
2215 * intermediate evaluations get wrong.
2216 */
2217 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002218 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002219 va_end(args);
2220
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002221 if (needed < allocated) {
2222 /* Note: on Solaris 8, the first iteration always
2223 * returns -1 if allocated is zero, so we force a
2224 * retry.
2225 */
2226 if (!allocated)
2227 needed = 0;
2228 else
2229 break;
2230 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002231
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002232 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002233 ret = realloc(ret, allocated);
2234 } while (ret);
2235
2236 if (needed < 0) {
2237 /* an error was encountered */
2238 free(ret);
2239 ret = NULL;
2240 }
2241
2242 if (out) {
2243 free(*out);
2244 *out = ret;
2245 }
2246
2247 return ret;
2248}
William Lallemand421f5b52012-02-06 18:15:57 +01002249
Willy Tarreau21c705b2012-09-14 11:40:36 +02002250/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2251 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002252 * freed by the caller. It also supports being passed a NULL which results in the same
2253 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002254 * Example of use :
2255 * parse(cmd, &err); (callee: memprintf(&err, ...))
2256 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2257 * free(err);
2258 */
2259char *indent_msg(char **out, int level)
2260{
2261 char *ret, *in, *p;
2262 int needed = 0;
2263 int lf = 0;
2264 int lastlf = 0;
2265 int len;
2266
Willy Tarreau70eec382012-10-10 08:56:47 +02002267 if (!out || !*out)
2268 return NULL;
2269
Willy Tarreau21c705b2012-09-14 11:40:36 +02002270 in = *out - 1;
2271 while ((in = strchr(in + 1, '\n')) != NULL) {
2272 lastlf = in - *out;
2273 lf++;
2274 }
2275
2276 if (!lf) /* single line, no LF, return it as-is */
2277 return *out;
2278
2279 len = strlen(*out);
2280
2281 if (lf == 1 && lastlf == len - 1) {
2282 /* single line, LF at end, strip it and return as-is */
2283 (*out)[lastlf] = 0;
2284 return *out;
2285 }
2286
2287 /* OK now we have at least one LF, we need to process the whole string
2288 * as a multi-line string. What we'll do :
2289 * - prefix with an LF if there is none
2290 * - add <level> spaces before each line
2291 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2292 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2293 */
2294
2295 needed = 1 + level * (lf + 1) + len + 1;
2296 p = ret = malloc(needed);
2297 in = *out;
2298
2299 /* skip initial LFs */
2300 while (*in == '\n')
2301 in++;
2302
2303 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2304 while (*in) {
2305 *p++ = '\n';
2306 memset(p, ' ', level);
2307 p += level;
2308 do {
2309 *p++ = *in++;
2310 } while (*in && *in != '\n');
2311 if (*in)
2312 in++;
2313 }
2314 *p = 0;
2315
2316 free(*out);
2317 *out = ret;
2318
2319 return ret;
2320}
2321
Willy Tarreaudad36a32013-03-11 01:20:04 +01002322/* Convert occurrences of environment variables in the input string to their
2323 * corresponding value. A variable is identified as a series of alphanumeric
2324 * characters or underscores following a '$' sign. The <in> string must be
2325 * free()able. NULL returns NULL. The resulting string might be reallocated if
2326 * some expansion is made. Variable names may also be enclosed into braces if
2327 * needed (eg: to concatenate alphanum characters).
2328 */
2329char *env_expand(char *in)
2330{
2331 char *txt_beg;
2332 char *out;
2333 char *txt_end;
2334 char *var_beg;
2335 char *var_end;
2336 char *value;
2337 char *next;
2338 int out_len;
2339 int val_len;
2340
2341 if (!in)
2342 return in;
2343
2344 value = out = NULL;
2345 out_len = 0;
2346
2347 txt_beg = in;
2348 do {
2349 /* look for next '$' sign in <in> */
2350 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2351
2352 if (!*txt_end && !out) /* end and no expansion performed */
2353 return in;
2354
2355 val_len = 0;
2356 next = txt_end;
2357 if (*txt_end == '$') {
2358 char save;
2359
2360 var_beg = txt_end + 1;
2361 if (*var_beg == '{')
2362 var_beg++;
2363
2364 var_end = var_beg;
2365 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2366 var_end++;
2367 }
2368
2369 next = var_end;
2370 if (*var_end == '}' && (var_beg > txt_end + 1))
2371 next++;
2372
2373 /* get value of the variable name at this location */
2374 save = *var_end;
2375 *var_end = '\0';
2376 value = getenv(var_beg);
2377 *var_end = save;
2378 val_len = value ? strlen(value) : 0;
2379 }
2380
2381 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2382 if (txt_end > txt_beg) {
2383 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2384 out_len += txt_end - txt_beg;
2385 }
2386 if (val_len) {
2387 memcpy(out + out_len, value, val_len);
2388 out_len += val_len;
2389 }
2390 out[out_len] = 0;
2391 txt_beg = next;
2392 } while (*txt_beg);
2393
2394 /* here we know that <out> was allocated and that we don't need <in> anymore */
2395 free(in);
2396 return out;
2397}
2398
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002399
2400/* same as strstr() but case-insensitive and with limit length */
2401const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2402{
2403 char *pptr, *sptr, *start;
2404 uint slen, plen;
2405 uint tmp1, tmp2;
2406
2407 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2408 return NULL;
2409
2410 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2411 return str1;
2412
2413 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2414 return NULL;
2415
2416 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2417 while (toupper(*start) != toupper(*str2)) {
2418 start++;
2419 slen--;
2420 tmp1++;
2421
2422 if (tmp1 >= len_str1)
2423 return NULL;
2424
2425 /* if pattern longer than string */
2426 if (slen < plen)
2427 return NULL;
2428 }
2429
2430 sptr = start;
2431 pptr = (char *)str2;
2432
2433 tmp2 = 0;
2434 while (toupper(*sptr) == toupper(*pptr)) {
2435 sptr++;
2436 pptr++;
2437 tmp2++;
2438
2439 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2440 return start;
2441 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2442 return NULL;
2443 }
2444 }
2445 return NULL;
2446}
2447
Willy Tarreaubaaee002006-06-26 02:48:02 +02002448/*
2449 * Local variables:
2450 * c-indent-level: 8
2451 * c-basic-offset: 8
2452 * End:
2453 */