blob: d435c3c5b35617f852919994695cb081df2fa4d4 [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 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100812int str2net(const char *str, int resolve, 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
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100837 if (!resolve)
838 goto out_err;
839
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200840 if ((he = gethostbyname(s)) == NULL) {
841 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200842 }
843 else
844 *addr = *(struct in_addr *) *(he->h_addr_list);
845 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200846
847 ret_val = 1;
848 out_free:
849 free(s);
850 return ret_val;
851 out_err:
852 ret_val = 0;
853 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200854}
855
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100856
857/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200858 * converts <str> to two struct in6_addr* which must be pre-allocated.
859 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
860 * is an optionnal number of bits (128 being the default).
861 * Returns 1 if OK, 0 if error.
862 */
863int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
864{
865 char *c, *s;
866 int ret_val = 0;
867 char *err;
868 unsigned long len = 128;
869
870 s = strdup(str);
871 if (!s)
872 return 0;
873
874 memset(mask, 0, sizeof(*mask));
875 memset(addr, 0, sizeof(*addr));
876
877 if ((c = strrchr(s, '/')) != NULL) {
878 *c++ = '\0'; /* c points to the mask */
879 if (!*c)
880 goto out_free;
881
882 len = strtoul(c, &err, 10);
883 if ((err && *err) || (unsigned)len > 128)
884 goto out_free;
885 }
886 *mask = len; /* OK we have a valid mask in <len> */
887
888 if (!inet_pton(AF_INET6, s, addr))
889 goto out_free;
890
891 ret_val = 1;
892 out_free:
893 free(s);
894 return ret_val;
895}
896
897
898/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100899 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100900 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100901int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100902{
903 int saw_digit, octets, ch;
904 u_char tmp[4], *tp;
905 const char *cp = addr;
906
907 saw_digit = 0;
908 octets = 0;
909 *(tp = tmp) = 0;
910
911 while (*addr) {
912 unsigned char digit = (ch = *addr++) - '0';
913 if (digit > 9 && ch != '.')
914 break;
915 if (digit <= 9) {
916 u_int new = *tp * 10 + digit;
917 if (new > 255)
918 return 0;
919 *tp = new;
920 if (!saw_digit) {
921 if (++octets > 4)
922 return 0;
923 saw_digit = 1;
924 }
925 } else if (ch == '.' && saw_digit) {
926 if (octets == 4)
927 return 0;
928 *++tp = 0;
929 saw_digit = 0;
930 } else
931 return 0;
932 }
933
934 if (octets < 4)
935 return 0;
936
937 memcpy(&dst->s_addr, tmp, 4);
938 return addr-cp-1;
939}
940
941/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100942 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100943 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100944int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100945{
946 const char *curr = url, *cp = url;
947 int ret, url_code = 0;
948 unsigned int http_code = 0;
949
950 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100951
952 /* FIXME: assume IPv4 only for now */
953 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
954 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
955 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100956
957 /* Firstly, try to find :// pattern */
958 while (curr < url+ulen && url_code != 0x3a2f2f) {
959 url_code = ((url_code & 0xffff) << 8);
960 url_code += (unsigned char)*curr++;
961 }
962
963 /* Secondly, if :// pattern is found, verify parsed stuff
964 * before pattern is matching our http pattern.
965 * If so parse ip address and port in uri.
966 *
967 * WARNING: Current code doesn't support dynamic async dns resolver.
968 */
969 if (url_code == 0x3a2f2f) {
970 while (cp < curr - 3)
971 http_code = (http_code << 8) + *cp++;
972 http_code |= 0x20202020; /* Turn everything to lower case */
973
974 /* HTTP url matching */
975 if (http_code == 0x68747470) {
976 /* We are looking for IP address. If you want to parse and
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100977 * resolve hostname found in url, you can use str2sa_range(), but
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100978 * be warned this can slow down global daemon performances
979 * while handling lagging dns responses.
980 */
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200981 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100982 if (!ret)
983 return -1;
984 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100985 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200986 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100987 }
988 return 0;
989 }
990
991 return -1;
992}
993
Willy Tarreau631f01c2011-09-05 00:36:48 +0200994/* Tries to convert a sockaddr_storage address to text form. Upon success, the
995 * address family is returned so that it's easy for the caller to adapt to the
996 * output format. Zero is returned if the address family is not supported. -1
997 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
998 * supported.
999 */
1000int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1001{
1002
1003 void *ptr;
1004
1005 if (size < 5)
1006 return 0;
1007 *str = '\0';
1008
1009 switch (addr->ss_family) {
1010 case AF_INET:
1011 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1012 break;
1013 case AF_INET6:
1014 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1015 break;
1016 case AF_UNIX:
1017 memcpy(str, "unix", 5);
1018 return addr->ss_family;
1019 default:
1020 return 0;
1021 }
1022
1023 if (inet_ntop(addr->ss_family, ptr, str, size))
1024 return addr->ss_family;
1025
1026 /* failed */
1027 return -1;
1028}
1029
Willy Tarreaubaaee002006-06-26 02:48:02 +02001030/* will try to encode the string <string> replacing all characters tagged in
1031 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1032 * prefixed by <escape>, and will store the result between <start> (included)
1033 * and <stop> (excluded), and will always terminate the string with a '\0'
1034 * before <stop>. The position of the '\0' is returned if the conversion
1035 * completes. If bytes are missing between <start> and <stop>, then the
1036 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1037 * cannot even be stored so we return <start> without writing the 0.
1038 * The input string must also be zero-terminated.
1039 */
1040const char hextab[16] = "0123456789ABCDEF";
1041char *encode_string(char *start, char *stop,
1042 const char escape, const fd_set *map,
1043 const char *string)
1044{
1045 if (start < stop) {
1046 stop--; /* reserve one byte for the final '\0' */
1047 while (start < stop && *string != '\0') {
1048 if (!FD_ISSET((unsigned char)(*string), map))
1049 *start++ = *string;
1050 else {
1051 if (start + 3 >= stop)
1052 break;
1053 *start++ = escape;
1054 *start++ = hextab[(*string >> 4) & 15];
1055 *start++ = hextab[*string & 15];
1056 }
1057 string++;
1058 }
1059 *start = '\0';
1060 }
1061 return start;
1062}
1063
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001064/*
1065 * Same behavior as encode_string() above, except that it encodes chunk
1066 * <chunk> instead of a string.
1067 */
1068char *encode_chunk(char *start, char *stop,
1069 const char escape, const fd_set *map,
1070 const struct chunk *chunk)
1071{
1072 char *str = chunk->str;
1073 char *end = chunk->str + chunk->len;
1074
1075 if (start < stop) {
1076 stop--; /* reserve one byte for the final '\0' */
1077 while (start < stop && str < end) {
1078 if (!FD_ISSET((unsigned char)(*str), map))
1079 *start++ = *str;
1080 else {
1081 if (start + 3 >= stop)
1082 break;
1083 *start++ = escape;
1084 *start++ = hextab[(*str >> 4) & 15];
1085 *start++ = hextab[*str & 15];
1086 }
1087 str++;
1088 }
1089 *start = '\0';
1090 }
1091 return start;
1092}
1093
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001094/* Decode an URL-encoded string in-place. The resulting string might
1095 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001096 * aborted, the string is truncated before the issue and a negative value is
1097 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001098 */
1099int url_decode(char *string)
1100{
1101 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001102 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001103
1104 in = string;
1105 out = string;
1106 while (*in) {
1107 switch (*in) {
1108 case '+' :
1109 *out++ = ' ';
1110 break;
1111 case '%' :
1112 if (!ishex(in[1]) || !ishex(in[2]))
1113 goto end;
1114 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1115 in += 2;
1116 break;
1117 default:
1118 *out++ = *in;
1119 break;
1120 }
1121 in++;
1122 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001123 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001124 end:
1125 *out = 0;
1126 return ret;
1127}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001128
Willy Tarreau6911fa42007-03-04 18:06:08 +01001129unsigned int str2ui(const char *s)
1130{
1131 return __str2ui(s);
1132}
1133
1134unsigned int str2uic(const char *s)
1135{
1136 return __str2uic(s);
1137}
1138
1139unsigned int strl2ui(const char *s, int len)
1140{
1141 return __strl2ui(s, len);
1142}
1143
1144unsigned int strl2uic(const char *s, int len)
1145{
1146 return __strl2uic(s, len);
1147}
1148
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001149unsigned int read_uint(const char **s, const char *end)
1150{
1151 return __read_uint(s, end);
1152}
1153
Willy Tarreau6911fa42007-03-04 18:06:08 +01001154/* This one is 7 times faster than strtol() on athlon with checks.
1155 * It returns the value of the number composed of all valid digits read,
1156 * and can process negative numbers too.
1157 */
1158int strl2ic(const char *s, int len)
1159{
1160 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001161 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001162
1163 if (len > 0) {
1164 if (*s != '-') {
1165 /* positive number */
1166 while (len-- > 0) {
1167 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001168 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001169 if (j > 9)
1170 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001171 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001172 }
1173 } else {
1174 /* negative number */
1175 s++;
1176 while (--len > 0) {
1177 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001178 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001179 if (j > 9)
1180 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001181 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001182 }
1183 }
1184 }
1185 return i;
1186}
1187
1188
1189/* This function reads exactly <len> chars from <s> and converts them to a
1190 * signed integer which it stores into <ret>. It accurately detects any error
1191 * (truncated string, invalid chars, overflows). It is meant to be used in
1192 * applications designed for hostile environments. It returns zero when the
1193 * number has successfully been converted, non-zero otherwise. When an error
1194 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1195 * faster than strtol().
1196 */
1197int strl2irc(const char *s, int len, int *ret)
1198{
1199 int i = 0;
1200 int j;
1201
1202 if (!len)
1203 return 1;
1204
1205 if (*s != '-') {
1206 /* positive number */
1207 while (len-- > 0) {
1208 j = (*s++) - '0';
1209 if (j > 9) return 1; /* invalid char */
1210 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1211 i = i * 10;
1212 if (i + j < i) return 1; /* check for addition overflow */
1213 i = i + j;
1214 }
1215 } else {
1216 /* negative number */
1217 s++;
1218 while (--len > 0) {
1219 j = (*s++) - '0';
1220 if (j > 9) return 1; /* invalid char */
1221 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1222 i = i * 10;
1223 if (i - j > i) return 1; /* check for subtract overflow */
1224 i = i - j;
1225 }
1226 }
1227 *ret = i;
1228 return 0;
1229}
1230
1231
1232/* This function reads exactly <len> chars from <s> and converts them to a
1233 * signed integer which it stores into <ret>. It accurately detects any error
1234 * (truncated string, invalid chars, overflows). It is meant to be used in
1235 * applications designed for hostile environments. It returns zero when the
1236 * number has successfully been converted, non-zero otherwise. When an error
1237 * is returned, the <ret> value is left untouched. It is about 3 times slower
1238 * than str2irc().
1239 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001240
1241int strl2llrc(const char *s, int len, long long *ret)
1242{
1243 long long i = 0;
1244 int j;
1245
1246 if (!len)
1247 return 1;
1248
1249 if (*s != '-') {
1250 /* positive number */
1251 while (len-- > 0) {
1252 j = (*s++) - '0';
1253 if (j > 9) return 1; /* invalid char */
1254 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1255 i = i * 10LL;
1256 if (i + j < i) return 1; /* check for addition overflow */
1257 i = i + j;
1258 }
1259 } else {
1260 /* negative number */
1261 s++;
1262 while (--len > 0) {
1263 j = (*s++) - '0';
1264 if (j > 9) return 1; /* invalid char */
1265 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1266 i = i * 10LL;
1267 if (i - j > i) return 1; /* check for subtract overflow */
1268 i = i - j;
1269 }
1270 }
1271 *ret = i;
1272 return 0;
1273}
1274
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001275/* This function is used with pat_parse_dotted_ver(). It converts a string
1276 * composed by two number separated by a dot. Each part must contain in 16 bits
1277 * because internally they will be represented as a 32-bit quantity stored in
1278 * a 64-bit integer. It returns zero when the number has successfully been
1279 * converted, non-zero otherwise. When an error is returned, the <ret> value
1280 * is left untouched.
1281 *
1282 * "1.3" -> 0x0000000000010003
1283 * "65535.65535" -> 0x00000000ffffffff
1284 */
1285int strl2llrc_dotted(const char *text, int len, long long *ret)
1286{
1287 const char *end = &text[len];
1288 const char *p;
1289 long long major, minor;
1290
1291 /* Look for dot. */
1292 for (p = text; p < end; p++)
1293 if (*p == '.')
1294 break;
1295
1296 /* Convert major. */
1297 if (strl2llrc(text, p - text, &major) != 0)
1298 return 1;
1299
1300 /* Check major. */
1301 if (major >= 65536)
1302 return 1;
1303
1304 /* Convert minor. */
1305 minor = 0;
1306 if (p < end)
1307 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1308 return 1;
1309
1310 /* Check minor. */
1311 if (minor >= 65536)
1312 return 1;
1313
1314 /* Compose value. */
1315 *ret = (major << 16) | (minor & 0xffff);
1316 return 0;
1317}
1318
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001319/* This function parses a time value optionally followed by a unit suffix among
1320 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1321 * expected by the caller. The computation does its best to avoid overflows.
1322 * The value is returned in <ret> if everything is fine, and a NULL is returned
1323 * by the function. In case of error, a pointer to the error is returned and
1324 * <ret> is left untouched. Values are automatically rounded up when needed.
1325 */
1326const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1327{
1328 unsigned imult, idiv;
1329 unsigned omult, odiv;
1330 unsigned value;
1331
1332 omult = odiv = 1;
1333
1334 switch (unit_flags & TIME_UNIT_MASK) {
1335 case TIME_UNIT_US: omult = 1000000; break;
1336 case TIME_UNIT_MS: omult = 1000; break;
1337 case TIME_UNIT_S: break;
1338 case TIME_UNIT_MIN: odiv = 60; break;
1339 case TIME_UNIT_HOUR: odiv = 3600; break;
1340 case TIME_UNIT_DAY: odiv = 86400; break;
1341 default: break;
1342 }
1343
1344 value = 0;
1345
1346 while (1) {
1347 unsigned int j;
1348
1349 j = *text - '0';
1350 if (j > 9)
1351 break;
1352 text++;
1353 value *= 10;
1354 value += j;
1355 }
1356
1357 imult = idiv = 1;
1358 switch (*text) {
1359 case '\0': /* no unit = default unit */
1360 imult = omult = idiv = odiv = 1;
1361 break;
1362 case 's': /* second = unscaled unit */
1363 break;
1364 case 'u': /* microsecond : "us" */
1365 if (text[1] == 's') {
1366 idiv = 1000000;
1367 text++;
1368 }
1369 break;
1370 case 'm': /* millisecond : "ms" or minute: "m" */
1371 if (text[1] == 's') {
1372 idiv = 1000;
1373 text++;
1374 } else
1375 imult = 60;
1376 break;
1377 case 'h': /* hour : "h" */
1378 imult = 3600;
1379 break;
1380 case 'd': /* day : "d" */
1381 imult = 86400;
1382 break;
1383 default:
1384 return text;
1385 break;
1386 }
1387
1388 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1389 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1390 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1391 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1392
1393 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1394 *ret = value;
1395 return NULL;
1396}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001397
Emeric Brun39132b22010-01-04 14:57:24 +01001398/* this function converts the string starting at <text> to an unsigned int
1399 * stored in <ret>. If an error is detected, the pointer to the unexpected
1400 * character is returned. If the conversio is succesful, NULL is returned.
1401 */
1402const char *parse_size_err(const char *text, unsigned *ret) {
1403 unsigned value = 0;
1404
1405 while (1) {
1406 unsigned int j;
1407
1408 j = *text - '0';
1409 if (j > 9)
1410 break;
1411 if (value > ~0U / 10)
1412 return text;
1413 value *= 10;
1414 if (value > (value + j))
1415 return text;
1416 value += j;
1417 text++;
1418 }
1419
1420 switch (*text) {
1421 case '\0':
1422 break;
1423 case 'K':
1424 case 'k':
1425 if (value > ~0U >> 10)
1426 return text;
1427 value = value << 10;
1428 break;
1429 case 'M':
1430 case 'm':
1431 if (value > ~0U >> 20)
1432 return text;
1433 value = value << 20;
1434 break;
1435 case 'G':
1436 case 'g':
1437 if (value > ~0U >> 30)
1438 return text;
1439 value = value << 30;
1440 break;
1441 default:
1442 return text;
1443 }
1444
1445 *ret = value;
1446 return NULL;
1447}
1448
Willy Tarreau126d4062013-12-03 17:50:47 +01001449/*
1450 * Parse binary string written in hexadecimal (source) and store the decoded
1451 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1452 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001453 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001454 */
1455int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1456{
1457 int len;
1458 const char *p = source;
1459 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001460 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001461
1462 len = strlen(source);
1463 if (len % 2) {
1464 memprintf(err, "an even number of hex digit is expected");
1465 return 0;
1466 }
1467
1468 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001469
Willy Tarreau126d4062013-12-03 17:50:47 +01001470 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001471 *binstr = calloc(len, sizeof(char));
1472 if (!*binstr) {
1473 memprintf(err, "out of memory while loading string pattern");
1474 return 0;
1475 }
1476 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001477 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001478 else {
1479 if (*binstrlen < len) {
1480 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1481 len, *binstrlen);
1482 return 0;
1483 }
1484 alloc = 0;
1485 }
1486 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001487
1488 i = j = 0;
1489 while (j < len) {
1490 if (!ishex(p[i++]))
1491 goto bad_input;
1492 if (!ishex(p[i++]))
1493 goto bad_input;
1494 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1495 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001496 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001497
1498bad_input:
1499 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001500 if (alloc)
1501 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001502 return 0;
1503}
1504
Willy Tarreau946ba592009-05-10 15:41:18 +02001505/* copies at most <n> characters from <src> and always terminates with '\0' */
1506char *my_strndup(const char *src, int n)
1507{
1508 int len = 0;
1509 char *ret;
1510
1511 while (len < n && src[len])
1512 len++;
1513
1514 ret = (char *)malloc(len + 1);
1515 if (!ret)
1516 return ret;
1517 memcpy(ret, src, len);
1518 ret[len] = '\0';
1519 return ret;
1520}
1521
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001522/*
1523 * search needle in haystack
1524 * returns the pointer if found, returns NULL otherwise
1525 */
1526const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1527{
1528 const void *c = NULL;
1529 unsigned char f;
1530
1531 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1532 return NULL;
1533
1534 f = *(char *)needle;
1535 c = haystack;
1536 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1537 if ((haystacklen - (c - haystack)) < needlelen)
1538 return NULL;
1539
1540 if (memcmp(c, needle, needlelen) == 0)
1541 return c;
1542 ++c;
1543 }
1544 return NULL;
1545}
1546
Willy Tarreau482b00d2009-10-04 22:48:42 +02001547/* This function returns the first unused key greater than or equal to <key> in
1548 * ID tree <root>. Zero is returned if no place is found.
1549 */
1550unsigned int get_next_id(struct eb_root *root, unsigned int key)
1551{
1552 struct eb32_node *used;
1553
1554 do {
1555 used = eb32_lookup_ge(root, key);
1556 if (!used || used->key > key)
1557 return key; /* key is available */
1558 key++;
1559 } while (key);
1560 return key;
1561}
1562
Willy Tarreau348238b2010-01-18 15:05:57 +01001563/* This function compares a sample word possibly followed by blanks to another
1564 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1565 * otherwise zero. This intends to be used when checking HTTP headers for some
1566 * values. Note that it validates a word followed only by blanks but does not
1567 * validate a word followed by blanks then other chars.
1568 */
1569int word_match(const char *sample, int slen, const char *word, int wlen)
1570{
1571 if (slen < wlen)
1572 return 0;
1573
1574 while (wlen) {
1575 char c = *sample ^ *word;
1576 if (c && c != ('A' ^ 'a'))
1577 return 0;
1578 sample++;
1579 word++;
1580 slen--;
1581 wlen--;
1582 }
1583
1584 while (slen) {
1585 if (*sample != ' ' && *sample != '\t')
1586 return 0;
1587 sample++;
1588 slen--;
1589 }
1590 return 1;
1591}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001592
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001593/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1594 * is particularly fast because it avoids expensive operations such as
1595 * multiplies, which are optimized away at the end. It requires a properly
1596 * formated address though (3 points).
1597 */
1598unsigned int inetaddr_host(const char *text)
1599{
1600 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1601 register unsigned int dig100, dig10, dig1;
1602 int s;
1603 const char *p, *d;
1604
1605 dig1 = dig10 = dig100 = ascii_zero;
1606 s = 24;
1607
1608 p = text;
1609 while (1) {
1610 if (((unsigned)(*p - '0')) <= 9) {
1611 p++;
1612 continue;
1613 }
1614
1615 /* here, we have a complete byte between <text> and <p> (exclusive) */
1616 if (p == text)
1617 goto end;
1618
1619 d = p - 1;
1620 dig1 |= (unsigned int)(*d << s);
1621 if (d == text)
1622 goto end;
1623
1624 d--;
1625 dig10 |= (unsigned int)(*d << s);
1626 if (d == text)
1627 goto end;
1628
1629 d--;
1630 dig100 |= (unsigned int)(*d << s);
1631 end:
1632 if (!s || *p != '.')
1633 break;
1634
1635 s -= 8;
1636 text = ++p;
1637 }
1638
1639 dig100 -= ascii_zero;
1640 dig10 -= ascii_zero;
1641 dig1 -= ascii_zero;
1642 return ((dig100 * 10) + dig10) * 10 + dig1;
1643}
1644
1645/*
1646 * Idem except the first unparsed character has to be passed in <stop>.
1647 */
1648unsigned int inetaddr_host_lim(const char *text, const char *stop)
1649{
1650 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1651 register unsigned int dig100, dig10, dig1;
1652 int s;
1653 const char *p, *d;
1654
1655 dig1 = dig10 = dig100 = ascii_zero;
1656 s = 24;
1657
1658 p = text;
1659 while (1) {
1660 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1661 p++;
1662 continue;
1663 }
1664
1665 /* here, we have a complete byte between <text> and <p> (exclusive) */
1666 if (p == text)
1667 goto end;
1668
1669 d = p - 1;
1670 dig1 |= (unsigned int)(*d << s);
1671 if (d == text)
1672 goto end;
1673
1674 d--;
1675 dig10 |= (unsigned int)(*d << s);
1676 if (d == text)
1677 goto end;
1678
1679 d--;
1680 dig100 |= (unsigned int)(*d << s);
1681 end:
1682 if (!s || p == stop || *p != '.')
1683 break;
1684
1685 s -= 8;
1686 text = ++p;
1687 }
1688
1689 dig100 -= ascii_zero;
1690 dig10 -= ascii_zero;
1691 dig1 -= ascii_zero;
1692 return ((dig100 * 10) + dig10) * 10 + dig1;
1693}
1694
1695/*
1696 * Idem except the pointer to first unparsed byte is returned into <ret> which
1697 * must not be NULL.
1698 */
Willy Tarreau74172752010-10-15 23:21:42 +02001699unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001700{
1701 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1702 register unsigned int dig100, dig10, dig1;
1703 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001704 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001705
1706 dig1 = dig10 = dig100 = ascii_zero;
1707 s = 24;
1708
1709 p = text;
1710 while (1) {
1711 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1712 p++;
1713 continue;
1714 }
1715
1716 /* here, we have a complete byte between <text> and <p> (exclusive) */
1717 if (p == text)
1718 goto end;
1719
1720 d = p - 1;
1721 dig1 |= (unsigned int)(*d << s);
1722 if (d == text)
1723 goto end;
1724
1725 d--;
1726 dig10 |= (unsigned int)(*d << s);
1727 if (d == text)
1728 goto end;
1729
1730 d--;
1731 dig100 |= (unsigned int)(*d << s);
1732 end:
1733 if (!s || p == stop || *p != '.')
1734 break;
1735
1736 s -= 8;
1737 text = ++p;
1738 }
1739
1740 *ret = p;
1741 dig100 -= ascii_zero;
1742 dig10 -= ascii_zero;
1743 dig1 -= ascii_zero;
1744 return ((dig100 * 10) + dig10) * 10 + dig1;
1745}
1746
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001747/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1748 * or the number of chars read in case of success. Maybe this could be replaced
1749 * by one of the functions above. Also, apparently this function does not support
1750 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001751 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001752 */
1753int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1754{
1755 const char *addr;
1756 int saw_digit, octets, ch;
1757 u_char tmp[4], *tp;
1758 const char *cp = buf;
1759
1760 saw_digit = 0;
1761 octets = 0;
1762 *(tp = tmp) = 0;
1763
1764 for (addr = buf; addr - buf < len; addr++) {
1765 unsigned char digit = (ch = *addr) - '0';
1766
1767 if (digit > 9 && ch != '.')
1768 break;
1769
1770 if (digit <= 9) {
1771 u_int new = *tp * 10 + digit;
1772
1773 if (new > 255)
1774 return 0;
1775
1776 *tp = new;
1777
1778 if (!saw_digit) {
1779 if (++octets > 4)
1780 return 0;
1781 saw_digit = 1;
1782 }
1783 } else if (ch == '.' && saw_digit) {
1784 if (octets == 4)
1785 return 0;
1786
1787 *++tp = 0;
1788 saw_digit = 0;
1789 } else
1790 return 0;
1791 }
1792
1793 if (octets < 4)
1794 return 0;
1795
1796 memcpy(&dst->s_addr, tmp, 4);
1797 return addr - cp;
1798}
1799
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001800/* This function converts the string in <buf> of the len <len> to
1801 * struct in6_addr <dst> which must be allocated by the caller.
1802 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01001803 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001804 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001805int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
1806{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001807 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01001808 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001809
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001810 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001811 return 0;
1812
1813 memcpy(null_term_ip6, buf, len);
1814 null_term_ip6[len] = '\0';
1815
Willy Tarreau075415a2013-12-12 11:29:39 +01001816 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001817 return 0;
1818
Willy Tarreau075415a2013-12-12 11:29:39 +01001819 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001820 return 1;
1821}
1822
Willy Tarreauacf95772010-06-14 19:09:21 +02001823/* To be used to quote config arg positions. Returns the short string at <ptr>
1824 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1825 * if ptr is NULL or empty. The string is locally allocated.
1826 */
1827const char *quote_arg(const char *ptr)
1828{
1829 static char val[32];
1830 int i;
1831
1832 if (!ptr || !*ptr)
1833 return "end of line";
1834 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001835 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001836 val[i] = *ptr++;
1837 val[i++] = '\'';
1838 val[i] = '\0';
1839 return val;
1840}
1841
Willy Tarreau5b180202010-07-18 10:40:48 +02001842/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1843int get_std_op(const char *str)
1844{
1845 int ret = -1;
1846
1847 if (*str == 'e' && str[1] == 'q')
1848 ret = STD_OP_EQ;
1849 else if (*str == 'n' && str[1] == 'e')
1850 ret = STD_OP_NE;
1851 else if (*str == 'l') {
1852 if (str[1] == 'e') ret = STD_OP_LE;
1853 else if (str[1] == 't') ret = STD_OP_LT;
1854 }
1855 else if (*str == 'g') {
1856 if (str[1] == 'e') ret = STD_OP_GE;
1857 else if (str[1] == 't') ret = STD_OP_GT;
1858 }
1859
1860 if (ret == -1 || str[2] != '\0')
1861 return -1;
1862 return ret;
1863}
1864
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001865/* hash a 32-bit integer to another 32-bit integer */
1866unsigned int full_hash(unsigned int a)
1867{
1868 return __full_hash(a);
1869}
1870
David du Colombier4f92d322011-03-24 11:09:31 +01001871/* Return non-zero if IPv4 address is part of the network,
1872 * otherwise zero.
1873 */
1874int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1875{
1876 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1877}
1878
1879/* Return non-zero if IPv6 address is part of the network,
1880 * otherwise zero.
1881 */
1882int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1883{
1884 int i;
1885
1886 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1887 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1888 (((int *)net)[i] & ((int *)mask)[i]))
1889 return 0;
1890 return 1;
1891}
1892
1893/* RFC 4291 prefix */
1894const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1895 0x00, 0x00, 0x00, 0x00,
1896 0x00, 0x00, 0xFF, 0xFF };
1897
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001898/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
1899 * Input and output may overlap.
1900 */
David du Colombier4f92d322011-03-24 11:09:31 +01001901void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1902{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001903 struct in_addr tmp_addr;
1904
1905 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01001906 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001907 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01001908}
1909
1910/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1911 * Return true if conversion is possible and false otherwise.
1912 */
1913int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1914{
1915 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1916 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1917 sizeof(struct in_addr));
1918 return 1;
1919 }
1920
1921 return 0;
1922}
1923
William Lallemand421f5b52012-02-06 18:15:57 +01001924char *human_time(int t, short hz_div) {
1925 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1926 char *p = rv;
1927 int cnt=2; // print two numbers
1928
1929 if (unlikely(t < 0 || hz_div <= 0)) {
1930 sprintf(p, "?");
1931 return rv;
1932 }
1933
1934 if (unlikely(hz_div > 1))
1935 t /= hz_div;
1936
1937 if (t >= DAY) {
1938 p += sprintf(p, "%dd", t / DAY);
1939 cnt--;
1940 }
1941
1942 if (cnt && t % DAY / HOUR) {
1943 p += sprintf(p, "%dh", t % DAY / HOUR);
1944 cnt--;
1945 }
1946
1947 if (cnt && t % HOUR / MINUTE) {
1948 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1949 cnt--;
1950 }
1951
1952 if ((cnt && t % MINUTE) || !t) // also display '0s'
1953 p += sprintf(p, "%ds", t % MINUTE / SEC);
1954
1955 return rv;
1956}
1957
1958const char *monthname[12] = {
1959 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1960 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1961};
1962
1963/* date2str_log: write a date in the format :
1964 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1965 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1966 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1967 *
1968 * without using sprintf. return a pointer to the last char written (\0) or
1969 * NULL if there isn't enough space.
1970 */
1971char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1972{
1973
1974 if (size < 25) /* the size is fixed: 24 chars + \0 */
1975 return NULL;
1976
1977 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1978 *dst++ = '/';
1979 memcpy(dst, monthname[tm->tm_mon], 3); // month
1980 dst += 3;
1981 *dst++ = '/';
1982 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1983 *dst++ = ':';
1984 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1985 *dst++ = ':';
1986 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1987 *dst++ = ':';
1988 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1989 *dst++ = '.';
1990 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1991 dst += 3; // only the 3 first digits
1992 *dst = '\0';
1993
1994 return dst;
1995}
1996
1997/* gmt2str_log: write a date in the format :
1998 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1999 * return a pointer to the last char written (\0) or
2000 * NULL if there isn't enough space.
2001 */
2002char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2003{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002004 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002005 return NULL;
2006
2007 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2008 *dst++ = '/';
2009 memcpy(dst, monthname[tm->tm_mon], 3); // month
2010 dst += 3;
2011 *dst++ = '/';
2012 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2013 *dst++ = ':';
2014 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2015 *dst++ = ':';
2016 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2017 *dst++ = ':';
2018 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2019 *dst++ = ' ';
2020 *dst++ = '+';
2021 *dst++ = '0';
2022 *dst++ = '0';
2023 *dst++ = '0';
2024 *dst++ = '0';
2025 *dst = '\0';
2026
2027 return dst;
2028}
2029
Yuxans Yao4e25b012012-10-19 10:36:09 +08002030/* localdate2str_log: write a date in the format :
2031 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2032 * * return a pointer to the last char written (\0) or
2033 * * NULL if there isn't enough space.
2034 */
2035char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2036{
2037 if (size < 27) /* the size is fixed: 26 chars + \0 */
2038 return NULL;
2039
2040 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2041 *dst++ = '/';
2042 memcpy(dst, monthname[tm->tm_mon], 3); // month
2043 dst += 3;
2044 *dst++ = '/';
2045 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2046 *dst++ = ':';
2047 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2048 *dst++ = ':';
2049 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2050 *dst++ = ':';
2051 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2052 *dst++ = ' ';
2053 memcpy(dst, localtimezone, 5); // timezone
2054 dst += 5;
2055 *dst = '\0';
2056
2057 return dst;
2058}
2059
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002060/* Dynamically allocates a string of the proper length to hold the formatted
2061 * output. NULL is returned on error. The caller is responsible for freeing the
2062 * memory area using free(). The resulting string is returned in <out> if the
2063 * pointer is not NULL. A previous version of <out> might be used to build the
2064 * new string, and it will be freed before returning if it is not NULL, which
2065 * makes it possible to build complex strings from iterative calls without
2066 * having to care about freeing intermediate values, as in the example below :
2067 *
2068 * memprintf(&err, "invalid argument: '%s'", arg);
2069 * ...
2070 * memprintf(&err, "parser said : <%s>\n", *err);
2071 * ...
2072 * free(*err);
2073 *
2074 * This means that <err> must be initialized to NULL before first invocation.
2075 * The return value also holds the allocated string, which eases error checking
2076 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002077 * passed instead and it will be ignored. The returned message will then also
2078 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002079 *
2080 * It is also convenient to use it without any free except the last one :
2081 * err = NULL;
2082 * if (!fct1(err)) report(*err);
2083 * if (!fct2(err)) report(*err);
2084 * if (!fct3(err)) report(*err);
2085 * free(*err);
2086 */
2087char *memprintf(char **out, const char *format, ...)
2088{
2089 va_list args;
2090 char *ret = NULL;
2091 int allocated = 0;
2092 int needed = 0;
2093
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002094 if (!out)
2095 return NULL;
2096
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002097 do {
2098 /* vsnprintf() will return the required length even when the
2099 * target buffer is NULL. We do this in a loop just in case
2100 * intermediate evaluations get wrong.
2101 */
2102 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002103 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002104 va_end(args);
2105
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002106 if (needed < allocated) {
2107 /* Note: on Solaris 8, the first iteration always
2108 * returns -1 if allocated is zero, so we force a
2109 * retry.
2110 */
2111 if (!allocated)
2112 needed = 0;
2113 else
2114 break;
2115 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002116
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002117 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002118 ret = realloc(ret, allocated);
2119 } while (ret);
2120
2121 if (needed < 0) {
2122 /* an error was encountered */
2123 free(ret);
2124 ret = NULL;
2125 }
2126
2127 if (out) {
2128 free(*out);
2129 *out = ret;
2130 }
2131
2132 return ret;
2133}
William Lallemand421f5b52012-02-06 18:15:57 +01002134
Willy Tarreau21c705b2012-09-14 11:40:36 +02002135/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2136 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002137 * freed by the caller. It also supports being passed a NULL which results in the same
2138 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002139 * Example of use :
2140 * parse(cmd, &err); (callee: memprintf(&err, ...))
2141 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2142 * free(err);
2143 */
2144char *indent_msg(char **out, int level)
2145{
2146 char *ret, *in, *p;
2147 int needed = 0;
2148 int lf = 0;
2149 int lastlf = 0;
2150 int len;
2151
Willy Tarreau70eec382012-10-10 08:56:47 +02002152 if (!out || !*out)
2153 return NULL;
2154
Willy Tarreau21c705b2012-09-14 11:40:36 +02002155 in = *out - 1;
2156 while ((in = strchr(in + 1, '\n')) != NULL) {
2157 lastlf = in - *out;
2158 lf++;
2159 }
2160
2161 if (!lf) /* single line, no LF, return it as-is */
2162 return *out;
2163
2164 len = strlen(*out);
2165
2166 if (lf == 1 && lastlf == len - 1) {
2167 /* single line, LF at end, strip it and return as-is */
2168 (*out)[lastlf] = 0;
2169 return *out;
2170 }
2171
2172 /* OK now we have at least one LF, we need to process the whole string
2173 * as a multi-line string. What we'll do :
2174 * - prefix with an LF if there is none
2175 * - add <level> spaces before each line
2176 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2177 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2178 */
2179
2180 needed = 1 + level * (lf + 1) + len + 1;
2181 p = ret = malloc(needed);
2182 in = *out;
2183
2184 /* skip initial LFs */
2185 while (*in == '\n')
2186 in++;
2187
2188 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2189 while (*in) {
2190 *p++ = '\n';
2191 memset(p, ' ', level);
2192 p += level;
2193 do {
2194 *p++ = *in++;
2195 } while (*in && *in != '\n');
2196 if (*in)
2197 in++;
2198 }
2199 *p = 0;
2200
2201 free(*out);
2202 *out = ret;
2203
2204 return ret;
2205}
2206
Willy Tarreaudad36a32013-03-11 01:20:04 +01002207/* Convert occurrences of environment variables in the input string to their
2208 * corresponding value. A variable is identified as a series of alphanumeric
2209 * characters or underscores following a '$' sign. The <in> string must be
2210 * free()able. NULL returns NULL. The resulting string might be reallocated if
2211 * some expansion is made. Variable names may also be enclosed into braces if
2212 * needed (eg: to concatenate alphanum characters).
2213 */
2214char *env_expand(char *in)
2215{
2216 char *txt_beg;
2217 char *out;
2218 char *txt_end;
2219 char *var_beg;
2220 char *var_end;
2221 char *value;
2222 char *next;
2223 int out_len;
2224 int val_len;
2225
2226 if (!in)
2227 return in;
2228
2229 value = out = NULL;
2230 out_len = 0;
2231
2232 txt_beg = in;
2233 do {
2234 /* look for next '$' sign in <in> */
2235 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2236
2237 if (!*txt_end && !out) /* end and no expansion performed */
2238 return in;
2239
2240 val_len = 0;
2241 next = txt_end;
2242 if (*txt_end == '$') {
2243 char save;
2244
2245 var_beg = txt_end + 1;
2246 if (*var_beg == '{')
2247 var_beg++;
2248
2249 var_end = var_beg;
2250 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2251 var_end++;
2252 }
2253
2254 next = var_end;
2255 if (*var_end == '}' && (var_beg > txt_end + 1))
2256 next++;
2257
2258 /* get value of the variable name at this location */
2259 save = *var_end;
2260 *var_end = '\0';
2261 value = getenv(var_beg);
2262 *var_end = save;
2263 val_len = value ? strlen(value) : 0;
2264 }
2265
2266 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2267 if (txt_end > txt_beg) {
2268 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2269 out_len += txt_end - txt_beg;
2270 }
2271 if (val_len) {
2272 memcpy(out + out_len, value, val_len);
2273 out_len += val_len;
2274 }
2275 out[out_len] = 0;
2276 txt_beg = next;
2277 } while (*txt_beg);
2278
2279 /* here we know that <out> was allocated and that we don't need <in> anymore */
2280 free(in);
2281 return out;
2282}
2283
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002284
2285/* same as strstr() but case-insensitive and with limit length */
2286const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2287{
2288 char *pptr, *sptr, *start;
2289 uint slen, plen;
2290 uint tmp1, tmp2;
2291
2292 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2293 return NULL;
2294
2295 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2296 return str1;
2297
2298 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2299 return NULL;
2300
2301 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2302 while (toupper(*start) != toupper(*str2)) {
2303 start++;
2304 slen--;
2305 tmp1++;
2306
2307 if (tmp1 >= len_str1)
2308 return NULL;
2309
2310 /* if pattern longer than string */
2311 if (slen < plen)
2312 return NULL;
2313 }
2314
2315 sptr = start;
2316 pptr = (char *)str2;
2317
2318 tmp2 = 0;
2319 while (toupper(*sptr) == toupper(*pptr)) {
2320 sptr++;
2321 pptr++;
2322 tmp2++;
2323
2324 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2325 return start;
2326 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2327 return NULL;
2328 }
2329 }
2330 return NULL;
2331}
2332
Willy Tarreaubaaee002006-06-26 02:48:02 +02002333/*
2334 * Local variables:
2335 * c-indent-level: 8
2336 * c-basic-offset: 8
2337 * End:
2338 */