blob: e9be0f97f5b4c847af56a8bb40bd9a91cf2a8c4f [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>
15#include <stdlib.h>
16#include <string.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010017#include <sys/socket.h>
18#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020019#include <netinet/in.h>
20#include <arpa/inet.h>
21
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020022#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020023#include <common/standard.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010024#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020025#include <proto/log.h>
26
Willy Tarreau72d759c2007-10-25 12:14:10 +020027/* enough to store 10 integers of :
28 * 2^64-1 = 18446744073709551615 or
29 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020030 *
31 * The HTML version needs room for adding the 25 characters
32 * '<span class="rls"></span>' around digits at positions 3N+1 in order
33 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020034 */
Willy Tarreaue7239b52009-03-29 13:41:58 +020035char itoa_str[10][171];
Willy Tarreaubaaee002006-06-26 02:48:02 +020036
37/*
38 * copies at most <size-1> chars from <src> to <dst>. Last char is always
39 * set to 0, unless <size> is 0. The number of chars copied is returned
40 * (excluding the terminating zero).
41 * This code has been optimized for size and speed : on x86, it's 45 bytes
42 * long, uses only registers, and consumes only 4 cycles per char.
43 */
44int strlcpy2(char *dst, const char *src, int size)
45{
46 char *orig = dst;
47 if (size) {
48 while (--size && (*dst = *src)) {
49 src++; dst++;
50 }
51 *dst = 0;
52 }
53 return dst - orig;
54}
55
56/*
Willy Tarreau72d759c2007-10-25 12:14:10 +020057 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +020058 * the ascii representation for number 'n' in decimal.
59 */
Emeric Brun3a7fce52010-01-04 14:54:38 +010060char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +020061{
62 char *pos;
63
Willy Tarreau72d759c2007-10-25 12:14:10 +020064 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +020065 *pos-- = '\0';
66
67 do {
68 *pos-- = '0' + n % 10;
69 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +020070 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +020071 return pos + 1;
72}
73
Willy Tarreau91092e52007-10-25 16:58:42 +020074/*
Willy Tarreaue7239b52009-03-29 13:41:58 +020075 * This function simply returns a locally allocated string containing
76 * the ascii representation for number 'n' in decimal, formatted for
77 * HTML output with tags to create visual grouping by 3 digits. The
78 * output needs to support at least 171 characters.
79 */
80const char *ulltoh_r(unsigned long long n, char *buffer, int size)
81{
82 char *start;
83 int digit = 0;
84
85 start = buffer + size;
86 *--start = '\0';
87
88 do {
89 if (digit == 3 && start >= buffer + 7)
90 memcpy(start -= 7, "</span>", 7);
91
92 if (start >= buffer + 1) {
93 *--start = '0' + n % 10;
94 n /= 10;
95 }
96
97 if (digit == 3 && start >= buffer + 18)
98 memcpy(start -= 18, "<span class=\"rls\">", 18);
99
100 if (digit++ == 3)
101 digit = 1;
102 } while (n && start > buffer);
103 return start;
104}
105
106/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200107 * This function simply returns a locally allocated string containing the ascii
108 * representation for number 'n' in decimal, unless n is 0 in which case it
109 * returns the alternate string (or an empty string if the alternate string is
110 * NULL). It use is intended for limits reported in reports, where it's
111 * desirable not to display anything if there is no limit. Warning! it shares
112 * the same vector as ultoa_r().
113 */
114const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
115{
116 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
117}
118
Robert Tsai81ae1952007-12-05 10:47:29 +0100119/*
120 * converts <str> to a struct sockaddr_un* which is locally allocated.
121 * The format is "/path", where "/path" is a path to a UNIX domain socket.
122 */
Willy Tarreaucaf720d2008-03-07 10:07:04 +0100123struct sockaddr_un *str2sun(const char *str)
Robert Tsai81ae1952007-12-05 10:47:29 +0100124{
Willy Tarreau127f9662007-12-06 00:53:51 +0100125 static struct sockaddr_un su;
Robert Tsai81ae1952007-12-05 10:47:29 +0100126 int strsz; /* length included null */
127
Willy Tarreau127f9662007-12-06 00:53:51 +0100128 memset(&su, 0, sizeof(su));
Robert Tsai81ae1952007-12-05 10:47:29 +0100129 strsz = strlen(str) + 1;
Willy Tarreau127f9662007-12-06 00:53:51 +0100130 if (strsz > sizeof(su.sun_path)) {
Robert Tsai81ae1952007-12-05 10:47:29 +0100131 Alert("Socket path '%s' too long (max %d)\n",
Willy Tarreau5e4a6f12009-04-11 19:42:49 +0200132 str, (int)sizeof(su.sun_path) - 1);
Willy Tarreaucaf720d2008-03-07 10:07:04 +0100133 } else {
134 su.sun_family = AF_UNIX;
135 memcpy(su.sun_path, str, strsz);
Robert Tsai81ae1952007-12-05 10:47:29 +0100136 }
Willy Tarreau127f9662007-12-06 00:53:51 +0100137 return &su;
Robert Tsai81ae1952007-12-05 10:47:29 +0100138}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200139
140/*
141 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
142 *
143 * It looks like this one would be a good candidate for inlining, but this is
144 * not interesting because it around 35 bytes long and often called multiple
145 * times within the same function.
146 */
147int ishex(char s)
148{
149 s -= '0';
150 if ((unsigned char)s <= 9)
151 return 1;
152 s -= 'A' - '0';
153 if ((unsigned char)s <= 5)
154 return 1;
155 s -= 'a' - 'A';
156 if ((unsigned char)s <= 5)
157 return 1;
158 return 0;
159}
160
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100161/*
Willy Tarreauda3b7c32009-11-02 20:12:52 +0100162 * Return integer equivalent of character <c> for a hex digit (0-9, a-f, A-F),
163 * otherwise -1. This compact form helps gcc produce efficient code.
164 */
165int hex2i(int c)
166{
167 if ((unsigned char)(c -= '0') > 9) {
168 if ((unsigned char)(c -= 'A' - '0') > 5 &&
169 (unsigned char)(c -= 'a' - 'A') > 5)
170 c = -11;
171 c += 10;
172 }
173 return c;
174}
175
176/*
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100177 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
178 * invalid character is found, a pointer to it is returned. If everything is
179 * fine, NULL is returned.
180 */
181const char *invalid_char(const char *name)
182{
183 if (!*name)
184 return name;
185
186 while (*name) {
Willy Tarreau127f9662007-12-06 00:53:51 +0100187 if (!isalnum((int)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100188 *name != '_' && *name != '-')
189 return name;
190 name++;
191 }
192 return NULL;
193}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200194
195/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200196 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
197 * If an invalid character is found, a pointer to it is returned.
198 * If everything is fine, NULL is returned.
199 */
200const char *invalid_domainchar(const char *name) {
201
202 if (!*name)
203 return name;
204
205 while (*name) {
206 if (!isalnum((int)*name) && *name != '.' &&
207 *name != '_' && *name != '-')
208 return name;
209
210 name++;
211 }
212
213 return NULL;
214}
215
216/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200217 * converts <str> to a struct sockaddr_in* which is locally allocated.
218 * The format is "addr:port", where "addr" can be a dotted IPv4 address,
219 * a host name, or empty or "*" to indicate INADDR_ANY.
220 */
221struct sockaddr_in *str2sa(char *str)
222{
223 static struct sockaddr_in sa;
224 char *c;
225 int port;
226
227 memset(&sa, 0, sizeof(sa));
228 str = strdup(str);
Willy Tarreauc6423482006-10-15 14:59:03 +0200229 if (str == NULL)
230 goto out_nofree;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200231
232 if ((c = strrchr(str,':')) != NULL) {
233 *c++ = '\0';
234 port = atol(c);
235 }
236 else
237 port = 0;
238
239 if (*str == '*' || *str == '\0') { /* INADDR_ANY */
240 sa.sin_addr.s_addr = INADDR_ANY;
241 }
242 else if (!inet_pton(AF_INET, str, &sa.sin_addr)) {
243 struct hostent *he;
244
245 if ((he = gethostbyname(str)) == NULL) {
246 Alert("Invalid server name: '%s'\n", str);
247 }
248 else
249 sa.sin_addr = *(struct in_addr *) *(he->h_addr_list);
250 }
251 sa.sin_port = htons(port);
252 sa.sin_family = AF_INET;
253
254 free(str);
Willy Tarreauc6423482006-10-15 14:59:03 +0200255 out_nofree:
Willy Tarreaubaaee002006-06-26 02:48:02 +0200256 return &sa;
257}
258
259/*
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200260 * converts <str> to a struct sockaddr_in* which is locally allocated, and a
261 * port range consisting in two integers. The low and high end are always set
262 * even if the port is unspecified, in which case (0,0) is returned. The low
263 * port is set in the sockaddr_in. Thus, it is enough to check the size of the
264 * returned range to know if an array must be allocated or not. The format is
265 * "addr[:port[-port]]", where "addr" can be a dotted IPv4 address, a host
266 * name, or empty or "*" to indicate INADDR_ANY.
267 */
268struct sockaddr_in *str2sa_range(char *str, int *low, int *high)
269{
270 static struct sockaddr_in sa;
271 char *c;
272 int portl, porth;
273
274 memset(&sa, 0, sizeof(sa));
275 str = strdup(str);
276 if (str == NULL)
277 goto out_nofree;
278
279 if ((c = strrchr(str,':')) != NULL) {
280 char *sep;
281 *c++ = '\0';
282 sep = strchr(c, '-');
283 if (sep)
284 *sep++ = '\0';
285 else
286 sep = c;
287 portl = atol(c);
288 porth = atol(sep);
289 }
290 else {
291 portl = 0;
292 porth = 0;
293 }
294
295 if (*str == '*' || *str == '\0') { /* INADDR_ANY */
296 sa.sin_addr.s_addr = INADDR_ANY;
297 }
298 else if (!inet_pton(AF_INET, str, &sa.sin_addr)) {
299 struct hostent *he;
300
301 if ((he = gethostbyname(str)) == NULL) {
302 Alert("Invalid server name: '%s'\n", str);
303 }
304 else
305 sa.sin_addr = *(struct in_addr *) *(he->h_addr_list);
306 }
307 sa.sin_port = htons(portl);
308 sa.sin_family = AF_INET;
309
310 *low = portl;
311 *high = porth;
312
313 free(str);
314 out_nofree:
315 return &sa;
316}
317
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100318/* converts <str> to a struct in_addr containing a network mask. It can be
319 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
320 * if the conversion succeeds otherwise non-zero.
321 */
322int str2mask(const char *str, struct in_addr *mask)
323{
324 if (strchr(str, '.') != NULL) { /* dotted notation */
325 if (!inet_pton(AF_INET, str, mask))
326 return 0;
327 }
328 else { /* mask length */
329 char *err;
330 unsigned long len = strtol(str, &err, 10);
331
332 if (!*str || (err && *err) || (unsigned)len > 32)
333 return 0;
334 if (len)
335 mask->s_addr = htonl(~0UL << (32 - len));
336 else
337 mask->s_addr = 0;
338 }
339 return 1;
340}
341
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200342/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200343 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200344 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
345 * is optionnal and either in the dotted or CIDR notation.
346 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
347 */
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200348int str2net(const char *str, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200349{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200350 __label__ out_free, out_err;
351 char *c, *s;
352 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200353
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200354 s = strdup(str);
355 if (!s)
356 return 0;
357
Willy Tarreaubaaee002006-06-26 02:48:02 +0200358 memset(mask, 0, sizeof(*mask));
359 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200360
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200361 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200362 *c++ = '\0';
363 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100364 if (!str2mask(c, mask))
365 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200366 }
367 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100368 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200369 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200370 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200371 struct hostent *he;
372
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200373 if ((he = gethostbyname(s)) == NULL) {
374 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200375 }
376 else
377 *addr = *(struct in_addr *) *(he->h_addr_list);
378 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200379
380 ret_val = 1;
381 out_free:
382 free(s);
383 return ret_val;
384 out_err:
385 ret_val = 0;
386 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200387}
388
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100389
390/*
391 * Parse IP address found in url.
392 */
Willy Tarreau106f9792009-09-19 07:54:16 +0200393int url2ip(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100394{
395 int saw_digit, octets, ch;
396 u_char tmp[4], *tp;
397 const char *cp = addr;
398
399 saw_digit = 0;
400 octets = 0;
401 *(tp = tmp) = 0;
402
403 while (*addr) {
404 unsigned char digit = (ch = *addr++) - '0';
405 if (digit > 9 && ch != '.')
406 break;
407 if (digit <= 9) {
408 u_int new = *tp * 10 + digit;
409 if (new > 255)
410 return 0;
411 *tp = new;
412 if (!saw_digit) {
413 if (++octets > 4)
414 return 0;
415 saw_digit = 1;
416 }
417 } else if (ch == '.' && saw_digit) {
418 if (octets == 4)
419 return 0;
420 *++tp = 0;
421 saw_digit = 0;
422 } else
423 return 0;
424 }
425
426 if (octets < 4)
427 return 0;
428
429 memcpy(&dst->s_addr, tmp, 4);
430 return addr-cp-1;
431}
432
433/*
434 * Resolve destination server from URL. Convert <str> to a sockaddr_in*.
435 */
436int url2sa(const char *url, int ulen, struct sockaddr_in *addr)
437{
438 const char *curr = url, *cp = url;
439 int ret, url_code = 0;
440 unsigned int http_code = 0;
441
442 /* Cleanup the room */
443 addr->sin_family = AF_INET;
444 addr->sin_addr.s_addr = 0;
445 addr->sin_port = 0;
446
447 /* Firstly, try to find :// pattern */
448 while (curr < url+ulen && url_code != 0x3a2f2f) {
449 url_code = ((url_code & 0xffff) << 8);
450 url_code += (unsigned char)*curr++;
451 }
452
453 /* Secondly, if :// pattern is found, verify parsed stuff
454 * before pattern is matching our http pattern.
455 * If so parse ip address and port in uri.
456 *
457 * WARNING: Current code doesn't support dynamic async dns resolver.
458 */
459 if (url_code == 0x3a2f2f) {
460 while (cp < curr - 3)
461 http_code = (http_code << 8) + *cp++;
462 http_code |= 0x20202020; /* Turn everything to lower case */
463
464 /* HTTP url matching */
465 if (http_code == 0x68747470) {
466 /* We are looking for IP address. If you want to parse and
467 * resolve hostname found in url, you can use str2sa(), but
468 * be warned this can slow down global daemon performances
469 * while handling lagging dns responses.
470 */
471 ret = url2ip(curr, &addr->sin_addr);
472 if (!ret)
473 return -1;
474 curr += ret;
Willy Tarreaud1cd2762007-12-02 10:55:56 +0100475 addr->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
476 addr->sin_port = htons(addr->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100477 }
478 return 0;
479 }
480
481 return -1;
482}
483
Willy Tarreaubaaee002006-06-26 02:48:02 +0200484/* will try to encode the string <string> replacing all characters tagged in
485 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
486 * prefixed by <escape>, and will store the result between <start> (included)
487 * and <stop> (excluded), and will always terminate the string with a '\0'
488 * before <stop>. The position of the '\0' is returned if the conversion
489 * completes. If bytes are missing between <start> and <stop>, then the
490 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
491 * cannot even be stored so we return <start> without writing the 0.
492 * The input string must also be zero-terminated.
493 */
494const char hextab[16] = "0123456789ABCDEF";
495char *encode_string(char *start, char *stop,
496 const char escape, const fd_set *map,
497 const char *string)
498{
499 if (start < stop) {
500 stop--; /* reserve one byte for the final '\0' */
501 while (start < stop && *string != '\0') {
502 if (!FD_ISSET((unsigned char)(*string), map))
503 *start++ = *string;
504 else {
505 if (start + 3 >= stop)
506 break;
507 *start++ = escape;
508 *start++ = hextab[(*string >> 4) & 15];
509 *start++ = hextab[*string & 15];
510 }
511 string++;
512 }
513 *start = '\0';
514 }
515 return start;
516}
517
518
Willy Tarreau6911fa42007-03-04 18:06:08 +0100519unsigned int str2ui(const char *s)
520{
521 return __str2ui(s);
522}
523
524unsigned int str2uic(const char *s)
525{
526 return __str2uic(s);
527}
528
529unsigned int strl2ui(const char *s, int len)
530{
531 return __strl2ui(s, len);
532}
533
534unsigned int strl2uic(const char *s, int len)
535{
536 return __strl2uic(s, len);
537}
538
539/* This one is 7 times faster than strtol() on athlon with checks.
540 * It returns the value of the number composed of all valid digits read,
541 * and can process negative numbers too.
542 */
543int strl2ic(const char *s, int len)
544{
545 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +0200546 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +0100547
548 if (len > 0) {
549 if (*s != '-') {
550 /* positive number */
551 while (len-- > 0) {
552 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +0200553 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +0100554 if (j > 9)
555 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +0200556 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +0100557 }
558 } else {
559 /* negative number */
560 s++;
561 while (--len > 0) {
562 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +0200563 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +0100564 if (j > 9)
565 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +0200566 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +0100567 }
568 }
569 }
570 return i;
571}
572
573
574/* This function reads exactly <len> chars from <s> and converts them to a
575 * signed integer which it stores into <ret>. It accurately detects any error
576 * (truncated string, invalid chars, overflows). It is meant to be used in
577 * applications designed for hostile environments. It returns zero when the
578 * number has successfully been converted, non-zero otherwise. When an error
579 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
580 * faster than strtol().
581 */
582int strl2irc(const char *s, int len, int *ret)
583{
584 int i = 0;
585 int j;
586
587 if (!len)
588 return 1;
589
590 if (*s != '-') {
591 /* positive number */
592 while (len-- > 0) {
593 j = (*s++) - '0';
594 if (j > 9) return 1; /* invalid char */
595 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
596 i = i * 10;
597 if (i + j < i) return 1; /* check for addition overflow */
598 i = i + j;
599 }
600 } else {
601 /* negative number */
602 s++;
603 while (--len > 0) {
604 j = (*s++) - '0';
605 if (j > 9) return 1; /* invalid char */
606 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
607 i = i * 10;
608 if (i - j > i) return 1; /* check for subtract overflow */
609 i = i - j;
610 }
611 }
612 *ret = i;
613 return 0;
614}
615
616
617/* This function reads exactly <len> chars from <s> and converts them to a
618 * signed integer which it stores into <ret>. It accurately detects any error
619 * (truncated string, invalid chars, overflows). It is meant to be used in
620 * applications designed for hostile environments. It returns zero when the
621 * number has successfully been converted, non-zero otherwise. When an error
622 * is returned, the <ret> value is left untouched. It is about 3 times slower
623 * than str2irc().
624 */
625#ifndef LLONG_MAX
626#define LLONG_MAX 9223372036854775807LL
627#define LLONG_MIN (-LLONG_MAX - 1LL)
628#endif
629
630int strl2llrc(const char *s, int len, long long *ret)
631{
632 long long i = 0;
633 int j;
634
635 if (!len)
636 return 1;
637
638 if (*s != '-') {
639 /* positive number */
640 while (len-- > 0) {
641 j = (*s++) - '0';
642 if (j > 9) return 1; /* invalid char */
643 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
644 i = i * 10LL;
645 if (i + j < i) return 1; /* check for addition overflow */
646 i = i + j;
647 }
648 } else {
649 /* negative number */
650 s++;
651 while (--len > 0) {
652 j = (*s++) - '0';
653 if (j > 9) return 1; /* invalid char */
654 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
655 i = i * 10LL;
656 if (i - j > i) return 1; /* check for subtract overflow */
657 i = i - j;
658 }
659 }
660 *ret = i;
661 return 0;
662}
663
Willy Tarreaua0d37b62007-12-02 22:00:35 +0100664/* This function parses a time value optionally followed by a unit suffix among
665 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
666 * expected by the caller. The computation does its best to avoid overflows.
667 * The value is returned in <ret> if everything is fine, and a NULL is returned
668 * by the function. In case of error, a pointer to the error is returned and
669 * <ret> is left untouched. Values are automatically rounded up when needed.
670 */
671const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
672{
673 unsigned imult, idiv;
674 unsigned omult, odiv;
675 unsigned value;
676
677 omult = odiv = 1;
678
679 switch (unit_flags & TIME_UNIT_MASK) {
680 case TIME_UNIT_US: omult = 1000000; break;
681 case TIME_UNIT_MS: omult = 1000; break;
682 case TIME_UNIT_S: break;
683 case TIME_UNIT_MIN: odiv = 60; break;
684 case TIME_UNIT_HOUR: odiv = 3600; break;
685 case TIME_UNIT_DAY: odiv = 86400; break;
686 default: break;
687 }
688
689 value = 0;
690
691 while (1) {
692 unsigned int j;
693
694 j = *text - '0';
695 if (j > 9)
696 break;
697 text++;
698 value *= 10;
699 value += j;
700 }
701
702 imult = idiv = 1;
703 switch (*text) {
704 case '\0': /* no unit = default unit */
705 imult = omult = idiv = odiv = 1;
706 break;
707 case 's': /* second = unscaled unit */
708 break;
709 case 'u': /* microsecond : "us" */
710 if (text[1] == 's') {
711 idiv = 1000000;
712 text++;
713 }
714 break;
715 case 'm': /* millisecond : "ms" or minute: "m" */
716 if (text[1] == 's') {
717 idiv = 1000;
718 text++;
719 } else
720 imult = 60;
721 break;
722 case 'h': /* hour : "h" */
723 imult = 3600;
724 break;
725 case 'd': /* day : "d" */
726 imult = 86400;
727 break;
728 default:
729 return text;
730 break;
731 }
732
733 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
734 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
735 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
736 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
737
738 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
739 *ret = value;
740 return NULL;
741}
Willy Tarreau6911fa42007-03-04 18:06:08 +0100742
Emeric Brun39132b22010-01-04 14:57:24 +0100743/* this function converts the string starting at <text> to an unsigned int
744 * stored in <ret>. If an error is detected, the pointer to the unexpected
745 * character is returned. If the conversio is succesful, NULL is returned.
746 */
747const char *parse_size_err(const char *text, unsigned *ret) {
748 unsigned value = 0;
749
750 while (1) {
751 unsigned int j;
752
753 j = *text - '0';
754 if (j > 9)
755 break;
756 if (value > ~0U / 10)
757 return text;
758 value *= 10;
759 if (value > (value + j))
760 return text;
761 value += j;
762 text++;
763 }
764
765 switch (*text) {
766 case '\0':
767 break;
768 case 'K':
769 case 'k':
770 if (value > ~0U >> 10)
771 return text;
772 value = value << 10;
773 break;
774 case 'M':
775 case 'm':
776 if (value > ~0U >> 20)
777 return text;
778 value = value << 20;
779 break;
780 case 'G':
781 case 'g':
782 if (value > ~0U >> 30)
783 return text;
784 value = value << 30;
785 break;
786 default:
787 return text;
788 }
789
790 *ret = value;
791 return NULL;
792}
793
Willy Tarreau946ba592009-05-10 15:41:18 +0200794/* copies at most <n> characters from <src> and always terminates with '\0' */
795char *my_strndup(const char *src, int n)
796{
797 int len = 0;
798 char *ret;
799
800 while (len < n && src[len])
801 len++;
802
803 ret = (char *)malloc(len + 1);
804 if (!ret)
805 return ret;
806 memcpy(ret, src, len);
807 ret[len] = '\0';
808 return ret;
809}
810
Willy Tarreau482b00d2009-10-04 22:48:42 +0200811/* This function returns the first unused key greater than or equal to <key> in
812 * ID tree <root>. Zero is returned if no place is found.
813 */
814unsigned int get_next_id(struct eb_root *root, unsigned int key)
815{
816 struct eb32_node *used;
817
818 do {
819 used = eb32_lookup_ge(root, key);
820 if (!used || used->key > key)
821 return key; /* key is available */
822 key++;
823 } while (key);
824 return key;
825}
826
Willy Tarreau348238b2010-01-18 15:05:57 +0100827/* This function compares a sample word possibly followed by blanks to another
828 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
829 * otherwise zero. This intends to be used when checking HTTP headers for some
830 * values. Note that it validates a word followed only by blanks but does not
831 * validate a word followed by blanks then other chars.
832 */
833int word_match(const char *sample, int slen, const char *word, int wlen)
834{
835 if (slen < wlen)
836 return 0;
837
838 while (wlen) {
839 char c = *sample ^ *word;
840 if (c && c != ('A' ^ 'a'))
841 return 0;
842 sample++;
843 word++;
844 slen--;
845 wlen--;
846 }
847
848 while (slen) {
849 if (*sample != ' ' && *sample != '\t')
850 return 0;
851 sample++;
852 slen--;
853 }
854 return 1;
855}
Willy Tarreau482b00d2009-10-04 22:48:42 +0200856
Willy Tarreaubaaee002006-06-26 02:48:02 +0200857/*
858 * Local variables:
859 * c-indent-level: 8
860 * c-basic-offset: 8
861 * End:
862 */