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