blob: ea06a87dadf757bdf8d42bdb1f6b548f7cf66dac [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/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100785 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100786 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100787int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100788{
789 int saw_digit, octets, ch;
790 u_char tmp[4], *tp;
791 const char *cp = addr;
792
793 saw_digit = 0;
794 octets = 0;
795 *(tp = tmp) = 0;
796
797 while (*addr) {
798 unsigned char digit = (ch = *addr++) - '0';
799 if (digit > 9 && ch != '.')
800 break;
801 if (digit <= 9) {
802 u_int new = *tp * 10 + digit;
803 if (new > 255)
804 return 0;
805 *tp = new;
806 if (!saw_digit) {
807 if (++octets > 4)
808 return 0;
809 saw_digit = 1;
810 }
811 } else if (ch == '.' && saw_digit) {
812 if (octets == 4)
813 return 0;
814 *++tp = 0;
815 saw_digit = 0;
816 } else
817 return 0;
818 }
819
820 if (octets < 4)
821 return 0;
822
823 memcpy(&dst->s_addr, tmp, 4);
824 return addr-cp-1;
825}
826
827/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100828 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100829 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100830int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100831{
832 const char *curr = url, *cp = url;
833 int ret, url_code = 0;
834 unsigned int http_code = 0;
835
836 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100837
838 /* FIXME: assume IPv4 only for now */
839 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
840 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
841 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100842
843 /* Firstly, try to find :// pattern */
844 while (curr < url+ulen && url_code != 0x3a2f2f) {
845 url_code = ((url_code & 0xffff) << 8);
846 url_code += (unsigned char)*curr++;
847 }
848
849 /* Secondly, if :// pattern is found, verify parsed stuff
850 * before pattern is matching our http pattern.
851 * If so parse ip address and port in uri.
852 *
853 * WARNING: Current code doesn't support dynamic async dns resolver.
854 */
855 if (url_code == 0x3a2f2f) {
856 while (cp < curr - 3)
857 http_code = (http_code << 8) + *cp++;
858 http_code |= 0x20202020; /* Turn everything to lower case */
859
860 /* HTTP url matching */
861 if (http_code == 0x68747470) {
862 /* We are looking for IP address. If you want to parse and
863 * resolve hostname found in url, you can use str2sa(), but
864 * be warned this can slow down global daemon performances
865 * while handling lagging dns responses.
866 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100867 ret = url2ipv4(curr, &((struct sockaddr_in *)&addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100868 if (!ret)
869 return -1;
870 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100871 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
872 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)&addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100873 }
874 return 0;
875 }
876
877 return -1;
878}
879
Willy Tarreau631f01c2011-09-05 00:36:48 +0200880/* Tries to convert a sockaddr_storage address to text form. Upon success, the
881 * address family is returned so that it's easy for the caller to adapt to the
882 * output format. Zero is returned if the address family is not supported. -1
883 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
884 * supported.
885 */
886int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
887{
888
889 void *ptr;
890
891 if (size < 5)
892 return 0;
893 *str = '\0';
894
895 switch (addr->ss_family) {
896 case AF_INET:
897 ptr = &((struct sockaddr_in *)addr)->sin_addr;
898 break;
899 case AF_INET6:
900 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
901 break;
902 case AF_UNIX:
903 memcpy(str, "unix", 5);
904 return addr->ss_family;
905 default:
906 return 0;
907 }
908
909 if (inet_ntop(addr->ss_family, ptr, str, size))
910 return addr->ss_family;
911
912 /* failed */
913 return -1;
914}
915
Willy Tarreaubaaee002006-06-26 02:48:02 +0200916/* will try to encode the string <string> replacing all characters tagged in
917 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
918 * prefixed by <escape>, and will store the result between <start> (included)
919 * and <stop> (excluded), and will always terminate the string with a '\0'
920 * before <stop>. The position of the '\0' is returned if the conversion
921 * completes. If bytes are missing between <start> and <stop>, then the
922 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
923 * cannot even be stored so we return <start> without writing the 0.
924 * The input string must also be zero-terminated.
925 */
926const char hextab[16] = "0123456789ABCDEF";
927char *encode_string(char *start, char *stop,
928 const char escape, const fd_set *map,
929 const char *string)
930{
931 if (start < stop) {
932 stop--; /* reserve one byte for the final '\0' */
933 while (start < stop && *string != '\0') {
934 if (!FD_ISSET((unsigned char)(*string), map))
935 *start++ = *string;
936 else {
937 if (start + 3 >= stop)
938 break;
939 *start++ = escape;
940 *start++ = hextab[(*string >> 4) & 15];
941 *start++ = hextab[*string & 15];
942 }
943 string++;
944 }
945 *start = '\0';
946 }
947 return start;
948}
949
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +0200950/* Decode an URL-encoded string in-place. The resulting string might
951 * be shorter. If some forbidden characters are found, the conversion is
952 * aborted, the string is truncated before the issue and non-zero is returned,
953 * otherwise the operation returns non-zero indicating success.
954 */
955int url_decode(char *string)
956{
957 char *in, *out;
958 int ret = 0;
959
960 in = string;
961 out = string;
962 while (*in) {
963 switch (*in) {
964 case '+' :
965 *out++ = ' ';
966 break;
967 case '%' :
968 if (!ishex(in[1]) || !ishex(in[2]))
969 goto end;
970 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
971 in += 2;
972 break;
973 default:
974 *out++ = *in;
975 break;
976 }
977 in++;
978 }
979 ret = 1; /* success */
980 end:
981 *out = 0;
982 return ret;
983}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200984
Willy Tarreau6911fa42007-03-04 18:06:08 +0100985unsigned int str2ui(const char *s)
986{
987 return __str2ui(s);
988}
989
990unsigned int str2uic(const char *s)
991{
992 return __str2uic(s);
993}
994
995unsigned int strl2ui(const char *s, int len)
996{
997 return __strl2ui(s, len);
998}
999
1000unsigned int strl2uic(const char *s, int len)
1001{
1002 return __strl2uic(s, len);
1003}
1004
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001005unsigned int read_uint(const char **s, const char *end)
1006{
1007 return __read_uint(s, end);
1008}
1009
Willy Tarreau6911fa42007-03-04 18:06:08 +01001010/* This one is 7 times faster than strtol() on athlon with checks.
1011 * It returns the value of the number composed of all valid digits read,
1012 * and can process negative numbers too.
1013 */
1014int strl2ic(const char *s, int len)
1015{
1016 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001017 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001018
1019 if (len > 0) {
1020 if (*s != '-') {
1021 /* positive number */
1022 while (len-- > 0) {
1023 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001024 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001025 if (j > 9)
1026 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001027 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001028 }
1029 } else {
1030 /* negative number */
1031 s++;
1032 while (--len > 0) {
1033 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001034 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001035 if (j > 9)
1036 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001037 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001038 }
1039 }
1040 }
1041 return i;
1042}
1043
1044
1045/* This function reads exactly <len> chars from <s> and converts them to a
1046 * signed integer which it stores into <ret>. It accurately detects any error
1047 * (truncated string, invalid chars, overflows). It is meant to be used in
1048 * applications designed for hostile environments. It returns zero when the
1049 * number has successfully been converted, non-zero otherwise. When an error
1050 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1051 * faster than strtol().
1052 */
1053int strl2irc(const char *s, int len, int *ret)
1054{
1055 int i = 0;
1056 int j;
1057
1058 if (!len)
1059 return 1;
1060
1061 if (*s != '-') {
1062 /* positive number */
1063 while (len-- > 0) {
1064 j = (*s++) - '0';
1065 if (j > 9) return 1; /* invalid char */
1066 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1067 i = i * 10;
1068 if (i + j < i) return 1; /* check for addition overflow */
1069 i = i + j;
1070 }
1071 } else {
1072 /* negative number */
1073 s++;
1074 while (--len > 0) {
1075 j = (*s++) - '0';
1076 if (j > 9) return 1; /* invalid char */
1077 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1078 i = i * 10;
1079 if (i - j > i) return 1; /* check for subtract overflow */
1080 i = i - j;
1081 }
1082 }
1083 *ret = i;
1084 return 0;
1085}
1086
1087
1088/* This function reads exactly <len> chars from <s> and converts them to a
1089 * signed integer which it stores into <ret>. It accurately detects any error
1090 * (truncated string, invalid chars, overflows). It is meant to be used in
1091 * applications designed for hostile environments. It returns zero when the
1092 * number has successfully been converted, non-zero otherwise. When an error
1093 * is returned, the <ret> value is left untouched. It is about 3 times slower
1094 * than str2irc().
1095 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001096
1097int strl2llrc(const char *s, int len, long long *ret)
1098{
1099 long long i = 0;
1100 int j;
1101
1102 if (!len)
1103 return 1;
1104
1105 if (*s != '-') {
1106 /* positive number */
1107 while (len-- > 0) {
1108 j = (*s++) - '0';
1109 if (j > 9) return 1; /* invalid char */
1110 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1111 i = i * 10LL;
1112 if (i + j < i) return 1; /* check for addition overflow */
1113 i = i + j;
1114 }
1115 } else {
1116 /* negative number */
1117 s++;
1118 while (--len > 0) {
1119 j = (*s++) - '0';
1120 if (j > 9) return 1; /* invalid char */
1121 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1122 i = i * 10LL;
1123 if (i - j > i) return 1; /* check for subtract overflow */
1124 i = i - j;
1125 }
1126 }
1127 *ret = i;
1128 return 0;
1129}
1130
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001131/* This function parses a time value optionally followed by a unit suffix among
1132 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1133 * expected by the caller. The computation does its best to avoid overflows.
1134 * The value is returned in <ret> if everything is fine, and a NULL is returned
1135 * by the function. In case of error, a pointer to the error is returned and
1136 * <ret> is left untouched. Values are automatically rounded up when needed.
1137 */
1138const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1139{
1140 unsigned imult, idiv;
1141 unsigned omult, odiv;
1142 unsigned value;
1143
1144 omult = odiv = 1;
1145
1146 switch (unit_flags & TIME_UNIT_MASK) {
1147 case TIME_UNIT_US: omult = 1000000; break;
1148 case TIME_UNIT_MS: omult = 1000; break;
1149 case TIME_UNIT_S: break;
1150 case TIME_UNIT_MIN: odiv = 60; break;
1151 case TIME_UNIT_HOUR: odiv = 3600; break;
1152 case TIME_UNIT_DAY: odiv = 86400; break;
1153 default: break;
1154 }
1155
1156 value = 0;
1157
1158 while (1) {
1159 unsigned int j;
1160
1161 j = *text - '0';
1162 if (j > 9)
1163 break;
1164 text++;
1165 value *= 10;
1166 value += j;
1167 }
1168
1169 imult = idiv = 1;
1170 switch (*text) {
1171 case '\0': /* no unit = default unit */
1172 imult = omult = idiv = odiv = 1;
1173 break;
1174 case 's': /* second = unscaled unit */
1175 break;
1176 case 'u': /* microsecond : "us" */
1177 if (text[1] == 's') {
1178 idiv = 1000000;
1179 text++;
1180 }
1181 break;
1182 case 'm': /* millisecond : "ms" or minute: "m" */
1183 if (text[1] == 's') {
1184 idiv = 1000;
1185 text++;
1186 } else
1187 imult = 60;
1188 break;
1189 case 'h': /* hour : "h" */
1190 imult = 3600;
1191 break;
1192 case 'd': /* day : "d" */
1193 imult = 86400;
1194 break;
1195 default:
1196 return text;
1197 break;
1198 }
1199
1200 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1201 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1202 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1203 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1204
1205 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1206 *ret = value;
1207 return NULL;
1208}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001209
Emeric Brun39132b22010-01-04 14:57:24 +01001210/* this function converts the string starting at <text> to an unsigned int
1211 * stored in <ret>. If an error is detected, the pointer to the unexpected
1212 * character is returned. If the conversio is succesful, NULL is returned.
1213 */
1214const char *parse_size_err(const char *text, unsigned *ret) {
1215 unsigned value = 0;
1216
1217 while (1) {
1218 unsigned int j;
1219
1220 j = *text - '0';
1221 if (j > 9)
1222 break;
1223 if (value > ~0U / 10)
1224 return text;
1225 value *= 10;
1226 if (value > (value + j))
1227 return text;
1228 value += j;
1229 text++;
1230 }
1231
1232 switch (*text) {
1233 case '\0':
1234 break;
1235 case 'K':
1236 case 'k':
1237 if (value > ~0U >> 10)
1238 return text;
1239 value = value << 10;
1240 break;
1241 case 'M':
1242 case 'm':
1243 if (value > ~0U >> 20)
1244 return text;
1245 value = value << 20;
1246 break;
1247 case 'G':
1248 case 'g':
1249 if (value > ~0U >> 30)
1250 return text;
1251 value = value << 30;
1252 break;
1253 default:
1254 return text;
1255 }
1256
1257 *ret = value;
1258 return NULL;
1259}
1260
Willy Tarreau946ba592009-05-10 15:41:18 +02001261/* copies at most <n> characters from <src> and always terminates with '\0' */
1262char *my_strndup(const char *src, int n)
1263{
1264 int len = 0;
1265 char *ret;
1266
1267 while (len < n && src[len])
1268 len++;
1269
1270 ret = (char *)malloc(len + 1);
1271 if (!ret)
1272 return ret;
1273 memcpy(ret, src, len);
1274 ret[len] = '\0';
1275 return ret;
1276}
1277
Willy Tarreau482b00d2009-10-04 22:48:42 +02001278/* This function returns the first unused key greater than or equal to <key> in
1279 * ID tree <root>. Zero is returned if no place is found.
1280 */
1281unsigned int get_next_id(struct eb_root *root, unsigned int key)
1282{
1283 struct eb32_node *used;
1284
1285 do {
1286 used = eb32_lookup_ge(root, key);
1287 if (!used || used->key > key)
1288 return key; /* key is available */
1289 key++;
1290 } while (key);
1291 return key;
1292}
1293
Willy Tarreau348238b2010-01-18 15:05:57 +01001294/* This function compares a sample word possibly followed by blanks to another
1295 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1296 * otherwise zero. This intends to be used when checking HTTP headers for some
1297 * values. Note that it validates a word followed only by blanks but does not
1298 * validate a word followed by blanks then other chars.
1299 */
1300int word_match(const char *sample, int slen, const char *word, int wlen)
1301{
1302 if (slen < wlen)
1303 return 0;
1304
1305 while (wlen) {
1306 char c = *sample ^ *word;
1307 if (c && c != ('A' ^ 'a'))
1308 return 0;
1309 sample++;
1310 word++;
1311 slen--;
1312 wlen--;
1313 }
1314
1315 while (slen) {
1316 if (*sample != ' ' && *sample != '\t')
1317 return 0;
1318 sample++;
1319 slen--;
1320 }
1321 return 1;
1322}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001323
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001324/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1325 * is particularly fast because it avoids expensive operations such as
1326 * multiplies, which are optimized away at the end. It requires a properly
1327 * formated address though (3 points).
1328 */
1329unsigned int inetaddr_host(const char *text)
1330{
1331 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1332 register unsigned int dig100, dig10, dig1;
1333 int s;
1334 const char *p, *d;
1335
1336 dig1 = dig10 = dig100 = ascii_zero;
1337 s = 24;
1338
1339 p = text;
1340 while (1) {
1341 if (((unsigned)(*p - '0')) <= 9) {
1342 p++;
1343 continue;
1344 }
1345
1346 /* here, we have a complete byte between <text> and <p> (exclusive) */
1347 if (p == text)
1348 goto end;
1349
1350 d = p - 1;
1351 dig1 |= (unsigned int)(*d << s);
1352 if (d == text)
1353 goto end;
1354
1355 d--;
1356 dig10 |= (unsigned int)(*d << s);
1357 if (d == text)
1358 goto end;
1359
1360 d--;
1361 dig100 |= (unsigned int)(*d << s);
1362 end:
1363 if (!s || *p != '.')
1364 break;
1365
1366 s -= 8;
1367 text = ++p;
1368 }
1369
1370 dig100 -= ascii_zero;
1371 dig10 -= ascii_zero;
1372 dig1 -= ascii_zero;
1373 return ((dig100 * 10) + dig10) * 10 + dig1;
1374}
1375
1376/*
1377 * Idem except the first unparsed character has to be passed in <stop>.
1378 */
1379unsigned int inetaddr_host_lim(const char *text, const char *stop)
1380{
1381 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1382 register unsigned int dig100, dig10, dig1;
1383 int s;
1384 const char *p, *d;
1385
1386 dig1 = dig10 = dig100 = ascii_zero;
1387 s = 24;
1388
1389 p = text;
1390 while (1) {
1391 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1392 p++;
1393 continue;
1394 }
1395
1396 /* here, we have a complete byte between <text> and <p> (exclusive) */
1397 if (p == text)
1398 goto end;
1399
1400 d = p - 1;
1401 dig1 |= (unsigned int)(*d << s);
1402 if (d == text)
1403 goto end;
1404
1405 d--;
1406 dig10 |= (unsigned int)(*d << s);
1407 if (d == text)
1408 goto end;
1409
1410 d--;
1411 dig100 |= (unsigned int)(*d << s);
1412 end:
1413 if (!s || p == stop || *p != '.')
1414 break;
1415
1416 s -= 8;
1417 text = ++p;
1418 }
1419
1420 dig100 -= ascii_zero;
1421 dig10 -= ascii_zero;
1422 dig1 -= ascii_zero;
1423 return ((dig100 * 10) + dig10) * 10 + dig1;
1424}
1425
1426/*
1427 * Idem except the pointer to first unparsed byte is returned into <ret> which
1428 * must not be NULL.
1429 */
Willy Tarreau74172752010-10-15 23:21:42 +02001430unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001431{
1432 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1433 register unsigned int dig100, dig10, dig1;
1434 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001435 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001436
1437 dig1 = dig10 = dig100 = ascii_zero;
1438 s = 24;
1439
1440 p = text;
1441 while (1) {
1442 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1443 p++;
1444 continue;
1445 }
1446
1447 /* here, we have a complete byte between <text> and <p> (exclusive) */
1448 if (p == text)
1449 goto end;
1450
1451 d = p - 1;
1452 dig1 |= (unsigned int)(*d << s);
1453 if (d == text)
1454 goto end;
1455
1456 d--;
1457 dig10 |= (unsigned int)(*d << s);
1458 if (d == text)
1459 goto end;
1460
1461 d--;
1462 dig100 |= (unsigned int)(*d << s);
1463 end:
1464 if (!s || p == stop || *p != '.')
1465 break;
1466
1467 s -= 8;
1468 text = ++p;
1469 }
1470
1471 *ret = p;
1472 dig100 -= ascii_zero;
1473 dig10 -= ascii_zero;
1474 dig1 -= ascii_zero;
1475 return ((dig100 * 10) + dig10) * 10 + dig1;
1476}
1477
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001478/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1479 * or the number of chars read in case of success. Maybe this could be replaced
1480 * by one of the functions above. Also, apparently this function does not support
1481 * hosts above 255 and requires exactly 4 octets.
1482 */
1483int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1484{
1485 const char *addr;
1486 int saw_digit, octets, ch;
1487 u_char tmp[4], *tp;
1488 const char *cp = buf;
1489
1490 saw_digit = 0;
1491 octets = 0;
1492 *(tp = tmp) = 0;
1493
1494 for (addr = buf; addr - buf < len; addr++) {
1495 unsigned char digit = (ch = *addr) - '0';
1496
1497 if (digit > 9 && ch != '.')
1498 break;
1499
1500 if (digit <= 9) {
1501 u_int new = *tp * 10 + digit;
1502
1503 if (new > 255)
1504 return 0;
1505
1506 *tp = new;
1507
1508 if (!saw_digit) {
1509 if (++octets > 4)
1510 return 0;
1511 saw_digit = 1;
1512 }
1513 } else if (ch == '.' && saw_digit) {
1514 if (octets == 4)
1515 return 0;
1516
1517 *++tp = 0;
1518 saw_digit = 0;
1519 } else
1520 return 0;
1521 }
1522
1523 if (octets < 4)
1524 return 0;
1525
1526 memcpy(&dst->s_addr, tmp, 4);
1527 return addr - cp;
1528}
1529
Willy Tarreauacf95772010-06-14 19:09:21 +02001530/* To be used to quote config arg positions. Returns the short string at <ptr>
1531 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1532 * if ptr is NULL or empty. The string is locally allocated.
1533 */
1534const char *quote_arg(const char *ptr)
1535{
1536 static char val[32];
1537 int i;
1538
1539 if (!ptr || !*ptr)
1540 return "end of line";
1541 val[0] = '\'';
1542 for (i = 1; i < sizeof(val) - 1 && *ptr; i++)
1543 val[i] = *ptr++;
1544 val[i++] = '\'';
1545 val[i] = '\0';
1546 return val;
1547}
1548
Willy Tarreau5b180202010-07-18 10:40:48 +02001549/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1550int get_std_op(const char *str)
1551{
1552 int ret = -1;
1553
1554 if (*str == 'e' && str[1] == 'q')
1555 ret = STD_OP_EQ;
1556 else if (*str == 'n' && str[1] == 'e')
1557 ret = STD_OP_NE;
1558 else if (*str == 'l') {
1559 if (str[1] == 'e') ret = STD_OP_LE;
1560 else if (str[1] == 't') ret = STD_OP_LT;
1561 }
1562 else if (*str == 'g') {
1563 if (str[1] == 'e') ret = STD_OP_GE;
1564 else if (str[1] == 't') ret = STD_OP_GT;
1565 }
1566
1567 if (ret == -1 || str[2] != '\0')
1568 return -1;
1569 return ret;
1570}
1571
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001572/* hash a 32-bit integer to another 32-bit integer */
1573unsigned int full_hash(unsigned int a)
1574{
1575 return __full_hash(a);
1576}
1577
David du Colombier4f92d322011-03-24 11:09:31 +01001578/* Return non-zero if IPv4 address is part of the network,
1579 * otherwise zero.
1580 */
1581int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1582{
1583 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1584}
1585
1586/* Return non-zero if IPv6 address is part of the network,
1587 * otherwise zero.
1588 */
1589int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1590{
1591 int i;
1592
1593 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1594 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1595 (((int *)net)[i] & ((int *)mask)[i]))
1596 return 0;
1597 return 1;
1598}
1599
1600/* RFC 4291 prefix */
1601const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1602 0x00, 0x00, 0x00, 0x00,
1603 0x00, 0x00, 0xFF, 0xFF };
1604
1605/* Map IPv4 adress on IPv6 address, as specified in RFC 3513. */
1606void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1607{
1608 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
1609 memcpy(sin6_addr->s6_addr+12, &sin_addr->s_addr, 4);
1610}
1611
1612/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1613 * Return true if conversion is possible and false otherwise.
1614 */
1615int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1616{
1617 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1618 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1619 sizeof(struct in_addr));
1620 return 1;
1621 }
1622
1623 return 0;
1624}
1625
William Lallemand421f5b52012-02-06 18:15:57 +01001626char *human_time(int t, short hz_div) {
1627 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1628 char *p = rv;
1629 int cnt=2; // print two numbers
1630
1631 if (unlikely(t < 0 || hz_div <= 0)) {
1632 sprintf(p, "?");
1633 return rv;
1634 }
1635
1636 if (unlikely(hz_div > 1))
1637 t /= hz_div;
1638
1639 if (t >= DAY) {
1640 p += sprintf(p, "%dd", t / DAY);
1641 cnt--;
1642 }
1643
1644 if (cnt && t % DAY / HOUR) {
1645 p += sprintf(p, "%dh", t % DAY / HOUR);
1646 cnt--;
1647 }
1648
1649 if (cnt && t % HOUR / MINUTE) {
1650 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1651 cnt--;
1652 }
1653
1654 if ((cnt && t % MINUTE) || !t) // also display '0s'
1655 p += sprintf(p, "%ds", t % MINUTE / SEC);
1656
1657 return rv;
1658}
1659
1660const char *monthname[12] = {
1661 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1662 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1663};
1664
1665/* date2str_log: write a date in the format :
1666 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1667 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1668 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1669 *
1670 * without using sprintf. return a pointer to the last char written (\0) or
1671 * NULL if there isn't enough space.
1672 */
1673char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1674{
1675
1676 if (size < 25) /* the size is fixed: 24 chars + \0 */
1677 return NULL;
1678
1679 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1680 *dst++ = '/';
1681 memcpy(dst, monthname[tm->tm_mon], 3); // month
1682 dst += 3;
1683 *dst++ = '/';
1684 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1685 *dst++ = ':';
1686 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1687 *dst++ = ':';
1688 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1689 *dst++ = ':';
1690 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1691 *dst++ = '.';
1692 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1693 dst += 3; // only the 3 first digits
1694 *dst = '\0';
1695
1696 return dst;
1697}
1698
1699/* gmt2str_log: write a date in the format :
1700 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1701 * return a pointer to the last char written (\0) or
1702 * NULL if there isn't enough space.
1703 */
1704char *gmt2str_log(char *dst, struct tm *tm, size_t size)
1705{
1706 if (size < 27) /* the size is fixed: 24 chars + \0 */
1707 return NULL;
1708
1709 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1710 *dst++ = '/';
1711 memcpy(dst, monthname[tm->tm_mon], 3); // month
1712 dst += 3;
1713 *dst++ = '/';
1714 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1715 *dst++ = ':';
1716 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1717 *dst++ = ':';
1718 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1719 *dst++ = ':';
1720 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1721 *dst++ = ' ';
1722 *dst++ = '+';
1723 *dst++ = '0';
1724 *dst++ = '0';
1725 *dst++ = '0';
1726 *dst++ = '0';
1727 *dst = '\0';
1728
1729 return dst;
1730}
1731
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001732/* Dynamically allocates a string of the proper length to hold the formatted
1733 * output. NULL is returned on error. The caller is responsible for freeing the
1734 * memory area using free(). The resulting string is returned in <out> if the
1735 * pointer is not NULL. A previous version of <out> might be used to build the
1736 * new string, and it will be freed before returning if it is not NULL, which
1737 * makes it possible to build complex strings from iterative calls without
1738 * having to care about freeing intermediate values, as in the example below :
1739 *
1740 * memprintf(&err, "invalid argument: '%s'", arg);
1741 * ...
1742 * memprintf(&err, "parser said : <%s>\n", *err);
1743 * ...
1744 * free(*err);
1745 *
1746 * This means that <err> must be initialized to NULL before first invocation.
1747 * The return value also holds the allocated string, which eases error checking
1748 * and immediate consumption. If the output pointer is not used, NULL must be
1749 * passed instead and it will be ignored.
1750 *
1751 * It is also convenient to use it without any free except the last one :
1752 * err = NULL;
1753 * if (!fct1(err)) report(*err);
1754 * if (!fct2(err)) report(*err);
1755 * if (!fct3(err)) report(*err);
1756 * free(*err);
1757 */
1758char *memprintf(char **out, const char *format, ...)
1759{
1760 va_list args;
1761 char *ret = NULL;
1762 int allocated = 0;
1763 int needed = 0;
1764
1765 do {
1766 /* vsnprintf() will return the required length even when the
1767 * target buffer is NULL. We do this in a loop just in case
1768 * intermediate evaluations get wrong.
1769 */
1770 va_start(args, format);
1771 needed = vsnprintf(ret, allocated, format, args) + 1;
1772 va_end(args);
1773
1774 if (needed <= allocated)
1775 break;
1776
1777 allocated = needed;
1778 ret = realloc(ret, allocated);
1779 } while (ret);
1780
1781 if (needed < 0) {
1782 /* an error was encountered */
1783 free(ret);
1784 ret = NULL;
1785 }
1786
1787 if (out) {
1788 free(*out);
1789 *out = ret;
1790 }
1791
1792 return ret;
1793}
William Lallemand421f5b52012-02-06 18:15:57 +01001794
Willy Tarreaubaaee002006-06-26 02:48:02 +02001795/*
1796 * Local variables:
1797 * c-indent-level: 8
1798 * c-basic-offset: 8
1799 * End:
1800 */