blob: 89af08f72a013e3d3d351b4ee6bb694c66a94c23 [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>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010027#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020028
Willy Tarreau56adcf22012-12-23 18:00:29 +010029/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020030 * 2^64-1 = 18446744073709551615 or
31 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020032 *
33 * The HTML version needs room for adding the 25 characters
34 * '<span class="rls"></span>' around digits at positions 3N+1 in order
35 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020036 */
Willy Tarreau56adcf22012-12-23 18:00:29 +010037char itoa_str[NB_ITOA_STR][171];
38int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020039
40/*
William Lallemande7340ec2012-01-24 11:15:39 +010041 * unsigned long long ASCII representation
42 *
43 * return the last char '\0' or NULL if no enough
44 * space in dst
45 */
46char *ulltoa(unsigned long long n, char *dst, size_t size)
47{
48 int i = 0;
49 char *res;
50
51 switch(n) {
52 case 1ULL ... 9ULL:
53 i = 0;
54 break;
55
56 case 10ULL ... 99ULL:
57 i = 1;
58 break;
59
60 case 100ULL ... 999ULL:
61 i = 2;
62 break;
63
64 case 1000ULL ... 9999ULL:
65 i = 3;
66 break;
67
68 case 10000ULL ... 99999ULL:
69 i = 4;
70 break;
71
72 case 100000ULL ... 999999ULL:
73 i = 5;
74 break;
75
76 case 1000000ULL ... 9999999ULL:
77 i = 6;
78 break;
79
80 case 10000000ULL ... 99999999ULL:
81 i = 7;
82 break;
83
84 case 100000000ULL ... 999999999ULL:
85 i = 8;
86 break;
87
88 case 1000000000ULL ... 9999999999ULL:
89 i = 9;
90 break;
91
92 case 10000000000ULL ... 99999999999ULL:
93 i = 10;
94 break;
95
96 case 100000000000ULL ... 999999999999ULL:
97 i = 11;
98 break;
99
100 case 1000000000000ULL ... 9999999999999ULL:
101 i = 12;
102 break;
103
104 case 10000000000000ULL ... 99999999999999ULL:
105 i = 13;
106 break;
107
108 case 100000000000000ULL ... 999999999999999ULL:
109 i = 14;
110 break;
111
112 case 1000000000000000ULL ... 9999999999999999ULL:
113 i = 15;
114 break;
115
116 case 10000000000000000ULL ... 99999999999999999ULL:
117 i = 16;
118 break;
119
120 case 100000000000000000ULL ... 999999999999999999ULL:
121 i = 17;
122 break;
123
124 case 1000000000000000000ULL ... 9999999999999999999ULL:
125 i = 18;
126 break;
127
128 case 10000000000000000000ULL ... ULLONG_MAX:
129 i = 19;
130 break;
131 }
132 if (i + 2 > size) // (i + 1) + '\0'
133 return NULL; // too long
134 res = dst + i + 1;
135 *res = '\0';
136 for (; i >= 0; i--) {
137 dst[i] = n % 10ULL + '0';
138 n /= 10ULL;
139 }
140 return res;
141}
142
143/*
144 * unsigned long ASCII representation
145 *
146 * return the last char '\0' or NULL if no enough
147 * space in dst
148 */
149char *ultoa_o(unsigned long n, char *dst, size_t size)
150{
151 int i = 0;
152 char *res;
153
154 switch (n) {
155 case 0U ... 9UL:
156 i = 0;
157 break;
158
159 case 10U ... 99UL:
160 i = 1;
161 break;
162
163 case 100U ... 999UL:
164 i = 2;
165 break;
166
167 case 1000U ... 9999UL:
168 i = 3;
169 break;
170
171 case 10000U ... 99999UL:
172 i = 4;
173 break;
174
175 case 100000U ... 999999UL:
176 i = 5;
177 break;
178
179 case 1000000U ... 9999999UL:
180 i = 6;
181 break;
182
183 case 10000000U ... 99999999UL:
184 i = 7;
185 break;
186
187 case 100000000U ... 999999999UL:
188 i = 8;
189 break;
190#if __WORDSIZE == 32
191
192 case 1000000000ULL ... ULONG_MAX:
193 i = 9;
194 break;
195
196#elif __WORDSIZE == 64
197
198 case 1000000000ULL ... 9999999999UL:
199 i = 9;
200 break;
201
202 case 10000000000ULL ... 99999999999UL:
203 i = 10;
204 break;
205
206 case 100000000000ULL ... 999999999999UL:
207 i = 11;
208 break;
209
210 case 1000000000000ULL ... 9999999999999UL:
211 i = 12;
212 break;
213
214 case 10000000000000ULL ... 99999999999999UL:
215 i = 13;
216 break;
217
218 case 100000000000000ULL ... 999999999999999UL:
219 i = 14;
220 break;
221
222 case 1000000000000000ULL ... 9999999999999999UL:
223 i = 15;
224 break;
225
226 case 10000000000000000ULL ... 99999999999999999UL:
227 i = 16;
228 break;
229
230 case 100000000000000000ULL ... 999999999999999999UL:
231 i = 17;
232 break;
233
234 case 1000000000000000000ULL ... 9999999999999999999UL:
235 i = 18;
236 break;
237
238 case 10000000000000000000ULL ... ULONG_MAX:
239 i = 19;
240 break;
241
242#endif
243 }
244 if (i + 2 > size) // (i + 1) + '\0'
245 return NULL; // too long
246 res = dst + i + 1;
247 *res = '\0';
248 for (; i >= 0; i--) {
249 dst[i] = n % 10U + '0';
250 n /= 10U;
251 }
252 return res;
253}
254
255/*
256 * signed long ASCII representation
257 *
258 * return the last char '\0' or NULL if no enough
259 * space in dst
260 */
261char *ltoa_o(long int n, char *dst, size_t size)
262{
263 char *pos = dst;
264
265 if (n < 0) {
266 if (size < 3)
267 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
268 *pos = '-';
269 pos++;
270 dst = ultoa_o(-n, pos, size - 1);
271 } else {
272 dst = ultoa_o(n, dst, size);
273 }
274 return dst;
275}
276
277/*
278 * signed long long ASCII representation
279 *
280 * return the last char '\0' or NULL if no enough
281 * space in dst
282 */
283char *lltoa(long long n, char *dst, size_t size)
284{
285 char *pos = dst;
286
287 if (n < 0) {
288 if (size < 3)
289 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
290 *pos = '-';
291 pos++;
292 dst = ulltoa(-n, pos, size - 1);
293 } else {
294 dst = ulltoa(n, dst, size);
295 }
296 return dst;
297}
298
299/*
300 * write a ascii representation of a unsigned into dst,
301 * return a pointer to the last character
302 * Pad the ascii representation with '0', using size.
303 */
304char *utoa_pad(unsigned int n, char *dst, size_t size)
305{
306 int i = 0;
307 char *ret;
308
309 switch(n) {
310 case 0U ... 9U:
311 i = 0;
312 break;
313
314 case 10U ... 99U:
315 i = 1;
316 break;
317
318 case 100U ... 999U:
319 i = 2;
320 break;
321
322 case 1000U ... 9999U:
323 i = 3;
324 break;
325
326 case 10000U ... 99999U:
327 i = 4;
328 break;
329
330 case 100000U ... 999999U:
331 i = 5;
332 break;
333
334 case 1000000U ... 9999999U:
335 i = 6;
336 break;
337
338 case 10000000U ... 99999999U:
339 i = 7;
340 break;
341
342 case 100000000U ... 999999999U:
343 i = 8;
344 break;
345
346 case 1000000000U ... 4294967295U:
347 i = 9;
348 break;
349 }
350 if (i + 2 > size) // (i + 1) + '\0'
351 return NULL; // too long
352 if (i < size)
353 i = size - 2; // padding - '\0'
354
355 ret = dst + i + 1;
356 *ret = '\0';
357 for (; i >= 0; i--) {
358 dst[i] = n % 10U + '0';
359 n /= 10U;
360 }
361 return ret;
362}
363
364/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200365 * copies at most <size-1> chars from <src> to <dst>. Last char is always
366 * set to 0, unless <size> is 0. The number of chars copied is returned
367 * (excluding the terminating zero).
368 * This code has been optimized for size and speed : on x86, it's 45 bytes
369 * long, uses only registers, and consumes only 4 cycles per char.
370 */
371int strlcpy2(char *dst, const char *src, int size)
372{
373 char *orig = dst;
374 if (size) {
375 while (--size && (*dst = *src)) {
376 src++; dst++;
377 }
378 *dst = 0;
379 }
380 return dst - orig;
381}
382
383/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200384 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200385 * the ascii representation for number 'n' in decimal.
386 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100387char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200388{
389 char *pos;
390
Willy Tarreau72d759c2007-10-25 12:14:10 +0200391 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200392 *pos-- = '\0';
393
394 do {
395 *pos-- = '0' + n % 10;
396 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200397 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200398 return pos + 1;
399}
400
Willy Tarreau91092e52007-10-25 16:58:42 +0200401/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200402 * This function simply returns a locally allocated string containing
403 * the ascii representation for number 'n' in decimal, formatted for
404 * HTML output with tags to create visual grouping by 3 digits. The
405 * output needs to support at least 171 characters.
406 */
407const char *ulltoh_r(unsigned long long n, char *buffer, int size)
408{
409 char *start;
410 int digit = 0;
411
412 start = buffer + size;
413 *--start = '\0';
414
415 do {
416 if (digit == 3 && start >= buffer + 7)
417 memcpy(start -= 7, "</span>", 7);
418
419 if (start >= buffer + 1) {
420 *--start = '0' + n % 10;
421 n /= 10;
422 }
423
424 if (digit == 3 && start >= buffer + 18)
425 memcpy(start -= 18, "<span class=\"rls\">", 18);
426
427 if (digit++ == 3)
428 digit = 1;
429 } while (n && start > buffer);
430 return start;
431}
432
433/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200434 * This function simply returns a locally allocated string containing the ascii
435 * representation for number 'n' in decimal, unless n is 0 in which case it
436 * returns the alternate string (or an empty string if the alternate string is
437 * NULL). It use is intended for limits reported in reports, where it's
438 * desirable not to display anything if there is no limit. Warning! it shares
439 * the same vector as ultoa_r().
440 */
441const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
442{
443 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
444}
445
Robert Tsai81ae1952007-12-05 10:47:29 +0100446/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200447 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
448 *
449 * It looks like this one would be a good candidate for inlining, but this is
450 * not interesting because it around 35 bytes long and often called multiple
451 * times within the same function.
452 */
453int ishex(char s)
454{
455 s -= '0';
456 if ((unsigned char)s <= 9)
457 return 1;
458 s -= 'A' - '0';
459 if ((unsigned char)s <= 5)
460 return 1;
461 s -= 'a' - 'A';
462 if ((unsigned char)s <= 5)
463 return 1;
464 return 0;
465}
466
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100467/*
468 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
469 * invalid character is found, a pointer to it is returned. If everything is
470 * fine, NULL is returned.
471 */
472const char *invalid_char(const char *name)
473{
474 if (!*name)
475 return name;
476
477 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100478 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100479 *name != '_' && *name != '-')
480 return name;
481 name++;
482 }
483 return NULL;
484}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200485
486/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200487 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
488 * If an invalid character is found, a pointer to it is returned.
489 * If everything is fine, NULL is returned.
490 */
491const char *invalid_domainchar(const char *name) {
492
493 if (!*name)
494 return name;
495
496 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100497 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200498 *name != '_' && *name != '-')
499 return name;
500
501 name++;
502 }
503
504 return NULL;
505}
506
507/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100508 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100509 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
510 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
511 * the function tries to guess the address family from the syntax. If the
512 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100513 * string is assumed to contain only an address, no port. The address can be a
514 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
515 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
516 * The return address will only have the address family and the address set,
517 * all other fields remain zero. The string is not supposed to be modified.
518 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200519 */
Willy Tarreau24709282013-03-10 21:32:12 +0100520static struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200521{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100522 struct hostent *he;
523
Willy Tarreaufab5a432011-03-04 15:31:53 +0100524 /* Any IPv6 address */
525 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100526 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
527 sa->ss_family = AF_INET6;
528 else if (sa->ss_family != AF_INET6)
529 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100530 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100531 }
532
Willy Tarreau24709282013-03-10 21:32:12 +0100533 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100534 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100535 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
536 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100537 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100538 }
539
540 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100541 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
542 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100543 sa->ss_family = AF_INET6;
544 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100545 }
546
547 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100548 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
549 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100550 sa->ss_family = AF_INET;
551 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100552 }
553
554 /* try to resolve an IPv4/IPv6 hostname */
555 he = gethostbyname(str);
556 if (he) {
Willy Tarreau24709282013-03-10 21:32:12 +0100557 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
558 sa->ss_family = he->h_addrtype;
559 else if (sa->ss_family != he->h_addrtype)
560 goto fail;
561
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100562 switch (sa->ss_family) {
Willy Tarreaufab5a432011-03-04 15:31:53 +0100563 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100564 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
565 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100566 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100567 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
568 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100569 }
David du Colombierd5f43282011-03-17 10:40:16 +0100570 }
571#ifdef USE_GETADDRINFO
572 else {
573 struct addrinfo hints, *result;
574
575 memset(&result, 0, sizeof(result));
576 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100577 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100578 hints.ai_socktype = SOCK_DGRAM;
579 hints.ai_flags = AI_PASSIVE;
580 hints.ai_protocol = 0;
581
582 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100583 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
584 sa->ss_family = result->ai_family;
585 else if (sa->ss_family != result->ai_family)
586 goto fail;
587
David du Colombierd5f43282011-03-17 10:40:16 +0100588 switch (result->ai_family) {
589 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100590 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
591 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100592 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100593 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
594 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100595 }
596 }
597
Sean Carey58ea0392013-02-15 23:39:18 +0100598 if (result)
599 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100600 }
David du Colombierd5f43282011-03-17 10:40:16 +0100601#endif
602 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100603 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100604 return NULL;
605}
606
607/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100608 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
609 * range or offset consisting in two integers that the caller will have to
610 * check to find the relevant input format. The following format are supported :
611 *
612 * String format | address | port | low | high
613 * addr | <addr> | 0 | 0 | 0
614 * addr: | <addr> | 0 | 0 | 0
615 * addr:port | <addr> | <port> | <port> | <port>
616 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
617 * addr:+port | <addr> | <port> | 0 | <port>
618 * addr:-port | <addr> |-<port> | <port> | 0
619 *
620 * The detection of a port range or increment by the caller is made by
621 * comparing <low> and <high>. If both are equal, then port 0 means no port
622 * was specified. The caller may pass NULL for <low> and <high> if it is not
623 * interested in retrieving port ranges.
624 *
625 * Note that <addr> above may also be :
626 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
627 * - "*" => family will be AF_INET and address will be INADDR_ANY
628 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
629 * - a host name => family and address will depend on host name resolving.
630 *
Willy Tarreau24709282013-03-10 21:32:12 +0100631 * A prefix may be passed in before the address above to force the family :
632 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
633 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
634 * - "unix@" => force address to be a path to a UNIX socket even if the
635 * path does not start with a '/'
Willy Tarreau40aa0702013-03-10 23:51:38 +0100636 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100637 *
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100638 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
639 * is mandatory after the IP address even when no port is specified. NULL is
640 * returned if the address cannot be parsed. The <low> and <high> ports are
Willy Tarreau24709282013-03-10 21:32:12 +0100641 * always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100642 *
643 * If <pfx> is non-null, it is used as a string prefix before any path-based
644 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100645 *
646 * When a file descriptor is passed, its value is put into the s_addr part of
647 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100648 */
Willy Tarreaud393a622013-03-04 18:22:00 +0100649struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100650{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100651 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100652 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100653 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100654 char *port1, *port2;
655 int portl, porth, porta;
656
657 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200658
Willy Tarreaudad36a32013-03-11 01:20:04 +0100659 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100660 if (str2 == NULL) {
661 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100662 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100663 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200664
Willy Tarreau24709282013-03-10 21:32:12 +0100665 memset(&ss, 0, sizeof(ss));
666
667 if (strncmp(str2, "unix@", 5) == 0) {
668 str2 += 5;
669 ss.ss_family = AF_UNIX;
670 }
671 else if (strncmp(str2, "ipv4@", 5) == 0) {
672 str2 += 5;
673 ss.ss_family = AF_INET;
674 }
675 else if (strncmp(str2, "ipv6@", 5) == 0) {
676 str2 += 5;
677 ss.ss_family = AF_INET6;
678 }
679 else if (*str2 == '/') {
680 ss.ss_family = AF_UNIX;
681 }
682 else
683 ss.ss_family = AF_UNSPEC;
684
Willy Tarreau40aa0702013-03-10 23:51:38 +0100685 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
686 char *endptr;
687
688 str2 += 3;
689 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
690
691 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100692 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100693 goto out;
694 }
695
696 /* we return AF_UNSPEC if we use a file descriptor number */
697 ss.ss_family = AF_UNSPEC;
698 }
699 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100700 int prefix_path_len;
701 int max_path_len;
702
703 /* complete unix socket path name during startup or soft-restart is
704 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
705 */
706 prefix_path_len = pfx ? strlen(pfx) : 0;
707 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
708 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
709
710 if (strlen(str2) > max_path_len) {
711 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
712 goto out;
713 }
714
Willy Tarreau15586382013-03-04 19:48:14 +0100715 if (pfx) {
716 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
717 strcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len, str2);
718 }
719 else {
720 strcpy(((struct sockaddr_un *)&ss)->sun_path, str2);
721 }
Willy Tarreau15586382013-03-04 19:48:14 +0100722 }
Willy Tarreau24709282013-03-10 21:32:12 +0100723 else { /* IPv4 and IPv6 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100724 port1 = strrchr(str2, ':');
725 if (port1)
726 *port1++ = '\0';
727 else
728 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200729
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100730 if (str2ip(str2, &ss) == NULL) {
731 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
732 goto out;
733 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100734
Willy Tarreaua39d1992013-04-01 20:37:42 +0200735 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100736 port2 = strchr(port1, '-');
737 if (port2)
738 *port2++ = '\0';
739 else
740 port2 = port1;
741 portl = atoi(port1);
742 porth = atoi(port2);
743 porta = portl;
744 }
745 else if (*port1 == '-') { /* negative offset */
746 portl = atoi(port1 + 1);
747 porta = -portl;
748 }
749 else if (*port1 == '+') { /* positive offset */
750 porth = atoi(port1 + 1);
751 porta = porth;
752 }
753 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100754 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100755 goto out;
756 }
757 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100758 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100759
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100760 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100761 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100762 if (low)
763 *low = portl;
764 if (high)
765 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100766 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100767 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200768}
769
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100770/* converts <str> to a struct in_addr containing a network mask. It can be
771 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
772 * if the conversion succeeds otherwise non-zero.
773 */
774int str2mask(const char *str, struct in_addr *mask)
775{
776 if (strchr(str, '.') != NULL) { /* dotted notation */
777 if (!inet_pton(AF_INET, str, mask))
778 return 0;
779 }
780 else { /* mask length */
781 char *err;
782 unsigned long len = strtol(str, &err, 10);
783
784 if (!*str || (err && *err) || (unsigned)len > 32)
785 return 0;
786 if (len)
787 mask->s_addr = htonl(~0UL << (32 - len));
788 else
789 mask->s_addr = 0;
790 }
791 return 1;
792}
793
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100794/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
795 * succeeds otherwise zero.
796 */
797int cidr2dotted(int cidr, struct in_addr *mask) {
798
799 if (cidr < 0 || cidr > 32)
800 return 0;
801
802 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
803 return 1;
804}
805
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200806/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200807 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200808 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
809 * is optionnal and either in the dotted or CIDR notation.
810 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
811 */
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200812int str2net(const char *str, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200813{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200814 __label__ out_free, out_err;
815 char *c, *s;
816 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200817
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200818 s = strdup(str);
819 if (!s)
820 return 0;
821
Willy Tarreaubaaee002006-06-26 02:48:02 +0200822 memset(mask, 0, sizeof(*mask));
823 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200824
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200825 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200826 *c++ = '\0';
827 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100828 if (!str2mask(c, mask))
829 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200830 }
831 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100832 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200833 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200834 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200835 struct hostent *he;
836
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200837 if ((he = gethostbyname(s)) == NULL) {
838 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200839 }
840 else
841 *addr = *(struct in_addr *) *(he->h_addr_list);
842 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200843
844 ret_val = 1;
845 out_free:
846 free(s);
847 return ret_val;
848 out_err:
849 ret_val = 0;
850 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200851}
852
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100853
854/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200855 * converts <str> to two struct in6_addr* which must be pre-allocated.
856 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
857 * is an optionnal number of bits (128 being the default).
858 * Returns 1 if OK, 0 if error.
859 */
860int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
861{
862 char *c, *s;
863 int ret_val = 0;
864 char *err;
865 unsigned long len = 128;
866
867 s = strdup(str);
868 if (!s)
869 return 0;
870
871 memset(mask, 0, sizeof(*mask));
872 memset(addr, 0, sizeof(*addr));
873
874 if ((c = strrchr(s, '/')) != NULL) {
875 *c++ = '\0'; /* c points to the mask */
876 if (!*c)
877 goto out_free;
878
879 len = strtoul(c, &err, 10);
880 if ((err && *err) || (unsigned)len > 128)
881 goto out_free;
882 }
883 *mask = len; /* OK we have a valid mask in <len> */
884
885 if (!inet_pton(AF_INET6, s, addr))
886 goto out_free;
887
888 ret_val = 1;
889 out_free:
890 free(s);
891 return ret_val;
892}
893
894
895/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100896 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100897 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100898int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100899{
900 int saw_digit, octets, ch;
901 u_char tmp[4], *tp;
902 const char *cp = addr;
903
904 saw_digit = 0;
905 octets = 0;
906 *(tp = tmp) = 0;
907
908 while (*addr) {
909 unsigned char digit = (ch = *addr++) - '0';
910 if (digit > 9 && ch != '.')
911 break;
912 if (digit <= 9) {
913 u_int new = *tp * 10 + digit;
914 if (new > 255)
915 return 0;
916 *tp = new;
917 if (!saw_digit) {
918 if (++octets > 4)
919 return 0;
920 saw_digit = 1;
921 }
922 } else if (ch == '.' && saw_digit) {
923 if (octets == 4)
924 return 0;
925 *++tp = 0;
926 saw_digit = 0;
927 } else
928 return 0;
929 }
930
931 if (octets < 4)
932 return 0;
933
934 memcpy(&dst->s_addr, tmp, 4);
935 return addr-cp-1;
936}
937
938/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100939 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100940 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100941int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100942{
943 const char *curr = url, *cp = url;
944 int ret, url_code = 0;
945 unsigned int http_code = 0;
946
947 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100948
949 /* FIXME: assume IPv4 only for now */
950 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
951 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
952 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100953
954 /* Firstly, try to find :// pattern */
955 while (curr < url+ulen && url_code != 0x3a2f2f) {
956 url_code = ((url_code & 0xffff) << 8);
957 url_code += (unsigned char)*curr++;
958 }
959
960 /* Secondly, if :// pattern is found, verify parsed stuff
961 * before pattern is matching our http pattern.
962 * If so parse ip address and port in uri.
963 *
964 * WARNING: Current code doesn't support dynamic async dns resolver.
965 */
966 if (url_code == 0x3a2f2f) {
967 while (cp < curr - 3)
968 http_code = (http_code << 8) + *cp++;
969 http_code |= 0x20202020; /* Turn everything to lower case */
970
971 /* HTTP url matching */
972 if (http_code == 0x68747470) {
973 /* We are looking for IP address. If you want to parse and
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100974 * resolve hostname found in url, you can use str2sa_range(), but
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100975 * be warned this can slow down global daemon performances
976 * while handling lagging dns responses.
977 */
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200978 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100979 if (!ret)
980 return -1;
981 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100982 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200983 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100984 }
985 return 0;
986 }
987
988 return -1;
989}
990
Willy Tarreau631f01c2011-09-05 00:36:48 +0200991/* Tries to convert a sockaddr_storage address to text form. Upon success, the
992 * address family is returned so that it's easy for the caller to adapt to the
993 * output format. Zero is returned if the address family is not supported. -1
994 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
995 * supported.
996 */
997int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
998{
999
1000 void *ptr;
1001
1002 if (size < 5)
1003 return 0;
1004 *str = '\0';
1005
1006 switch (addr->ss_family) {
1007 case AF_INET:
1008 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1009 break;
1010 case AF_INET6:
1011 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1012 break;
1013 case AF_UNIX:
1014 memcpy(str, "unix", 5);
1015 return addr->ss_family;
1016 default:
1017 return 0;
1018 }
1019
1020 if (inet_ntop(addr->ss_family, ptr, str, size))
1021 return addr->ss_family;
1022
1023 /* failed */
1024 return -1;
1025}
1026
Willy Tarreaubaaee002006-06-26 02:48:02 +02001027/* will try to encode the string <string> replacing all characters tagged in
1028 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1029 * prefixed by <escape>, and will store the result between <start> (included)
1030 * and <stop> (excluded), and will always terminate the string with a '\0'
1031 * before <stop>. The position of the '\0' is returned if the conversion
1032 * completes. If bytes are missing between <start> and <stop>, then the
1033 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1034 * cannot even be stored so we return <start> without writing the 0.
1035 * The input string must also be zero-terminated.
1036 */
1037const char hextab[16] = "0123456789ABCDEF";
1038char *encode_string(char *start, char *stop,
1039 const char escape, const fd_set *map,
1040 const char *string)
1041{
1042 if (start < stop) {
1043 stop--; /* reserve one byte for the final '\0' */
1044 while (start < stop && *string != '\0') {
1045 if (!FD_ISSET((unsigned char)(*string), map))
1046 *start++ = *string;
1047 else {
1048 if (start + 3 >= stop)
1049 break;
1050 *start++ = escape;
1051 *start++ = hextab[(*string >> 4) & 15];
1052 *start++ = hextab[*string & 15];
1053 }
1054 string++;
1055 }
1056 *start = '\0';
1057 }
1058 return start;
1059}
1060
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001061/*
1062 * Same behavior as encode_string() above, except that it encodes chunk
1063 * <chunk> instead of a string.
1064 */
1065char *encode_chunk(char *start, char *stop,
1066 const char escape, const fd_set *map,
1067 const struct chunk *chunk)
1068{
1069 char *str = chunk->str;
1070 char *end = chunk->str + chunk->len;
1071
1072 if (start < stop) {
1073 stop--; /* reserve one byte for the final '\0' */
1074 while (start < stop && str < end) {
1075 if (!FD_ISSET((unsigned char)(*str), map))
1076 *start++ = *str;
1077 else {
1078 if (start + 3 >= stop)
1079 break;
1080 *start++ = escape;
1081 *start++ = hextab[(*str >> 4) & 15];
1082 *start++ = hextab[*str & 15];
1083 }
1084 str++;
1085 }
1086 *start = '\0';
1087 }
1088 return start;
1089}
1090
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001091/* Decode an URL-encoded string in-place. The resulting string might
1092 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001093 * aborted, the string is truncated before the issue and a negative value is
1094 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001095 */
1096int url_decode(char *string)
1097{
1098 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001099 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001100
1101 in = string;
1102 out = string;
1103 while (*in) {
1104 switch (*in) {
1105 case '+' :
1106 *out++ = ' ';
1107 break;
1108 case '%' :
1109 if (!ishex(in[1]) || !ishex(in[2]))
1110 goto end;
1111 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1112 in += 2;
1113 break;
1114 default:
1115 *out++ = *in;
1116 break;
1117 }
1118 in++;
1119 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001120 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001121 end:
1122 *out = 0;
1123 return ret;
1124}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001125
Willy Tarreau6911fa42007-03-04 18:06:08 +01001126unsigned int str2ui(const char *s)
1127{
1128 return __str2ui(s);
1129}
1130
1131unsigned int str2uic(const char *s)
1132{
1133 return __str2uic(s);
1134}
1135
1136unsigned int strl2ui(const char *s, int len)
1137{
1138 return __strl2ui(s, len);
1139}
1140
1141unsigned int strl2uic(const char *s, int len)
1142{
1143 return __strl2uic(s, len);
1144}
1145
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001146unsigned int read_uint(const char **s, const char *end)
1147{
1148 return __read_uint(s, end);
1149}
1150
Willy Tarreau6911fa42007-03-04 18:06:08 +01001151/* This one is 7 times faster than strtol() on athlon with checks.
1152 * It returns the value of the number composed of all valid digits read,
1153 * and can process negative numbers too.
1154 */
1155int strl2ic(const char *s, int len)
1156{
1157 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001158 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001159
1160 if (len > 0) {
1161 if (*s != '-') {
1162 /* positive number */
1163 while (len-- > 0) {
1164 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001165 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001166 if (j > 9)
1167 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001168 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001169 }
1170 } else {
1171 /* negative number */
1172 s++;
1173 while (--len > 0) {
1174 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001175 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001176 if (j > 9)
1177 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001178 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001179 }
1180 }
1181 }
1182 return i;
1183}
1184
1185
1186/* This function reads exactly <len> chars from <s> and converts them to a
1187 * signed integer which it stores into <ret>. It accurately detects any error
1188 * (truncated string, invalid chars, overflows). It is meant to be used in
1189 * applications designed for hostile environments. It returns zero when the
1190 * number has successfully been converted, non-zero otherwise. When an error
1191 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1192 * faster than strtol().
1193 */
1194int strl2irc(const char *s, int len, int *ret)
1195{
1196 int i = 0;
1197 int j;
1198
1199 if (!len)
1200 return 1;
1201
1202 if (*s != '-') {
1203 /* positive number */
1204 while (len-- > 0) {
1205 j = (*s++) - '0';
1206 if (j > 9) return 1; /* invalid char */
1207 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1208 i = i * 10;
1209 if (i + j < i) return 1; /* check for addition overflow */
1210 i = i + j;
1211 }
1212 } else {
1213 /* negative number */
1214 s++;
1215 while (--len > 0) {
1216 j = (*s++) - '0';
1217 if (j > 9) return 1; /* invalid char */
1218 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1219 i = i * 10;
1220 if (i - j > i) return 1; /* check for subtract overflow */
1221 i = i - j;
1222 }
1223 }
1224 *ret = i;
1225 return 0;
1226}
1227
1228
1229/* This function reads exactly <len> chars from <s> and converts them to a
1230 * signed integer which it stores into <ret>. It accurately detects any error
1231 * (truncated string, invalid chars, overflows). It is meant to be used in
1232 * applications designed for hostile environments. It returns zero when the
1233 * number has successfully been converted, non-zero otherwise. When an error
1234 * is returned, the <ret> value is left untouched. It is about 3 times slower
1235 * than str2irc().
1236 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001237
1238int strl2llrc(const char *s, int len, long long *ret)
1239{
1240 long long i = 0;
1241 int j;
1242
1243 if (!len)
1244 return 1;
1245
1246 if (*s != '-') {
1247 /* positive number */
1248 while (len-- > 0) {
1249 j = (*s++) - '0';
1250 if (j > 9) return 1; /* invalid char */
1251 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1252 i = i * 10LL;
1253 if (i + j < i) return 1; /* check for addition overflow */
1254 i = i + j;
1255 }
1256 } else {
1257 /* negative number */
1258 s++;
1259 while (--len > 0) {
1260 j = (*s++) - '0';
1261 if (j > 9) return 1; /* invalid char */
1262 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1263 i = i * 10LL;
1264 if (i - j > i) return 1; /* check for subtract overflow */
1265 i = i - j;
1266 }
1267 }
1268 *ret = i;
1269 return 0;
1270}
1271
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001272/* This function is used with pat_parse_dotted_ver(). It converts a string
1273 * composed by two number separated by a dot. Each part must contain in 16 bits
1274 * because internally they will be represented as a 32-bit quantity stored in
1275 * a 64-bit integer. It returns zero when the number has successfully been
1276 * converted, non-zero otherwise. When an error is returned, the <ret> value
1277 * is left untouched.
1278 *
1279 * "1.3" -> 0x0000000000010003
1280 * "65535.65535" -> 0x00000000ffffffff
1281 */
1282int strl2llrc_dotted(const char *text, int len, long long *ret)
1283{
1284 const char *end = &text[len];
1285 const char *p;
1286 long long major, minor;
1287
1288 /* Look for dot. */
1289 for (p = text; p < end; p++)
1290 if (*p == '.')
1291 break;
1292
1293 /* Convert major. */
1294 if (strl2llrc(text, p - text, &major) != 0)
1295 return 1;
1296
1297 /* Check major. */
1298 if (major >= 65536)
1299 return 1;
1300
1301 /* Convert minor. */
1302 minor = 0;
1303 if (p < end)
1304 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1305 return 1;
1306
1307 /* Check minor. */
1308 if (minor >= 65536)
1309 return 1;
1310
1311 /* Compose value. */
1312 *ret = (major << 16) | (minor & 0xffff);
1313 return 0;
1314}
1315
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001316/* This function parses a time value optionally followed by a unit suffix among
1317 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1318 * expected by the caller. The computation does its best to avoid overflows.
1319 * The value is returned in <ret> if everything is fine, and a NULL is returned
1320 * by the function. In case of error, a pointer to the error is returned and
1321 * <ret> is left untouched. Values are automatically rounded up when needed.
1322 */
1323const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1324{
1325 unsigned imult, idiv;
1326 unsigned omult, odiv;
1327 unsigned value;
1328
1329 omult = odiv = 1;
1330
1331 switch (unit_flags & TIME_UNIT_MASK) {
1332 case TIME_UNIT_US: omult = 1000000; break;
1333 case TIME_UNIT_MS: omult = 1000; break;
1334 case TIME_UNIT_S: break;
1335 case TIME_UNIT_MIN: odiv = 60; break;
1336 case TIME_UNIT_HOUR: odiv = 3600; break;
1337 case TIME_UNIT_DAY: odiv = 86400; break;
1338 default: break;
1339 }
1340
1341 value = 0;
1342
1343 while (1) {
1344 unsigned int j;
1345
1346 j = *text - '0';
1347 if (j > 9)
1348 break;
1349 text++;
1350 value *= 10;
1351 value += j;
1352 }
1353
1354 imult = idiv = 1;
1355 switch (*text) {
1356 case '\0': /* no unit = default unit */
1357 imult = omult = idiv = odiv = 1;
1358 break;
1359 case 's': /* second = unscaled unit */
1360 break;
1361 case 'u': /* microsecond : "us" */
1362 if (text[1] == 's') {
1363 idiv = 1000000;
1364 text++;
1365 }
1366 break;
1367 case 'm': /* millisecond : "ms" or minute: "m" */
1368 if (text[1] == 's') {
1369 idiv = 1000;
1370 text++;
1371 } else
1372 imult = 60;
1373 break;
1374 case 'h': /* hour : "h" */
1375 imult = 3600;
1376 break;
1377 case 'd': /* day : "d" */
1378 imult = 86400;
1379 break;
1380 default:
1381 return text;
1382 break;
1383 }
1384
1385 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1386 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1387 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1388 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1389
1390 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1391 *ret = value;
1392 return NULL;
1393}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001394
Emeric Brun39132b22010-01-04 14:57:24 +01001395/* this function converts the string starting at <text> to an unsigned int
1396 * stored in <ret>. If an error is detected, the pointer to the unexpected
1397 * character is returned. If the conversio is succesful, NULL is returned.
1398 */
1399const char *parse_size_err(const char *text, unsigned *ret) {
1400 unsigned value = 0;
1401
1402 while (1) {
1403 unsigned int j;
1404
1405 j = *text - '0';
1406 if (j > 9)
1407 break;
1408 if (value > ~0U / 10)
1409 return text;
1410 value *= 10;
1411 if (value > (value + j))
1412 return text;
1413 value += j;
1414 text++;
1415 }
1416
1417 switch (*text) {
1418 case '\0':
1419 break;
1420 case 'K':
1421 case 'k':
1422 if (value > ~0U >> 10)
1423 return text;
1424 value = value << 10;
1425 break;
1426 case 'M':
1427 case 'm':
1428 if (value > ~0U >> 20)
1429 return text;
1430 value = value << 20;
1431 break;
1432 case 'G':
1433 case 'g':
1434 if (value > ~0U >> 30)
1435 return text;
1436 value = value << 30;
1437 break;
1438 default:
1439 return text;
1440 }
1441
1442 *ret = value;
1443 return NULL;
1444}
1445
Willy Tarreau126d4062013-12-03 17:50:47 +01001446/*
1447 * Parse binary string written in hexadecimal (source) and store the decoded
1448 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1449 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001450 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001451 */
1452int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1453{
1454 int len;
1455 const char *p = source;
1456 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001457 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001458
1459 len = strlen(source);
1460 if (len % 2) {
1461 memprintf(err, "an even number of hex digit is expected");
1462 return 0;
1463 }
1464
1465 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001466
Willy Tarreau126d4062013-12-03 17:50:47 +01001467 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001468 *binstr = calloc(len, sizeof(char));
1469 if (!*binstr) {
1470 memprintf(err, "out of memory while loading string pattern");
1471 return 0;
1472 }
1473 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001474 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001475 else {
1476 if (*binstrlen < len) {
1477 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1478 len, *binstrlen);
1479 return 0;
1480 }
1481 alloc = 0;
1482 }
1483 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001484
1485 i = j = 0;
1486 while (j < len) {
1487 if (!ishex(p[i++]))
1488 goto bad_input;
1489 if (!ishex(p[i++]))
1490 goto bad_input;
1491 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1492 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001493 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001494
1495bad_input:
1496 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001497 if (alloc)
1498 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001499 return 0;
1500}
1501
Willy Tarreau946ba592009-05-10 15:41:18 +02001502/* copies at most <n> characters from <src> and always terminates with '\0' */
1503char *my_strndup(const char *src, int n)
1504{
1505 int len = 0;
1506 char *ret;
1507
1508 while (len < n && src[len])
1509 len++;
1510
1511 ret = (char *)malloc(len + 1);
1512 if (!ret)
1513 return ret;
1514 memcpy(ret, src, len);
1515 ret[len] = '\0';
1516 return ret;
1517}
1518
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001519/*
1520 * search needle in haystack
1521 * returns the pointer if found, returns NULL otherwise
1522 */
1523const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1524{
1525 const void *c = NULL;
1526 unsigned char f;
1527
1528 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1529 return NULL;
1530
1531 f = *(char *)needle;
1532 c = haystack;
1533 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1534 if ((haystacklen - (c - haystack)) < needlelen)
1535 return NULL;
1536
1537 if (memcmp(c, needle, needlelen) == 0)
1538 return c;
1539 ++c;
1540 }
1541 return NULL;
1542}
1543
Willy Tarreau482b00d2009-10-04 22:48:42 +02001544/* This function returns the first unused key greater than or equal to <key> in
1545 * ID tree <root>. Zero is returned if no place is found.
1546 */
1547unsigned int get_next_id(struct eb_root *root, unsigned int key)
1548{
1549 struct eb32_node *used;
1550
1551 do {
1552 used = eb32_lookup_ge(root, key);
1553 if (!used || used->key > key)
1554 return key; /* key is available */
1555 key++;
1556 } while (key);
1557 return key;
1558}
1559
Willy Tarreau348238b2010-01-18 15:05:57 +01001560/* This function compares a sample word possibly followed by blanks to another
1561 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1562 * otherwise zero. This intends to be used when checking HTTP headers for some
1563 * values. Note that it validates a word followed only by blanks but does not
1564 * validate a word followed by blanks then other chars.
1565 */
1566int word_match(const char *sample, int slen, const char *word, int wlen)
1567{
1568 if (slen < wlen)
1569 return 0;
1570
1571 while (wlen) {
1572 char c = *sample ^ *word;
1573 if (c && c != ('A' ^ 'a'))
1574 return 0;
1575 sample++;
1576 word++;
1577 slen--;
1578 wlen--;
1579 }
1580
1581 while (slen) {
1582 if (*sample != ' ' && *sample != '\t')
1583 return 0;
1584 sample++;
1585 slen--;
1586 }
1587 return 1;
1588}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001589
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001590/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1591 * is particularly fast because it avoids expensive operations such as
1592 * multiplies, which are optimized away at the end. It requires a properly
1593 * formated address though (3 points).
1594 */
1595unsigned int inetaddr_host(const char *text)
1596{
1597 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1598 register unsigned int dig100, dig10, dig1;
1599 int s;
1600 const char *p, *d;
1601
1602 dig1 = dig10 = dig100 = ascii_zero;
1603 s = 24;
1604
1605 p = text;
1606 while (1) {
1607 if (((unsigned)(*p - '0')) <= 9) {
1608 p++;
1609 continue;
1610 }
1611
1612 /* here, we have a complete byte between <text> and <p> (exclusive) */
1613 if (p == text)
1614 goto end;
1615
1616 d = p - 1;
1617 dig1 |= (unsigned int)(*d << s);
1618 if (d == text)
1619 goto end;
1620
1621 d--;
1622 dig10 |= (unsigned int)(*d << s);
1623 if (d == text)
1624 goto end;
1625
1626 d--;
1627 dig100 |= (unsigned int)(*d << s);
1628 end:
1629 if (!s || *p != '.')
1630 break;
1631
1632 s -= 8;
1633 text = ++p;
1634 }
1635
1636 dig100 -= ascii_zero;
1637 dig10 -= ascii_zero;
1638 dig1 -= ascii_zero;
1639 return ((dig100 * 10) + dig10) * 10 + dig1;
1640}
1641
1642/*
1643 * Idem except the first unparsed character has to be passed in <stop>.
1644 */
1645unsigned int inetaddr_host_lim(const char *text, const char *stop)
1646{
1647 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1648 register unsigned int dig100, dig10, dig1;
1649 int s;
1650 const char *p, *d;
1651
1652 dig1 = dig10 = dig100 = ascii_zero;
1653 s = 24;
1654
1655 p = text;
1656 while (1) {
1657 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1658 p++;
1659 continue;
1660 }
1661
1662 /* here, we have a complete byte between <text> and <p> (exclusive) */
1663 if (p == text)
1664 goto end;
1665
1666 d = p - 1;
1667 dig1 |= (unsigned int)(*d << s);
1668 if (d == text)
1669 goto end;
1670
1671 d--;
1672 dig10 |= (unsigned int)(*d << s);
1673 if (d == text)
1674 goto end;
1675
1676 d--;
1677 dig100 |= (unsigned int)(*d << s);
1678 end:
1679 if (!s || p == stop || *p != '.')
1680 break;
1681
1682 s -= 8;
1683 text = ++p;
1684 }
1685
1686 dig100 -= ascii_zero;
1687 dig10 -= ascii_zero;
1688 dig1 -= ascii_zero;
1689 return ((dig100 * 10) + dig10) * 10 + dig1;
1690}
1691
1692/*
1693 * Idem except the pointer to first unparsed byte is returned into <ret> which
1694 * must not be NULL.
1695 */
Willy Tarreau74172752010-10-15 23:21:42 +02001696unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001697{
1698 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1699 register unsigned int dig100, dig10, dig1;
1700 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001701 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001702
1703 dig1 = dig10 = dig100 = ascii_zero;
1704 s = 24;
1705
1706 p = text;
1707 while (1) {
1708 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1709 p++;
1710 continue;
1711 }
1712
1713 /* here, we have a complete byte between <text> and <p> (exclusive) */
1714 if (p == text)
1715 goto end;
1716
1717 d = p - 1;
1718 dig1 |= (unsigned int)(*d << s);
1719 if (d == text)
1720 goto end;
1721
1722 d--;
1723 dig10 |= (unsigned int)(*d << s);
1724 if (d == text)
1725 goto end;
1726
1727 d--;
1728 dig100 |= (unsigned int)(*d << s);
1729 end:
1730 if (!s || p == stop || *p != '.')
1731 break;
1732
1733 s -= 8;
1734 text = ++p;
1735 }
1736
1737 *ret = p;
1738 dig100 -= ascii_zero;
1739 dig10 -= ascii_zero;
1740 dig1 -= ascii_zero;
1741 return ((dig100 * 10) + dig10) * 10 + dig1;
1742}
1743
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001744/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1745 * or the number of chars read in case of success. Maybe this could be replaced
1746 * by one of the functions above. Also, apparently this function does not support
1747 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001748 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001749 */
1750int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1751{
1752 const char *addr;
1753 int saw_digit, octets, ch;
1754 u_char tmp[4], *tp;
1755 const char *cp = buf;
1756
1757 saw_digit = 0;
1758 octets = 0;
1759 *(tp = tmp) = 0;
1760
1761 for (addr = buf; addr - buf < len; addr++) {
1762 unsigned char digit = (ch = *addr) - '0';
1763
1764 if (digit > 9 && ch != '.')
1765 break;
1766
1767 if (digit <= 9) {
1768 u_int new = *tp * 10 + digit;
1769
1770 if (new > 255)
1771 return 0;
1772
1773 *tp = new;
1774
1775 if (!saw_digit) {
1776 if (++octets > 4)
1777 return 0;
1778 saw_digit = 1;
1779 }
1780 } else if (ch == '.' && saw_digit) {
1781 if (octets == 4)
1782 return 0;
1783
1784 *++tp = 0;
1785 saw_digit = 0;
1786 } else
1787 return 0;
1788 }
1789
1790 if (octets < 4)
1791 return 0;
1792
1793 memcpy(&dst->s_addr, tmp, 4);
1794 return addr - cp;
1795}
1796
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001797/* This function converts the string in <buf> of the len <len> to
1798 * struct in6_addr <dst> which must be allocated by the caller.
1799 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01001800 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001801 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001802int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
1803{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001804 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01001805 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001806
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001807 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001808 return 0;
1809
1810 memcpy(null_term_ip6, buf, len);
1811 null_term_ip6[len] = '\0';
1812
Willy Tarreau075415a2013-12-12 11:29:39 +01001813 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001814 return 0;
1815
Willy Tarreau075415a2013-12-12 11:29:39 +01001816 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001817 return 1;
1818}
1819
Willy Tarreauacf95772010-06-14 19:09:21 +02001820/* To be used to quote config arg positions. Returns the short string at <ptr>
1821 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1822 * if ptr is NULL or empty. The string is locally allocated.
1823 */
1824const char *quote_arg(const char *ptr)
1825{
1826 static char val[32];
1827 int i;
1828
1829 if (!ptr || !*ptr)
1830 return "end of line";
1831 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001832 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001833 val[i] = *ptr++;
1834 val[i++] = '\'';
1835 val[i] = '\0';
1836 return val;
1837}
1838
Willy Tarreau5b180202010-07-18 10:40:48 +02001839/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1840int get_std_op(const char *str)
1841{
1842 int ret = -1;
1843
1844 if (*str == 'e' && str[1] == 'q')
1845 ret = STD_OP_EQ;
1846 else if (*str == 'n' && str[1] == 'e')
1847 ret = STD_OP_NE;
1848 else if (*str == 'l') {
1849 if (str[1] == 'e') ret = STD_OP_LE;
1850 else if (str[1] == 't') ret = STD_OP_LT;
1851 }
1852 else if (*str == 'g') {
1853 if (str[1] == 'e') ret = STD_OP_GE;
1854 else if (str[1] == 't') ret = STD_OP_GT;
1855 }
1856
1857 if (ret == -1 || str[2] != '\0')
1858 return -1;
1859 return ret;
1860}
1861
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001862/* hash a 32-bit integer to another 32-bit integer */
1863unsigned int full_hash(unsigned int a)
1864{
1865 return __full_hash(a);
1866}
1867
David du Colombier4f92d322011-03-24 11:09:31 +01001868/* Return non-zero if IPv4 address is part of the network,
1869 * otherwise zero.
1870 */
1871int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1872{
1873 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1874}
1875
1876/* Return non-zero if IPv6 address is part of the network,
1877 * otherwise zero.
1878 */
1879int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1880{
1881 int i;
1882
1883 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1884 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1885 (((int *)net)[i] & ((int *)mask)[i]))
1886 return 0;
1887 return 1;
1888}
1889
1890/* RFC 4291 prefix */
1891const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1892 0x00, 0x00, 0x00, 0x00,
1893 0x00, 0x00, 0xFF, 0xFF };
1894
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001895/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
1896 * Input and output may overlap.
1897 */
David du Colombier4f92d322011-03-24 11:09:31 +01001898void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1899{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001900 struct in_addr tmp_addr;
1901
1902 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01001903 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001904 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01001905}
1906
1907/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1908 * Return true if conversion is possible and false otherwise.
1909 */
1910int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1911{
1912 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1913 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1914 sizeof(struct in_addr));
1915 return 1;
1916 }
1917
1918 return 0;
1919}
1920
William Lallemand421f5b52012-02-06 18:15:57 +01001921char *human_time(int t, short hz_div) {
1922 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1923 char *p = rv;
1924 int cnt=2; // print two numbers
1925
1926 if (unlikely(t < 0 || hz_div <= 0)) {
1927 sprintf(p, "?");
1928 return rv;
1929 }
1930
1931 if (unlikely(hz_div > 1))
1932 t /= hz_div;
1933
1934 if (t >= DAY) {
1935 p += sprintf(p, "%dd", t / DAY);
1936 cnt--;
1937 }
1938
1939 if (cnt && t % DAY / HOUR) {
1940 p += sprintf(p, "%dh", t % DAY / HOUR);
1941 cnt--;
1942 }
1943
1944 if (cnt && t % HOUR / MINUTE) {
1945 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1946 cnt--;
1947 }
1948
1949 if ((cnt && t % MINUTE) || !t) // also display '0s'
1950 p += sprintf(p, "%ds", t % MINUTE / SEC);
1951
1952 return rv;
1953}
1954
1955const char *monthname[12] = {
1956 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1957 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1958};
1959
1960/* date2str_log: write a date in the format :
1961 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1962 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1963 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1964 *
1965 * without using sprintf. return a pointer to the last char written (\0) or
1966 * NULL if there isn't enough space.
1967 */
1968char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1969{
1970
1971 if (size < 25) /* the size is fixed: 24 chars + \0 */
1972 return NULL;
1973
1974 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1975 *dst++ = '/';
1976 memcpy(dst, monthname[tm->tm_mon], 3); // month
1977 dst += 3;
1978 *dst++ = '/';
1979 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1980 *dst++ = ':';
1981 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1982 *dst++ = ':';
1983 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1984 *dst++ = ':';
1985 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1986 *dst++ = '.';
1987 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1988 dst += 3; // only the 3 first digits
1989 *dst = '\0';
1990
1991 return dst;
1992}
1993
1994/* gmt2str_log: write a date in the format :
1995 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1996 * return a pointer to the last char written (\0) or
1997 * NULL if there isn't enough space.
1998 */
1999char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2000{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002001 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002002 return NULL;
2003
2004 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2005 *dst++ = '/';
2006 memcpy(dst, monthname[tm->tm_mon], 3); // month
2007 dst += 3;
2008 *dst++ = '/';
2009 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2010 *dst++ = ':';
2011 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2012 *dst++ = ':';
2013 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2014 *dst++ = ':';
2015 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2016 *dst++ = ' ';
2017 *dst++ = '+';
2018 *dst++ = '0';
2019 *dst++ = '0';
2020 *dst++ = '0';
2021 *dst++ = '0';
2022 *dst = '\0';
2023
2024 return dst;
2025}
2026
Yuxans Yao4e25b012012-10-19 10:36:09 +08002027/* localdate2str_log: write a date in the format :
2028 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2029 * * return a pointer to the last char written (\0) or
2030 * * NULL if there isn't enough space.
2031 */
2032char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2033{
2034 if (size < 27) /* the size is fixed: 26 chars + \0 */
2035 return NULL;
2036
2037 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2038 *dst++ = '/';
2039 memcpy(dst, monthname[tm->tm_mon], 3); // month
2040 dst += 3;
2041 *dst++ = '/';
2042 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2043 *dst++ = ':';
2044 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2045 *dst++ = ':';
2046 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2047 *dst++ = ':';
2048 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2049 *dst++ = ' ';
2050 memcpy(dst, localtimezone, 5); // timezone
2051 dst += 5;
2052 *dst = '\0';
2053
2054 return dst;
2055}
2056
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002057/* Dynamically allocates a string of the proper length to hold the formatted
2058 * output. NULL is returned on error. The caller is responsible for freeing the
2059 * memory area using free(). The resulting string is returned in <out> if the
2060 * pointer is not NULL. A previous version of <out> might be used to build the
2061 * new string, and it will be freed before returning if it is not NULL, which
2062 * makes it possible to build complex strings from iterative calls without
2063 * having to care about freeing intermediate values, as in the example below :
2064 *
2065 * memprintf(&err, "invalid argument: '%s'", arg);
2066 * ...
2067 * memprintf(&err, "parser said : <%s>\n", *err);
2068 * ...
2069 * free(*err);
2070 *
2071 * This means that <err> must be initialized to NULL before first invocation.
2072 * The return value also holds the allocated string, which eases error checking
2073 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002074 * passed instead and it will be ignored. The returned message will then also
2075 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002076 *
2077 * It is also convenient to use it without any free except the last one :
2078 * err = NULL;
2079 * if (!fct1(err)) report(*err);
2080 * if (!fct2(err)) report(*err);
2081 * if (!fct3(err)) report(*err);
2082 * free(*err);
2083 */
2084char *memprintf(char **out, const char *format, ...)
2085{
2086 va_list args;
2087 char *ret = NULL;
2088 int allocated = 0;
2089 int needed = 0;
2090
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002091 if (!out)
2092 return NULL;
2093
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002094 do {
2095 /* vsnprintf() will return the required length even when the
2096 * target buffer is NULL. We do this in a loop just in case
2097 * intermediate evaluations get wrong.
2098 */
2099 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002100 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002101 va_end(args);
2102
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002103 if (needed < allocated) {
2104 /* Note: on Solaris 8, the first iteration always
2105 * returns -1 if allocated is zero, so we force a
2106 * retry.
2107 */
2108 if (!allocated)
2109 needed = 0;
2110 else
2111 break;
2112 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002113
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002114 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002115 ret = realloc(ret, allocated);
2116 } while (ret);
2117
2118 if (needed < 0) {
2119 /* an error was encountered */
2120 free(ret);
2121 ret = NULL;
2122 }
2123
2124 if (out) {
2125 free(*out);
2126 *out = ret;
2127 }
2128
2129 return ret;
2130}
William Lallemand421f5b52012-02-06 18:15:57 +01002131
Willy Tarreau21c705b2012-09-14 11:40:36 +02002132/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2133 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002134 * freed by the caller. It also supports being passed a NULL which results in the same
2135 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002136 * Example of use :
2137 * parse(cmd, &err); (callee: memprintf(&err, ...))
2138 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2139 * free(err);
2140 */
2141char *indent_msg(char **out, int level)
2142{
2143 char *ret, *in, *p;
2144 int needed = 0;
2145 int lf = 0;
2146 int lastlf = 0;
2147 int len;
2148
Willy Tarreau70eec382012-10-10 08:56:47 +02002149 if (!out || !*out)
2150 return NULL;
2151
Willy Tarreau21c705b2012-09-14 11:40:36 +02002152 in = *out - 1;
2153 while ((in = strchr(in + 1, '\n')) != NULL) {
2154 lastlf = in - *out;
2155 lf++;
2156 }
2157
2158 if (!lf) /* single line, no LF, return it as-is */
2159 return *out;
2160
2161 len = strlen(*out);
2162
2163 if (lf == 1 && lastlf == len - 1) {
2164 /* single line, LF at end, strip it and return as-is */
2165 (*out)[lastlf] = 0;
2166 return *out;
2167 }
2168
2169 /* OK now we have at least one LF, we need to process the whole string
2170 * as a multi-line string. What we'll do :
2171 * - prefix with an LF if there is none
2172 * - add <level> spaces before each line
2173 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2174 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2175 */
2176
2177 needed = 1 + level * (lf + 1) + len + 1;
2178 p = ret = malloc(needed);
2179 in = *out;
2180
2181 /* skip initial LFs */
2182 while (*in == '\n')
2183 in++;
2184
2185 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2186 while (*in) {
2187 *p++ = '\n';
2188 memset(p, ' ', level);
2189 p += level;
2190 do {
2191 *p++ = *in++;
2192 } while (*in && *in != '\n');
2193 if (*in)
2194 in++;
2195 }
2196 *p = 0;
2197
2198 free(*out);
2199 *out = ret;
2200
2201 return ret;
2202}
2203
Willy Tarreaudad36a32013-03-11 01:20:04 +01002204/* Convert occurrences of environment variables in the input string to their
2205 * corresponding value. A variable is identified as a series of alphanumeric
2206 * characters or underscores following a '$' sign. The <in> string must be
2207 * free()able. NULL returns NULL. The resulting string might be reallocated if
2208 * some expansion is made. Variable names may also be enclosed into braces if
2209 * needed (eg: to concatenate alphanum characters).
2210 */
2211char *env_expand(char *in)
2212{
2213 char *txt_beg;
2214 char *out;
2215 char *txt_end;
2216 char *var_beg;
2217 char *var_end;
2218 char *value;
2219 char *next;
2220 int out_len;
2221 int val_len;
2222
2223 if (!in)
2224 return in;
2225
2226 value = out = NULL;
2227 out_len = 0;
2228
2229 txt_beg = in;
2230 do {
2231 /* look for next '$' sign in <in> */
2232 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2233
2234 if (!*txt_end && !out) /* end and no expansion performed */
2235 return in;
2236
2237 val_len = 0;
2238 next = txt_end;
2239 if (*txt_end == '$') {
2240 char save;
2241
2242 var_beg = txt_end + 1;
2243 if (*var_beg == '{')
2244 var_beg++;
2245
2246 var_end = var_beg;
2247 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2248 var_end++;
2249 }
2250
2251 next = var_end;
2252 if (*var_end == '}' && (var_beg > txt_end + 1))
2253 next++;
2254
2255 /* get value of the variable name at this location */
2256 save = *var_end;
2257 *var_end = '\0';
2258 value = getenv(var_beg);
2259 *var_end = save;
2260 val_len = value ? strlen(value) : 0;
2261 }
2262
2263 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2264 if (txt_end > txt_beg) {
2265 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2266 out_len += txt_end - txt_beg;
2267 }
2268 if (val_len) {
2269 memcpy(out + out_len, value, val_len);
2270 out_len += val_len;
2271 }
2272 out[out_len] = 0;
2273 txt_beg = next;
2274 } while (*txt_beg);
2275
2276 /* here we know that <out> was allocated and that we don't need <in> anymore */
2277 free(in);
2278 return out;
2279}
2280
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002281
2282/* same as strstr() but case-insensitive and with limit length */
2283const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2284{
2285 char *pptr, *sptr, *start;
2286 uint slen, plen;
2287 uint tmp1, tmp2;
2288
2289 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2290 return NULL;
2291
2292 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2293 return str1;
2294
2295 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2296 return NULL;
2297
2298 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2299 while (toupper(*start) != toupper(*str2)) {
2300 start++;
2301 slen--;
2302 tmp1++;
2303
2304 if (tmp1 >= len_str1)
2305 return NULL;
2306
2307 /* if pattern longer than string */
2308 if (slen < plen)
2309 return NULL;
2310 }
2311
2312 sptr = start;
2313 pptr = (char *)str2;
2314
2315 tmp2 = 0;
2316 while (toupper(*sptr) == toupper(*pptr)) {
2317 sptr++;
2318 pptr++;
2319 tmp2++;
2320
2321 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2322 return start;
2323 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2324 return NULL;
2325 }
2326 }
2327 return NULL;
2328}
2329
Willy Tarreaubaaee002006-06-26 02:48:02 +02002330/*
2331 * Local variables:
2332 * c-indent-level: 8
2333 * c-basic-offset: 8
2334 * End:
2335 */