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