blob: 569ecaac1830a8fa4c18e0921c40b37b4dfaf3e9 [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;
703
704 /* complete unix socket path name during startup or soft-restart is
705 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
706 */
707 prefix_path_len = pfx ? strlen(pfx) : 0;
708 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
709 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
710
711 if (strlen(str2) > max_path_len) {
712 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
713 goto out;
714 }
715
Willy Tarreau15586382013-03-04 19:48:14 +0100716 if (pfx) {
717 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
718 strcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len, str2);
719 }
720 else {
721 strcpy(((struct sockaddr_un *)&ss)->sun_path, str2);
722 }
Willy Tarreau15586382013-03-04 19:48:14 +0100723 }
Willy Tarreau24709282013-03-10 21:32:12 +0100724 else { /* IPv4 and IPv6 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 port1 = strrchr(str2, ':');
726 if (port1)
727 *port1++ = '\0';
728 else
729 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200730
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100731 if (str2ip(str2, &ss) == NULL) {
732 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
733 goto out;
734 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100735
Willy Tarreaua39d1992013-04-01 20:37:42 +0200736 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100737 port2 = strchr(port1, '-');
738 if (port2)
739 *port2++ = '\0';
740 else
741 port2 = port1;
742 portl = atoi(port1);
743 porth = atoi(port2);
744 porta = portl;
745 }
746 else if (*port1 == '-') { /* negative offset */
747 portl = atoi(port1 + 1);
748 porta = -portl;
749 }
750 else if (*port1 == '+') { /* positive offset */
751 porth = atoi(port1 + 1);
752 porta = porth;
753 }
754 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100755 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100756 goto out;
757 }
758 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100759 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100760
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100761 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100762 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100763 if (low)
764 *low = portl;
765 if (high)
766 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100767 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100768 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200769}
770
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100771/* converts <str> to a struct in_addr containing a network mask. It can be
772 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
773 * if the conversion succeeds otherwise non-zero.
774 */
775int str2mask(const char *str, struct in_addr *mask)
776{
777 if (strchr(str, '.') != NULL) { /* dotted notation */
778 if (!inet_pton(AF_INET, str, mask))
779 return 0;
780 }
781 else { /* mask length */
782 char *err;
783 unsigned long len = strtol(str, &err, 10);
784
785 if (!*str || (err && *err) || (unsigned)len > 32)
786 return 0;
787 if (len)
788 mask->s_addr = htonl(~0UL << (32 - len));
789 else
790 mask->s_addr = 0;
791 }
792 return 1;
793}
794
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100795/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
796 * succeeds otherwise zero.
797 */
798int cidr2dotted(int cidr, struct in_addr *mask) {
799
800 if (cidr < 0 || cidr > 32)
801 return 0;
802
803 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
804 return 1;
805}
806
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200807/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200808 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200809 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
810 * is optionnal and either in the dotted or CIDR notation.
811 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
812 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100813int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200814{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200815 __label__ out_free, out_err;
816 char *c, *s;
817 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200818
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200819 s = strdup(str);
820 if (!s)
821 return 0;
822
Willy Tarreaubaaee002006-06-26 02:48:02 +0200823 memset(mask, 0, sizeof(*mask));
824 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200825
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200826 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200827 *c++ = '\0';
828 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100829 if (!str2mask(c, mask))
830 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200831 }
832 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100833 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200834 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200835 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200836 struct hostent *he;
837
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100838 if (!resolve)
839 goto out_err;
840
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200841 if ((he = gethostbyname(s)) == NULL) {
842 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200843 }
844 else
845 *addr = *(struct in_addr *) *(he->h_addr_list);
846 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200847
848 ret_val = 1;
849 out_free:
850 free(s);
851 return ret_val;
852 out_err:
853 ret_val = 0;
854 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200855}
856
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100857
858/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200859 * converts <str> to two struct in6_addr* which must be pre-allocated.
860 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
861 * is an optionnal number of bits (128 being the default).
862 * Returns 1 if OK, 0 if error.
863 */
864int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
865{
866 char *c, *s;
867 int ret_val = 0;
868 char *err;
869 unsigned long len = 128;
870
871 s = strdup(str);
872 if (!s)
873 return 0;
874
875 memset(mask, 0, sizeof(*mask));
876 memset(addr, 0, sizeof(*addr));
877
878 if ((c = strrchr(s, '/')) != NULL) {
879 *c++ = '\0'; /* c points to the mask */
880 if (!*c)
881 goto out_free;
882
883 len = strtoul(c, &err, 10);
884 if ((err && *err) || (unsigned)len > 128)
885 goto out_free;
886 }
887 *mask = len; /* OK we have a valid mask in <len> */
888
889 if (!inet_pton(AF_INET6, s, addr))
890 goto out_free;
891
892 ret_val = 1;
893 out_free:
894 free(s);
895 return ret_val;
896}
897
898
899/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100900 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100901 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100902int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100903{
904 int saw_digit, octets, ch;
905 u_char tmp[4], *tp;
906 const char *cp = addr;
907
908 saw_digit = 0;
909 octets = 0;
910 *(tp = tmp) = 0;
911
912 while (*addr) {
913 unsigned char digit = (ch = *addr++) - '0';
914 if (digit > 9 && ch != '.')
915 break;
916 if (digit <= 9) {
917 u_int new = *tp * 10 + digit;
918 if (new > 255)
919 return 0;
920 *tp = new;
921 if (!saw_digit) {
922 if (++octets > 4)
923 return 0;
924 saw_digit = 1;
925 }
926 } else if (ch == '.' && saw_digit) {
927 if (octets == 4)
928 return 0;
929 *++tp = 0;
930 saw_digit = 0;
931 } else
932 return 0;
933 }
934
935 if (octets < 4)
936 return 0;
937
938 memcpy(&dst->s_addr, tmp, 4);
939 return addr-cp-1;
940}
941
942/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100943 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
944 * <out> contain the code of the dectected scheme, the start and length of
945 * the hostname. Actually only http and https are supported. <out> can be NULL.
946 * This function returns the consumed length. It is useful if you parse complete
947 * url like http://host:port/path, because the consumed length corresponds to
948 * the first character of the path. If the conversion fails, it returns -1.
949 *
950 * This function tries to resolve the DNS name if haproxy is in starting mode.
951 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100952 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100953int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100954{
955 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100956 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100957 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100958 unsigned long long int http_code = 0;
959 int default_port;
960 struct hostent *he;
961 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100962
963 /* Firstly, try to find :// pattern */
964 while (curr < url+ulen && url_code != 0x3a2f2f) {
965 url_code = ((url_code & 0xffff) << 8);
966 url_code += (unsigned char)*curr++;
967 }
968
969 /* Secondly, if :// pattern is found, verify parsed stuff
970 * before pattern is matching our http pattern.
971 * If so parse ip address and port in uri.
972 *
973 * WARNING: Current code doesn't support dynamic async dns resolver.
974 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100975 if (url_code != 0x3a2f2f)
976 return -1;
977
978 /* Copy scheme, and utrn to lower case. */
979 while (cp < curr - 3)
980 http_code = (http_code << 8) + *cp++;
981 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100982
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100983 /* HTTP or HTTPS url matching */
984 if (http_code == 0x2020202068747470ULL) {
985 default_port = 80;
986 if (out)
987 out->scheme = SCH_HTTP;
988 }
989 else if (http_code == 0x2020206874747073ULL) {
990 default_port = 443;
991 if (out)
992 out->scheme = SCH_HTTPS;
993 }
994 else
995 return -1;
996
997 /* If the next char is '[', the host address is IPv6. */
998 if (*curr == '[') {
999 curr++;
1000
1001 /* Check trash size */
1002 if (trash.size < ulen)
1003 return -1;
1004
1005 /* Look for ']' and copy the address in a trash buffer. */
1006 p = trash.str;
1007 for (end = curr;
1008 end < url + ulen && *end != ']';
1009 end++, p++)
1010 *p = *end;
1011 if (*end != ']')
1012 return -1;
1013 *p = '\0';
1014
1015 /* Update out. */
1016 if (out) {
1017 out->host = curr;
1018 out->host_len = end - curr;
1019 }
1020
1021 /* Try IPv6 decoding. */
1022 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1023 return -1;
1024 end++;
1025
1026 /* Decode port. */
1027 if (*end == ':') {
1028 end++;
1029 default_port = read_uint(&end, url + ulen);
1030 }
1031 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1032 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1033 return end - url;
1034 }
1035 else {
1036 /* We are looking for IP address. If you want to parse and
1037 * resolve hostname found in url, you can use str2sa_range(), but
1038 * be warned this can slow down global daemon performances
1039 * while handling lagging dns responses.
1040 */
1041 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1042 if (ret) {
1043 /* Update out. */
1044 if (out) {
1045 out->host = curr;
1046 out->host_len = ret;
1047 }
1048
1049 curr += ret;
1050
1051 /* Decode port. */
1052 if (*curr == ':') {
1053 curr++;
1054 default_port = read_uint(&curr, url + ulen);
1055 }
1056 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1057
1058 /* Set family. */
1059 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1060 return curr - url;
1061 }
1062 else if (global.mode & MODE_STARTING) {
1063 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1064 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001065 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001066
1067 /* look for : or / or end */
1068 for (end = curr;
1069 end < url + ulen && *end != '/' && *end != ':';
1070 end++);
1071 memcpy(trash.str, curr, end - curr);
1072 trash.str[end - curr] = '\0';
1073
1074 /* try to resolve an IPv4/IPv6 hostname */
1075 he = gethostbyname(trash.str);
1076 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001077 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001078
1079 /* Update out. */
1080 if (out) {
1081 out->host = curr;
1082 out->host_len = end - curr;
1083 }
1084
1085 /* Decode port. */
1086 if (*end == ':') {
1087 end++;
1088 default_port = read_uint(&end, url + ulen);
1089 }
1090
1091 /* Copy IP address, set port and family. */
1092 switch (he->h_addrtype) {
1093 case AF_INET:
1094 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1095 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1096 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1097 return end - url;
1098
1099 case AF_INET6:
1100 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1101 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1102 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1103 return end - url;
1104 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001105 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001106 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001107 return -1;
1108}
1109
Willy Tarreau631f01c2011-09-05 00:36:48 +02001110/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1111 * address family is returned so that it's easy for the caller to adapt to the
1112 * output format. Zero is returned if the address family is not supported. -1
1113 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1114 * supported.
1115 */
1116int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1117{
1118
1119 void *ptr;
1120
1121 if (size < 5)
1122 return 0;
1123 *str = '\0';
1124
1125 switch (addr->ss_family) {
1126 case AF_INET:
1127 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1128 break;
1129 case AF_INET6:
1130 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1131 break;
1132 case AF_UNIX:
1133 memcpy(str, "unix", 5);
1134 return addr->ss_family;
1135 default:
1136 return 0;
1137 }
1138
1139 if (inet_ntop(addr->ss_family, ptr, str, size))
1140 return addr->ss_family;
1141
1142 /* failed */
1143 return -1;
1144}
1145
Willy Tarreaubaaee002006-06-26 02:48:02 +02001146/* will try to encode the string <string> replacing all characters tagged in
1147 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1148 * prefixed by <escape>, and will store the result between <start> (included)
1149 * and <stop> (excluded), and will always terminate the string with a '\0'
1150 * before <stop>. The position of the '\0' is returned if the conversion
1151 * completes. If bytes are missing between <start> and <stop>, then the
1152 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1153 * cannot even be stored so we return <start> without writing the 0.
1154 * The input string must also be zero-terminated.
1155 */
1156const char hextab[16] = "0123456789ABCDEF";
1157char *encode_string(char *start, char *stop,
1158 const char escape, const fd_set *map,
1159 const char *string)
1160{
1161 if (start < stop) {
1162 stop--; /* reserve one byte for the final '\0' */
1163 while (start < stop && *string != '\0') {
1164 if (!FD_ISSET((unsigned char)(*string), map))
1165 *start++ = *string;
1166 else {
1167 if (start + 3 >= stop)
1168 break;
1169 *start++ = escape;
1170 *start++ = hextab[(*string >> 4) & 15];
1171 *start++ = hextab[*string & 15];
1172 }
1173 string++;
1174 }
1175 *start = '\0';
1176 }
1177 return start;
1178}
1179
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001180/*
1181 * Same behavior as encode_string() above, except that it encodes chunk
1182 * <chunk> instead of a string.
1183 */
1184char *encode_chunk(char *start, char *stop,
1185 const char escape, const fd_set *map,
1186 const struct chunk *chunk)
1187{
1188 char *str = chunk->str;
1189 char *end = chunk->str + chunk->len;
1190
1191 if (start < stop) {
1192 stop--; /* reserve one byte for the final '\0' */
1193 while (start < stop && str < end) {
1194 if (!FD_ISSET((unsigned char)(*str), map))
1195 *start++ = *str;
1196 else {
1197 if (start + 3 >= stop)
1198 break;
1199 *start++ = escape;
1200 *start++ = hextab[(*str >> 4) & 15];
1201 *start++ = hextab[*str & 15];
1202 }
1203 str++;
1204 }
1205 *start = '\0';
1206 }
1207 return start;
1208}
1209
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001210/* Decode an URL-encoded string in-place. The resulting string might
1211 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001212 * aborted, the string is truncated before the issue and a negative value is
1213 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001214 */
1215int url_decode(char *string)
1216{
1217 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001218 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001219
1220 in = string;
1221 out = string;
1222 while (*in) {
1223 switch (*in) {
1224 case '+' :
1225 *out++ = ' ';
1226 break;
1227 case '%' :
1228 if (!ishex(in[1]) || !ishex(in[2]))
1229 goto end;
1230 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1231 in += 2;
1232 break;
1233 default:
1234 *out++ = *in;
1235 break;
1236 }
1237 in++;
1238 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001239 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001240 end:
1241 *out = 0;
1242 return ret;
1243}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001244
Willy Tarreau6911fa42007-03-04 18:06:08 +01001245unsigned int str2ui(const char *s)
1246{
1247 return __str2ui(s);
1248}
1249
1250unsigned int str2uic(const char *s)
1251{
1252 return __str2uic(s);
1253}
1254
1255unsigned int strl2ui(const char *s, int len)
1256{
1257 return __strl2ui(s, len);
1258}
1259
1260unsigned int strl2uic(const char *s, int len)
1261{
1262 return __strl2uic(s, len);
1263}
1264
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001265unsigned int read_uint(const char **s, const char *end)
1266{
1267 return __read_uint(s, end);
1268}
1269
Willy Tarreau6911fa42007-03-04 18:06:08 +01001270/* This one is 7 times faster than strtol() on athlon with checks.
1271 * It returns the value of the number composed of all valid digits read,
1272 * and can process negative numbers too.
1273 */
1274int strl2ic(const char *s, int len)
1275{
1276 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001277 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001278
1279 if (len > 0) {
1280 if (*s != '-') {
1281 /* positive number */
1282 while (len-- > 0) {
1283 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001284 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001285 if (j > 9)
1286 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001287 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001288 }
1289 } else {
1290 /* negative number */
1291 s++;
1292 while (--len > 0) {
1293 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001294 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001295 if (j > 9)
1296 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001297 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001298 }
1299 }
1300 }
1301 return i;
1302}
1303
1304
1305/* This function reads exactly <len> chars from <s> and converts them to a
1306 * signed integer which it stores into <ret>. It accurately detects any error
1307 * (truncated string, invalid chars, overflows). It is meant to be used in
1308 * applications designed for hostile environments. It returns zero when the
1309 * number has successfully been converted, non-zero otherwise. When an error
1310 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1311 * faster than strtol().
1312 */
1313int strl2irc(const char *s, int len, int *ret)
1314{
1315 int i = 0;
1316 int j;
1317
1318 if (!len)
1319 return 1;
1320
1321 if (*s != '-') {
1322 /* positive number */
1323 while (len-- > 0) {
1324 j = (*s++) - '0';
1325 if (j > 9) return 1; /* invalid char */
1326 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1327 i = i * 10;
1328 if (i + j < i) return 1; /* check for addition overflow */
1329 i = i + j;
1330 }
1331 } else {
1332 /* negative number */
1333 s++;
1334 while (--len > 0) {
1335 j = (*s++) - '0';
1336 if (j > 9) return 1; /* invalid char */
1337 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1338 i = i * 10;
1339 if (i - j > i) return 1; /* check for subtract overflow */
1340 i = i - j;
1341 }
1342 }
1343 *ret = i;
1344 return 0;
1345}
1346
1347
1348/* This function reads exactly <len> chars from <s> and converts them to a
1349 * signed integer which it stores into <ret>. It accurately detects any error
1350 * (truncated string, invalid chars, overflows). It is meant to be used in
1351 * applications designed for hostile environments. It returns zero when the
1352 * number has successfully been converted, non-zero otherwise. When an error
1353 * is returned, the <ret> value is left untouched. It is about 3 times slower
1354 * than str2irc().
1355 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001356
1357int strl2llrc(const char *s, int len, long long *ret)
1358{
1359 long long i = 0;
1360 int j;
1361
1362 if (!len)
1363 return 1;
1364
1365 if (*s != '-') {
1366 /* positive number */
1367 while (len-- > 0) {
1368 j = (*s++) - '0';
1369 if (j > 9) return 1; /* invalid char */
1370 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1371 i = i * 10LL;
1372 if (i + j < i) return 1; /* check for addition overflow */
1373 i = i + j;
1374 }
1375 } else {
1376 /* negative number */
1377 s++;
1378 while (--len > 0) {
1379 j = (*s++) - '0';
1380 if (j > 9) return 1; /* invalid char */
1381 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1382 i = i * 10LL;
1383 if (i - j > i) return 1; /* check for subtract overflow */
1384 i = i - j;
1385 }
1386 }
1387 *ret = i;
1388 return 0;
1389}
1390
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001391/* This function is used with pat_parse_dotted_ver(). It converts a string
1392 * composed by two number separated by a dot. Each part must contain in 16 bits
1393 * because internally they will be represented as a 32-bit quantity stored in
1394 * a 64-bit integer. It returns zero when the number has successfully been
1395 * converted, non-zero otherwise. When an error is returned, the <ret> value
1396 * is left untouched.
1397 *
1398 * "1.3" -> 0x0000000000010003
1399 * "65535.65535" -> 0x00000000ffffffff
1400 */
1401int strl2llrc_dotted(const char *text, int len, long long *ret)
1402{
1403 const char *end = &text[len];
1404 const char *p;
1405 long long major, minor;
1406
1407 /* Look for dot. */
1408 for (p = text; p < end; p++)
1409 if (*p == '.')
1410 break;
1411
1412 /* Convert major. */
1413 if (strl2llrc(text, p - text, &major) != 0)
1414 return 1;
1415
1416 /* Check major. */
1417 if (major >= 65536)
1418 return 1;
1419
1420 /* Convert minor. */
1421 minor = 0;
1422 if (p < end)
1423 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1424 return 1;
1425
1426 /* Check minor. */
1427 if (minor >= 65536)
1428 return 1;
1429
1430 /* Compose value. */
1431 *ret = (major << 16) | (minor & 0xffff);
1432 return 0;
1433}
1434
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001435/* This function parses a time value optionally followed by a unit suffix among
1436 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1437 * expected by the caller. The computation does its best to avoid overflows.
1438 * The value is returned in <ret> if everything is fine, and a NULL is returned
1439 * by the function. In case of error, a pointer to the error is returned and
1440 * <ret> is left untouched. Values are automatically rounded up when needed.
1441 */
1442const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1443{
1444 unsigned imult, idiv;
1445 unsigned omult, odiv;
1446 unsigned value;
1447
1448 omult = odiv = 1;
1449
1450 switch (unit_flags & TIME_UNIT_MASK) {
1451 case TIME_UNIT_US: omult = 1000000; break;
1452 case TIME_UNIT_MS: omult = 1000; break;
1453 case TIME_UNIT_S: break;
1454 case TIME_UNIT_MIN: odiv = 60; break;
1455 case TIME_UNIT_HOUR: odiv = 3600; break;
1456 case TIME_UNIT_DAY: odiv = 86400; break;
1457 default: break;
1458 }
1459
1460 value = 0;
1461
1462 while (1) {
1463 unsigned int j;
1464
1465 j = *text - '0';
1466 if (j > 9)
1467 break;
1468 text++;
1469 value *= 10;
1470 value += j;
1471 }
1472
1473 imult = idiv = 1;
1474 switch (*text) {
1475 case '\0': /* no unit = default unit */
1476 imult = omult = idiv = odiv = 1;
1477 break;
1478 case 's': /* second = unscaled unit */
1479 break;
1480 case 'u': /* microsecond : "us" */
1481 if (text[1] == 's') {
1482 idiv = 1000000;
1483 text++;
1484 }
1485 break;
1486 case 'm': /* millisecond : "ms" or minute: "m" */
1487 if (text[1] == 's') {
1488 idiv = 1000;
1489 text++;
1490 } else
1491 imult = 60;
1492 break;
1493 case 'h': /* hour : "h" */
1494 imult = 3600;
1495 break;
1496 case 'd': /* day : "d" */
1497 imult = 86400;
1498 break;
1499 default:
1500 return text;
1501 break;
1502 }
1503
1504 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1505 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1506 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1507 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1508
1509 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1510 *ret = value;
1511 return NULL;
1512}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001513
Emeric Brun39132b22010-01-04 14:57:24 +01001514/* this function converts the string starting at <text> to an unsigned int
1515 * stored in <ret>. If an error is detected, the pointer to the unexpected
1516 * character is returned. If the conversio is succesful, NULL is returned.
1517 */
1518const char *parse_size_err(const char *text, unsigned *ret) {
1519 unsigned value = 0;
1520
1521 while (1) {
1522 unsigned int j;
1523
1524 j = *text - '0';
1525 if (j > 9)
1526 break;
1527 if (value > ~0U / 10)
1528 return text;
1529 value *= 10;
1530 if (value > (value + j))
1531 return text;
1532 value += j;
1533 text++;
1534 }
1535
1536 switch (*text) {
1537 case '\0':
1538 break;
1539 case 'K':
1540 case 'k':
1541 if (value > ~0U >> 10)
1542 return text;
1543 value = value << 10;
1544 break;
1545 case 'M':
1546 case 'm':
1547 if (value > ~0U >> 20)
1548 return text;
1549 value = value << 20;
1550 break;
1551 case 'G':
1552 case 'g':
1553 if (value > ~0U >> 30)
1554 return text;
1555 value = value << 30;
1556 break;
1557 default:
1558 return text;
1559 }
1560
1561 *ret = value;
1562 return NULL;
1563}
1564
Willy Tarreau126d4062013-12-03 17:50:47 +01001565/*
1566 * Parse binary string written in hexadecimal (source) and store the decoded
1567 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1568 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001569 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001570 */
1571int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1572{
1573 int len;
1574 const char *p = source;
1575 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001576 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001577
1578 len = strlen(source);
1579 if (len % 2) {
1580 memprintf(err, "an even number of hex digit is expected");
1581 return 0;
1582 }
1583
1584 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001585
Willy Tarreau126d4062013-12-03 17:50:47 +01001586 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001587 *binstr = calloc(len, sizeof(char));
1588 if (!*binstr) {
1589 memprintf(err, "out of memory while loading string pattern");
1590 return 0;
1591 }
1592 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001593 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001594 else {
1595 if (*binstrlen < len) {
1596 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1597 len, *binstrlen);
1598 return 0;
1599 }
1600 alloc = 0;
1601 }
1602 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001603
1604 i = j = 0;
1605 while (j < len) {
1606 if (!ishex(p[i++]))
1607 goto bad_input;
1608 if (!ishex(p[i++]))
1609 goto bad_input;
1610 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1611 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001612 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001613
1614bad_input:
1615 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001616 if (alloc)
1617 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001618 return 0;
1619}
1620
Willy Tarreau946ba592009-05-10 15:41:18 +02001621/* copies at most <n> characters from <src> and always terminates with '\0' */
1622char *my_strndup(const char *src, int n)
1623{
1624 int len = 0;
1625 char *ret;
1626
1627 while (len < n && src[len])
1628 len++;
1629
1630 ret = (char *)malloc(len + 1);
1631 if (!ret)
1632 return ret;
1633 memcpy(ret, src, len);
1634 ret[len] = '\0';
1635 return ret;
1636}
1637
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001638/*
1639 * search needle in haystack
1640 * returns the pointer if found, returns NULL otherwise
1641 */
1642const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1643{
1644 const void *c = NULL;
1645 unsigned char f;
1646
1647 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1648 return NULL;
1649
1650 f = *(char *)needle;
1651 c = haystack;
1652 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1653 if ((haystacklen - (c - haystack)) < needlelen)
1654 return NULL;
1655
1656 if (memcmp(c, needle, needlelen) == 0)
1657 return c;
1658 ++c;
1659 }
1660 return NULL;
1661}
1662
Willy Tarreau482b00d2009-10-04 22:48:42 +02001663/* This function returns the first unused key greater than or equal to <key> in
1664 * ID tree <root>. Zero is returned if no place is found.
1665 */
1666unsigned int get_next_id(struct eb_root *root, unsigned int key)
1667{
1668 struct eb32_node *used;
1669
1670 do {
1671 used = eb32_lookup_ge(root, key);
1672 if (!used || used->key > key)
1673 return key; /* key is available */
1674 key++;
1675 } while (key);
1676 return key;
1677}
1678
Willy Tarreau348238b2010-01-18 15:05:57 +01001679/* This function compares a sample word possibly followed by blanks to another
1680 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1681 * otherwise zero. This intends to be used when checking HTTP headers for some
1682 * values. Note that it validates a word followed only by blanks but does not
1683 * validate a word followed by blanks then other chars.
1684 */
1685int word_match(const char *sample, int slen, const char *word, int wlen)
1686{
1687 if (slen < wlen)
1688 return 0;
1689
1690 while (wlen) {
1691 char c = *sample ^ *word;
1692 if (c && c != ('A' ^ 'a'))
1693 return 0;
1694 sample++;
1695 word++;
1696 slen--;
1697 wlen--;
1698 }
1699
1700 while (slen) {
1701 if (*sample != ' ' && *sample != '\t')
1702 return 0;
1703 sample++;
1704 slen--;
1705 }
1706 return 1;
1707}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001708
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001709/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1710 * is particularly fast because it avoids expensive operations such as
1711 * multiplies, which are optimized away at the end. It requires a properly
1712 * formated address though (3 points).
1713 */
1714unsigned int inetaddr_host(const char *text)
1715{
1716 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1717 register unsigned int dig100, dig10, dig1;
1718 int s;
1719 const char *p, *d;
1720
1721 dig1 = dig10 = dig100 = ascii_zero;
1722 s = 24;
1723
1724 p = text;
1725 while (1) {
1726 if (((unsigned)(*p - '0')) <= 9) {
1727 p++;
1728 continue;
1729 }
1730
1731 /* here, we have a complete byte between <text> and <p> (exclusive) */
1732 if (p == text)
1733 goto end;
1734
1735 d = p - 1;
1736 dig1 |= (unsigned int)(*d << s);
1737 if (d == text)
1738 goto end;
1739
1740 d--;
1741 dig10 |= (unsigned int)(*d << s);
1742 if (d == text)
1743 goto end;
1744
1745 d--;
1746 dig100 |= (unsigned int)(*d << s);
1747 end:
1748 if (!s || *p != '.')
1749 break;
1750
1751 s -= 8;
1752 text = ++p;
1753 }
1754
1755 dig100 -= ascii_zero;
1756 dig10 -= ascii_zero;
1757 dig1 -= ascii_zero;
1758 return ((dig100 * 10) + dig10) * 10 + dig1;
1759}
1760
1761/*
1762 * Idem except the first unparsed character has to be passed in <stop>.
1763 */
1764unsigned int inetaddr_host_lim(const char *text, const char *stop)
1765{
1766 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1767 register unsigned int dig100, dig10, dig1;
1768 int s;
1769 const char *p, *d;
1770
1771 dig1 = dig10 = dig100 = ascii_zero;
1772 s = 24;
1773
1774 p = text;
1775 while (1) {
1776 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1777 p++;
1778 continue;
1779 }
1780
1781 /* here, we have a complete byte between <text> and <p> (exclusive) */
1782 if (p == text)
1783 goto end;
1784
1785 d = p - 1;
1786 dig1 |= (unsigned int)(*d << s);
1787 if (d == text)
1788 goto end;
1789
1790 d--;
1791 dig10 |= (unsigned int)(*d << s);
1792 if (d == text)
1793 goto end;
1794
1795 d--;
1796 dig100 |= (unsigned int)(*d << s);
1797 end:
1798 if (!s || p == stop || *p != '.')
1799 break;
1800
1801 s -= 8;
1802 text = ++p;
1803 }
1804
1805 dig100 -= ascii_zero;
1806 dig10 -= ascii_zero;
1807 dig1 -= ascii_zero;
1808 return ((dig100 * 10) + dig10) * 10 + dig1;
1809}
1810
1811/*
1812 * Idem except the pointer to first unparsed byte is returned into <ret> which
1813 * must not be NULL.
1814 */
Willy Tarreau74172752010-10-15 23:21:42 +02001815unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001816{
1817 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1818 register unsigned int dig100, dig10, dig1;
1819 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001820 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001821
1822 dig1 = dig10 = dig100 = ascii_zero;
1823 s = 24;
1824
1825 p = text;
1826 while (1) {
1827 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1828 p++;
1829 continue;
1830 }
1831
1832 /* here, we have a complete byte between <text> and <p> (exclusive) */
1833 if (p == text)
1834 goto end;
1835
1836 d = p - 1;
1837 dig1 |= (unsigned int)(*d << s);
1838 if (d == text)
1839 goto end;
1840
1841 d--;
1842 dig10 |= (unsigned int)(*d << s);
1843 if (d == text)
1844 goto end;
1845
1846 d--;
1847 dig100 |= (unsigned int)(*d << s);
1848 end:
1849 if (!s || p == stop || *p != '.')
1850 break;
1851
1852 s -= 8;
1853 text = ++p;
1854 }
1855
1856 *ret = p;
1857 dig100 -= ascii_zero;
1858 dig10 -= ascii_zero;
1859 dig1 -= ascii_zero;
1860 return ((dig100 * 10) + dig10) * 10 + dig1;
1861}
1862
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001863/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1864 * or the number of chars read in case of success. Maybe this could be replaced
1865 * by one of the functions above. Also, apparently this function does not support
1866 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001867 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001868 */
1869int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1870{
1871 const char *addr;
1872 int saw_digit, octets, ch;
1873 u_char tmp[4], *tp;
1874 const char *cp = buf;
1875
1876 saw_digit = 0;
1877 octets = 0;
1878 *(tp = tmp) = 0;
1879
1880 for (addr = buf; addr - buf < len; addr++) {
1881 unsigned char digit = (ch = *addr) - '0';
1882
1883 if (digit > 9 && ch != '.')
1884 break;
1885
1886 if (digit <= 9) {
1887 u_int new = *tp * 10 + digit;
1888
1889 if (new > 255)
1890 return 0;
1891
1892 *tp = new;
1893
1894 if (!saw_digit) {
1895 if (++octets > 4)
1896 return 0;
1897 saw_digit = 1;
1898 }
1899 } else if (ch == '.' && saw_digit) {
1900 if (octets == 4)
1901 return 0;
1902
1903 *++tp = 0;
1904 saw_digit = 0;
1905 } else
1906 return 0;
1907 }
1908
1909 if (octets < 4)
1910 return 0;
1911
1912 memcpy(&dst->s_addr, tmp, 4);
1913 return addr - cp;
1914}
1915
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001916/* This function converts the string in <buf> of the len <len> to
1917 * struct in6_addr <dst> which must be allocated by the caller.
1918 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01001919 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001920 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001921int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
1922{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001923 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01001924 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001925
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001926 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001927 return 0;
1928
1929 memcpy(null_term_ip6, buf, len);
1930 null_term_ip6[len] = '\0';
1931
Willy Tarreau075415a2013-12-12 11:29:39 +01001932 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001933 return 0;
1934
Willy Tarreau075415a2013-12-12 11:29:39 +01001935 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001936 return 1;
1937}
1938
Willy Tarreauacf95772010-06-14 19:09:21 +02001939/* To be used to quote config arg positions. Returns the short string at <ptr>
1940 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1941 * if ptr is NULL or empty. The string is locally allocated.
1942 */
1943const char *quote_arg(const char *ptr)
1944{
1945 static char val[32];
1946 int i;
1947
1948 if (!ptr || !*ptr)
1949 return "end of line";
1950 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001951 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001952 val[i] = *ptr++;
1953 val[i++] = '\'';
1954 val[i] = '\0';
1955 return val;
1956}
1957
Willy Tarreau5b180202010-07-18 10:40:48 +02001958/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1959int get_std_op(const char *str)
1960{
1961 int ret = -1;
1962
1963 if (*str == 'e' && str[1] == 'q')
1964 ret = STD_OP_EQ;
1965 else if (*str == 'n' && str[1] == 'e')
1966 ret = STD_OP_NE;
1967 else if (*str == 'l') {
1968 if (str[1] == 'e') ret = STD_OP_LE;
1969 else if (str[1] == 't') ret = STD_OP_LT;
1970 }
1971 else if (*str == 'g') {
1972 if (str[1] == 'e') ret = STD_OP_GE;
1973 else if (str[1] == 't') ret = STD_OP_GT;
1974 }
1975
1976 if (ret == -1 || str[2] != '\0')
1977 return -1;
1978 return ret;
1979}
1980
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001981/* hash a 32-bit integer to another 32-bit integer */
1982unsigned int full_hash(unsigned int a)
1983{
1984 return __full_hash(a);
1985}
1986
David du Colombier4f92d322011-03-24 11:09:31 +01001987/* Return non-zero if IPv4 address is part of the network,
1988 * otherwise zero.
1989 */
1990int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1991{
1992 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1993}
1994
1995/* Return non-zero if IPv6 address is part of the network,
1996 * otherwise zero.
1997 */
1998int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1999{
2000 int i;
2001
2002 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2003 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2004 (((int *)net)[i] & ((int *)mask)[i]))
2005 return 0;
2006 return 1;
2007}
2008
2009/* RFC 4291 prefix */
2010const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2011 0x00, 0x00, 0x00, 0x00,
2012 0x00, 0x00, 0xFF, 0xFF };
2013
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002014/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2015 * Input and output may overlap.
2016 */
David du Colombier4f92d322011-03-24 11:09:31 +01002017void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2018{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002019 struct in_addr tmp_addr;
2020
2021 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002022 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002023 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002024}
2025
2026/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2027 * Return true if conversion is possible and false otherwise.
2028 */
2029int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2030{
2031 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2032 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2033 sizeof(struct in_addr));
2034 return 1;
2035 }
2036
2037 return 0;
2038}
2039
William Lallemand421f5b52012-02-06 18:15:57 +01002040char *human_time(int t, short hz_div) {
2041 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2042 char *p = rv;
2043 int cnt=2; // print two numbers
2044
2045 if (unlikely(t < 0 || hz_div <= 0)) {
2046 sprintf(p, "?");
2047 return rv;
2048 }
2049
2050 if (unlikely(hz_div > 1))
2051 t /= hz_div;
2052
2053 if (t >= DAY) {
2054 p += sprintf(p, "%dd", t / DAY);
2055 cnt--;
2056 }
2057
2058 if (cnt && t % DAY / HOUR) {
2059 p += sprintf(p, "%dh", t % DAY / HOUR);
2060 cnt--;
2061 }
2062
2063 if (cnt && t % HOUR / MINUTE) {
2064 p += sprintf(p, "%dm", t % HOUR / MINUTE);
2065 cnt--;
2066 }
2067
2068 if ((cnt && t % MINUTE) || !t) // also display '0s'
2069 p += sprintf(p, "%ds", t % MINUTE / SEC);
2070
2071 return rv;
2072}
2073
2074const char *monthname[12] = {
2075 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2076 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2077};
2078
2079/* date2str_log: write a date in the format :
2080 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2081 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2082 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2083 *
2084 * without using sprintf. return a pointer to the last char written (\0) or
2085 * NULL if there isn't enough space.
2086 */
2087char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2088{
2089
2090 if (size < 25) /* the size is fixed: 24 chars + \0 */
2091 return NULL;
2092
2093 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2094 *dst++ = '/';
2095 memcpy(dst, monthname[tm->tm_mon], 3); // month
2096 dst += 3;
2097 *dst++ = '/';
2098 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2099 *dst++ = ':';
2100 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2101 *dst++ = ':';
2102 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2103 *dst++ = ':';
2104 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2105 *dst++ = '.';
2106 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2107 dst += 3; // only the 3 first digits
2108 *dst = '\0';
2109
2110 return dst;
2111}
2112
2113/* gmt2str_log: write a date in the format :
2114 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2115 * return a pointer to the last char written (\0) or
2116 * NULL if there isn't enough space.
2117 */
2118char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2119{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002120 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002121 return NULL;
2122
2123 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2124 *dst++ = '/';
2125 memcpy(dst, monthname[tm->tm_mon], 3); // month
2126 dst += 3;
2127 *dst++ = '/';
2128 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2129 *dst++ = ':';
2130 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2131 *dst++ = ':';
2132 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2133 *dst++ = ':';
2134 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2135 *dst++ = ' ';
2136 *dst++ = '+';
2137 *dst++ = '0';
2138 *dst++ = '0';
2139 *dst++ = '0';
2140 *dst++ = '0';
2141 *dst = '\0';
2142
2143 return dst;
2144}
2145
Yuxans Yao4e25b012012-10-19 10:36:09 +08002146/* localdate2str_log: write a date in the format :
2147 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2148 * * return a pointer to the last char written (\0) or
2149 * * NULL if there isn't enough space.
2150 */
2151char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2152{
2153 if (size < 27) /* the size is fixed: 26 chars + \0 */
2154 return NULL;
2155
2156 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2157 *dst++ = '/';
2158 memcpy(dst, monthname[tm->tm_mon], 3); // month
2159 dst += 3;
2160 *dst++ = '/';
2161 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2162 *dst++ = ':';
2163 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2164 *dst++ = ':';
2165 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2166 *dst++ = ':';
2167 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2168 *dst++ = ' ';
2169 memcpy(dst, localtimezone, 5); // timezone
2170 dst += 5;
2171 *dst = '\0';
2172
2173 return dst;
2174}
2175
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002176/* Dynamically allocates a string of the proper length to hold the formatted
2177 * output. NULL is returned on error. The caller is responsible for freeing the
2178 * memory area using free(). The resulting string is returned in <out> if the
2179 * pointer is not NULL. A previous version of <out> might be used to build the
2180 * new string, and it will be freed before returning if it is not NULL, which
2181 * makes it possible to build complex strings from iterative calls without
2182 * having to care about freeing intermediate values, as in the example below :
2183 *
2184 * memprintf(&err, "invalid argument: '%s'", arg);
2185 * ...
2186 * memprintf(&err, "parser said : <%s>\n", *err);
2187 * ...
2188 * free(*err);
2189 *
2190 * This means that <err> must be initialized to NULL before first invocation.
2191 * The return value also holds the allocated string, which eases error checking
2192 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002193 * passed instead and it will be ignored. The returned message will then also
2194 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002195 *
2196 * It is also convenient to use it without any free except the last one :
2197 * err = NULL;
2198 * if (!fct1(err)) report(*err);
2199 * if (!fct2(err)) report(*err);
2200 * if (!fct3(err)) report(*err);
2201 * free(*err);
2202 */
2203char *memprintf(char **out, const char *format, ...)
2204{
2205 va_list args;
2206 char *ret = NULL;
2207 int allocated = 0;
2208 int needed = 0;
2209
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002210 if (!out)
2211 return NULL;
2212
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002213 do {
2214 /* vsnprintf() will return the required length even when the
2215 * target buffer is NULL. We do this in a loop just in case
2216 * intermediate evaluations get wrong.
2217 */
2218 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002219 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002220 va_end(args);
2221
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002222 if (needed < allocated) {
2223 /* Note: on Solaris 8, the first iteration always
2224 * returns -1 if allocated is zero, so we force a
2225 * retry.
2226 */
2227 if (!allocated)
2228 needed = 0;
2229 else
2230 break;
2231 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002232
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002233 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002234 ret = realloc(ret, allocated);
2235 } while (ret);
2236
2237 if (needed < 0) {
2238 /* an error was encountered */
2239 free(ret);
2240 ret = NULL;
2241 }
2242
2243 if (out) {
2244 free(*out);
2245 *out = ret;
2246 }
2247
2248 return ret;
2249}
William Lallemand421f5b52012-02-06 18:15:57 +01002250
Willy Tarreau21c705b2012-09-14 11:40:36 +02002251/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2252 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002253 * freed by the caller. It also supports being passed a NULL which results in the same
2254 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002255 * Example of use :
2256 * parse(cmd, &err); (callee: memprintf(&err, ...))
2257 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2258 * free(err);
2259 */
2260char *indent_msg(char **out, int level)
2261{
2262 char *ret, *in, *p;
2263 int needed = 0;
2264 int lf = 0;
2265 int lastlf = 0;
2266 int len;
2267
Willy Tarreau70eec382012-10-10 08:56:47 +02002268 if (!out || !*out)
2269 return NULL;
2270
Willy Tarreau21c705b2012-09-14 11:40:36 +02002271 in = *out - 1;
2272 while ((in = strchr(in + 1, '\n')) != NULL) {
2273 lastlf = in - *out;
2274 lf++;
2275 }
2276
2277 if (!lf) /* single line, no LF, return it as-is */
2278 return *out;
2279
2280 len = strlen(*out);
2281
2282 if (lf == 1 && lastlf == len - 1) {
2283 /* single line, LF at end, strip it and return as-is */
2284 (*out)[lastlf] = 0;
2285 return *out;
2286 }
2287
2288 /* OK now we have at least one LF, we need to process the whole string
2289 * as a multi-line string. What we'll do :
2290 * - prefix with an LF if there is none
2291 * - add <level> spaces before each line
2292 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2293 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2294 */
2295
2296 needed = 1 + level * (lf + 1) + len + 1;
2297 p = ret = malloc(needed);
2298 in = *out;
2299
2300 /* skip initial LFs */
2301 while (*in == '\n')
2302 in++;
2303
2304 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2305 while (*in) {
2306 *p++ = '\n';
2307 memset(p, ' ', level);
2308 p += level;
2309 do {
2310 *p++ = *in++;
2311 } while (*in && *in != '\n');
2312 if (*in)
2313 in++;
2314 }
2315 *p = 0;
2316
2317 free(*out);
2318 *out = ret;
2319
2320 return ret;
2321}
2322
Willy Tarreaudad36a32013-03-11 01:20:04 +01002323/* Convert occurrences of environment variables in the input string to their
2324 * corresponding value. A variable is identified as a series of alphanumeric
2325 * characters or underscores following a '$' sign. The <in> string must be
2326 * free()able. NULL returns NULL. The resulting string might be reallocated if
2327 * some expansion is made. Variable names may also be enclosed into braces if
2328 * needed (eg: to concatenate alphanum characters).
2329 */
2330char *env_expand(char *in)
2331{
2332 char *txt_beg;
2333 char *out;
2334 char *txt_end;
2335 char *var_beg;
2336 char *var_end;
2337 char *value;
2338 char *next;
2339 int out_len;
2340 int val_len;
2341
2342 if (!in)
2343 return in;
2344
2345 value = out = NULL;
2346 out_len = 0;
2347
2348 txt_beg = in;
2349 do {
2350 /* look for next '$' sign in <in> */
2351 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2352
2353 if (!*txt_end && !out) /* end and no expansion performed */
2354 return in;
2355
2356 val_len = 0;
2357 next = txt_end;
2358 if (*txt_end == '$') {
2359 char save;
2360
2361 var_beg = txt_end + 1;
2362 if (*var_beg == '{')
2363 var_beg++;
2364
2365 var_end = var_beg;
2366 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2367 var_end++;
2368 }
2369
2370 next = var_end;
2371 if (*var_end == '}' && (var_beg > txt_end + 1))
2372 next++;
2373
2374 /* get value of the variable name at this location */
2375 save = *var_end;
2376 *var_end = '\0';
2377 value = getenv(var_beg);
2378 *var_end = save;
2379 val_len = value ? strlen(value) : 0;
2380 }
2381
2382 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2383 if (txt_end > txt_beg) {
2384 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2385 out_len += txt_end - txt_beg;
2386 }
2387 if (val_len) {
2388 memcpy(out + out_len, value, val_len);
2389 out_len += val_len;
2390 }
2391 out[out_len] = 0;
2392 txt_beg = next;
2393 } while (*txt_beg);
2394
2395 /* here we know that <out> was allocated and that we don't need <in> anymore */
2396 free(in);
2397 return out;
2398}
2399
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002400
2401/* same as strstr() but case-insensitive and with limit length */
2402const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2403{
2404 char *pptr, *sptr, *start;
2405 uint slen, plen;
2406 uint tmp1, tmp2;
2407
2408 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2409 return NULL;
2410
2411 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2412 return str1;
2413
2414 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2415 return NULL;
2416
2417 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2418 while (toupper(*start) != toupper(*str2)) {
2419 start++;
2420 slen--;
2421 tmp1++;
2422
2423 if (tmp1 >= len_str1)
2424 return NULL;
2425
2426 /* if pattern longer than string */
2427 if (slen < plen)
2428 return NULL;
2429 }
2430
2431 sptr = start;
2432 pptr = (char *)str2;
2433
2434 tmp2 = 0;
2435 while (toupper(*sptr) == toupper(*pptr)) {
2436 sptr++;
2437 pptr++;
2438 tmp2++;
2439
2440 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2441 return start;
2442 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2443 return NULL;
2444 }
2445 }
2446 return NULL;
2447}
2448
Willy Tarreaubaaee002006-06-26 02:48:02 +02002449/*
2450 * Local variables:
2451 * c-indent-level: 8
2452 * c-basic-offset: 8
2453 * End:
2454 */