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