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