blob: 81df8b194915d3020da71df92e9010b83c63c090 [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
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001260/* This function is used with pat_parse_dotted_ver(). It converts a string
1261 * composed by two number separated by a dot. Each part must contain in 16 bits
1262 * because internally they will be represented as a 32-bit quantity stored in
1263 * a 64-bit integer. It returns zero when the number has successfully been
1264 * converted, non-zero otherwise. When an error is returned, the <ret> value
1265 * is left untouched.
1266 *
1267 * "1.3" -> 0x0000000000010003
1268 * "65535.65535" -> 0x00000000ffffffff
1269 */
1270int strl2llrc_dotted(const char *text, int len, long long *ret)
1271{
1272 const char *end = &text[len];
1273 const char *p;
1274 long long major, minor;
1275
1276 /* Look for dot. */
1277 for (p = text; p < end; p++)
1278 if (*p == '.')
1279 break;
1280
1281 /* Convert major. */
1282 if (strl2llrc(text, p - text, &major) != 0)
1283 return 1;
1284
1285 /* Check major. */
1286 if (major >= 65536)
1287 return 1;
1288
1289 /* Convert minor. */
1290 minor = 0;
1291 if (p < end)
1292 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1293 return 1;
1294
1295 /* Check minor. */
1296 if (minor >= 65536)
1297 return 1;
1298
1299 /* Compose value. */
1300 *ret = (major << 16) | (minor & 0xffff);
1301 return 0;
1302}
1303
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001304/* This function parses a time value optionally followed by a unit suffix among
1305 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1306 * expected by the caller. The computation does its best to avoid overflows.
1307 * The value is returned in <ret> if everything is fine, and a NULL is returned
1308 * by the function. In case of error, a pointer to the error is returned and
1309 * <ret> is left untouched. Values are automatically rounded up when needed.
1310 */
1311const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1312{
1313 unsigned imult, idiv;
1314 unsigned omult, odiv;
1315 unsigned value;
1316
1317 omult = odiv = 1;
1318
1319 switch (unit_flags & TIME_UNIT_MASK) {
1320 case TIME_UNIT_US: omult = 1000000; break;
1321 case TIME_UNIT_MS: omult = 1000; break;
1322 case TIME_UNIT_S: break;
1323 case TIME_UNIT_MIN: odiv = 60; break;
1324 case TIME_UNIT_HOUR: odiv = 3600; break;
1325 case TIME_UNIT_DAY: odiv = 86400; break;
1326 default: break;
1327 }
1328
1329 value = 0;
1330
1331 while (1) {
1332 unsigned int j;
1333
1334 j = *text - '0';
1335 if (j > 9)
1336 break;
1337 text++;
1338 value *= 10;
1339 value += j;
1340 }
1341
1342 imult = idiv = 1;
1343 switch (*text) {
1344 case '\0': /* no unit = default unit */
1345 imult = omult = idiv = odiv = 1;
1346 break;
1347 case 's': /* second = unscaled unit */
1348 break;
1349 case 'u': /* microsecond : "us" */
1350 if (text[1] == 's') {
1351 idiv = 1000000;
1352 text++;
1353 }
1354 break;
1355 case 'm': /* millisecond : "ms" or minute: "m" */
1356 if (text[1] == 's') {
1357 idiv = 1000;
1358 text++;
1359 } else
1360 imult = 60;
1361 break;
1362 case 'h': /* hour : "h" */
1363 imult = 3600;
1364 break;
1365 case 'd': /* day : "d" */
1366 imult = 86400;
1367 break;
1368 default:
1369 return text;
1370 break;
1371 }
1372
1373 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1374 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1375 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1376 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1377
1378 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1379 *ret = value;
1380 return NULL;
1381}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001382
Emeric Brun39132b22010-01-04 14:57:24 +01001383/* this function converts the string starting at <text> to an unsigned int
1384 * stored in <ret>. If an error is detected, the pointer to the unexpected
1385 * character is returned. If the conversio is succesful, NULL is returned.
1386 */
1387const char *parse_size_err(const char *text, unsigned *ret) {
1388 unsigned value = 0;
1389
1390 while (1) {
1391 unsigned int j;
1392
1393 j = *text - '0';
1394 if (j > 9)
1395 break;
1396 if (value > ~0U / 10)
1397 return text;
1398 value *= 10;
1399 if (value > (value + j))
1400 return text;
1401 value += j;
1402 text++;
1403 }
1404
1405 switch (*text) {
1406 case '\0':
1407 break;
1408 case 'K':
1409 case 'k':
1410 if (value > ~0U >> 10)
1411 return text;
1412 value = value << 10;
1413 break;
1414 case 'M':
1415 case 'm':
1416 if (value > ~0U >> 20)
1417 return text;
1418 value = value << 20;
1419 break;
1420 case 'G':
1421 case 'g':
1422 if (value > ~0U >> 30)
1423 return text;
1424 value = value << 30;
1425 break;
1426 default:
1427 return text;
1428 }
1429
1430 *ret = value;
1431 return NULL;
1432}
1433
Willy Tarreau126d4062013-12-03 17:50:47 +01001434/*
1435 * Parse binary string written in hexadecimal (source) and store the decoded
1436 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1437 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001438 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001439 */
1440int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1441{
1442 int len;
1443 const char *p = source;
1444 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001445 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001446
1447 len = strlen(source);
1448 if (len % 2) {
1449 memprintf(err, "an even number of hex digit is expected");
1450 return 0;
1451 }
1452
1453 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001454
Willy Tarreau126d4062013-12-03 17:50:47 +01001455 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001456 *binstr = calloc(len, sizeof(char));
1457 if (!*binstr) {
1458 memprintf(err, "out of memory while loading string pattern");
1459 return 0;
1460 }
1461 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001462 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001463 else {
1464 if (*binstrlen < len) {
1465 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1466 len, *binstrlen);
1467 return 0;
1468 }
1469 alloc = 0;
1470 }
1471 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001472
1473 i = j = 0;
1474 while (j < len) {
1475 if (!ishex(p[i++]))
1476 goto bad_input;
1477 if (!ishex(p[i++]))
1478 goto bad_input;
1479 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1480 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001481 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001482
1483bad_input:
1484 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001485 if (alloc)
1486 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001487 return 0;
1488}
1489
Willy Tarreau946ba592009-05-10 15:41:18 +02001490/* copies at most <n> characters from <src> and always terminates with '\0' */
1491char *my_strndup(const char *src, int n)
1492{
1493 int len = 0;
1494 char *ret;
1495
1496 while (len < n && src[len])
1497 len++;
1498
1499 ret = (char *)malloc(len + 1);
1500 if (!ret)
1501 return ret;
1502 memcpy(ret, src, len);
1503 ret[len] = '\0';
1504 return ret;
1505}
1506
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001507/*
1508 * search needle in haystack
1509 * returns the pointer if found, returns NULL otherwise
1510 */
1511const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1512{
1513 const void *c = NULL;
1514 unsigned char f;
1515
1516 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1517 return NULL;
1518
1519 f = *(char *)needle;
1520 c = haystack;
1521 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1522 if ((haystacklen - (c - haystack)) < needlelen)
1523 return NULL;
1524
1525 if (memcmp(c, needle, needlelen) == 0)
1526 return c;
1527 ++c;
1528 }
1529 return NULL;
1530}
1531
Willy Tarreau482b00d2009-10-04 22:48:42 +02001532/* This function returns the first unused key greater than or equal to <key> in
1533 * ID tree <root>. Zero is returned if no place is found.
1534 */
1535unsigned int get_next_id(struct eb_root *root, unsigned int key)
1536{
1537 struct eb32_node *used;
1538
1539 do {
1540 used = eb32_lookup_ge(root, key);
1541 if (!used || used->key > key)
1542 return key; /* key is available */
1543 key++;
1544 } while (key);
1545 return key;
1546}
1547
Willy Tarreau348238b2010-01-18 15:05:57 +01001548/* This function compares a sample word possibly followed by blanks to another
1549 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1550 * otherwise zero. This intends to be used when checking HTTP headers for some
1551 * values. Note that it validates a word followed only by blanks but does not
1552 * validate a word followed by blanks then other chars.
1553 */
1554int word_match(const char *sample, int slen, const char *word, int wlen)
1555{
1556 if (slen < wlen)
1557 return 0;
1558
1559 while (wlen) {
1560 char c = *sample ^ *word;
1561 if (c && c != ('A' ^ 'a'))
1562 return 0;
1563 sample++;
1564 word++;
1565 slen--;
1566 wlen--;
1567 }
1568
1569 while (slen) {
1570 if (*sample != ' ' && *sample != '\t')
1571 return 0;
1572 sample++;
1573 slen--;
1574 }
1575 return 1;
1576}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001577
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001578/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1579 * is particularly fast because it avoids expensive operations such as
1580 * multiplies, which are optimized away at the end. It requires a properly
1581 * formated address though (3 points).
1582 */
1583unsigned int inetaddr_host(const char *text)
1584{
1585 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1586 register unsigned int dig100, dig10, dig1;
1587 int s;
1588 const char *p, *d;
1589
1590 dig1 = dig10 = dig100 = ascii_zero;
1591 s = 24;
1592
1593 p = text;
1594 while (1) {
1595 if (((unsigned)(*p - '0')) <= 9) {
1596 p++;
1597 continue;
1598 }
1599
1600 /* here, we have a complete byte between <text> and <p> (exclusive) */
1601 if (p == text)
1602 goto end;
1603
1604 d = p - 1;
1605 dig1 |= (unsigned int)(*d << s);
1606 if (d == text)
1607 goto end;
1608
1609 d--;
1610 dig10 |= (unsigned int)(*d << s);
1611 if (d == text)
1612 goto end;
1613
1614 d--;
1615 dig100 |= (unsigned int)(*d << s);
1616 end:
1617 if (!s || *p != '.')
1618 break;
1619
1620 s -= 8;
1621 text = ++p;
1622 }
1623
1624 dig100 -= ascii_zero;
1625 dig10 -= ascii_zero;
1626 dig1 -= ascii_zero;
1627 return ((dig100 * 10) + dig10) * 10 + dig1;
1628}
1629
1630/*
1631 * Idem except the first unparsed character has to be passed in <stop>.
1632 */
1633unsigned int inetaddr_host_lim(const char *text, const char *stop)
1634{
1635 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1636 register unsigned int dig100, dig10, dig1;
1637 int s;
1638 const char *p, *d;
1639
1640 dig1 = dig10 = dig100 = ascii_zero;
1641 s = 24;
1642
1643 p = text;
1644 while (1) {
1645 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1646 p++;
1647 continue;
1648 }
1649
1650 /* here, we have a complete byte between <text> and <p> (exclusive) */
1651 if (p == text)
1652 goto end;
1653
1654 d = p - 1;
1655 dig1 |= (unsigned int)(*d << s);
1656 if (d == text)
1657 goto end;
1658
1659 d--;
1660 dig10 |= (unsigned int)(*d << s);
1661 if (d == text)
1662 goto end;
1663
1664 d--;
1665 dig100 |= (unsigned int)(*d << s);
1666 end:
1667 if (!s || p == stop || *p != '.')
1668 break;
1669
1670 s -= 8;
1671 text = ++p;
1672 }
1673
1674 dig100 -= ascii_zero;
1675 dig10 -= ascii_zero;
1676 dig1 -= ascii_zero;
1677 return ((dig100 * 10) + dig10) * 10 + dig1;
1678}
1679
1680/*
1681 * Idem except the pointer to first unparsed byte is returned into <ret> which
1682 * must not be NULL.
1683 */
Willy Tarreau74172752010-10-15 23:21:42 +02001684unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001685{
1686 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1687 register unsigned int dig100, dig10, dig1;
1688 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001689 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001690
1691 dig1 = dig10 = dig100 = ascii_zero;
1692 s = 24;
1693
1694 p = text;
1695 while (1) {
1696 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1697 p++;
1698 continue;
1699 }
1700
1701 /* here, we have a complete byte between <text> and <p> (exclusive) */
1702 if (p == text)
1703 goto end;
1704
1705 d = p - 1;
1706 dig1 |= (unsigned int)(*d << s);
1707 if (d == text)
1708 goto end;
1709
1710 d--;
1711 dig10 |= (unsigned int)(*d << s);
1712 if (d == text)
1713 goto end;
1714
1715 d--;
1716 dig100 |= (unsigned int)(*d << s);
1717 end:
1718 if (!s || p == stop || *p != '.')
1719 break;
1720
1721 s -= 8;
1722 text = ++p;
1723 }
1724
1725 *ret = p;
1726 dig100 -= ascii_zero;
1727 dig10 -= ascii_zero;
1728 dig1 -= ascii_zero;
1729 return ((dig100 * 10) + dig10) * 10 + dig1;
1730}
1731
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001732/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1733 * or the number of chars read in case of success. Maybe this could be replaced
1734 * by one of the functions above. Also, apparently this function does not support
1735 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001736 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001737 */
1738int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1739{
1740 const char *addr;
1741 int saw_digit, octets, ch;
1742 u_char tmp[4], *tp;
1743 const char *cp = buf;
1744
1745 saw_digit = 0;
1746 octets = 0;
1747 *(tp = tmp) = 0;
1748
1749 for (addr = buf; addr - buf < len; addr++) {
1750 unsigned char digit = (ch = *addr) - '0';
1751
1752 if (digit > 9 && ch != '.')
1753 break;
1754
1755 if (digit <= 9) {
1756 u_int new = *tp * 10 + digit;
1757
1758 if (new > 255)
1759 return 0;
1760
1761 *tp = new;
1762
1763 if (!saw_digit) {
1764 if (++octets > 4)
1765 return 0;
1766 saw_digit = 1;
1767 }
1768 } else if (ch == '.' && saw_digit) {
1769 if (octets == 4)
1770 return 0;
1771
1772 *++tp = 0;
1773 saw_digit = 0;
1774 } else
1775 return 0;
1776 }
1777
1778 if (octets < 4)
1779 return 0;
1780
1781 memcpy(&dst->s_addr, tmp, 4);
1782 return addr - cp;
1783}
1784
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001785/* This function converts the string in <buf> of the len <len> to
1786 * struct in6_addr <dst> which must be allocated by the caller.
1787 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01001788 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001789 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001790int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
1791{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001792 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01001793 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001794
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001795 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001796 return 0;
1797
1798 memcpy(null_term_ip6, buf, len);
1799 null_term_ip6[len] = '\0';
1800
Willy Tarreau075415a2013-12-12 11:29:39 +01001801 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001802 return 0;
1803
Willy Tarreau075415a2013-12-12 11:29:39 +01001804 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001805 return 1;
1806}
1807
Willy Tarreauacf95772010-06-14 19:09:21 +02001808/* To be used to quote config arg positions. Returns the short string at <ptr>
1809 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1810 * if ptr is NULL or empty. The string is locally allocated.
1811 */
1812const char *quote_arg(const char *ptr)
1813{
1814 static char val[32];
1815 int i;
1816
1817 if (!ptr || !*ptr)
1818 return "end of line";
1819 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001820 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001821 val[i] = *ptr++;
1822 val[i++] = '\'';
1823 val[i] = '\0';
1824 return val;
1825}
1826
Willy Tarreau5b180202010-07-18 10:40:48 +02001827/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1828int get_std_op(const char *str)
1829{
1830 int ret = -1;
1831
1832 if (*str == 'e' && str[1] == 'q')
1833 ret = STD_OP_EQ;
1834 else if (*str == 'n' && str[1] == 'e')
1835 ret = STD_OP_NE;
1836 else if (*str == 'l') {
1837 if (str[1] == 'e') ret = STD_OP_LE;
1838 else if (str[1] == 't') ret = STD_OP_LT;
1839 }
1840 else if (*str == 'g') {
1841 if (str[1] == 'e') ret = STD_OP_GE;
1842 else if (str[1] == 't') ret = STD_OP_GT;
1843 }
1844
1845 if (ret == -1 || str[2] != '\0')
1846 return -1;
1847 return ret;
1848}
1849
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001850/* hash a 32-bit integer to another 32-bit integer */
1851unsigned int full_hash(unsigned int a)
1852{
1853 return __full_hash(a);
1854}
1855
David du Colombier4f92d322011-03-24 11:09:31 +01001856/* Return non-zero if IPv4 address is part of the network,
1857 * otherwise zero.
1858 */
1859int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1860{
1861 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1862}
1863
1864/* Return non-zero if IPv6 address is part of the network,
1865 * otherwise zero.
1866 */
1867int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1868{
1869 int i;
1870
1871 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1872 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1873 (((int *)net)[i] & ((int *)mask)[i]))
1874 return 0;
1875 return 1;
1876}
1877
1878/* RFC 4291 prefix */
1879const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1880 0x00, 0x00, 0x00, 0x00,
1881 0x00, 0x00, 0xFF, 0xFF };
1882
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001883/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
1884 * Input and output may overlap.
1885 */
David du Colombier4f92d322011-03-24 11:09:31 +01001886void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1887{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001888 struct in_addr tmp_addr;
1889
1890 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01001891 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01001892 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01001893}
1894
1895/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1896 * Return true if conversion is possible and false otherwise.
1897 */
1898int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1899{
1900 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1901 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1902 sizeof(struct in_addr));
1903 return 1;
1904 }
1905
1906 return 0;
1907}
1908
William Lallemand421f5b52012-02-06 18:15:57 +01001909char *human_time(int t, short hz_div) {
1910 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1911 char *p = rv;
1912 int cnt=2; // print two numbers
1913
1914 if (unlikely(t < 0 || hz_div <= 0)) {
1915 sprintf(p, "?");
1916 return rv;
1917 }
1918
1919 if (unlikely(hz_div > 1))
1920 t /= hz_div;
1921
1922 if (t >= DAY) {
1923 p += sprintf(p, "%dd", t / DAY);
1924 cnt--;
1925 }
1926
1927 if (cnt && t % DAY / HOUR) {
1928 p += sprintf(p, "%dh", t % DAY / HOUR);
1929 cnt--;
1930 }
1931
1932 if (cnt && t % HOUR / MINUTE) {
1933 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1934 cnt--;
1935 }
1936
1937 if ((cnt && t % MINUTE) || !t) // also display '0s'
1938 p += sprintf(p, "%ds", t % MINUTE / SEC);
1939
1940 return rv;
1941}
1942
1943const char *monthname[12] = {
1944 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1945 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1946};
1947
1948/* date2str_log: write a date in the format :
1949 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1950 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1951 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1952 *
1953 * without using sprintf. return a pointer to the last char written (\0) or
1954 * NULL if there isn't enough space.
1955 */
1956char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1957{
1958
1959 if (size < 25) /* the size is fixed: 24 chars + \0 */
1960 return NULL;
1961
1962 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1963 *dst++ = '/';
1964 memcpy(dst, monthname[tm->tm_mon], 3); // month
1965 dst += 3;
1966 *dst++ = '/';
1967 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1968 *dst++ = ':';
1969 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1970 *dst++ = ':';
1971 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1972 *dst++ = ':';
1973 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1974 *dst++ = '.';
1975 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1976 dst += 3; // only the 3 first digits
1977 *dst = '\0';
1978
1979 return dst;
1980}
1981
1982/* gmt2str_log: write a date in the format :
1983 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1984 * return a pointer to the last char written (\0) or
1985 * NULL if there isn't enough space.
1986 */
1987char *gmt2str_log(char *dst, struct tm *tm, size_t size)
1988{
Yuxans Yao4e25b012012-10-19 10:36:09 +08001989 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01001990 return NULL;
1991
1992 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1993 *dst++ = '/';
1994 memcpy(dst, monthname[tm->tm_mon], 3); // month
1995 dst += 3;
1996 *dst++ = '/';
1997 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1998 *dst++ = ':';
1999 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2000 *dst++ = ':';
2001 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2002 *dst++ = ':';
2003 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2004 *dst++ = ' ';
2005 *dst++ = '+';
2006 *dst++ = '0';
2007 *dst++ = '0';
2008 *dst++ = '0';
2009 *dst++ = '0';
2010 *dst = '\0';
2011
2012 return dst;
2013}
2014
Yuxans Yao4e25b012012-10-19 10:36:09 +08002015/* localdate2str_log: write a date in the format :
2016 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2017 * * return a pointer to the last char written (\0) or
2018 * * NULL if there isn't enough space.
2019 */
2020char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2021{
2022 if (size < 27) /* the size is fixed: 26 chars + \0 */
2023 return NULL;
2024
2025 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2026 *dst++ = '/';
2027 memcpy(dst, monthname[tm->tm_mon], 3); // month
2028 dst += 3;
2029 *dst++ = '/';
2030 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2031 *dst++ = ':';
2032 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2033 *dst++ = ':';
2034 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2035 *dst++ = ':';
2036 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2037 *dst++ = ' ';
2038 memcpy(dst, localtimezone, 5); // timezone
2039 dst += 5;
2040 *dst = '\0';
2041
2042 return dst;
2043}
2044
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002045/* Dynamically allocates a string of the proper length to hold the formatted
2046 * output. NULL is returned on error. The caller is responsible for freeing the
2047 * memory area using free(). The resulting string is returned in <out> if the
2048 * pointer is not NULL. A previous version of <out> might be used to build the
2049 * new string, and it will be freed before returning if it is not NULL, which
2050 * makes it possible to build complex strings from iterative calls without
2051 * having to care about freeing intermediate values, as in the example below :
2052 *
2053 * memprintf(&err, "invalid argument: '%s'", arg);
2054 * ...
2055 * memprintf(&err, "parser said : <%s>\n", *err);
2056 * ...
2057 * free(*err);
2058 *
2059 * This means that <err> must be initialized to NULL before first invocation.
2060 * The return value also holds the allocated string, which eases error checking
2061 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002062 * passed instead and it will be ignored. The returned message will then also
2063 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002064 *
2065 * It is also convenient to use it without any free except the last one :
2066 * err = NULL;
2067 * if (!fct1(err)) report(*err);
2068 * if (!fct2(err)) report(*err);
2069 * if (!fct3(err)) report(*err);
2070 * free(*err);
2071 */
2072char *memprintf(char **out, const char *format, ...)
2073{
2074 va_list args;
2075 char *ret = NULL;
2076 int allocated = 0;
2077 int needed = 0;
2078
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002079 if (!out)
2080 return NULL;
2081
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002082 do {
2083 /* vsnprintf() will return the required length even when the
2084 * target buffer is NULL. We do this in a loop just in case
2085 * intermediate evaluations get wrong.
2086 */
2087 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002088 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002089 va_end(args);
2090
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002091 if (needed < allocated) {
2092 /* Note: on Solaris 8, the first iteration always
2093 * returns -1 if allocated is zero, so we force a
2094 * retry.
2095 */
2096 if (!allocated)
2097 needed = 0;
2098 else
2099 break;
2100 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002101
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002102 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002103 ret = realloc(ret, allocated);
2104 } while (ret);
2105
2106 if (needed < 0) {
2107 /* an error was encountered */
2108 free(ret);
2109 ret = NULL;
2110 }
2111
2112 if (out) {
2113 free(*out);
2114 *out = ret;
2115 }
2116
2117 return ret;
2118}
William Lallemand421f5b52012-02-06 18:15:57 +01002119
Willy Tarreau21c705b2012-09-14 11:40:36 +02002120/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2121 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002122 * freed by the caller. It also supports being passed a NULL which results in the same
2123 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002124 * Example of use :
2125 * parse(cmd, &err); (callee: memprintf(&err, ...))
2126 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2127 * free(err);
2128 */
2129char *indent_msg(char **out, int level)
2130{
2131 char *ret, *in, *p;
2132 int needed = 0;
2133 int lf = 0;
2134 int lastlf = 0;
2135 int len;
2136
Willy Tarreau70eec382012-10-10 08:56:47 +02002137 if (!out || !*out)
2138 return NULL;
2139
Willy Tarreau21c705b2012-09-14 11:40:36 +02002140 in = *out - 1;
2141 while ((in = strchr(in + 1, '\n')) != NULL) {
2142 lastlf = in - *out;
2143 lf++;
2144 }
2145
2146 if (!lf) /* single line, no LF, return it as-is */
2147 return *out;
2148
2149 len = strlen(*out);
2150
2151 if (lf == 1 && lastlf == len - 1) {
2152 /* single line, LF at end, strip it and return as-is */
2153 (*out)[lastlf] = 0;
2154 return *out;
2155 }
2156
2157 /* OK now we have at least one LF, we need to process the whole string
2158 * as a multi-line string. What we'll do :
2159 * - prefix with an LF if there is none
2160 * - add <level> spaces before each line
2161 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2162 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2163 */
2164
2165 needed = 1 + level * (lf + 1) + len + 1;
2166 p = ret = malloc(needed);
2167 in = *out;
2168
2169 /* skip initial LFs */
2170 while (*in == '\n')
2171 in++;
2172
2173 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2174 while (*in) {
2175 *p++ = '\n';
2176 memset(p, ' ', level);
2177 p += level;
2178 do {
2179 *p++ = *in++;
2180 } while (*in && *in != '\n');
2181 if (*in)
2182 in++;
2183 }
2184 *p = 0;
2185
2186 free(*out);
2187 *out = ret;
2188
2189 return ret;
2190}
2191
Willy Tarreaudad36a32013-03-11 01:20:04 +01002192/* Convert occurrences of environment variables in the input string to their
2193 * corresponding value. A variable is identified as a series of alphanumeric
2194 * characters or underscores following a '$' sign. The <in> string must be
2195 * free()able. NULL returns NULL. The resulting string might be reallocated if
2196 * some expansion is made. Variable names may also be enclosed into braces if
2197 * needed (eg: to concatenate alphanum characters).
2198 */
2199char *env_expand(char *in)
2200{
2201 char *txt_beg;
2202 char *out;
2203 char *txt_end;
2204 char *var_beg;
2205 char *var_end;
2206 char *value;
2207 char *next;
2208 int out_len;
2209 int val_len;
2210
2211 if (!in)
2212 return in;
2213
2214 value = out = NULL;
2215 out_len = 0;
2216
2217 txt_beg = in;
2218 do {
2219 /* look for next '$' sign in <in> */
2220 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2221
2222 if (!*txt_end && !out) /* end and no expansion performed */
2223 return in;
2224
2225 val_len = 0;
2226 next = txt_end;
2227 if (*txt_end == '$') {
2228 char save;
2229
2230 var_beg = txt_end + 1;
2231 if (*var_beg == '{')
2232 var_beg++;
2233
2234 var_end = var_beg;
2235 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2236 var_end++;
2237 }
2238
2239 next = var_end;
2240 if (*var_end == '}' && (var_beg > txt_end + 1))
2241 next++;
2242
2243 /* get value of the variable name at this location */
2244 save = *var_end;
2245 *var_end = '\0';
2246 value = getenv(var_beg);
2247 *var_end = save;
2248 val_len = value ? strlen(value) : 0;
2249 }
2250
2251 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2252 if (txt_end > txt_beg) {
2253 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2254 out_len += txt_end - txt_beg;
2255 }
2256 if (val_len) {
2257 memcpy(out + out_len, value, val_len);
2258 out_len += val_len;
2259 }
2260 out[out_len] = 0;
2261 txt_beg = next;
2262 } while (*txt_beg);
2263
2264 /* here we know that <out> was allocated and that we don't need <in> anymore */
2265 free(in);
2266 return out;
2267}
2268
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002269
2270/* same as strstr() but case-insensitive and with limit length */
2271const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2272{
2273 char *pptr, *sptr, *start;
2274 uint slen, plen;
2275 uint tmp1, tmp2;
2276
2277 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2278 return NULL;
2279
2280 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2281 return str1;
2282
2283 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2284 return NULL;
2285
2286 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2287 while (toupper(*start) != toupper(*str2)) {
2288 start++;
2289 slen--;
2290 tmp1++;
2291
2292 if (tmp1 >= len_str1)
2293 return NULL;
2294
2295 /* if pattern longer than string */
2296 if (slen < plen)
2297 return NULL;
2298 }
2299
2300 sptr = start;
2301 pptr = (char *)str2;
2302
2303 tmp2 = 0;
2304 while (toupper(*sptr) == toupper(*pptr)) {
2305 sptr++;
2306 pptr++;
2307 tmp2++;
2308
2309 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2310 return start;
2311 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2312 return NULL;
2313 }
2314 }
2315 return NULL;
2316}
2317
Willy Tarreaubaaee002006-06-26 02:48:02 +02002318/*
2319 * Local variables:
2320 * c-indent-level: 8
2321 * c-basic-offset: 8
2322 * End:
2323 */