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