blob: db0e0e409085f5e450cf07c68f18ceac21274769 [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
Sean Carey58ea0392013-02-15 23:39:18 +0100603 if (result)
604 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100605 }
David du Colombierd5f43282011-03-17 10:40:16 +0100606#endif
607 /* unsupported address family */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100608
609 return NULL;
610}
611
612/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100613 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
614 * range or offset consisting in two integers that the caller will have to
615 * check to find the relevant input format. The following format are supported :
616 *
617 * String format | address | port | low | high
618 * addr | <addr> | 0 | 0 | 0
619 * addr: | <addr> | 0 | 0 | 0
620 * addr:port | <addr> | <port> | <port> | <port>
621 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
622 * addr:+port | <addr> | <port> | 0 | <port>
623 * addr:-port | <addr> |-<port> | <port> | 0
624 *
625 * The detection of a port range or increment by the caller is made by
626 * comparing <low> and <high>. If both are equal, then port 0 means no port
627 * was specified. The caller may pass NULL for <low> and <high> if it is not
628 * interested in retrieving port ranges.
629 *
630 * Note that <addr> above may also be :
631 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
632 * - "*" => family will be AF_INET and address will be INADDR_ANY
633 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
634 * - a host name => family and address will depend on host name resolving.
635 *
636 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
637 * is mandatory after the IP address even when no port is specified. NULL is
638 * returned if the address cannot be parsed. The <low> and <high> ports are
639 * always initialized if non-null.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100640 */
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100641struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100642{
David du Colombier6f5ccb12011-03-10 22:26:24 +0100643 struct sockaddr_storage *ret = NULL;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100644 char *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100645 char *port1, *port2;
646 int portl, porth, porta;
647
648 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200649
Willy Tarreaufab5a432011-03-04 15:31:53 +0100650 str2 = strdup(str);
651 if (str2 == NULL)
Willy Tarreaud5191e72010-02-09 20:50:45 +0100652 goto out;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200653
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100654 port1 = strrchr(str2, ':');
655 if (port1)
656 *port1++ = '\0';
Willy Tarreaubaaee002006-06-26 02:48:02 +0200657 else
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100658 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200659
Willy Tarreaufab5a432011-03-04 15:31:53 +0100660 ret = str2ip(str2);
661 if (!ret)
662 goto out;
663
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100664 if (isdigit(*port1)) { /* single port or range */
665 port2 = strchr(port1, '-');
666 if (port2)
667 *port2++ = '\0';
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200668 else
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100669 port2 = port1;
670 portl = atoi(port1);
671 porth = atoi(port2);
672 porta = portl;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200673 }
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100674 else if (*port1 == '-') { /* negative offset */
675 portl = atoi(port1 + 1);
676 porta = -portl;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200677 }
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100678 else if (*port1 == '+') { /* positive offset */
679 porth = atoi(port1 + 1);
680 porta = porth;
681 }
682 else if (*port1) /* other any unexpected char */
683 ret = NULL;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100684
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100685 set_host_port(ret, porta);
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200686
Willy Tarreaud5191e72010-02-09 20:50:45 +0100687 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100688 if (low)
689 *low = portl;
690 if (high)
691 *high = porth;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100692 free(str2);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100693 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200694}
695
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100696/* converts <str> to a struct in_addr containing a network mask. It can be
697 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
698 * if the conversion succeeds otherwise non-zero.
699 */
700int str2mask(const char *str, struct in_addr *mask)
701{
702 if (strchr(str, '.') != NULL) { /* dotted notation */
703 if (!inet_pton(AF_INET, str, mask))
704 return 0;
705 }
706 else { /* mask length */
707 char *err;
708 unsigned long len = strtol(str, &err, 10);
709
710 if (!*str || (err && *err) || (unsigned)len > 32)
711 return 0;
712 if (len)
713 mask->s_addr = htonl(~0UL << (32 - len));
714 else
715 mask->s_addr = 0;
716 }
717 return 1;
718}
719
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200720/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200721 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200722 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
723 * is optionnal and either in the dotted or CIDR notation.
724 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
725 */
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200726int str2net(const char *str, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200727{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200728 __label__ out_free, out_err;
729 char *c, *s;
730 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200731
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200732 s = strdup(str);
733 if (!s)
734 return 0;
735
Willy Tarreaubaaee002006-06-26 02:48:02 +0200736 memset(mask, 0, sizeof(*mask));
737 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200738
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200739 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200740 *c++ = '\0';
741 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100742 if (!str2mask(c, mask))
743 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200744 }
745 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100746 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200747 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200748 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200749 struct hostent *he;
750
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200751 if ((he = gethostbyname(s)) == NULL) {
752 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200753 }
754 else
755 *addr = *(struct in_addr *) *(he->h_addr_list);
756 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200757
758 ret_val = 1;
759 out_free:
760 free(s);
761 return ret_val;
762 out_err:
763 ret_val = 0;
764 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200765}
766
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100767
768/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200769 * converts <str> to two struct in6_addr* which must be pre-allocated.
770 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
771 * is an optionnal number of bits (128 being the default).
772 * Returns 1 if OK, 0 if error.
773 */
774int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
775{
776 char *c, *s;
777 int ret_val = 0;
778 char *err;
779 unsigned long len = 128;
780
781 s = strdup(str);
782 if (!s)
783 return 0;
784
785 memset(mask, 0, sizeof(*mask));
786 memset(addr, 0, sizeof(*addr));
787
788 if ((c = strrchr(s, '/')) != NULL) {
789 *c++ = '\0'; /* c points to the mask */
790 if (!*c)
791 goto out_free;
792
793 len = strtoul(c, &err, 10);
794 if ((err && *err) || (unsigned)len > 128)
795 goto out_free;
796 }
797 *mask = len; /* OK we have a valid mask in <len> */
798
799 if (!inet_pton(AF_INET6, s, addr))
800 goto out_free;
801
802 ret_val = 1;
803 out_free:
804 free(s);
805 return ret_val;
806}
807
808
809/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100810 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100811 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100812int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100813{
814 int saw_digit, octets, ch;
815 u_char tmp[4], *tp;
816 const char *cp = addr;
817
818 saw_digit = 0;
819 octets = 0;
820 *(tp = tmp) = 0;
821
822 while (*addr) {
823 unsigned char digit = (ch = *addr++) - '0';
824 if (digit > 9 && ch != '.')
825 break;
826 if (digit <= 9) {
827 u_int new = *tp * 10 + digit;
828 if (new > 255)
829 return 0;
830 *tp = new;
831 if (!saw_digit) {
832 if (++octets > 4)
833 return 0;
834 saw_digit = 1;
835 }
836 } else if (ch == '.' && saw_digit) {
837 if (octets == 4)
838 return 0;
839 *++tp = 0;
840 saw_digit = 0;
841 } else
842 return 0;
843 }
844
845 if (octets < 4)
846 return 0;
847
848 memcpy(&dst->s_addr, tmp, 4);
849 return addr-cp-1;
850}
851
852/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100853 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100854 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100855int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100856{
857 const char *curr = url, *cp = url;
858 int ret, url_code = 0;
859 unsigned int http_code = 0;
860
861 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100862
863 /* FIXME: assume IPv4 only for now */
864 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
865 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
866 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100867
868 /* Firstly, try to find :// pattern */
869 while (curr < url+ulen && url_code != 0x3a2f2f) {
870 url_code = ((url_code & 0xffff) << 8);
871 url_code += (unsigned char)*curr++;
872 }
873
874 /* Secondly, if :// pattern is found, verify parsed stuff
875 * before pattern is matching our http pattern.
876 * If so parse ip address and port in uri.
877 *
878 * WARNING: Current code doesn't support dynamic async dns resolver.
879 */
880 if (url_code == 0x3a2f2f) {
881 while (cp < curr - 3)
882 http_code = (http_code << 8) + *cp++;
883 http_code |= 0x20202020; /* Turn everything to lower case */
884
885 /* HTTP url matching */
886 if (http_code == 0x68747470) {
887 /* We are looking for IP address. If you want to parse and
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100888 * resolve hostname found in url, you can use str2sa_range(), but
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100889 * be warned this can slow down global daemon performances
890 * while handling lagging dns responses.
891 */
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200892 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100893 if (!ret)
894 return -1;
895 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100896 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200897 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100898 }
899 return 0;
900 }
901
902 return -1;
903}
904
Willy Tarreau631f01c2011-09-05 00:36:48 +0200905/* Tries to convert a sockaddr_storage address to text form. Upon success, the
906 * address family is returned so that it's easy for the caller to adapt to the
907 * output format. Zero is returned if the address family is not supported. -1
908 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
909 * supported.
910 */
911int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
912{
913
914 void *ptr;
915
916 if (size < 5)
917 return 0;
918 *str = '\0';
919
920 switch (addr->ss_family) {
921 case AF_INET:
922 ptr = &((struct sockaddr_in *)addr)->sin_addr;
923 break;
924 case AF_INET6:
925 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
926 break;
927 case AF_UNIX:
928 memcpy(str, "unix", 5);
929 return addr->ss_family;
930 default:
931 return 0;
932 }
933
934 if (inet_ntop(addr->ss_family, ptr, str, size))
935 return addr->ss_family;
936
937 /* failed */
938 return -1;
939}
940
Willy Tarreaubaaee002006-06-26 02:48:02 +0200941/* will try to encode the string <string> replacing all characters tagged in
942 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
943 * prefixed by <escape>, and will store the result between <start> (included)
944 * and <stop> (excluded), and will always terminate the string with a '\0'
945 * before <stop>. The position of the '\0' is returned if the conversion
946 * completes. If bytes are missing between <start> and <stop>, then the
947 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
948 * cannot even be stored so we return <start> without writing the 0.
949 * The input string must also be zero-terminated.
950 */
951const char hextab[16] = "0123456789ABCDEF";
952char *encode_string(char *start, char *stop,
953 const char escape, const fd_set *map,
954 const char *string)
955{
956 if (start < stop) {
957 stop--; /* reserve one byte for the final '\0' */
958 while (start < stop && *string != '\0') {
959 if (!FD_ISSET((unsigned char)(*string), map))
960 *start++ = *string;
961 else {
962 if (start + 3 >= stop)
963 break;
964 *start++ = escape;
965 *start++ = hextab[(*string >> 4) & 15];
966 *start++ = hextab[*string & 15];
967 }
968 string++;
969 }
970 *start = '\0';
971 }
972 return start;
973}
974
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +0200975/* Decode an URL-encoded string in-place. The resulting string might
976 * be shorter. If some forbidden characters are found, the conversion is
977 * aborted, the string is truncated before the issue and non-zero is returned,
978 * otherwise the operation returns non-zero indicating success.
979 */
980int url_decode(char *string)
981{
982 char *in, *out;
983 int ret = 0;
984
985 in = string;
986 out = string;
987 while (*in) {
988 switch (*in) {
989 case '+' :
990 *out++ = ' ';
991 break;
992 case '%' :
993 if (!ishex(in[1]) || !ishex(in[2]))
994 goto end;
995 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
996 in += 2;
997 break;
998 default:
999 *out++ = *in;
1000 break;
1001 }
1002 in++;
1003 }
1004 ret = 1; /* success */
1005 end:
1006 *out = 0;
1007 return ret;
1008}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001009
Willy Tarreau6911fa42007-03-04 18:06:08 +01001010unsigned int str2ui(const char *s)
1011{
1012 return __str2ui(s);
1013}
1014
1015unsigned int str2uic(const char *s)
1016{
1017 return __str2uic(s);
1018}
1019
1020unsigned int strl2ui(const char *s, int len)
1021{
1022 return __strl2ui(s, len);
1023}
1024
1025unsigned int strl2uic(const char *s, int len)
1026{
1027 return __strl2uic(s, len);
1028}
1029
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001030unsigned int read_uint(const char **s, const char *end)
1031{
1032 return __read_uint(s, end);
1033}
1034
Willy Tarreau6911fa42007-03-04 18:06:08 +01001035/* This one is 7 times faster than strtol() on athlon with checks.
1036 * It returns the value of the number composed of all valid digits read,
1037 * and can process negative numbers too.
1038 */
1039int strl2ic(const char *s, int len)
1040{
1041 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001042 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001043
1044 if (len > 0) {
1045 if (*s != '-') {
1046 /* positive number */
1047 while (len-- > 0) {
1048 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001049 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001050 if (j > 9)
1051 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001052 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001053 }
1054 } else {
1055 /* negative number */
1056 s++;
1057 while (--len > 0) {
1058 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001059 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001060 if (j > 9)
1061 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001062 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001063 }
1064 }
1065 }
1066 return i;
1067}
1068
1069
1070/* This function reads exactly <len> chars from <s> and converts them to a
1071 * signed integer which it stores into <ret>. It accurately detects any error
1072 * (truncated string, invalid chars, overflows). It is meant to be used in
1073 * applications designed for hostile environments. It returns zero when the
1074 * number has successfully been converted, non-zero otherwise. When an error
1075 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1076 * faster than strtol().
1077 */
1078int strl2irc(const char *s, int len, int *ret)
1079{
1080 int i = 0;
1081 int j;
1082
1083 if (!len)
1084 return 1;
1085
1086 if (*s != '-') {
1087 /* positive number */
1088 while (len-- > 0) {
1089 j = (*s++) - '0';
1090 if (j > 9) return 1; /* invalid char */
1091 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1092 i = i * 10;
1093 if (i + j < i) return 1; /* check for addition overflow */
1094 i = i + j;
1095 }
1096 } else {
1097 /* negative number */
1098 s++;
1099 while (--len > 0) {
1100 j = (*s++) - '0';
1101 if (j > 9) return 1; /* invalid char */
1102 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1103 i = i * 10;
1104 if (i - j > i) return 1; /* check for subtract overflow */
1105 i = i - j;
1106 }
1107 }
1108 *ret = i;
1109 return 0;
1110}
1111
1112
1113/* This function reads exactly <len> chars from <s> and converts them to a
1114 * signed integer which it stores into <ret>. It accurately detects any error
1115 * (truncated string, invalid chars, overflows). It is meant to be used in
1116 * applications designed for hostile environments. It returns zero when the
1117 * number has successfully been converted, non-zero otherwise. When an error
1118 * is returned, the <ret> value is left untouched. It is about 3 times slower
1119 * than str2irc().
1120 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001121
1122int strl2llrc(const char *s, int len, long long *ret)
1123{
1124 long long i = 0;
1125 int j;
1126
1127 if (!len)
1128 return 1;
1129
1130 if (*s != '-') {
1131 /* positive number */
1132 while (len-- > 0) {
1133 j = (*s++) - '0';
1134 if (j > 9) return 1; /* invalid char */
1135 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1136 i = i * 10LL;
1137 if (i + j < i) return 1; /* check for addition overflow */
1138 i = i + j;
1139 }
1140 } else {
1141 /* negative number */
1142 s++;
1143 while (--len > 0) {
1144 j = (*s++) - '0';
1145 if (j > 9) return 1; /* invalid char */
1146 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1147 i = i * 10LL;
1148 if (i - j > i) return 1; /* check for subtract overflow */
1149 i = i - j;
1150 }
1151 }
1152 *ret = i;
1153 return 0;
1154}
1155
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001156/* This function parses a time value optionally followed by a unit suffix among
1157 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1158 * expected by the caller. The computation does its best to avoid overflows.
1159 * The value is returned in <ret> if everything is fine, and a NULL is returned
1160 * by the function. In case of error, a pointer to the error is returned and
1161 * <ret> is left untouched. Values are automatically rounded up when needed.
1162 */
1163const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1164{
1165 unsigned imult, idiv;
1166 unsigned omult, odiv;
1167 unsigned value;
1168
1169 omult = odiv = 1;
1170
1171 switch (unit_flags & TIME_UNIT_MASK) {
1172 case TIME_UNIT_US: omult = 1000000; break;
1173 case TIME_UNIT_MS: omult = 1000; break;
1174 case TIME_UNIT_S: break;
1175 case TIME_UNIT_MIN: odiv = 60; break;
1176 case TIME_UNIT_HOUR: odiv = 3600; break;
1177 case TIME_UNIT_DAY: odiv = 86400; break;
1178 default: break;
1179 }
1180
1181 value = 0;
1182
1183 while (1) {
1184 unsigned int j;
1185
1186 j = *text - '0';
1187 if (j > 9)
1188 break;
1189 text++;
1190 value *= 10;
1191 value += j;
1192 }
1193
1194 imult = idiv = 1;
1195 switch (*text) {
1196 case '\0': /* no unit = default unit */
1197 imult = omult = idiv = odiv = 1;
1198 break;
1199 case 's': /* second = unscaled unit */
1200 break;
1201 case 'u': /* microsecond : "us" */
1202 if (text[1] == 's') {
1203 idiv = 1000000;
1204 text++;
1205 }
1206 break;
1207 case 'm': /* millisecond : "ms" or minute: "m" */
1208 if (text[1] == 's') {
1209 idiv = 1000;
1210 text++;
1211 } else
1212 imult = 60;
1213 break;
1214 case 'h': /* hour : "h" */
1215 imult = 3600;
1216 break;
1217 case 'd': /* day : "d" */
1218 imult = 86400;
1219 break;
1220 default:
1221 return text;
1222 break;
1223 }
1224
1225 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1226 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1227 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1228 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1229
1230 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1231 *ret = value;
1232 return NULL;
1233}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001234
Emeric Brun39132b22010-01-04 14:57:24 +01001235/* this function converts the string starting at <text> to an unsigned int
1236 * stored in <ret>. If an error is detected, the pointer to the unexpected
1237 * character is returned. If the conversio is succesful, NULL is returned.
1238 */
1239const char *parse_size_err(const char *text, unsigned *ret) {
1240 unsigned value = 0;
1241
1242 while (1) {
1243 unsigned int j;
1244
1245 j = *text - '0';
1246 if (j > 9)
1247 break;
1248 if (value > ~0U / 10)
1249 return text;
1250 value *= 10;
1251 if (value > (value + j))
1252 return text;
1253 value += j;
1254 text++;
1255 }
1256
1257 switch (*text) {
1258 case '\0':
1259 break;
1260 case 'K':
1261 case 'k':
1262 if (value > ~0U >> 10)
1263 return text;
1264 value = value << 10;
1265 break;
1266 case 'M':
1267 case 'm':
1268 if (value > ~0U >> 20)
1269 return text;
1270 value = value << 20;
1271 break;
1272 case 'G':
1273 case 'g':
1274 if (value > ~0U >> 30)
1275 return text;
1276 value = value << 30;
1277 break;
1278 default:
1279 return text;
1280 }
1281
1282 *ret = value;
1283 return NULL;
1284}
1285
Willy Tarreau946ba592009-05-10 15:41:18 +02001286/* copies at most <n> characters from <src> and always terminates with '\0' */
1287char *my_strndup(const char *src, int n)
1288{
1289 int len = 0;
1290 char *ret;
1291
1292 while (len < n && src[len])
1293 len++;
1294
1295 ret = (char *)malloc(len + 1);
1296 if (!ret)
1297 return ret;
1298 memcpy(ret, src, len);
1299 ret[len] = '\0';
1300 return ret;
1301}
1302
Willy Tarreau482b00d2009-10-04 22:48:42 +02001303/* This function returns the first unused key greater than or equal to <key> in
1304 * ID tree <root>. Zero is returned if no place is found.
1305 */
1306unsigned int get_next_id(struct eb_root *root, unsigned int key)
1307{
1308 struct eb32_node *used;
1309
1310 do {
1311 used = eb32_lookup_ge(root, key);
1312 if (!used || used->key > key)
1313 return key; /* key is available */
1314 key++;
1315 } while (key);
1316 return key;
1317}
1318
Willy Tarreau348238b2010-01-18 15:05:57 +01001319/* This function compares a sample word possibly followed by blanks to another
1320 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1321 * otherwise zero. This intends to be used when checking HTTP headers for some
1322 * values. Note that it validates a word followed only by blanks but does not
1323 * validate a word followed by blanks then other chars.
1324 */
1325int word_match(const char *sample, int slen, const char *word, int wlen)
1326{
1327 if (slen < wlen)
1328 return 0;
1329
1330 while (wlen) {
1331 char c = *sample ^ *word;
1332 if (c && c != ('A' ^ 'a'))
1333 return 0;
1334 sample++;
1335 word++;
1336 slen--;
1337 wlen--;
1338 }
1339
1340 while (slen) {
1341 if (*sample != ' ' && *sample != '\t')
1342 return 0;
1343 sample++;
1344 slen--;
1345 }
1346 return 1;
1347}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001348
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001349/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1350 * is particularly fast because it avoids expensive operations such as
1351 * multiplies, which are optimized away at the end. It requires a properly
1352 * formated address though (3 points).
1353 */
1354unsigned int inetaddr_host(const char *text)
1355{
1356 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1357 register unsigned int dig100, dig10, dig1;
1358 int s;
1359 const char *p, *d;
1360
1361 dig1 = dig10 = dig100 = ascii_zero;
1362 s = 24;
1363
1364 p = text;
1365 while (1) {
1366 if (((unsigned)(*p - '0')) <= 9) {
1367 p++;
1368 continue;
1369 }
1370
1371 /* here, we have a complete byte between <text> and <p> (exclusive) */
1372 if (p == text)
1373 goto end;
1374
1375 d = p - 1;
1376 dig1 |= (unsigned int)(*d << s);
1377 if (d == text)
1378 goto end;
1379
1380 d--;
1381 dig10 |= (unsigned int)(*d << s);
1382 if (d == text)
1383 goto end;
1384
1385 d--;
1386 dig100 |= (unsigned int)(*d << s);
1387 end:
1388 if (!s || *p != '.')
1389 break;
1390
1391 s -= 8;
1392 text = ++p;
1393 }
1394
1395 dig100 -= ascii_zero;
1396 dig10 -= ascii_zero;
1397 dig1 -= ascii_zero;
1398 return ((dig100 * 10) + dig10) * 10 + dig1;
1399}
1400
1401/*
1402 * Idem except the first unparsed character has to be passed in <stop>.
1403 */
1404unsigned int inetaddr_host_lim(const char *text, const char *stop)
1405{
1406 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1407 register unsigned int dig100, dig10, dig1;
1408 int s;
1409 const char *p, *d;
1410
1411 dig1 = dig10 = dig100 = ascii_zero;
1412 s = 24;
1413
1414 p = text;
1415 while (1) {
1416 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1417 p++;
1418 continue;
1419 }
1420
1421 /* here, we have a complete byte between <text> and <p> (exclusive) */
1422 if (p == text)
1423 goto end;
1424
1425 d = p - 1;
1426 dig1 |= (unsigned int)(*d << s);
1427 if (d == text)
1428 goto end;
1429
1430 d--;
1431 dig10 |= (unsigned int)(*d << s);
1432 if (d == text)
1433 goto end;
1434
1435 d--;
1436 dig100 |= (unsigned int)(*d << s);
1437 end:
1438 if (!s || p == stop || *p != '.')
1439 break;
1440
1441 s -= 8;
1442 text = ++p;
1443 }
1444
1445 dig100 -= ascii_zero;
1446 dig10 -= ascii_zero;
1447 dig1 -= ascii_zero;
1448 return ((dig100 * 10) + dig10) * 10 + dig1;
1449}
1450
1451/*
1452 * Idem except the pointer to first unparsed byte is returned into <ret> which
1453 * must not be NULL.
1454 */
Willy Tarreau74172752010-10-15 23:21:42 +02001455unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001456{
1457 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1458 register unsigned int dig100, dig10, dig1;
1459 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001460 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001461
1462 dig1 = dig10 = dig100 = ascii_zero;
1463 s = 24;
1464
1465 p = text;
1466 while (1) {
1467 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1468 p++;
1469 continue;
1470 }
1471
1472 /* here, we have a complete byte between <text> and <p> (exclusive) */
1473 if (p == text)
1474 goto end;
1475
1476 d = p - 1;
1477 dig1 |= (unsigned int)(*d << s);
1478 if (d == text)
1479 goto end;
1480
1481 d--;
1482 dig10 |= (unsigned int)(*d << s);
1483 if (d == text)
1484 goto end;
1485
1486 d--;
1487 dig100 |= (unsigned int)(*d << s);
1488 end:
1489 if (!s || p == stop || *p != '.')
1490 break;
1491
1492 s -= 8;
1493 text = ++p;
1494 }
1495
1496 *ret = p;
1497 dig100 -= ascii_zero;
1498 dig10 -= ascii_zero;
1499 dig1 -= ascii_zero;
1500 return ((dig100 * 10) + dig10) * 10 + dig1;
1501}
1502
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001503/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1504 * or the number of chars read in case of success. Maybe this could be replaced
1505 * by one of the functions above. Also, apparently this function does not support
1506 * hosts above 255 and requires exactly 4 octets.
1507 */
1508int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1509{
1510 const char *addr;
1511 int saw_digit, octets, ch;
1512 u_char tmp[4], *tp;
1513 const char *cp = buf;
1514
1515 saw_digit = 0;
1516 octets = 0;
1517 *(tp = tmp) = 0;
1518
1519 for (addr = buf; addr - buf < len; addr++) {
1520 unsigned char digit = (ch = *addr) - '0';
1521
1522 if (digit > 9 && ch != '.')
1523 break;
1524
1525 if (digit <= 9) {
1526 u_int new = *tp * 10 + digit;
1527
1528 if (new > 255)
1529 return 0;
1530
1531 *tp = new;
1532
1533 if (!saw_digit) {
1534 if (++octets > 4)
1535 return 0;
1536 saw_digit = 1;
1537 }
1538 } else if (ch == '.' && saw_digit) {
1539 if (octets == 4)
1540 return 0;
1541
1542 *++tp = 0;
1543 saw_digit = 0;
1544 } else
1545 return 0;
1546 }
1547
1548 if (octets < 4)
1549 return 0;
1550
1551 memcpy(&dst->s_addr, tmp, 4);
1552 return addr - cp;
1553}
1554
Willy Tarreauacf95772010-06-14 19:09:21 +02001555/* To be used to quote config arg positions. Returns the short string at <ptr>
1556 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1557 * if ptr is NULL or empty. The string is locally allocated.
1558 */
1559const char *quote_arg(const char *ptr)
1560{
1561 static char val[32];
1562 int i;
1563
1564 if (!ptr || !*ptr)
1565 return "end of line";
1566 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001567 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001568 val[i] = *ptr++;
1569 val[i++] = '\'';
1570 val[i] = '\0';
1571 return val;
1572}
1573
Willy Tarreau5b180202010-07-18 10:40:48 +02001574/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1575int get_std_op(const char *str)
1576{
1577 int ret = -1;
1578
1579 if (*str == 'e' && str[1] == 'q')
1580 ret = STD_OP_EQ;
1581 else if (*str == 'n' && str[1] == 'e')
1582 ret = STD_OP_NE;
1583 else if (*str == 'l') {
1584 if (str[1] == 'e') ret = STD_OP_LE;
1585 else if (str[1] == 't') ret = STD_OP_LT;
1586 }
1587 else if (*str == 'g') {
1588 if (str[1] == 'e') ret = STD_OP_GE;
1589 else if (str[1] == 't') ret = STD_OP_GT;
1590 }
1591
1592 if (ret == -1 || str[2] != '\0')
1593 return -1;
1594 return ret;
1595}
1596
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001597/* hash a 32-bit integer to another 32-bit integer */
1598unsigned int full_hash(unsigned int a)
1599{
1600 return __full_hash(a);
1601}
1602
David du Colombier4f92d322011-03-24 11:09:31 +01001603/* Return non-zero if IPv4 address is part of the network,
1604 * otherwise zero.
1605 */
1606int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1607{
1608 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1609}
1610
1611/* Return non-zero if IPv6 address is part of the network,
1612 * otherwise zero.
1613 */
1614int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1615{
1616 int i;
1617
1618 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1619 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1620 (((int *)net)[i] & ((int *)mask)[i]))
1621 return 0;
1622 return 1;
1623}
1624
1625/* RFC 4291 prefix */
1626const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1627 0x00, 0x00, 0x00, 0x00,
1628 0x00, 0x00, 0xFF, 0xFF };
1629
1630/* Map IPv4 adress on IPv6 address, as specified in RFC 3513. */
1631void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1632{
1633 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
1634 memcpy(sin6_addr->s6_addr+12, &sin_addr->s_addr, 4);
1635}
1636
1637/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1638 * Return true if conversion is possible and false otherwise.
1639 */
1640int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1641{
1642 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1643 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1644 sizeof(struct in_addr));
1645 return 1;
1646 }
1647
1648 return 0;
1649}
1650
William Lallemand421f5b52012-02-06 18:15:57 +01001651char *human_time(int t, short hz_div) {
1652 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1653 char *p = rv;
1654 int cnt=2; // print two numbers
1655
1656 if (unlikely(t < 0 || hz_div <= 0)) {
1657 sprintf(p, "?");
1658 return rv;
1659 }
1660
1661 if (unlikely(hz_div > 1))
1662 t /= hz_div;
1663
1664 if (t >= DAY) {
1665 p += sprintf(p, "%dd", t / DAY);
1666 cnt--;
1667 }
1668
1669 if (cnt && t % DAY / HOUR) {
1670 p += sprintf(p, "%dh", t % DAY / HOUR);
1671 cnt--;
1672 }
1673
1674 if (cnt && t % HOUR / MINUTE) {
1675 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1676 cnt--;
1677 }
1678
1679 if ((cnt && t % MINUTE) || !t) // also display '0s'
1680 p += sprintf(p, "%ds", t % MINUTE / SEC);
1681
1682 return rv;
1683}
1684
1685const char *monthname[12] = {
1686 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1687 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1688};
1689
1690/* date2str_log: write a date in the format :
1691 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1692 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1693 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1694 *
1695 * without using sprintf. return a pointer to the last char written (\0) or
1696 * NULL if there isn't enough space.
1697 */
1698char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1699{
1700
1701 if (size < 25) /* the size is fixed: 24 chars + \0 */
1702 return NULL;
1703
1704 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1705 *dst++ = '/';
1706 memcpy(dst, monthname[tm->tm_mon], 3); // month
1707 dst += 3;
1708 *dst++ = '/';
1709 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1710 *dst++ = ':';
1711 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1712 *dst++ = ':';
1713 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1714 *dst++ = ':';
1715 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1716 *dst++ = '.';
1717 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1718 dst += 3; // only the 3 first digits
1719 *dst = '\0';
1720
1721 return dst;
1722}
1723
1724/* gmt2str_log: write a date in the format :
1725 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1726 * return a pointer to the last char written (\0) or
1727 * NULL if there isn't enough space.
1728 */
1729char *gmt2str_log(char *dst, struct tm *tm, size_t size)
1730{
Yuxans Yao4e25b012012-10-19 10:36:09 +08001731 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01001732 return NULL;
1733
1734 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1735 *dst++ = '/';
1736 memcpy(dst, monthname[tm->tm_mon], 3); // month
1737 dst += 3;
1738 *dst++ = '/';
1739 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1740 *dst++ = ':';
1741 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1742 *dst++ = ':';
1743 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1744 *dst++ = ':';
1745 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1746 *dst++ = ' ';
1747 *dst++ = '+';
1748 *dst++ = '0';
1749 *dst++ = '0';
1750 *dst++ = '0';
1751 *dst++ = '0';
1752 *dst = '\0';
1753
1754 return dst;
1755}
1756
Yuxans Yao4e25b012012-10-19 10:36:09 +08001757/* localdate2str_log: write a date in the format :
1758 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
1759 * * return a pointer to the last char written (\0) or
1760 * * NULL if there isn't enough space.
1761 */
1762char *localdate2str_log(char *dst, struct tm *tm, size_t size)
1763{
1764 if (size < 27) /* the size is fixed: 26 chars + \0 */
1765 return NULL;
1766
1767 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1768 *dst++ = '/';
1769 memcpy(dst, monthname[tm->tm_mon], 3); // month
1770 dst += 3;
1771 *dst++ = '/';
1772 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1773 *dst++ = ':';
1774 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1775 *dst++ = ':';
1776 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1777 *dst++ = ':';
1778 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1779 *dst++ = ' ';
1780 memcpy(dst, localtimezone, 5); // timezone
1781 dst += 5;
1782 *dst = '\0';
1783
1784 return dst;
1785}
1786
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001787/* Dynamically allocates a string of the proper length to hold the formatted
1788 * output. NULL is returned on error. The caller is responsible for freeing the
1789 * memory area using free(). The resulting string is returned in <out> if the
1790 * pointer is not NULL. A previous version of <out> might be used to build the
1791 * new string, and it will be freed before returning if it is not NULL, which
1792 * makes it possible to build complex strings from iterative calls without
1793 * having to care about freeing intermediate values, as in the example below :
1794 *
1795 * memprintf(&err, "invalid argument: '%s'", arg);
1796 * ...
1797 * memprintf(&err, "parser said : <%s>\n", *err);
1798 * ...
1799 * free(*err);
1800 *
1801 * This means that <err> must be initialized to NULL before first invocation.
1802 * The return value also holds the allocated string, which eases error checking
1803 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02001804 * passed instead and it will be ignored. The returned message will then also
1805 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001806 *
1807 * It is also convenient to use it without any free except the last one :
1808 * err = NULL;
1809 * if (!fct1(err)) report(*err);
1810 * if (!fct2(err)) report(*err);
1811 * if (!fct3(err)) report(*err);
1812 * free(*err);
1813 */
1814char *memprintf(char **out, const char *format, ...)
1815{
1816 va_list args;
1817 char *ret = NULL;
1818 int allocated = 0;
1819 int needed = 0;
1820
Willy Tarreaueb6cead2012-09-20 19:43:14 +02001821 if (!out)
1822 return NULL;
1823
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001824 do {
1825 /* vsnprintf() will return the required length even when the
1826 * target buffer is NULL. We do this in a loop just in case
1827 * intermediate evaluations get wrong.
1828 */
1829 va_start(args, format);
1830 needed = vsnprintf(ret, allocated, format, args) + 1;
1831 va_end(args);
1832
1833 if (needed <= allocated)
1834 break;
1835
1836 allocated = needed;
1837 ret = realloc(ret, allocated);
1838 } while (ret);
1839
1840 if (needed < 0) {
1841 /* an error was encountered */
1842 free(ret);
1843 ret = NULL;
1844 }
1845
1846 if (out) {
1847 free(*out);
1848 *out = ret;
1849 }
1850
1851 return ret;
1852}
William Lallemand421f5b52012-02-06 18:15:57 +01001853
Willy Tarreau21c705b2012-09-14 11:40:36 +02001854/* Used to add <level> spaces before each line of <out>, unless there is only one line.
1855 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02001856 * freed by the caller. It also supports being passed a NULL which results in the same
1857 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02001858 * Example of use :
1859 * parse(cmd, &err); (callee: memprintf(&err, ...))
1860 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
1861 * free(err);
1862 */
1863char *indent_msg(char **out, int level)
1864{
1865 char *ret, *in, *p;
1866 int needed = 0;
1867 int lf = 0;
1868 int lastlf = 0;
1869 int len;
1870
Willy Tarreau70eec382012-10-10 08:56:47 +02001871 if (!out || !*out)
1872 return NULL;
1873
Willy Tarreau21c705b2012-09-14 11:40:36 +02001874 in = *out - 1;
1875 while ((in = strchr(in + 1, '\n')) != NULL) {
1876 lastlf = in - *out;
1877 lf++;
1878 }
1879
1880 if (!lf) /* single line, no LF, return it as-is */
1881 return *out;
1882
1883 len = strlen(*out);
1884
1885 if (lf == 1 && lastlf == len - 1) {
1886 /* single line, LF at end, strip it and return as-is */
1887 (*out)[lastlf] = 0;
1888 return *out;
1889 }
1890
1891 /* OK now we have at least one LF, we need to process the whole string
1892 * as a multi-line string. What we'll do :
1893 * - prefix with an LF if there is none
1894 * - add <level> spaces before each line
1895 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
1896 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
1897 */
1898
1899 needed = 1 + level * (lf + 1) + len + 1;
1900 p = ret = malloc(needed);
1901 in = *out;
1902
1903 /* skip initial LFs */
1904 while (*in == '\n')
1905 in++;
1906
1907 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
1908 while (*in) {
1909 *p++ = '\n';
1910 memset(p, ' ', level);
1911 p += level;
1912 do {
1913 *p++ = *in++;
1914 } while (*in && *in != '\n');
1915 if (*in)
1916 in++;
1917 }
1918 *p = 0;
1919
1920 free(*out);
1921 *out = ret;
1922
1923 return ret;
1924}
1925
Willy Tarreaubaaee002006-06-26 02:48:02 +02001926/*
1927 * Local variables:
1928 * c-indent-level: 8
1929 * c-basic-offset: 8
1930 * End:
1931 */