blob: 46c940d66ca0781986893e2a674d0fcaa1974685 [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
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200794/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200795 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200796 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
797 * is optionnal and either in the dotted or CIDR notation.
798 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
799 */
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200800int str2net(const char *str, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200801{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200802 __label__ out_free, out_err;
803 char *c, *s;
804 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200805
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200806 s = strdup(str);
807 if (!s)
808 return 0;
809
Willy Tarreaubaaee002006-06-26 02:48:02 +0200810 memset(mask, 0, sizeof(*mask));
811 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200812
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200813 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200814 *c++ = '\0';
815 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100816 if (!str2mask(c, mask))
817 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200818 }
819 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100820 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200821 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200822 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200823 struct hostent *he;
824
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200825 if ((he = gethostbyname(s)) == NULL) {
826 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200827 }
828 else
829 *addr = *(struct in_addr *) *(he->h_addr_list);
830 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200831
832 ret_val = 1;
833 out_free:
834 free(s);
835 return ret_val;
836 out_err:
837 ret_val = 0;
838 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200839}
840
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100841
842/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200843 * converts <str> to two struct in6_addr* which must be pre-allocated.
844 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
845 * is an optionnal number of bits (128 being the default).
846 * Returns 1 if OK, 0 if error.
847 */
848int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
849{
850 char *c, *s;
851 int ret_val = 0;
852 char *err;
853 unsigned long len = 128;
854
855 s = strdup(str);
856 if (!s)
857 return 0;
858
859 memset(mask, 0, sizeof(*mask));
860 memset(addr, 0, sizeof(*addr));
861
862 if ((c = strrchr(s, '/')) != NULL) {
863 *c++ = '\0'; /* c points to the mask */
864 if (!*c)
865 goto out_free;
866
867 len = strtoul(c, &err, 10);
868 if ((err && *err) || (unsigned)len > 128)
869 goto out_free;
870 }
871 *mask = len; /* OK we have a valid mask in <len> */
872
873 if (!inet_pton(AF_INET6, s, addr))
874 goto out_free;
875
876 ret_val = 1;
877 out_free:
878 free(s);
879 return ret_val;
880}
881
882
883/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100884 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100885 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100886int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100887{
888 int saw_digit, octets, ch;
889 u_char tmp[4], *tp;
890 const char *cp = addr;
891
892 saw_digit = 0;
893 octets = 0;
894 *(tp = tmp) = 0;
895
896 while (*addr) {
897 unsigned char digit = (ch = *addr++) - '0';
898 if (digit > 9 && ch != '.')
899 break;
900 if (digit <= 9) {
901 u_int new = *tp * 10 + digit;
902 if (new > 255)
903 return 0;
904 *tp = new;
905 if (!saw_digit) {
906 if (++octets > 4)
907 return 0;
908 saw_digit = 1;
909 }
910 } else if (ch == '.' && saw_digit) {
911 if (octets == 4)
912 return 0;
913 *++tp = 0;
914 saw_digit = 0;
915 } else
916 return 0;
917 }
918
919 if (octets < 4)
920 return 0;
921
922 memcpy(&dst->s_addr, tmp, 4);
923 return addr-cp-1;
924}
925
926/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100927 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100928 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100929int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100930{
931 const char *curr = url, *cp = url;
932 int ret, url_code = 0;
933 unsigned int http_code = 0;
934
935 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100936
937 /* FIXME: assume IPv4 only for now */
938 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
939 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
940 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100941
942 /* Firstly, try to find :// pattern */
943 while (curr < url+ulen && url_code != 0x3a2f2f) {
944 url_code = ((url_code & 0xffff) << 8);
945 url_code += (unsigned char)*curr++;
946 }
947
948 /* Secondly, if :// pattern is found, verify parsed stuff
949 * before pattern is matching our http pattern.
950 * If so parse ip address and port in uri.
951 *
952 * WARNING: Current code doesn't support dynamic async dns resolver.
953 */
954 if (url_code == 0x3a2f2f) {
955 while (cp < curr - 3)
956 http_code = (http_code << 8) + *cp++;
957 http_code |= 0x20202020; /* Turn everything to lower case */
958
959 /* HTTP url matching */
960 if (http_code == 0x68747470) {
961 /* We are looking for IP address. If you want to parse and
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100962 * resolve hostname found in url, you can use str2sa_range(), but
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100963 * be warned this can slow down global daemon performances
964 * while handling lagging dns responses.
965 */
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200966 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100967 if (!ret)
968 return -1;
969 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100970 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200971 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100972 }
973 return 0;
974 }
975
976 return -1;
977}
978
Willy Tarreau631f01c2011-09-05 00:36:48 +0200979/* Tries to convert a sockaddr_storage address to text form. Upon success, the
980 * address family is returned so that it's easy for the caller to adapt to the
981 * output format. Zero is returned if the address family is not supported. -1
982 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
983 * supported.
984 */
985int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
986{
987
988 void *ptr;
989
990 if (size < 5)
991 return 0;
992 *str = '\0';
993
994 switch (addr->ss_family) {
995 case AF_INET:
996 ptr = &((struct sockaddr_in *)addr)->sin_addr;
997 break;
998 case AF_INET6:
999 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1000 break;
1001 case AF_UNIX:
1002 memcpy(str, "unix", 5);
1003 return addr->ss_family;
1004 default:
1005 return 0;
1006 }
1007
1008 if (inet_ntop(addr->ss_family, ptr, str, size))
1009 return addr->ss_family;
1010
1011 /* failed */
1012 return -1;
1013}
1014
Willy Tarreaubaaee002006-06-26 02:48:02 +02001015/* will try to encode the string <string> replacing all characters tagged in
1016 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1017 * prefixed by <escape>, and will store the result between <start> (included)
1018 * and <stop> (excluded), and will always terminate the string with a '\0'
1019 * before <stop>. The position of the '\0' is returned if the conversion
1020 * completes. If bytes are missing between <start> and <stop>, then the
1021 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1022 * cannot even be stored so we return <start> without writing the 0.
1023 * The input string must also be zero-terminated.
1024 */
1025const char hextab[16] = "0123456789ABCDEF";
1026char *encode_string(char *start, char *stop,
1027 const char escape, const fd_set *map,
1028 const char *string)
1029{
1030 if (start < stop) {
1031 stop--; /* reserve one byte for the final '\0' */
1032 while (start < stop && *string != '\0') {
1033 if (!FD_ISSET((unsigned char)(*string), map))
1034 *start++ = *string;
1035 else {
1036 if (start + 3 >= stop)
1037 break;
1038 *start++ = escape;
1039 *start++ = hextab[(*string >> 4) & 15];
1040 *start++ = hextab[*string & 15];
1041 }
1042 string++;
1043 }
1044 *start = '\0';
1045 }
1046 return start;
1047}
1048
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001049/*
1050 * Same behavior as encode_string() above, except that it encodes chunk
1051 * <chunk> instead of a string.
1052 */
1053char *encode_chunk(char *start, char *stop,
1054 const char escape, const fd_set *map,
1055 const struct chunk *chunk)
1056{
1057 char *str = chunk->str;
1058 char *end = chunk->str + chunk->len;
1059
1060 if (start < stop) {
1061 stop--; /* reserve one byte for the final '\0' */
1062 while (start < stop && str < end) {
1063 if (!FD_ISSET((unsigned char)(*str), map))
1064 *start++ = *str;
1065 else {
1066 if (start + 3 >= stop)
1067 break;
1068 *start++ = escape;
1069 *start++ = hextab[(*str >> 4) & 15];
1070 *start++ = hextab[*str & 15];
1071 }
1072 str++;
1073 }
1074 *start = '\0';
1075 }
1076 return start;
1077}
1078
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001079/* Decode an URL-encoded string in-place. The resulting string might
1080 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001081 * aborted, the string is truncated before the issue and a negative value is
1082 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001083 */
1084int url_decode(char *string)
1085{
1086 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001087 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001088
1089 in = string;
1090 out = string;
1091 while (*in) {
1092 switch (*in) {
1093 case '+' :
1094 *out++ = ' ';
1095 break;
1096 case '%' :
1097 if (!ishex(in[1]) || !ishex(in[2]))
1098 goto end;
1099 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1100 in += 2;
1101 break;
1102 default:
1103 *out++ = *in;
1104 break;
1105 }
1106 in++;
1107 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001108 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001109 end:
1110 *out = 0;
1111 return ret;
1112}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001113
Willy Tarreau6911fa42007-03-04 18:06:08 +01001114unsigned int str2ui(const char *s)
1115{
1116 return __str2ui(s);
1117}
1118
1119unsigned int str2uic(const char *s)
1120{
1121 return __str2uic(s);
1122}
1123
1124unsigned int strl2ui(const char *s, int len)
1125{
1126 return __strl2ui(s, len);
1127}
1128
1129unsigned int strl2uic(const char *s, int len)
1130{
1131 return __strl2uic(s, len);
1132}
1133
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001134unsigned int read_uint(const char **s, const char *end)
1135{
1136 return __read_uint(s, end);
1137}
1138
Willy Tarreau6911fa42007-03-04 18:06:08 +01001139/* This one is 7 times faster than strtol() on athlon with checks.
1140 * It returns the value of the number composed of all valid digits read,
1141 * and can process negative numbers too.
1142 */
1143int strl2ic(const char *s, int len)
1144{
1145 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001146 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001147
1148 if (len > 0) {
1149 if (*s != '-') {
1150 /* positive number */
1151 while (len-- > 0) {
1152 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001153 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001154 if (j > 9)
1155 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001156 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001157 }
1158 } else {
1159 /* negative number */
1160 s++;
1161 while (--len > 0) {
1162 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001163 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001164 if (j > 9)
1165 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001166 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001167 }
1168 }
1169 }
1170 return i;
1171}
1172
1173
1174/* This function reads exactly <len> chars from <s> and converts them to a
1175 * signed integer which it stores into <ret>. It accurately detects any error
1176 * (truncated string, invalid chars, overflows). It is meant to be used in
1177 * applications designed for hostile environments. It returns zero when the
1178 * number has successfully been converted, non-zero otherwise. When an error
1179 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1180 * faster than strtol().
1181 */
1182int strl2irc(const char *s, int len, int *ret)
1183{
1184 int i = 0;
1185 int j;
1186
1187 if (!len)
1188 return 1;
1189
1190 if (*s != '-') {
1191 /* positive number */
1192 while (len-- > 0) {
1193 j = (*s++) - '0';
1194 if (j > 9) return 1; /* invalid char */
1195 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1196 i = i * 10;
1197 if (i + j < i) return 1; /* check for addition overflow */
1198 i = i + j;
1199 }
1200 } else {
1201 /* negative number */
1202 s++;
1203 while (--len > 0) {
1204 j = (*s++) - '0';
1205 if (j > 9) return 1; /* invalid char */
1206 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1207 i = i * 10;
1208 if (i - j > i) return 1; /* check for subtract overflow */
1209 i = i - j;
1210 }
1211 }
1212 *ret = i;
1213 return 0;
1214}
1215
1216
1217/* This function reads exactly <len> chars from <s> and converts them to a
1218 * signed integer which it stores into <ret>. It accurately detects any error
1219 * (truncated string, invalid chars, overflows). It is meant to be used in
1220 * applications designed for hostile environments. It returns zero when the
1221 * number has successfully been converted, non-zero otherwise. When an error
1222 * is returned, the <ret> value is left untouched. It is about 3 times slower
1223 * than str2irc().
1224 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001225
1226int strl2llrc(const char *s, int len, long long *ret)
1227{
1228 long long i = 0;
1229 int j;
1230
1231 if (!len)
1232 return 1;
1233
1234 if (*s != '-') {
1235 /* positive number */
1236 while (len-- > 0) {
1237 j = (*s++) - '0';
1238 if (j > 9) return 1; /* invalid char */
1239 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1240 i = i * 10LL;
1241 if (i + j < i) return 1; /* check for addition overflow */
1242 i = i + j;
1243 }
1244 } else {
1245 /* negative number */
1246 s++;
1247 while (--len > 0) {
1248 j = (*s++) - '0';
1249 if (j > 9) return 1; /* invalid char */
1250 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1251 i = i * 10LL;
1252 if (i - j > i) return 1; /* check for subtract overflow */
1253 i = i - j;
1254 }
1255 }
1256 *ret = i;
1257 return 0;
1258}
1259
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001260/* This function parses a time value optionally followed by a unit suffix among
1261 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1262 * expected by the caller. The computation does its best to avoid overflows.
1263 * The value is returned in <ret> if everything is fine, and a NULL is returned
1264 * by the function. In case of error, a pointer to the error is returned and
1265 * <ret> is left untouched. Values are automatically rounded up when needed.
1266 */
1267const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1268{
1269 unsigned imult, idiv;
1270 unsigned omult, odiv;
1271 unsigned value;
1272
1273 omult = odiv = 1;
1274
1275 switch (unit_flags & TIME_UNIT_MASK) {
1276 case TIME_UNIT_US: omult = 1000000; break;
1277 case TIME_UNIT_MS: omult = 1000; break;
1278 case TIME_UNIT_S: break;
1279 case TIME_UNIT_MIN: odiv = 60; break;
1280 case TIME_UNIT_HOUR: odiv = 3600; break;
1281 case TIME_UNIT_DAY: odiv = 86400; break;
1282 default: break;
1283 }
1284
1285 value = 0;
1286
1287 while (1) {
1288 unsigned int j;
1289
1290 j = *text - '0';
1291 if (j > 9)
1292 break;
1293 text++;
1294 value *= 10;
1295 value += j;
1296 }
1297
1298 imult = idiv = 1;
1299 switch (*text) {
1300 case '\0': /* no unit = default unit */
1301 imult = omult = idiv = odiv = 1;
1302 break;
1303 case 's': /* second = unscaled unit */
1304 break;
1305 case 'u': /* microsecond : "us" */
1306 if (text[1] == 's') {
1307 idiv = 1000000;
1308 text++;
1309 }
1310 break;
1311 case 'm': /* millisecond : "ms" or minute: "m" */
1312 if (text[1] == 's') {
1313 idiv = 1000;
1314 text++;
1315 } else
1316 imult = 60;
1317 break;
1318 case 'h': /* hour : "h" */
1319 imult = 3600;
1320 break;
1321 case 'd': /* day : "d" */
1322 imult = 86400;
1323 break;
1324 default:
1325 return text;
1326 break;
1327 }
1328
1329 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1330 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1331 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1332 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1333
1334 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1335 *ret = value;
1336 return NULL;
1337}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001338
Emeric Brun39132b22010-01-04 14:57:24 +01001339/* this function converts the string starting at <text> to an unsigned int
1340 * stored in <ret>. If an error is detected, the pointer to the unexpected
1341 * character is returned. If the conversio is succesful, NULL is returned.
1342 */
1343const char *parse_size_err(const char *text, unsigned *ret) {
1344 unsigned value = 0;
1345
1346 while (1) {
1347 unsigned int j;
1348
1349 j = *text - '0';
1350 if (j > 9)
1351 break;
1352 if (value > ~0U / 10)
1353 return text;
1354 value *= 10;
1355 if (value > (value + j))
1356 return text;
1357 value += j;
1358 text++;
1359 }
1360
1361 switch (*text) {
1362 case '\0':
1363 break;
1364 case 'K':
1365 case 'k':
1366 if (value > ~0U >> 10)
1367 return text;
1368 value = value << 10;
1369 break;
1370 case 'M':
1371 case 'm':
1372 if (value > ~0U >> 20)
1373 return text;
1374 value = value << 20;
1375 break;
1376 case 'G':
1377 case 'g':
1378 if (value > ~0U >> 30)
1379 return text;
1380 value = value << 30;
1381 break;
1382 default:
1383 return text;
1384 }
1385
1386 *ret = value;
1387 return NULL;
1388}
1389
Willy Tarreau126d4062013-12-03 17:50:47 +01001390/*
1391 * Parse binary string written in hexadecimal (source) and store the decoded
1392 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1393 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001394 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001395 */
1396int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1397{
1398 int len;
1399 const char *p = source;
1400 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001401 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001402
1403 len = strlen(source);
1404 if (len % 2) {
1405 memprintf(err, "an even number of hex digit is expected");
1406 return 0;
1407 }
1408
1409 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001410
Willy Tarreau126d4062013-12-03 17:50:47 +01001411 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001412 *binstr = calloc(len, sizeof(char));
1413 if (!*binstr) {
1414 memprintf(err, "out of memory while loading string pattern");
1415 return 0;
1416 }
1417 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001418 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001419 else {
1420 if (*binstrlen < len) {
1421 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1422 len, *binstrlen);
1423 return 0;
1424 }
1425 alloc = 0;
1426 }
1427 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001428
1429 i = j = 0;
1430 while (j < len) {
1431 if (!ishex(p[i++]))
1432 goto bad_input;
1433 if (!ishex(p[i++]))
1434 goto bad_input;
1435 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1436 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001437 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001438
1439bad_input:
1440 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001441 if (alloc)
1442 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001443 return 0;
1444}
1445
Willy Tarreau946ba592009-05-10 15:41:18 +02001446/* copies at most <n> characters from <src> and always terminates with '\0' */
1447char *my_strndup(const char *src, int n)
1448{
1449 int len = 0;
1450 char *ret;
1451
1452 while (len < n && src[len])
1453 len++;
1454
1455 ret = (char *)malloc(len + 1);
1456 if (!ret)
1457 return ret;
1458 memcpy(ret, src, len);
1459 ret[len] = '\0';
1460 return ret;
1461}
1462
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001463/*
1464 * search needle in haystack
1465 * returns the pointer if found, returns NULL otherwise
1466 */
1467const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1468{
1469 const void *c = NULL;
1470 unsigned char f;
1471
1472 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1473 return NULL;
1474
1475 f = *(char *)needle;
1476 c = haystack;
1477 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1478 if ((haystacklen - (c - haystack)) < needlelen)
1479 return NULL;
1480
1481 if (memcmp(c, needle, needlelen) == 0)
1482 return c;
1483 ++c;
1484 }
1485 return NULL;
1486}
1487
Willy Tarreau482b00d2009-10-04 22:48:42 +02001488/* This function returns the first unused key greater than or equal to <key> in
1489 * ID tree <root>. Zero is returned if no place is found.
1490 */
1491unsigned int get_next_id(struct eb_root *root, unsigned int key)
1492{
1493 struct eb32_node *used;
1494
1495 do {
1496 used = eb32_lookup_ge(root, key);
1497 if (!used || used->key > key)
1498 return key; /* key is available */
1499 key++;
1500 } while (key);
1501 return key;
1502}
1503
Willy Tarreau348238b2010-01-18 15:05:57 +01001504/* This function compares a sample word possibly followed by blanks to another
1505 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1506 * otherwise zero. This intends to be used when checking HTTP headers for some
1507 * values. Note that it validates a word followed only by blanks but does not
1508 * validate a word followed by blanks then other chars.
1509 */
1510int word_match(const char *sample, int slen, const char *word, int wlen)
1511{
1512 if (slen < wlen)
1513 return 0;
1514
1515 while (wlen) {
1516 char c = *sample ^ *word;
1517 if (c && c != ('A' ^ 'a'))
1518 return 0;
1519 sample++;
1520 word++;
1521 slen--;
1522 wlen--;
1523 }
1524
1525 while (slen) {
1526 if (*sample != ' ' && *sample != '\t')
1527 return 0;
1528 sample++;
1529 slen--;
1530 }
1531 return 1;
1532}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001533
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001534/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1535 * is particularly fast because it avoids expensive operations such as
1536 * multiplies, which are optimized away at the end. It requires a properly
1537 * formated address though (3 points).
1538 */
1539unsigned int inetaddr_host(const char *text)
1540{
1541 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1542 register unsigned int dig100, dig10, dig1;
1543 int s;
1544 const char *p, *d;
1545
1546 dig1 = dig10 = dig100 = ascii_zero;
1547 s = 24;
1548
1549 p = text;
1550 while (1) {
1551 if (((unsigned)(*p - '0')) <= 9) {
1552 p++;
1553 continue;
1554 }
1555
1556 /* here, we have a complete byte between <text> and <p> (exclusive) */
1557 if (p == text)
1558 goto end;
1559
1560 d = p - 1;
1561 dig1 |= (unsigned int)(*d << s);
1562 if (d == text)
1563 goto end;
1564
1565 d--;
1566 dig10 |= (unsigned int)(*d << s);
1567 if (d == text)
1568 goto end;
1569
1570 d--;
1571 dig100 |= (unsigned int)(*d << s);
1572 end:
1573 if (!s || *p != '.')
1574 break;
1575
1576 s -= 8;
1577 text = ++p;
1578 }
1579
1580 dig100 -= ascii_zero;
1581 dig10 -= ascii_zero;
1582 dig1 -= ascii_zero;
1583 return ((dig100 * 10) + dig10) * 10 + dig1;
1584}
1585
1586/*
1587 * Idem except the first unparsed character has to be passed in <stop>.
1588 */
1589unsigned int inetaddr_host_lim(const char *text, const char *stop)
1590{
1591 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1592 register unsigned int dig100, dig10, dig1;
1593 int s;
1594 const char *p, *d;
1595
1596 dig1 = dig10 = dig100 = ascii_zero;
1597 s = 24;
1598
1599 p = text;
1600 while (1) {
1601 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1602 p++;
1603 continue;
1604 }
1605
1606 /* here, we have a complete byte between <text> and <p> (exclusive) */
1607 if (p == text)
1608 goto end;
1609
1610 d = p - 1;
1611 dig1 |= (unsigned int)(*d << s);
1612 if (d == text)
1613 goto end;
1614
1615 d--;
1616 dig10 |= (unsigned int)(*d << s);
1617 if (d == text)
1618 goto end;
1619
1620 d--;
1621 dig100 |= (unsigned int)(*d << s);
1622 end:
1623 if (!s || p == stop || *p != '.')
1624 break;
1625
1626 s -= 8;
1627 text = ++p;
1628 }
1629
1630 dig100 -= ascii_zero;
1631 dig10 -= ascii_zero;
1632 dig1 -= ascii_zero;
1633 return ((dig100 * 10) + dig10) * 10 + dig1;
1634}
1635
1636/*
1637 * Idem except the pointer to first unparsed byte is returned into <ret> which
1638 * must not be NULL.
1639 */
Willy Tarreau74172752010-10-15 23:21:42 +02001640unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001641{
1642 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1643 register unsigned int dig100, dig10, dig1;
1644 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001645 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001646
1647 dig1 = dig10 = dig100 = ascii_zero;
1648 s = 24;
1649
1650 p = text;
1651 while (1) {
1652 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1653 p++;
1654 continue;
1655 }
1656
1657 /* here, we have a complete byte between <text> and <p> (exclusive) */
1658 if (p == text)
1659 goto end;
1660
1661 d = p - 1;
1662 dig1 |= (unsigned int)(*d << s);
1663 if (d == text)
1664 goto end;
1665
1666 d--;
1667 dig10 |= (unsigned int)(*d << s);
1668 if (d == text)
1669 goto end;
1670
1671 d--;
1672 dig100 |= (unsigned int)(*d << s);
1673 end:
1674 if (!s || p == stop || *p != '.')
1675 break;
1676
1677 s -= 8;
1678 text = ++p;
1679 }
1680
1681 *ret = p;
1682 dig100 -= ascii_zero;
1683 dig10 -= ascii_zero;
1684 dig1 -= ascii_zero;
1685 return ((dig100 * 10) + dig10) * 10 + dig1;
1686}
1687
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001688/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1689 * or the number of chars read in case of success. Maybe this could be replaced
1690 * by one of the functions above. Also, apparently this function does not support
1691 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001692 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001693 */
1694int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1695{
1696 const char *addr;
1697 int saw_digit, octets, ch;
1698 u_char tmp[4], *tp;
1699 const char *cp = buf;
1700
1701 saw_digit = 0;
1702 octets = 0;
1703 *(tp = tmp) = 0;
1704
1705 for (addr = buf; addr - buf < len; addr++) {
1706 unsigned char digit = (ch = *addr) - '0';
1707
1708 if (digit > 9 && ch != '.')
1709 break;
1710
1711 if (digit <= 9) {
1712 u_int new = *tp * 10 + digit;
1713
1714 if (new > 255)
1715 return 0;
1716
1717 *tp = new;
1718
1719 if (!saw_digit) {
1720 if (++octets > 4)
1721 return 0;
1722 saw_digit = 1;
1723 }
1724 } else if (ch == '.' && saw_digit) {
1725 if (octets == 4)
1726 return 0;
1727
1728 *++tp = 0;
1729 saw_digit = 0;
1730 } else
1731 return 0;
1732 }
1733
1734 if (octets < 4)
1735 return 0;
1736
1737 memcpy(&dst->s_addr, tmp, 4);
1738 return addr - cp;
1739}
1740
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001741/* This function converts the string in <buf> of the len <len> to
1742 * struct in6_addr <dst> which must be allocated by the caller.
1743 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01001744 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001745 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001746int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
1747{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001748 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01001749 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001750
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001751 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001752 return 0;
1753
1754 memcpy(null_term_ip6, buf, len);
1755 null_term_ip6[len] = '\0';
1756
Willy Tarreau075415a2013-12-12 11:29:39 +01001757 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001758 return 0;
1759
Willy Tarreau075415a2013-12-12 11:29:39 +01001760 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001761 return 1;
1762}
1763
Willy Tarreauacf95772010-06-14 19:09:21 +02001764/* To be used to quote config arg positions. Returns the short string at <ptr>
1765 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1766 * if ptr is NULL or empty. The string is locally allocated.
1767 */
1768const char *quote_arg(const char *ptr)
1769{
1770 static char val[32];
1771 int i;
1772
1773 if (!ptr || !*ptr)
1774 return "end of line";
1775 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001776 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001777 val[i] = *ptr++;
1778 val[i++] = '\'';
1779 val[i] = '\0';
1780 return val;
1781}
1782
Willy Tarreau5b180202010-07-18 10:40:48 +02001783/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1784int get_std_op(const char *str)
1785{
1786 int ret = -1;
1787
1788 if (*str == 'e' && str[1] == 'q')
1789 ret = STD_OP_EQ;
1790 else if (*str == 'n' && str[1] == 'e')
1791 ret = STD_OP_NE;
1792 else if (*str == 'l') {
1793 if (str[1] == 'e') ret = STD_OP_LE;
1794 else if (str[1] == 't') ret = STD_OP_LT;
1795 }
1796 else if (*str == 'g') {
1797 if (str[1] == 'e') ret = STD_OP_GE;
1798 else if (str[1] == 't') ret = STD_OP_GT;
1799 }
1800
1801 if (ret == -1 || str[2] != '\0')
1802 return -1;
1803 return ret;
1804}
1805
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001806/* hash a 32-bit integer to another 32-bit integer */
1807unsigned int full_hash(unsigned int a)
1808{
1809 return __full_hash(a);
1810}
1811
David du Colombier4f92d322011-03-24 11:09:31 +01001812/* Return non-zero if IPv4 address is part of the network,
1813 * otherwise zero.
1814 */
1815int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1816{
1817 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1818}
1819
1820/* Return non-zero if IPv6 address is part of the network,
1821 * otherwise zero.
1822 */
1823int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1824{
1825 int i;
1826
1827 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1828 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1829 (((int *)net)[i] & ((int *)mask)[i]))
1830 return 0;
1831 return 1;
1832}
1833
1834/* RFC 4291 prefix */
1835const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1836 0x00, 0x00, 0x00, 0x00,
1837 0x00, 0x00, 0xFF, 0xFF };
1838
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001839/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
1840 * Input and output may overlap.
1841 */
David du Colombier4f92d322011-03-24 11:09:31 +01001842void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1843{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001844 struct in_addr tmp_addr;
1845
1846 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01001847 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001848 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01001849}
1850
1851/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1852 * Return true if conversion is possible and false otherwise.
1853 */
1854int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1855{
1856 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1857 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1858 sizeof(struct in_addr));
1859 return 1;
1860 }
1861
1862 return 0;
1863}
1864
William Lallemand421f5b52012-02-06 18:15:57 +01001865char *human_time(int t, short hz_div) {
1866 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1867 char *p = rv;
1868 int cnt=2; // print two numbers
1869
1870 if (unlikely(t < 0 || hz_div <= 0)) {
1871 sprintf(p, "?");
1872 return rv;
1873 }
1874
1875 if (unlikely(hz_div > 1))
1876 t /= hz_div;
1877
1878 if (t >= DAY) {
1879 p += sprintf(p, "%dd", t / DAY);
1880 cnt--;
1881 }
1882
1883 if (cnt && t % DAY / HOUR) {
1884 p += sprintf(p, "%dh", t % DAY / HOUR);
1885 cnt--;
1886 }
1887
1888 if (cnt && t % HOUR / MINUTE) {
1889 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1890 cnt--;
1891 }
1892
1893 if ((cnt && t % MINUTE) || !t) // also display '0s'
1894 p += sprintf(p, "%ds", t % MINUTE / SEC);
1895
1896 return rv;
1897}
1898
1899const char *monthname[12] = {
1900 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1901 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1902};
1903
1904/* date2str_log: write a date in the format :
1905 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1906 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1907 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1908 *
1909 * without using sprintf. return a pointer to the last char written (\0) or
1910 * NULL if there isn't enough space.
1911 */
1912char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1913{
1914
1915 if (size < 25) /* the size is fixed: 24 chars + \0 */
1916 return NULL;
1917
1918 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1919 *dst++ = '/';
1920 memcpy(dst, monthname[tm->tm_mon], 3); // month
1921 dst += 3;
1922 *dst++ = '/';
1923 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1924 *dst++ = ':';
1925 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1926 *dst++ = ':';
1927 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1928 *dst++ = ':';
1929 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1930 *dst++ = '.';
1931 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1932 dst += 3; // only the 3 first digits
1933 *dst = '\0';
1934
1935 return dst;
1936}
1937
1938/* gmt2str_log: write a date in the format :
1939 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1940 * return a pointer to the last char written (\0) or
1941 * NULL if there isn't enough space.
1942 */
1943char *gmt2str_log(char *dst, struct tm *tm, size_t size)
1944{
Yuxans Yao4e25b012012-10-19 10:36:09 +08001945 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01001946 return NULL;
1947
1948 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1949 *dst++ = '/';
1950 memcpy(dst, monthname[tm->tm_mon], 3); // month
1951 dst += 3;
1952 *dst++ = '/';
1953 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1954 *dst++ = ':';
1955 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1956 *dst++ = ':';
1957 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1958 *dst++ = ':';
1959 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1960 *dst++ = ' ';
1961 *dst++ = '+';
1962 *dst++ = '0';
1963 *dst++ = '0';
1964 *dst++ = '0';
1965 *dst++ = '0';
1966 *dst = '\0';
1967
1968 return dst;
1969}
1970
Yuxans Yao4e25b012012-10-19 10:36:09 +08001971/* localdate2str_log: write a date in the format :
1972 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
1973 * * return a pointer to the last char written (\0) or
1974 * * NULL if there isn't enough space.
1975 */
1976char *localdate2str_log(char *dst, struct tm *tm, size_t size)
1977{
1978 if (size < 27) /* the size is fixed: 26 chars + \0 */
1979 return NULL;
1980
1981 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1982 *dst++ = '/';
1983 memcpy(dst, monthname[tm->tm_mon], 3); // month
1984 dst += 3;
1985 *dst++ = '/';
1986 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1987 *dst++ = ':';
1988 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1989 *dst++ = ':';
1990 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1991 *dst++ = ':';
1992 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1993 *dst++ = ' ';
1994 memcpy(dst, localtimezone, 5); // timezone
1995 dst += 5;
1996 *dst = '\0';
1997
1998 return dst;
1999}
2000
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002001/* Dynamically allocates a string of the proper length to hold the formatted
2002 * output. NULL is returned on error. The caller is responsible for freeing the
2003 * memory area using free(). The resulting string is returned in <out> if the
2004 * pointer is not NULL. A previous version of <out> might be used to build the
2005 * new string, and it will be freed before returning if it is not NULL, which
2006 * makes it possible to build complex strings from iterative calls without
2007 * having to care about freeing intermediate values, as in the example below :
2008 *
2009 * memprintf(&err, "invalid argument: '%s'", arg);
2010 * ...
2011 * memprintf(&err, "parser said : <%s>\n", *err);
2012 * ...
2013 * free(*err);
2014 *
2015 * This means that <err> must be initialized to NULL before first invocation.
2016 * The return value also holds the allocated string, which eases error checking
2017 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002018 * passed instead and it will be ignored. The returned message will then also
2019 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002020 *
2021 * It is also convenient to use it without any free except the last one :
2022 * err = NULL;
2023 * if (!fct1(err)) report(*err);
2024 * if (!fct2(err)) report(*err);
2025 * if (!fct3(err)) report(*err);
2026 * free(*err);
2027 */
2028char *memprintf(char **out, const char *format, ...)
2029{
2030 va_list args;
2031 char *ret = NULL;
2032 int allocated = 0;
2033 int needed = 0;
2034
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002035 if (!out)
2036 return NULL;
2037
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002038 do {
2039 /* vsnprintf() will return the required length even when the
2040 * target buffer is NULL. We do this in a loop just in case
2041 * intermediate evaluations get wrong.
2042 */
2043 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002044 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002045 va_end(args);
2046
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002047 if (needed < allocated) {
2048 /* Note: on Solaris 8, the first iteration always
2049 * returns -1 if allocated is zero, so we force a
2050 * retry.
2051 */
2052 if (!allocated)
2053 needed = 0;
2054 else
2055 break;
2056 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002057
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002058 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002059 ret = realloc(ret, allocated);
2060 } while (ret);
2061
2062 if (needed < 0) {
2063 /* an error was encountered */
2064 free(ret);
2065 ret = NULL;
2066 }
2067
2068 if (out) {
2069 free(*out);
2070 *out = ret;
2071 }
2072
2073 return ret;
2074}
William Lallemand421f5b52012-02-06 18:15:57 +01002075
Willy Tarreau21c705b2012-09-14 11:40:36 +02002076/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2077 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002078 * freed by the caller. It also supports being passed a NULL which results in the same
2079 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002080 * Example of use :
2081 * parse(cmd, &err); (callee: memprintf(&err, ...))
2082 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2083 * free(err);
2084 */
2085char *indent_msg(char **out, int level)
2086{
2087 char *ret, *in, *p;
2088 int needed = 0;
2089 int lf = 0;
2090 int lastlf = 0;
2091 int len;
2092
Willy Tarreau70eec382012-10-10 08:56:47 +02002093 if (!out || !*out)
2094 return NULL;
2095
Willy Tarreau21c705b2012-09-14 11:40:36 +02002096 in = *out - 1;
2097 while ((in = strchr(in + 1, '\n')) != NULL) {
2098 lastlf = in - *out;
2099 lf++;
2100 }
2101
2102 if (!lf) /* single line, no LF, return it as-is */
2103 return *out;
2104
2105 len = strlen(*out);
2106
2107 if (lf == 1 && lastlf == len - 1) {
2108 /* single line, LF at end, strip it and return as-is */
2109 (*out)[lastlf] = 0;
2110 return *out;
2111 }
2112
2113 /* OK now we have at least one LF, we need to process the whole string
2114 * as a multi-line string. What we'll do :
2115 * - prefix with an LF if there is none
2116 * - add <level> spaces before each line
2117 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2118 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2119 */
2120
2121 needed = 1 + level * (lf + 1) + len + 1;
2122 p = ret = malloc(needed);
2123 in = *out;
2124
2125 /* skip initial LFs */
2126 while (*in == '\n')
2127 in++;
2128
2129 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2130 while (*in) {
2131 *p++ = '\n';
2132 memset(p, ' ', level);
2133 p += level;
2134 do {
2135 *p++ = *in++;
2136 } while (*in && *in != '\n');
2137 if (*in)
2138 in++;
2139 }
2140 *p = 0;
2141
2142 free(*out);
2143 *out = ret;
2144
2145 return ret;
2146}
2147
Willy Tarreaudad36a32013-03-11 01:20:04 +01002148/* Convert occurrences of environment variables in the input string to their
2149 * corresponding value. A variable is identified as a series of alphanumeric
2150 * characters or underscores following a '$' sign. The <in> string must be
2151 * free()able. NULL returns NULL. The resulting string might be reallocated if
2152 * some expansion is made. Variable names may also be enclosed into braces if
2153 * needed (eg: to concatenate alphanum characters).
2154 */
2155char *env_expand(char *in)
2156{
2157 char *txt_beg;
2158 char *out;
2159 char *txt_end;
2160 char *var_beg;
2161 char *var_end;
2162 char *value;
2163 char *next;
2164 int out_len;
2165 int val_len;
2166
2167 if (!in)
2168 return in;
2169
2170 value = out = NULL;
2171 out_len = 0;
2172
2173 txt_beg = in;
2174 do {
2175 /* look for next '$' sign in <in> */
2176 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2177
2178 if (!*txt_end && !out) /* end and no expansion performed */
2179 return in;
2180
2181 val_len = 0;
2182 next = txt_end;
2183 if (*txt_end == '$') {
2184 char save;
2185
2186 var_beg = txt_end + 1;
2187 if (*var_beg == '{')
2188 var_beg++;
2189
2190 var_end = var_beg;
2191 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2192 var_end++;
2193 }
2194
2195 next = var_end;
2196 if (*var_end == '}' && (var_beg > txt_end + 1))
2197 next++;
2198
2199 /* get value of the variable name at this location */
2200 save = *var_end;
2201 *var_end = '\0';
2202 value = getenv(var_beg);
2203 *var_end = save;
2204 val_len = value ? strlen(value) : 0;
2205 }
2206
2207 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2208 if (txt_end > txt_beg) {
2209 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2210 out_len += txt_end - txt_beg;
2211 }
2212 if (val_len) {
2213 memcpy(out + out_len, value, val_len);
2214 out_len += val_len;
2215 }
2216 out[out_len] = 0;
2217 txt_beg = next;
2218 } while (*txt_beg);
2219
2220 /* here we know that <out> was allocated and that we don't need <in> anymore */
2221 free(in);
2222 return out;
2223}
2224
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002225
2226/* same as strstr() but case-insensitive and with limit length */
2227const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2228{
2229 char *pptr, *sptr, *start;
2230 uint slen, plen;
2231 uint tmp1, tmp2;
2232
2233 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2234 return NULL;
2235
2236 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2237 return str1;
2238
2239 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2240 return NULL;
2241
2242 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2243 while (toupper(*start) != toupper(*str2)) {
2244 start++;
2245 slen--;
2246 tmp1++;
2247
2248 if (tmp1 >= len_str1)
2249 return NULL;
2250
2251 /* if pattern longer than string */
2252 if (slen < plen)
2253 return NULL;
2254 }
2255
2256 sptr = start;
2257 pptr = (char *)str2;
2258
2259 tmp2 = 0;
2260 while (toupper(*sptr) == toupper(*pptr)) {
2261 sptr++;
2262 pptr++;
2263 tmp2++;
2264
2265 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2266 return start;
2267 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2268 return NULL;
2269 }
2270 }
2271 return NULL;
2272}
2273
Willy Tarreaubaaee002006-06-26 02:48:02 +02002274/*
2275 * Local variables:
2276 * c-indent-level: 8
2277 * c-basic-offset: 8
2278 * End:
2279 */