blob: 31f4ddd6fb27d58767dceed7594964853885bdc1 [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
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020024#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020025#include <common/standard.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010026#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020027
Willy Tarreau72d759c2007-10-25 12:14:10 +020028/* enough to store 10 integers of :
29 * 2^64-1 = 18446744073709551615 or
30 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020031 *
32 * The HTML version needs room for adding the 25 characters
33 * '<span class="rls"></span>' around digits at positions 3N+1 in order
34 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020035 */
Willy Tarreaue7239b52009-03-29 13:41:58 +020036char itoa_str[10][171];
Willy Tarreaubaaee002006-06-26 02:48:02 +020037
38/*
William Lallemande7340ec2012-01-24 11:15:39 +010039 * unsigned long long ASCII representation
40 *
41 * return the last char '\0' or NULL if no enough
42 * space in dst
43 */
44char *ulltoa(unsigned long long n, char *dst, size_t size)
45{
46 int i = 0;
47 char *res;
48
49 switch(n) {
50 case 1ULL ... 9ULL:
51 i = 0;
52 break;
53
54 case 10ULL ... 99ULL:
55 i = 1;
56 break;
57
58 case 100ULL ... 999ULL:
59 i = 2;
60 break;
61
62 case 1000ULL ... 9999ULL:
63 i = 3;
64 break;
65
66 case 10000ULL ... 99999ULL:
67 i = 4;
68 break;
69
70 case 100000ULL ... 999999ULL:
71 i = 5;
72 break;
73
74 case 1000000ULL ... 9999999ULL:
75 i = 6;
76 break;
77
78 case 10000000ULL ... 99999999ULL:
79 i = 7;
80 break;
81
82 case 100000000ULL ... 999999999ULL:
83 i = 8;
84 break;
85
86 case 1000000000ULL ... 9999999999ULL:
87 i = 9;
88 break;
89
90 case 10000000000ULL ... 99999999999ULL:
91 i = 10;
92 break;
93
94 case 100000000000ULL ... 999999999999ULL:
95 i = 11;
96 break;
97
98 case 1000000000000ULL ... 9999999999999ULL:
99 i = 12;
100 break;
101
102 case 10000000000000ULL ... 99999999999999ULL:
103 i = 13;
104 break;
105
106 case 100000000000000ULL ... 999999999999999ULL:
107 i = 14;
108 break;
109
110 case 1000000000000000ULL ... 9999999999999999ULL:
111 i = 15;
112 break;
113
114 case 10000000000000000ULL ... 99999999999999999ULL:
115 i = 16;
116 break;
117
118 case 100000000000000000ULL ... 999999999999999999ULL:
119 i = 17;
120 break;
121
122 case 1000000000000000000ULL ... 9999999999999999999ULL:
123 i = 18;
124 break;
125
126 case 10000000000000000000ULL ... ULLONG_MAX:
127 i = 19;
128 break;
129 }
130 if (i + 2 > size) // (i + 1) + '\0'
131 return NULL; // too long
132 res = dst + i + 1;
133 *res = '\0';
134 for (; i >= 0; i--) {
135 dst[i] = n % 10ULL + '0';
136 n /= 10ULL;
137 }
138 return res;
139}
140
141/*
142 * unsigned long ASCII representation
143 *
144 * return the last char '\0' or NULL if no enough
145 * space in dst
146 */
147char *ultoa_o(unsigned long n, char *dst, size_t size)
148{
149 int i = 0;
150 char *res;
151
152 switch (n) {
153 case 0U ... 9UL:
154 i = 0;
155 break;
156
157 case 10U ... 99UL:
158 i = 1;
159 break;
160
161 case 100U ... 999UL:
162 i = 2;
163 break;
164
165 case 1000U ... 9999UL:
166 i = 3;
167 break;
168
169 case 10000U ... 99999UL:
170 i = 4;
171 break;
172
173 case 100000U ... 999999UL:
174 i = 5;
175 break;
176
177 case 1000000U ... 9999999UL:
178 i = 6;
179 break;
180
181 case 10000000U ... 99999999UL:
182 i = 7;
183 break;
184
185 case 100000000U ... 999999999UL:
186 i = 8;
187 break;
188#if __WORDSIZE == 32
189
190 case 1000000000ULL ... ULONG_MAX:
191 i = 9;
192 break;
193
194#elif __WORDSIZE == 64
195
196 case 1000000000ULL ... 9999999999UL:
197 i = 9;
198 break;
199
200 case 10000000000ULL ... 99999999999UL:
201 i = 10;
202 break;
203
204 case 100000000000ULL ... 999999999999UL:
205 i = 11;
206 break;
207
208 case 1000000000000ULL ... 9999999999999UL:
209 i = 12;
210 break;
211
212 case 10000000000000ULL ... 99999999999999UL:
213 i = 13;
214 break;
215
216 case 100000000000000ULL ... 999999999999999UL:
217 i = 14;
218 break;
219
220 case 1000000000000000ULL ... 9999999999999999UL:
221 i = 15;
222 break;
223
224 case 10000000000000000ULL ... 99999999999999999UL:
225 i = 16;
226 break;
227
228 case 100000000000000000ULL ... 999999999999999999UL:
229 i = 17;
230 break;
231
232 case 1000000000000000000ULL ... 9999999999999999999UL:
233 i = 18;
234 break;
235
236 case 10000000000000000000ULL ... ULONG_MAX:
237 i = 19;
238 break;
239
240#endif
241 }
242 if (i + 2 > size) // (i + 1) + '\0'
243 return NULL; // too long
244 res = dst + i + 1;
245 *res = '\0';
246 for (; i >= 0; i--) {
247 dst[i] = n % 10U + '0';
248 n /= 10U;
249 }
250 return res;
251}
252
253/*
254 * signed long ASCII representation
255 *
256 * return the last char '\0' or NULL if no enough
257 * space in dst
258 */
259char *ltoa_o(long int n, char *dst, size_t size)
260{
261 char *pos = dst;
262
263 if (n < 0) {
264 if (size < 3)
265 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
266 *pos = '-';
267 pos++;
268 dst = ultoa_o(-n, pos, size - 1);
269 } else {
270 dst = ultoa_o(n, dst, size);
271 }
272 return dst;
273}
274
275/*
276 * signed long long ASCII representation
277 *
278 * return the last char '\0' or NULL if no enough
279 * space in dst
280 */
281char *lltoa(long long n, char *dst, size_t size)
282{
283 char *pos = dst;
284
285 if (n < 0) {
286 if (size < 3)
287 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
288 *pos = '-';
289 pos++;
290 dst = ulltoa(-n, pos, size - 1);
291 } else {
292 dst = ulltoa(n, dst, size);
293 }
294 return dst;
295}
296
297/*
298 * write a ascii representation of a unsigned into dst,
299 * return a pointer to the last character
300 * Pad the ascii representation with '0', using size.
301 */
302char *utoa_pad(unsigned int n, char *dst, size_t size)
303{
304 int i = 0;
305 char *ret;
306
307 switch(n) {
308 case 0U ... 9U:
309 i = 0;
310 break;
311
312 case 10U ... 99U:
313 i = 1;
314 break;
315
316 case 100U ... 999U:
317 i = 2;
318 break;
319
320 case 1000U ... 9999U:
321 i = 3;
322 break;
323
324 case 10000U ... 99999U:
325 i = 4;
326 break;
327
328 case 100000U ... 999999U:
329 i = 5;
330 break;
331
332 case 1000000U ... 9999999U:
333 i = 6;
334 break;
335
336 case 10000000U ... 99999999U:
337 i = 7;
338 break;
339
340 case 100000000U ... 999999999U:
341 i = 8;
342 break;
343
344 case 1000000000U ... 4294967295U:
345 i = 9;
346 break;
347 }
348 if (i + 2 > size) // (i + 1) + '\0'
349 return NULL; // too long
350 if (i < size)
351 i = size - 2; // padding - '\0'
352
353 ret = dst + i + 1;
354 *ret = '\0';
355 for (; i >= 0; i--) {
356 dst[i] = n % 10U + '0';
357 n /= 10U;
358 }
359 return ret;
360}
361
362/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200363 * copies at most <size-1> chars from <src> to <dst>. Last char is always
364 * set to 0, unless <size> is 0. The number of chars copied is returned
365 * (excluding the terminating zero).
366 * This code has been optimized for size and speed : on x86, it's 45 bytes
367 * long, uses only registers, and consumes only 4 cycles per char.
368 */
369int strlcpy2(char *dst, const char *src, int size)
370{
371 char *orig = dst;
372 if (size) {
373 while (--size && (*dst = *src)) {
374 src++; dst++;
375 }
376 *dst = 0;
377 }
378 return dst - orig;
379}
380
381/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200382 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200383 * the ascii representation for number 'n' in decimal.
384 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100385char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200386{
387 char *pos;
388
Willy Tarreau72d759c2007-10-25 12:14:10 +0200389 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200390 *pos-- = '\0';
391
392 do {
393 *pos-- = '0' + n % 10;
394 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200395 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200396 return pos + 1;
397}
398
Willy Tarreau91092e52007-10-25 16:58:42 +0200399/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200400 * This function simply returns a locally allocated string containing
401 * the ascii representation for number 'n' in decimal, formatted for
402 * HTML output with tags to create visual grouping by 3 digits. The
403 * output needs to support at least 171 characters.
404 */
405const char *ulltoh_r(unsigned long long n, char *buffer, int size)
406{
407 char *start;
408 int digit = 0;
409
410 start = buffer + size;
411 *--start = '\0';
412
413 do {
414 if (digit == 3 && start >= buffer + 7)
415 memcpy(start -= 7, "</span>", 7);
416
417 if (start >= buffer + 1) {
418 *--start = '0' + n % 10;
419 n /= 10;
420 }
421
422 if (digit == 3 && start >= buffer + 18)
423 memcpy(start -= 18, "<span class=\"rls\">", 18);
424
425 if (digit++ == 3)
426 digit = 1;
427 } while (n && start > buffer);
428 return start;
429}
430
431/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200432 * This function simply returns a locally allocated string containing the ascii
433 * representation for number 'n' in decimal, unless n is 0 in which case it
434 * returns the alternate string (or an empty string if the alternate string is
435 * NULL). It use is intended for limits reported in reports, where it's
436 * desirable not to display anything if there is no limit. Warning! it shares
437 * the same vector as ultoa_r().
438 */
439const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
440{
441 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
442}
443
Robert Tsai81ae1952007-12-05 10:47:29 +0100444/*
445 * converts <str> to a struct sockaddr_un* which is locally allocated.
446 * The format is "/path", where "/path" is a path to a UNIX domain socket.
Willy Tarreaud5191e72010-02-09 20:50:45 +0100447 * NULL is returned if the socket path is invalid (too long).
Robert Tsai81ae1952007-12-05 10:47:29 +0100448 */
Willy Tarreaucaf720d2008-03-07 10:07:04 +0100449struct sockaddr_un *str2sun(const char *str)
Robert Tsai81ae1952007-12-05 10:47:29 +0100450{
Willy Tarreau127f9662007-12-06 00:53:51 +0100451 static struct sockaddr_un su;
Robert Tsai81ae1952007-12-05 10:47:29 +0100452 int strsz; /* length included null */
453
Willy Tarreau127f9662007-12-06 00:53:51 +0100454 memset(&su, 0, sizeof(su));
Robert Tsai81ae1952007-12-05 10:47:29 +0100455 strsz = strlen(str) + 1;
Willy Tarreau127f9662007-12-06 00:53:51 +0100456 if (strsz > sizeof(su.sun_path)) {
Willy Tarreaud5191e72010-02-09 20:50:45 +0100457 return NULL;
Willy Tarreaucaf720d2008-03-07 10:07:04 +0100458 } else {
459 su.sun_family = AF_UNIX;
460 memcpy(su.sun_path, str, strsz);
Robert Tsai81ae1952007-12-05 10:47:29 +0100461 }
Willy Tarreau127f9662007-12-06 00:53:51 +0100462 return &su;
Robert Tsai81ae1952007-12-05 10:47:29 +0100463}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200464
465/*
466 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
467 *
468 * It looks like this one would be a good candidate for inlining, but this is
469 * not interesting because it around 35 bytes long and often called multiple
470 * times within the same function.
471 */
472int ishex(char s)
473{
474 s -= '0';
475 if ((unsigned char)s <= 9)
476 return 1;
477 s -= 'A' - '0';
478 if ((unsigned char)s <= 5)
479 return 1;
480 s -= 'a' - 'A';
481 if ((unsigned char)s <= 5)
482 return 1;
483 return 0;
484}
485
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100486/*
Willy Tarreauda3b7c32009-11-02 20:12:52 +0100487 * Return integer equivalent of character <c> for a hex digit (0-9, a-f, A-F),
488 * otherwise -1. This compact form helps gcc produce efficient code.
489 */
490int hex2i(int c)
491{
492 if ((unsigned char)(c -= '0') > 9) {
493 if ((unsigned char)(c -= 'A' - '0') > 5 &&
494 (unsigned char)(c -= 'a' - 'A') > 5)
495 c = -11;
496 c += 10;
497 }
498 return c;
499}
500
501/*
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100502 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
503 * invalid character is found, a pointer to it is returned. If everything is
504 * fine, NULL is returned.
505 */
506const char *invalid_char(const char *name)
507{
508 if (!*name)
509 return name;
510
511 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100512 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100513 *name != '_' && *name != '-')
514 return name;
515 name++;
516 }
517 return NULL;
518}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200519
520/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200521 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
522 * If an invalid character is found, a pointer to it is returned.
523 * If everything is fine, NULL is returned.
524 */
525const char *invalid_domainchar(const char *name) {
526
527 if (!*name)
528 return name;
529
530 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100531 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200532 *name != '_' && *name != '-')
533 return name;
534
535 name++;
536 }
537
538 return NULL;
539}
540
541/*
Willy Tarreaufab5a432011-03-04 15:31:53 +0100542 * converts <str> to a struct sockaddr_storage* which is locally allocated. The
543 * string is assumed to contain only an address, no port. The address can be a
544 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
545 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
546 * The return address will only have the address family and the address set,
547 * all other fields remain zero. The string is not supposed to be modified.
548 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200549 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100550struct sockaddr_storage *str2ip(const char *str)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200551{
David du Colombier6f5ccb12011-03-10 22:26:24 +0100552 static struct sockaddr_storage sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100553 struct hostent *he;
554
555 memset(&sa, 0, sizeof(sa));
556
557 /* Any IPv6 address */
558 if (str[0] == ':' && str[1] == ':' && !str[2]) {
559 sa.ss_family = AF_INET6;
560 return &sa;
561 }
562
563 /* Any IPv4 address */
564 if (!str[0] || (str[0] == '*' && !str[1])) {
565 sa.ss_family = AF_INET;
566 return &sa;
567 }
568
569 /* check for IPv6 first */
570 if (inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)&sa)->sin6_addr)) {
571 sa.ss_family = AF_INET6;
572 return &sa;
573 }
574
575 /* then check for IPv4 */
576 if (inet_pton(AF_INET, str, &((struct sockaddr_in *)&sa)->sin_addr)) {
577 sa.ss_family = AF_INET;
578 return &sa;
579 }
580
581 /* try to resolve an IPv4/IPv6 hostname */
582 he = gethostbyname(str);
583 if (he) {
584 sa.ss_family = he->h_addrtype;
585 switch (sa.ss_family) {
586 case AF_INET:
587 ((struct sockaddr_in *)&sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
588 return &sa;
589 case AF_INET6:
590 ((struct sockaddr_in6 *)&sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
591 return &sa;
592 }
David du Colombierd5f43282011-03-17 10:40:16 +0100593 }
594#ifdef USE_GETADDRINFO
595 else {
596 struct addrinfo hints, *result;
597
598 memset(&result, 0, sizeof(result));
599 memset(&hints, 0, sizeof(hints));
600 hints.ai_family = AF_UNSPEC;
601 hints.ai_socktype = SOCK_DGRAM;
602 hints.ai_flags = AI_PASSIVE;
603 hints.ai_protocol = 0;
604
605 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
606 sa.ss_family = result->ai_family;
607 switch (result->ai_family) {
608 case AF_INET:
609 memcpy((struct sockaddr_in *)&sa, result->ai_addr, result->ai_addrlen);
610 return &sa;
611 case AF_INET6:
612 memcpy((struct sockaddr_in6 *)&sa, result->ai_addr, result->ai_addrlen);
613 return &sa;
614 }
615 }
616
617 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100618 }
David du Colombierd5f43282011-03-17 10:40:16 +0100619#endif
620 /* unsupported address family */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100621
622 return NULL;
623}
624
625/*
626 * converts <str> to a locally allocated struct sockaddr_storage *.
627 * The format is "addr[:[port]]", where "addr" can be a dotted IPv4 address, an
628 * IPv6 address, a host name, or empty or "*" to indicate INADDR_ANY. If an IPv6
629 * address wants to ignore port, it must be terminated by a trailing colon (':').
630 * The IPv6 '::' address is IN6ADDR_ANY, so in order to bind to a given port on
631 * IPv6, use ":::port". NULL is returned if the host part cannot be resolved.
632 */
633struct sockaddr_storage *str2sa(const char *str)
634{
David du Colombier6f5ccb12011-03-10 22:26:24 +0100635 struct sockaddr_storage *ret = NULL;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100636 char *str2;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200637 char *c;
638 int port;
639
Willy Tarreaufab5a432011-03-04 15:31:53 +0100640 str2 = strdup(str);
641 if (str2 == NULL)
Willy Tarreaud5191e72010-02-09 20:50:45 +0100642 goto out;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200643
Willy Tarreaufab5a432011-03-04 15:31:53 +0100644 if ((c = strrchr(str2, ':')) != NULL) { /* Port */
Willy Tarreaubaaee002006-06-26 02:48:02 +0200645 *c++ = '\0';
646 port = atol(c);
647 }
648 else
649 port = 0;
650
Willy Tarreaufab5a432011-03-04 15:31:53 +0100651 ret = str2ip(str2);
652 if (!ret)
653 goto out;
654
Willy Tarreau86ad42c2011-08-27 12:29:07 +0200655 set_host_port(ret, port);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100656 out:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100657 free(str2);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100658 return ret;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200659}
660
661/*
Willy Tarreaufab5a432011-03-04 15:31:53 +0100662 * converts <str> to a locally allocated struct sockaddr_storage *, and a
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200663 * port range consisting in two integers. The low and high end are always set
664 * even if the port is unspecified, in which case (0,0) is returned. The low
Willy Tarreaufab5a432011-03-04 15:31:53 +0100665 * port is set in the sockaddr. Thus, it is enough to check the size of the
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200666 * returned range to know if an array must be allocated or not. The format is
Willy Tarreaufab5a432011-03-04 15:31:53 +0100667 * "addr[:[port[-port]]]", where "addr" can be a dotted IPv4 address, an IPv6
668 * address, a host name, or empty or "*" to indicate INADDR_ANY. If an IPv6
669 * address wants to ignore port, it must be terminated by a trailing colon (':').
670 * The IPv6 '::' address is IN6ADDR_ANY, so in order to bind to a given port on
671 * IPv6, use ":::port". NULL is returned if the host part cannot be resolved.
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200672 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100673struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high)
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200674{
David du Colombier6f5ccb12011-03-10 22:26:24 +0100675 struct sockaddr_storage *ret = NULL;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100676 char *str2;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200677 char *c;
678 int portl, porth;
679
Willy Tarreaufab5a432011-03-04 15:31:53 +0100680 str2 = strdup(str);
681 if (str2 == NULL)
Willy Tarreaud5191e72010-02-09 20:50:45 +0100682 goto out;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200683
Willy Tarreaufab5a432011-03-04 15:31:53 +0100684 if ((c = strrchr(str2,':')) != NULL) { /* Port */
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200685 char *sep;
686 *c++ = '\0';
687 sep = strchr(c, '-');
688 if (sep)
689 *sep++ = '\0';
690 else
691 sep = c;
692 portl = atol(c);
693 porth = atol(sep);
694 }
695 else {
696 portl = 0;
697 porth = 0;
698 }
699
Willy Tarreaufab5a432011-03-04 15:31:53 +0100700 ret = str2ip(str2);
701 if (!ret)
702 goto out;
703
Willy Tarreau86ad42c2011-08-27 12:29:07 +0200704 set_host_port(ret, portl);
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200705
706 *low = portl;
707 *high = porth;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100708 out:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100709 free(str2);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100710 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200711}
712
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100713/* converts <str> to a struct in_addr containing a network mask. It can be
714 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
715 * if the conversion succeeds otherwise non-zero.
716 */
717int str2mask(const char *str, struct in_addr *mask)
718{
719 if (strchr(str, '.') != NULL) { /* dotted notation */
720 if (!inet_pton(AF_INET, str, mask))
721 return 0;
722 }
723 else { /* mask length */
724 char *err;
725 unsigned long len = strtol(str, &err, 10);
726
727 if (!*str || (err && *err) || (unsigned)len > 32)
728 return 0;
729 if (len)
730 mask->s_addr = htonl(~0UL << (32 - len));
731 else
732 mask->s_addr = 0;
733 }
734 return 1;
735}
736
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200737/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200738 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200739 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
740 * is optionnal and either in the dotted or CIDR notation.
741 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
742 */
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200743int str2net(const char *str, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200744{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200745 __label__ out_free, out_err;
746 char *c, *s;
747 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200748
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200749 s = strdup(str);
750 if (!s)
751 return 0;
752
Willy Tarreaubaaee002006-06-26 02:48:02 +0200753 memset(mask, 0, sizeof(*mask));
754 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200755
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200756 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200757 *c++ = '\0';
758 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100759 if (!str2mask(c, mask))
760 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200761 }
762 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100763 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200764 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200765 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200766 struct hostent *he;
767
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200768 if ((he = gethostbyname(s)) == NULL) {
769 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200770 }
771 else
772 *addr = *(struct in_addr *) *(he->h_addr_list);
773 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200774
775 ret_val = 1;
776 out_free:
777 free(s);
778 return ret_val;
779 out_err:
780 ret_val = 0;
781 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200782}
783
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100784
785/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200786 * converts <str> to two struct in6_addr* which must be pre-allocated.
787 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
788 * is an optionnal number of bits (128 being the default).
789 * Returns 1 if OK, 0 if error.
790 */
791int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
792{
793 char *c, *s;
794 int ret_val = 0;
795 char *err;
796 unsigned long len = 128;
797
798 s = strdup(str);
799 if (!s)
800 return 0;
801
802 memset(mask, 0, sizeof(*mask));
803 memset(addr, 0, sizeof(*addr));
804
805 if ((c = strrchr(s, '/')) != NULL) {
806 *c++ = '\0'; /* c points to the mask */
807 if (!*c)
808 goto out_free;
809
810 len = strtoul(c, &err, 10);
811 if ((err && *err) || (unsigned)len > 128)
812 goto out_free;
813 }
814 *mask = len; /* OK we have a valid mask in <len> */
815
816 if (!inet_pton(AF_INET6, s, addr))
817 goto out_free;
818
819 ret_val = 1;
820 out_free:
821 free(s);
822 return ret_val;
823}
824
825
826/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100827 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100828 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100829int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100830{
831 int saw_digit, octets, ch;
832 u_char tmp[4], *tp;
833 const char *cp = addr;
834
835 saw_digit = 0;
836 octets = 0;
837 *(tp = tmp) = 0;
838
839 while (*addr) {
840 unsigned char digit = (ch = *addr++) - '0';
841 if (digit > 9 && ch != '.')
842 break;
843 if (digit <= 9) {
844 u_int new = *tp * 10 + digit;
845 if (new > 255)
846 return 0;
847 *tp = new;
848 if (!saw_digit) {
849 if (++octets > 4)
850 return 0;
851 saw_digit = 1;
852 }
853 } else if (ch == '.' && saw_digit) {
854 if (octets == 4)
855 return 0;
856 *++tp = 0;
857 saw_digit = 0;
858 } else
859 return 0;
860 }
861
862 if (octets < 4)
863 return 0;
864
865 memcpy(&dst->s_addr, tmp, 4);
866 return addr-cp-1;
867}
868
869/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100870 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100871 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100872int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100873{
874 const char *curr = url, *cp = url;
875 int ret, url_code = 0;
876 unsigned int http_code = 0;
877
878 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100879
880 /* FIXME: assume IPv4 only for now */
881 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
882 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
883 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100884
885 /* Firstly, try to find :// pattern */
886 while (curr < url+ulen && url_code != 0x3a2f2f) {
887 url_code = ((url_code & 0xffff) << 8);
888 url_code += (unsigned char)*curr++;
889 }
890
891 /* Secondly, if :// pattern is found, verify parsed stuff
892 * before pattern is matching our http pattern.
893 * If so parse ip address and port in uri.
894 *
895 * WARNING: Current code doesn't support dynamic async dns resolver.
896 */
897 if (url_code == 0x3a2f2f) {
898 while (cp < curr - 3)
899 http_code = (http_code << 8) + *cp++;
900 http_code |= 0x20202020; /* Turn everything to lower case */
901
902 /* HTTP url matching */
903 if (http_code == 0x68747470) {
904 /* We are looking for IP address. If you want to parse and
905 * resolve hostname found in url, you can use str2sa(), but
906 * be warned this can slow down global daemon performances
907 * while handling lagging dns responses.
908 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100909 ret = url2ipv4(curr, &((struct sockaddr_in *)&addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100910 if (!ret)
911 return -1;
912 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100913 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
914 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)&addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100915 }
916 return 0;
917 }
918
919 return -1;
920}
921
Willy Tarreau631f01c2011-09-05 00:36:48 +0200922/* Tries to convert a sockaddr_storage address to text form. Upon success, the
923 * address family is returned so that it's easy for the caller to adapt to the
924 * output format. Zero is returned if the address family is not supported. -1
925 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
926 * supported.
927 */
928int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
929{
930
931 void *ptr;
932
933 if (size < 5)
934 return 0;
935 *str = '\0';
936
937 switch (addr->ss_family) {
938 case AF_INET:
939 ptr = &((struct sockaddr_in *)addr)->sin_addr;
940 break;
941 case AF_INET6:
942 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
943 break;
944 case AF_UNIX:
945 memcpy(str, "unix", 5);
946 return addr->ss_family;
947 default:
948 return 0;
949 }
950
951 if (inet_ntop(addr->ss_family, ptr, str, size))
952 return addr->ss_family;
953
954 /* failed */
955 return -1;
956}
957
Willy Tarreaubaaee002006-06-26 02:48:02 +0200958/* will try to encode the string <string> replacing all characters tagged in
959 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
960 * prefixed by <escape>, and will store the result between <start> (included)
961 * and <stop> (excluded), and will always terminate the string with a '\0'
962 * before <stop>. The position of the '\0' is returned if the conversion
963 * completes. If bytes are missing between <start> and <stop>, then the
964 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
965 * cannot even be stored so we return <start> without writing the 0.
966 * The input string must also be zero-terminated.
967 */
968const char hextab[16] = "0123456789ABCDEF";
969char *encode_string(char *start, char *stop,
970 const char escape, const fd_set *map,
971 const char *string)
972{
973 if (start < stop) {
974 stop--; /* reserve one byte for the final '\0' */
975 while (start < stop && *string != '\0') {
976 if (!FD_ISSET((unsigned char)(*string), map))
977 *start++ = *string;
978 else {
979 if (start + 3 >= stop)
980 break;
981 *start++ = escape;
982 *start++ = hextab[(*string >> 4) & 15];
983 *start++ = hextab[*string & 15];
984 }
985 string++;
986 }
987 *start = '\0';
988 }
989 return start;
990}
991
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +0200992/* Decode an URL-encoded string in-place. The resulting string might
993 * be shorter. If some forbidden characters are found, the conversion is
994 * aborted, the string is truncated before the issue and non-zero is returned,
995 * otherwise the operation returns non-zero indicating success.
996 */
997int url_decode(char *string)
998{
999 char *in, *out;
1000 int ret = 0;
1001
1002 in = string;
1003 out = string;
1004 while (*in) {
1005 switch (*in) {
1006 case '+' :
1007 *out++ = ' ';
1008 break;
1009 case '%' :
1010 if (!ishex(in[1]) || !ishex(in[2]))
1011 goto end;
1012 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1013 in += 2;
1014 break;
1015 default:
1016 *out++ = *in;
1017 break;
1018 }
1019 in++;
1020 }
1021 ret = 1; /* success */
1022 end:
1023 *out = 0;
1024 return ret;
1025}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001026
Willy Tarreau6911fa42007-03-04 18:06:08 +01001027unsigned int str2ui(const char *s)
1028{
1029 return __str2ui(s);
1030}
1031
1032unsigned int str2uic(const char *s)
1033{
1034 return __str2uic(s);
1035}
1036
1037unsigned int strl2ui(const char *s, int len)
1038{
1039 return __strl2ui(s, len);
1040}
1041
1042unsigned int strl2uic(const char *s, int len)
1043{
1044 return __strl2uic(s, len);
1045}
1046
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001047unsigned int read_uint(const char **s, const char *end)
1048{
1049 return __read_uint(s, end);
1050}
1051
Willy Tarreau6911fa42007-03-04 18:06:08 +01001052/* This one is 7 times faster than strtol() on athlon with checks.
1053 * It returns the value of the number composed of all valid digits read,
1054 * and can process negative numbers too.
1055 */
1056int strl2ic(const char *s, int len)
1057{
1058 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001059 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001060
1061 if (len > 0) {
1062 if (*s != '-') {
1063 /* positive number */
1064 while (len-- > 0) {
1065 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001066 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001067 if (j > 9)
1068 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001069 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001070 }
1071 } else {
1072 /* negative number */
1073 s++;
1074 while (--len > 0) {
1075 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001076 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001077 if (j > 9)
1078 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001079 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001080 }
1081 }
1082 }
1083 return i;
1084}
1085
1086
1087/* This function reads exactly <len> chars from <s> and converts them to a
1088 * signed integer which it stores into <ret>. It accurately detects any error
1089 * (truncated string, invalid chars, overflows). It is meant to be used in
1090 * applications designed for hostile environments. It returns zero when the
1091 * number has successfully been converted, non-zero otherwise. When an error
1092 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1093 * faster than strtol().
1094 */
1095int strl2irc(const char *s, int len, int *ret)
1096{
1097 int i = 0;
1098 int j;
1099
1100 if (!len)
1101 return 1;
1102
1103 if (*s != '-') {
1104 /* positive number */
1105 while (len-- > 0) {
1106 j = (*s++) - '0';
1107 if (j > 9) return 1; /* invalid char */
1108 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1109 i = i * 10;
1110 if (i + j < i) return 1; /* check for addition overflow */
1111 i = i + j;
1112 }
1113 } else {
1114 /* negative number */
1115 s++;
1116 while (--len > 0) {
1117 j = (*s++) - '0';
1118 if (j > 9) return 1; /* invalid char */
1119 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1120 i = i * 10;
1121 if (i - j > i) return 1; /* check for subtract overflow */
1122 i = i - j;
1123 }
1124 }
1125 *ret = i;
1126 return 0;
1127}
1128
1129
1130/* This function reads exactly <len> chars from <s> and converts them to a
1131 * signed integer which it stores into <ret>. It accurately detects any error
1132 * (truncated string, invalid chars, overflows). It is meant to be used in
1133 * applications designed for hostile environments. It returns zero when the
1134 * number has successfully been converted, non-zero otherwise. When an error
1135 * is returned, the <ret> value is left untouched. It is about 3 times slower
1136 * than str2irc().
1137 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001138
1139int strl2llrc(const char *s, int len, long long *ret)
1140{
1141 long long i = 0;
1142 int j;
1143
1144 if (!len)
1145 return 1;
1146
1147 if (*s != '-') {
1148 /* positive number */
1149 while (len-- > 0) {
1150 j = (*s++) - '0';
1151 if (j > 9) return 1; /* invalid char */
1152 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1153 i = i * 10LL;
1154 if (i + j < i) return 1; /* check for addition overflow */
1155 i = i + j;
1156 }
1157 } else {
1158 /* negative number */
1159 s++;
1160 while (--len > 0) {
1161 j = (*s++) - '0';
1162 if (j > 9) return 1; /* invalid char */
1163 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1164 i = i * 10LL;
1165 if (i - j > i) return 1; /* check for subtract overflow */
1166 i = i - j;
1167 }
1168 }
1169 *ret = i;
1170 return 0;
1171}
1172
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001173/* This function parses a time value optionally followed by a unit suffix among
1174 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1175 * expected by the caller. The computation does its best to avoid overflows.
1176 * The value is returned in <ret> if everything is fine, and a NULL is returned
1177 * by the function. In case of error, a pointer to the error is returned and
1178 * <ret> is left untouched. Values are automatically rounded up when needed.
1179 */
1180const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1181{
1182 unsigned imult, idiv;
1183 unsigned omult, odiv;
1184 unsigned value;
1185
1186 omult = odiv = 1;
1187
1188 switch (unit_flags & TIME_UNIT_MASK) {
1189 case TIME_UNIT_US: omult = 1000000; break;
1190 case TIME_UNIT_MS: omult = 1000; break;
1191 case TIME_UNIT_S: break;
1192 case TIME_UNIT_MIN: odiv = 60; break;
1193 case TIME_UNIT_HOUR: odiv = 3600; break;
1194 case TIME_UNIT_DAY: odiv = 86400; break;
1195 default: break;
1196 }
1197
1198 value = 0;
1199
1200 while (1) {
1201 unsigned int j;
1202
1203 j = *text - '0';
1204 if (j > 9)
1205 break;
1206 text++;
1207 value *= 10;
1208 value += j;
1209 }
1210
1211 imult = idiv = 1;
1212 switch (*text) {
1213 case '\0': /* no unit = default unit */
1214 imult = omult = idiv = odiv = 1;
1215 break;
1216 case 's': /* second = unscaled unit */
1217 break;
1218 case 'u': /* microsecond : "us" */
1219 if (text[1] == 's') {
1220 idiv = 1000000;
1221 text++;
1222 }
1223 break;
1224 case 'm': /* millisecond : "ms" or minute: "m" */
1225 if (text[1] == 's') {
1226 idiv = 1000;
1227 text++;
1228 } else
1229 imult = 60;
1230 break;
1231 case 'h': /* hour : "h" */
1232 imult = 3600;
1233 break;
1234 case 'd': /* day : "d" */
1235 imult = 86400;
1236 break;
1237 default:
1238 return text;
1239 break;
1240 }
1241
1242 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1243 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1244 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1245 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1246
1247 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1248 *ret = value;
1249 return NULL;
1250}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001251
Emeric Brun39132b22010-01-04 14:57:24 +01001252/* this function converts the string starting at <text> to an unsigned int
1253 * stored in <ret>. If an error is detected, the pointer to the unexpected
1254 * character is returned. If the conversio is succesful, NULL is returned.
1255 */
1256const char *parse_size_err(const char *text, unsigned *ret) {
1257 unsigned value = 0;
1258
1259 while (1) {
1260 unsigned int j;
1261
1262 j = *text - '0';
1263 if (j > 9)
1264 break;
1265 if (value > ~0U / 10)
1266 return text;
1267 value *= 10;
1268 if (value > (value + j))
1269 return text;
1270 value += j;
1271 text++;
1272 }
1273
1274 switch (*text) {
1275 case '\0':
1276 break;
1277 case 'K':
1278 case 'k':
1279 if (value > ~0U >> 10)
1280 return text;
1281 value = value << 10;
1282 break;
1283 case 'M':
1284 case 'm':
1285 if (value > ~0U >> 20)
1286 return text;
1287 value = value << 20;
1288 break;
1289 case 'G':
1290 case 'g':
1291 if (value > ~0U >> 30)
1292 return text;
1293 value = value << 30;
1294 break;
1295 default:
1296 return text;
1297 }
1298
1299 *ret = value;
1300 return NULL;
1301}
1302
Willy Tarreau946ba592009-05-10 15:41:18 +02001303/* copies at most <n> characters from <src> and always terminates with '\0' */
1304char *my_strndup(const char *src, int n)
1305{
1306 int len = 0;
1307 char *ret;
1308
1309 while (len < n && src[len])
1310 len++;
1311
1312 ret = (char *)malloc(len + 1);
1313 if (!ret)
1314 return ret;
1315 memcpy(ret, src, len);
1316 ret[len] = '\0';
1317 return ret;
1318}
1319
Willy Tarreau482b00d2009-10-04 22:48:42 +02001320/* This function returns the first unused key greater than or equal to <key> in
1321 * ID tree <root>. Zero is returned if no place is found.
1322 */
1323unsigned int get_next_id(struct eb_root *root, unsigned int key)
1324{
1325 struct eb32_node *used;
1326
1327 do {
1328 used = eb32_lookup_ge(root, key);
1329 if (!used || used->key > key)
1330 return key; /* key is available */
1331 key++;
1332 } while (key);
1333 return key;
1334}
1335
Willy Tarreau348238b2010-01-18 15:05:57 +01001336/* This function compares a sample word possibly followed by blanks to another
1337 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1338 * otherwise zero. This intends to be used when checking HTTP headers for some
1339 * values. Note that it validates a word followed only by blanks but does not
1340 * validate a word followed by blanks then other chars.
1341 */
1342int word_match(const char *sample, int slen, const char *word, int wlen)
1343{
1344 if (slen < wlen)
1345 return 0;
1346
1347 while (wlen) {
1348 char c = *sample ^ *word;
1349 if (c && c != ('A' ^ 'a'))
1350 return 0;
1351 sample++;
1352 word++;
1353 slen--;
1354 wlen--;
1355 }
1356
1357 while (slen) {
1358 if (*sample != ' ' && *sample != '\t')
1359 return 0;
1360 sample++;
1361 slen--;
1362 }
1363 return 1;
1364}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001365
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001366/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1367 * is particularly fast because it avoids expensive operations such as
1368 * multiplies, which are optimized away at the end. It requires a properly
1369 * formated address though (3 points).
1370 */
1371unsigned int inetaddr_host(const char *text)
1372{
1373 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1374 register unsigned int dig100, dig10, dig1;
1375 int s;
1376 const char *p, *d;
1377
1378 dig1 = dig10 = dig100 = ascii_zero;
1379 s = 24;
1380
1381 p = text;
1382 while (1) {
1383 if (((unsigned)(*p - '0')) <= 9) {
1384 p++;
1385 continue;
1386 }
1387
1388 /* here, we have a complete byte between <text> and <p> (exclusive) */
1389 if (p == text)
1390 goto end;
1391
1392 d = p - 1;
1393 dig1 |= (unsigned int)(*d << s);
1394 if (d == text)
1395 goto end;
1396
1397 d--;
1398 dig10 |= (unsigned int)(*d << s);
1399 if (d == text)
1400 goto end;
1401
1402 d--;
1403 dig100 |= (unsigned int)(*d << s);
1404 end:
1405 if (!s || *p != '.')
1406 break;
1407
1408 s -= 8;
1409 text = ++p;
1410 }
1411
1412 dig100 -= ascii_zero;
1413 dig10 -= ascii_zero;
1414 dig1 -= ascii_zero;
1415 return ((dig100 * 10) + dig10) * 10 + dig1;
1416}
1417
1418/*
1419 * Idem except the first unparsed character has to be passed in <stop>.
1420 */
1421unsigned int inetaddr_host_lim(const char *text, const char *stop)
1422{
1423 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1424 register unsigned int dig100, dig10, dig1;
1425 int s;
1426 const char *p, *d;
1427
1428 dig1 = dig10 = dig100 = ascii_zero;
1429 s = 24;
1430
1431 p = text;
1432 while (1) {
1433 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1434 p++;
1435 continue;
1436 }
1437
1438 /* here, we have a complete byte between <text> and <p> (exclusive) */
1439 if (p == text)
1440 goto end;
1441
1442 d = p - 1;
1443 dig1 |= (unsigned int)(*d << s);
1444 if (d == text)
1445 goto end;
1446
1447 d--;
1448 dig10 |= (unsigned int)(*d << s);
1449 if (d == text)
1450 goto end;
1451
1452 d--;
1453 dig100 |= (unsigned int)(*d << s);
1454 end:
1455 if (!s || p == stop || *p != '.')
1456 break;
1457
1458 s -= 8;
1459 text = ++p;
1460 }
1461
1462 dig100 -= ascii_zero;
1463 dig10 -= ascii_zero;
1464 dig1 -= ascii_zero;
1465 return ((dig100 * 10) + dig10) * 10 + dig1;
1466}
1467
1468/*
1469 * Idem except the pointer to first unparsed byte is returned into <ret> which
1470 * must not be NULL.
1471 */
Willy Tarreau74172752010-10-15 23:21:42 +02001472unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001473{
1474 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1475 register unsigned int dig100, dig10, dig1;
1476 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001477 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001478
1479 dig1 = dig10 = dig100 = ascii_zero;
1480 s = 24;
1481
1482 p = text;
1483 while (1) {
1484 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1485 p++;
1486 continue;
1487 }
1488
1489 /* here, we have a complete byte between <text> and <p> (exclusive) */
1490 if (p == text)
1491 goto end;
1492
1493 d = p - 1;
1494 dig1 |= (unsigned int)(*d << s);
1495 if (d == text)
1496 goto end;
1497
1498 d--;
1499 dig10 |= (unsigned int)(*d << s);
1500 if (d == text)
1501 goto end;
1502
1503 d--;
1504 dig100 |= (unsigned int)(*d << s);
1505 end:
1506 if (!s || p == stop || *p != '.')
1507 break;
1508
1509 s -= 8;
1510 text = ++p;
1511 }
1512
1513 *ret = p;
1514 dig100 -= ascii_zero;
1515 dig10 -= ascii_zero;
1516 dig1 -= ascii_zero;
1517 return ((dig100 * 10) + dig10) * 10 + dig1;
1518}
1519
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001520/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1521 * or the number of chars read in case of success. Maybe this could be replaced
1522 * by one of the functions above. Also, apparently this function does not support
1523 * hosts above 255 and requires exactly 4 octets.
1524 */
1525int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1526{
1527 const char *addr;
1528 int saw_digit, octets, ch;
1529 u_char tmp[4], *tp;
1530 const char *cp = buf;
1531
1532 saw_digit = 0;
1533 octets = 0;
1534 *(tp = tmp) = 0;
1535
1536 for (addr = buf; addr - buf < len; addr++) {
1537 unsigned char digit = (ch = *addr) - '0';
1538
1539 if (digit > 9 && ch != '.')
1540 break;
1541
1542 if (digit <= 9) {
1543 u_int new = *tp * 10 + digit;
1544
1545 if (new > 255)
1546 return 0;
1547
1548 *tp = new;
1549
1550 if (!saw_digit) {
1551 if (++octets > 4)
1552 return 0;
1553 saw_digit = 1;
1554 }
1555 } else if (ch == '.' && saw_digit) {
1556 if (octets == 4)
1557 return 0;
1558
1559 *++tp = 0;
1560 saw_digit = 0;
1561 } else
1562 return 0;
1563 }
1564
1565 if (octets < 4)
1566 return 0;
1567
1568 memcpy(&dst->s_addr, tmp, 4);
1569 return addr - cp;
1570}
1571
Willy Tarreauacf95772010-06-14 19:09:21 +02001572/* To be used to quote config arg positions. Returns the short string at <ptr>
1573 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1574 * if ptr is NULL or empty. The string is locally allocated.
1575 */
1576const char *quote_arg(const char *ptr)
1577{
1578 static char val[32];
1579 int i;
1580
1581 if (!ptr || !*ptr)
1582 return "end of line";
1583 val[0] = '\'';
1584 for (i = 1; i < sizeof(val) - 1 && *ptr; i++)
1585 val[i] = *ptr++;
1586 val[i++] = '\'';
1587 val[i] = '\0';
1588 return val;
1589}
1590
Willy Tarreau5b180202010-07-18 10:40:48 +02001591/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1592int get_std_op(const char *str)
1593{
1594 int ret = -1;
1595
1596 if (*str == 'e' && str[1] == 'q')
1597 ret = STD_OP_EQ;
1598 else if (*str == 'n' && str[1] == 'e')
1599 ret = STD_OP_NE;
1600 else if (*str == 'l') {
1601 if (str[1] == 'e') ret = STD_OP_LE;
1602 else if (str[1] == 't') ret = STD_OP_LT;
1603 }
1604 else if (*str == 'g') {
1605 if (str[1] == 'e') ret = STD_OP_GE;
1606 else if (str[1] == 't') ret = STD_OP_GT;
1607 }
1608
1609 if (ret == -1 || str[2] != '\0')
1610 return -1;
1611 return ret;
1612}
1613
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001614/* hash a 32-bit integer to another 32-bit integer */
1615unsigned int full_hash(unsigned int a)
1616{
1617 return __full_hash(a);
1618}
1619
David du Colombier4f92d322011-03-24 11:09:31 +01001620/* Return non-zero if IPv4 address is part of the network,
1621 * otherwise zero.
1622 */
1623int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1624{
1625 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1626}
1627
1628/* Return non-zero if IPv6 address is part of the network,
1629 * otherwise zero.
1630 */
1631int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1632{
1633 int i;
1634
1635 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1636 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1637 (((int *)net)[i] & ((int *)mask)[i]))
1638 return 0;
1639 return 1;
1640}
1641
1642/* RFC 4291 prefix */
1643const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1644 0x00, 0x00, 0x00, 0x00,
1645 0x00, 0x00, 0xFF, 0xFF };
1646
1647/* Map IPv4 adress on IPv6 address, as specified in RFC 3513. */
1648void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1649{
1650 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
1651 memcpy(sin6_addr->s6_addr+12, &sin_addr->s_addr, 4);
1652}
1653
1654/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1655 * Return true if conversion is possible and false otherwise.
1656 */
1657int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1658{
1659 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1660 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1661 sizeof(struct in_addr));
1662 return 1;
1663 }
1664
1665 return 0;
1666}
1667
William Lallemand421f5b52012-02-06 18:15:57 +01001668char *human_time(int t, short hz_div) {
1669 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1670 char *p = rv;
1671 int cnt=2; // print two numbers
1672
1673 if (unlikely(t < 0 || hz_div <= 0)) {
1674 sprintf(p, "?");
1675 return rv;
1676 }
1677
1678 if (unlikely(hz_div > 1))
1679 t /= hz_div;
1680
1681 if (t >= DAY) {
1682 p += sprintf(p, "%dd", t / DAY);
1683 cnt--;
1684 }
1685
1686 if (cnt && t % DAY / HOUR) {
1687 p += sprintf(p, "%dh", t % DAY / HOUR);
1688 cnt--;
1689 }
1690
1691 if (cnt && t % HOUR / MINUTE) {
1692 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1693 cnt--;
1694 }
1695
1696 if ((cnt && t % MINUTE) || !t) // also display '0s'
1697 p += sprintf(p, "%ds", t % MINUTE / SEC);
1698
1699 return rv;
1700}
1701
1702const char *monthname[12] = {
1703 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1704 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1705};
1706
1707/* date2str_log: write a date in the format :
1708 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1709 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1710 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1711 *
1712 * without using sprintf. return a pointer to the last char written (\0) or
1713 * NULL if there isn't enough space.
1714 */
1715char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1716{
1717
1718 if (size < 25) /* the size is fixed: 24 chars + \0 */
1719 return NULL;
1720
1721 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1722 *dst++ = '/';
1723 memcpy(dst, monthname[tm->tm_mon], 3); // month
1724 dst += 3;
1725 *dst++ = '/';
1726 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1727 *dst++ = ':';
1728 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1729 *dst++ = ':';
1730 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1731 *dst++ = ':';
1732 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1733 *dst++ = '.';
1734 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1735 dst += 3; // only the 3 first digits
1736 *dst = '\0';
1737
1738 return dst;
1739}
1740
1741/* gmt2str_log: write a date in the format :
1742 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1743 * return a pointer to the last char written (\0) or
1744 * NULL if there isn't enough space.
1745 */
1746char *gmt2str_log(char *dst, struct tm *tm, size_t size)
1747{
1748 if (size < 27) /* the size is fixed: 24 chars + \0 */
1749 return NULL;
1750
1751 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1752 *dst++ = '/';
1753 memcpy(dst, monthname[tm->tm_mon], 3); // month
1754 dst += 3;
1755 *dst++ = '/';
1756 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1757 *dst++ = ':';
1758 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1759 *dst++ = ':';
1760 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1761 *dst++ = ':';
1762 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1763 *dst++ = ' ';
1764 *dst++ = '+';
1765 *dst++ = '0';
1766 *dst++ = '0';
1767 *dst++ = '0';
1768 *dst++ = '0';
1769 *dst = '\0';
1770
1771 return dst;
1772}
1773
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001774/* Dynamically allocates a string of the proper length to hold the formatted
1775 * output. NULL is returned on error. The caller is responsible for freeing the
1776 * memory area using free(). The resulting string is returned in <out> if the
1777 * pointer is not NULL. A previous version of <out> might be used to build the
1778 * new string, and it will be freed before returning if it is not NULL, which
1779 * makes it possible to build complex strings from iterative calls without
1780 * having to care about freeing intermediate values, as in the example below :
1781 *
1782 * memprintf(&err, "invalid argument: '%s'", arg);
1783 * ...
1784 * memprintf(&err, "parser said : <%s>\n", *err);
1785 * ...
1786 * free(*err);
1787 *
1788 * This means that <err> must be initialized to NULL before first invocation.
1789 * The return value also holds the allocated string, which eases error checking
1790 * and immediate consumption. If the output pointer is not used, NULL must be
1791 * passed instead and it will be ignored.
1792 *
1793 * It is also convenient to use it without any free except the last one :
1794 * err = NULL;
1795 * if (!fct1(err)) report(*err);
1796 * if (!fct2(err)) report(*err);
1797 * if (!fct3(err)) report(*err);
1798 * free(*err);
1799 */
1800char *memprintf(char **out, const char *format, ...)
1801{
1802 va_list args;
1803 char *ret = NULL;
1804 int allocated = 0;
1805 int needed = 0;
1806
1807 do {
1808 /* vsnprintf() will return the required length even when the
1809 * target buffer is NULL. We do this in a loop just in case
1810 * intermediate evaluations get wrong.
1811 */
1812 va_start(args, format);
1813 needed = vsnprintf(ret, allocated, format, args) + 1;
1814 va_end(args);
1815
1816 if (needed <= allocated)
1817 break;
1818
1819 allocated = needed;
1820 ret = realloc(ret, allocated);
1821 } while (ret);
1822
1823 if (needed < 0) {
1824 /* an error was encountered */
1825 free(ret);
1826 ret = NULL;
1827 }
1828
1829 if (out) {
1830 free(*out);
1831 *out = ret;
1832 }
1833
1834 return ret;
1835}
William Lallemand421f5b52012-02-06 18:15:57 +01001836
Willy Tarreau21c705b2012-09-14 11:40:36 +02001837/* Used to add <level> spaces before each line of <out>, unless there is only one line.
1838 * The input argument is automatically freed and reassigned. The result will have to be
1839 * freed by the caller.
1840 * Example of use :
1841 * parse(cmd, &err); (callee: memprintf(&err, ...))
1842 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
1843 * free(err);
1844 */
1845char *indent_msg(char **out, int level)
1846{
1847 char *ret, *in, *p;
1848 int needed = 0;
1849 int lf = 0;
1850 int lastlf = 0;
1851 int len;
1852
1853 in = *out - 1;
1854 while ((in = strchr(in + 1, '\n')) != NULL) {
1855 lastlf = in - *out;
1856 lf++;
1857 }
1858
1859 if (!lf) /* single line, no LF, return it as-is */
1860 return *out;
1861
1862 len = strlen(*out);
1863
1864 if (lf == 1 && lastlf == len - 1) {
1865 /* single line, LF at end, strip it and return as-is */
1866 (*out)[lastlf] = 0;
1867 return *out;
1868 }
1869
1870 /* OK now we have at least one LF, we need to process the whole string
1871 * as a multi-line string. What we'll do :
1872 * - prefix with an LF if there is none
1873 * - add <level> spaces before each line
1874 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
1875 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
1876 */
1877
1878 needed = 1 + level * (lf + 1) + len + 1;
1879 p = ret = malloc(needed);
1880 in = *out;
1881
1882 /* skip initial LFs */
1883 while (*in == '\n')
1884 in++;
1885
1886 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
1887 while (*in) {
1888 *p++ = '\n';
1889 memset(p, ' ', level);
1890 p += level;
1891 do {
1892 *p++ = *in++;
1893 } while (*in && *in != '\n');
1894 if (*in)
1895 in++;
1896 }
1897 *p = 0;
1898
1899 free(*out);
1900 *out = ret;
1901
1902 return ret;
1903}
1904
Willy Tarreaubaaee002006-06-26 02:48:02 +02001905/*
1906 * Local variables:
1907 * c-indent-level: 8
1908 * c-basic-offset: 8
1909 * End:
1910 */