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