blob: c491534eb69c1d0d268ff62dbab179ac938ae8b6 [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/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200446 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
447 *
448 * It looks like this one would be a good candidate for inlining, but this is
449 * not interesting because it around 35 bytes long and often called multiple
450 * times within the same function.
451 */
452int ishex(char s)
453{
454 s -= '0';
455 if ((unsigned char)s <= 9)
456 return 1;
457 s -= 'A' - '0';
458 if ((unsigned char)s <= 5)
459 return 1;
460 s -= 'a' - 'A';
461 if ((unsigned char)s <= 5)
462 return 1;
463 return 0;
464}
465
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100466/*
467 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
468 * invalid character is found, a pointer to it is returned. If everything is
469 * fine, NULL is returned.
470 */
471const char *invalid_char(const char *name)
472{
473 if (!*name)
474 return name;
475
476 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100477 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100478 *name != '_' && *name != '-')
479 return name;
480 name++;
481 }
482 return NULL;
483}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200484
485/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200486 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
487 * If an invalid character is found, a pointer to it is returned.
488 * If everything is fine, NULL is returned.
489 */
490const char *invalid_domainchar(const char *name) {
491
492 if (!*name)
493 return name;
494
495 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100496 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200497 *name != '_' && *name != '-')
498 return name;
499
500 name++;
501 }
502
503 return NULL;
504}
505
506/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100507 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100508 * string is assumed to contain only an address, no port. The address can be a
509 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
510 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
511 * The return address will only have the address family and the address set,
512 * all other fields remain zero. The string is not supposed to be modified.
513 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200514 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100515struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200516{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100517 struct hostent *he;
518
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100519 memset(sa, 0, sizeof(sa));
Willy Tarreaufab5a432011-03-04 15:31:53 +0100520
521 /* Any IPv6 address */
522 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100523 sa->ss_family = AF_INET6;
524 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100525 }
526
527 /* Any IPv4 address */
528 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100529 sa->ss_family = AF_INET;
530 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100531 }
532
533 /* check for IPv6 first */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100534 if (inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
535 sa->ss_family = AF_INET6;
536 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100537 }
538
539 /* then check for IPv4 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100540 if (inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
541 sa->ss_family = AF_INET;
542 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100543 }
544
545 /* try to resolve an IPv4/IPv6 hostname */
546 he = gethostbyname(str);
547 if (he) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100548 sa->ss_family = he->h_addrtype;
549 switch (sa->ss_family) {
Willy Tarreaufab5a432011-03-04 15:31:53 +0100550 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100551 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
552 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100553 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100554 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
555 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100556 }
David du Colombierd5f43282011-03-17 10:40:16 +0100557 }
558#ifdef USE_GETADDRINFO
559 else {
560 struct addrinfo hints, *result;
561
562 memset(&result, 0, sizeof(result));
563 memset(&hints, 0, sizeof(hints));
564 hints.ai_family = AF_UNSPEC;
565 hints.ai_socktype = SOCK_DGRAM;
566 hints.ai_flags = AI_PASSIVE;
567 hints.ai_protocol = 0;
568
569 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100570 sa->ss_family = result->ai_family;
David du Colombierd5f43282011-03-17 10:40:16 +0100571 switch (result->ai_family) {
572 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100573 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
574 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100575 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100576 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
577 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100578 }
579 }
580
Sean Carey58ea0392013-02-15 23:39:18 +0100581 if (result)
582 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100583 }
David du Colombierd5f43282011-03-17 10:40:16 +0100584#endif
585 /* unsupported address family */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100586
587 return NULL;
588}
589
590/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100591 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
592 * range or offset consisting in two integers that the caller will have to
593 * check to find the relevant input format. The following format are supported :
594 *
595 * String format | address | port | low | high
596 * addr | <addr> | 0 | 0 | 0
597 * addr: | <addr> | 0 | 0 | 0
598 * addr:port | <addr> | <port> | <port> | <port>
599 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
600 * addr:+port | <addr> | <port> | 0 | <port>
601 * addr:-port | <addr> |-<port> | <port> | 0
602 *
603 * The detection of a port range or increment by the caller is made by
604 * comparing <low> and <high>. If both are equal, then port 0 means no port
605 * was specified. The caller may pass NULL for <low> and <high> if it is not
606 * interested in retrieving port ranges.
607 *
608 * Note that <addr> above may also be :
609 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
610 * - "*" => family will be AF_INET and address will be INADDR_ANY
611 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
612 * - a host name => family and address will depend on host name resolving.
613 *
614 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
615 * is mandatory after the IP address even when no port is specified. NULL is
616 * returned if the address cannot be parsed. The <low> and <high> ports are
617 * always initialized if non-null.
Willy Tarreaud393a622013-03-04 18:22:00 +0100618 *
619 * If <pfx> is non-null, it is used as a string prefix before any path-based
620 * address (typically the path to a unix socket).
Willy Tarreaufab5a432011-03-04 15:31:53 +0100621 */
Willy Tarreaud393a622013-03-04 18:22:00 +0100622struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100623{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100624 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100625 struct sockaddr_storage *ret = NULL;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100626 char *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100627 char *port1, *port2;
628 int portl, porth, porta;
629
630 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200631
Willy Tarreaufab5a432011-03-04 15:31:53 +0100632 str2 = strdup(str);
Willy Tarreaudf350f12013-03-01 20:22:54 +0100633 if (str2 == NULL) {
634 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100635 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100636 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200637
Willy Tarreau15586382013-03-04 19:48:14 +0100638 if (*str2 == '/') {
639 /* unix socket */
Willy Tarreau15586382013-03-04 19:48:14 +0100640 int prefix_path_len;
641 int max_path_len;
642
643 /* complete unix socket path name during startup or soft-restart is
644 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
645 */
646 prefix_path_len = pfx ? strlen(pfx) : 0;
647 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
648 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
649
650 if (strlen(str2) > max_path_len) {
651 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
652 goto out;
653 }
654
655 memset(&ss, 0, sizeof(ss));
656 ss.ss_family = AF_UNIX;
657 if (pfx) {
658 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
659 strcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len, str2);
660 }
661 else {
662 strcpy(((struct sockaddr_un *)&ss)->sun_path, str2);
663 }
Willy Tarreau15586382013-03-04 19:48:14 +0100664 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100665 else {
666 port1 = strrchr(str2, ':');
667 if (port1)
668 *port1++ = '\0';
669 else
670 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200671
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100672 if (str2ip(str2, &ss) == NULL) {
673 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
674 goto out;
675 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100676
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100677 if (isdigit(*port1)) { /* single port or range */
678 port2 = strchr(port1, '-');
679 if (port2)
680 *port2++ = '\0';
681 else
682 port2 = port1;
683 portl = atoi(port1);
684 porth = atoi(port2);
685 porta = portl;
686 }
687 else if (*port1 == '-') { /* negative offset */
688 portl = atoi(port1 + 1);
689 porta = -portl;
690 }
691 else if (*port1 == '+') { /* positive offset */
692 porth = atoi(port1 + 1);
693 porta = porth;
694 }
695 else if (*port1) { /* other any unexpected char */
696 memprintf(err, "invalid character '%c' in port number '%s'\n", *port1, port1);
697 goto out;
698 }
699 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100700 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100701
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100702 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100703 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100704 if (low)
705 *low = portl;
706 if (high)
707 *high = porth;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100708 free(str2);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100709 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200710}
711
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100712/* converts <str> to a struct in_addr containing a network mask. It can be
713 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
714 * if the conversion succeeds otherwise non-zero.
715 */
716int str2mask(const char *str, struct in_addr *mask)
717{
718 if (strchr(str, '.') != NULL) { /* dotted notation */
719 if (!inet_pton(AF_INET, str, mask))
720 return 0;
721 }
722 else { /* mask length */
723 char *err;
724 unsigned long len = strtol(str, &err, 10);
725
726 if (!*str || (err && *err) || (unsigned)len > 32)
727 return 0;
728 if (len)
729 mask->s_addr = htonl(~0UL << (32 - len));
730 else
731 mask->s_addr = 0;
732 }
733 return 1;
734}
735
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200736/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200737 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200738 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
739 * is optionnal and either in the dotted or CIDR notation.
740 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
741 */
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200742int str2net(const char *str, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200743{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200744 __label__ out_free, out_err;
745 char *c, *s;
746 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200747
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200748 s = strdup(str);
749 if (!s)
750 return 0;
751
Willy Tarreaubaaee002006-06-26 02:48:02 +0200752 memset(mask, 0, sizeof(*mask));
753 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200754
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200755 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200756 *c++ = '\0';
757 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100758 if (!str2mask(c, mask))
759 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200760 }
761 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100762 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200763 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200764 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200765 struct hostent *he;
766
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200767 if ((he = gethostbyname(s)) == NULL) {
768 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200769 }
770 else
771 *addr = *(struct in_addr *) *(he->h_addr_list);
772 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200773
774 ret_val = 1;
775 out_free:
776 free(s);
777 return ret_val;
778 out_err:
779 ret_val = 0;
780 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200781}
782
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100783
784/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200785 * converts <str> to two struct in6_addr* which must be pre-allocated.
786 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
787 * is an optionnal number of bits (128 being the default).
788 * Returns 1 if OK, 0 if error.
789 */
790int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
791{
792 char *c, *s;
793 int ret_val = 0;
794 char *err;
795 unsigned long len = 128;
796
797 s = strdup(str);
798 if (!s)
799 return 0;
800
801 memset(mask, 0, sizeof(*mask));
802 memset(addr, 0, sizeof(*addr));
803
804 if ((c = strrchr(s, '/')) != NULL) {
805 *c++ = '\0'; /* c points to the mask */
806 if (!*c)
807 goto out_free;
808
809 len = strtoul(c, &err, 10);
810 if ((err && *err) || (unsigned)len > 128)
811 goto out_free;
812 }
813 *mask = len; /* OK we have a valid mask in <len> */
814
815 if (!inet_pton(AF_INET6, s, addr))
816 goto out_free;
817
818 ret_val = 1;
819 out_free:
820 free(s);
821 return ret_val;
822}
823
824
825/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100826 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100827 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100828int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100829{
830 int saw_digit, octets, ch;
831 u_char tmp[4], *tp;
832 const char *cp = addr;
833
834 saw_digit = 0;
835 octets = 0;
836 *(tp = tmp) = 0;
837
838 while (*addr) {
839 unsigned char digit = (ch = *addr++) - '0';
840 if (digit > 9 && ch != '.')
841 break;
842 if (digit <= 9) {
843 u_int new = *tp * 10 + digit;
844 if (new > 255)
845 return 0;
846 *tp = new;
847 if (!saw_digit) {
848 if (++octets > 4)
849 return 0;
850 saw_digit = 1;
851 }
852 } else if (ch == '.' && saw_digit) {
853 if (octets == 4)
854 return 0;
855 *++tp = 0;
856 saw_digit = 0;
857 } else
858 return 0;
859 }
860
861 if (octets < 4)
862 return 0;
863
864 memcpy(&dst->s_addr, tmp, 4);
865 return addr-cp-1;
866}
867
868/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100869 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100870 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100871int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100872{
873 const char *curr = url, *cp = url;
874 int ret, url_code = 0;
875 unsigned int http_code = 0;
876
877 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100878
879 /* FIXME: assume IPv4 only for now */
880 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
881 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
882 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100883
884 /* Firstly, try to find :// pattern */
885 while (curr < url+ulen && url_code != 0x3a2f2f) {
886 url_code = ((url_code & 0xffff) << 8);
887 url_code += (unsigned char)*curr++;
888 }
889
890 /* Secondly, if :// pattern is found, verify parsed stuff
891 * before pattern is matching our http pattern.
892 * If so parse ip address and port in uri.
893 *
894 * WARNING: Current code doesn't support dynamic async dns resolver.
895 */
896 if (url_code == 0x3a2f2f) {
897 while (cp < curr - 3)
898 http_code = (http_code << 8) + *cp++;
899 http_code |= 0x20202020; /* Turn everything to lower case */
900
901 /* HTTP url matching */
902 if (http_code == 0x68747470) {
903 /* We are looking for IP address. If you want to parse and
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100904 * resolve hostname found in url, you can use str2sa_range(), but
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100905 * be warned this can slow down global daemon performances
906 * while handling lagging dns responses.
907 */
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200908 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100909 if (!ret)
910 return -1;
911 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100912 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200913 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100914 }
915 return 0;
916 }
917
918 return -1;
919}
920
Willy Tarreau631f01c2011-09-05 00:36:48 +0200921/* Tries to convert a sockaddr_storage address to text form. Upon success, the
922 * address family is returned so that it's easy for the caller to adapt to the
923 * output format. Zero is returned if the address family is not supported. -1
924 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
925 * supported.
926 */
927int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
928{
929
930 void *ptr;
931
932 if (size < 5)
933 return 0;
934 *str = '\0';
935
936 switch (addr->ss_family) {
937 case AF_INET:
938 ptr = &((struct sockaddr_in *)addr)->sin_addr;
939 break;
940 case AF_INET6:
941 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
942 break;
943 case AF_UNIX:
944 memcpy(str, "unix", 5);
945 return addr->ss_family;
946 default:
947 return 0;
948 }
949
950 if (inet_ntop(addr->ss_family, ptr, str, size))
951 return addr->ss_family;
952
953 /* failed */
954 return -1;
955}
956
Willy Tarreaubaaee002006-06-26 02:48:02 +0200957/* will try to encode the string <string> replacing all characters tagged in
958 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
959 * prefixed by <escape>, and will store the result between <start> (included)
960 * and <stop> (excluded), and will always terminate the string with a '\0'
961 * before <stop>. The position of the '\0' is returned if the conversion
962 * completes. If bytes are missing between <start> and <stop>, then the
963 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
964 * cannot even be stored so we return <start> without writing the 0.
965 * The input string must also be zero-terminated.
966 */
967const char hextab[16] = "0123456789ABCDEF";
968char *encode_string(char *start, char *stop,
969 const char escape, const fd_set *map,
970 const char *string)
971{
972 if (start < stop) {
973 stop--; /* reserve one byte for the final '\0' */
974 while (start < stop && *string != '\0') {
975 if (!FD_ISSET((unsigned char)(*string), map))
976 *start++ = *string;
977 else {
978 if (start + 3 >= stop)
979 break;
980 *start++ = escape;
981 *start++ = hextab[(*string >> 4) & 15];
982 *start++ = hextab[*string & 15];
983 }
984 string++;
985 }
986 *start = '\0';
987 }
988 return start;
989}
990
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +0200991/* Decode an URL-encoded string in-place. The resulting string might
992 * be shorter. If some forbidden characters are found, the conversion is
993 * aborted, the string is truncated before the issue and non-zero is returned,
994 * otherwise the operation returns non-zero indicating success.
995 */
996int url_decode(char *string)
997{
998 char *in, *out;
999 int ret = 0;
1000
1001 in = string;
1002 out = string;
1003 while (*in) {
1004 switch (*in) {
1005 case '+' :
1006 *out++ = ' ';
1007 break;
1008 case '%' :
1009 if (!ishex(in[1]) || !ishex(in[2]))
1010 goto end;
1011 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1012 in += 2;
1013 break;
1014 default:
1015 *out++ = *in;
1016 break;
1017 }
1018 in++;
1019 }
1020 ret = 1; /* success */
1021 end:
1022 *out = 0;
1023 return ret;
1024}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001025
Willy Tarreau6911fa42007-03-04 18:06:08 +01001026unsigned int str2ui(const char *s)
1027{
1028 return __str2ui(s);
1029}
1030
1031unsigned int str2uic(const char *s)
1032{
1033 return __str2uic(s);
1034}
1035
1036unsigned int strl2ui(const char *s, int len)
1037{
1038 return __strl2ui(s, len);
1039}
1040
1041unsigned int strl2uic(const char *s, int len)
1042{
1043 return __strl2uic(s, len);
1044}
1045
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001046unsigned int read_uint(const char **s, const char *end)
1047{
1048 return __read_uint(s, end);
1049}
1050
Willy Tarreau6911fa42007-03-04 18:06:08 +01001051/* This one is 7 times faster than strtol() on athlon with checks.
1052 * It returns the value of the number composed of all valid digits read,
1053 * and can process negative numbers too.
1054 */
1055int strl2ic(const char *s, int len)
1056{
1057 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001058 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001059
1060 if (len > 0) {
1061 if (*s != '-') {
1062 /* positive number */
1063 while (len-- > 0) {
1064 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001065 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001066 if (j > 9)
1067 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001068 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001069 }
1070 } else {
1071 /* negative number */
1072 s++;
1073 while (--len > 0) {
1074 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001075 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001076 if (j > 9)
1077 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001078 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001079 }
1080 }
1081 }
1082 return i;
1083}
1084
1085
1086/* This function reads exactly <len> chars from <s> and converts them to a
1087 * signed integer which it stores into <ret>. It accurately detects any error
1088 * (truncated string, invalid chars, overflows). It is meant to be used in
1089 * applications designed for hostile environments. It returns zero when the
1090 * number has successfully been converted, non-zero otherwise. When an error
1091 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1092 * faster than strtol().
1093 */
1094int strl2irc(const char *s, int len, int *ret)
1095{
1096 int i = 0;
1097 int j;
1098
1099 if (!len)
1100 return 1;
1101
1102 if (*s != '-') {
1103 /* positive number */
1104 while (len-- > 0) {
1105 j = (*s++) - '0';
1106 if (j > 9) return 1; /* invalid char */
1107 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1108 i = i * 10;
1109 if (i + j < i) return 1; /* check for addition overflow */
1110 i = i + j;
1111 }
1112 } else {
1113 /* negative number */
1114 s++;
1115 while (--len > 0) {
1116 j = (*s++) - '0';
1117 if (j > 9) return 1; /* invalid char */
1118 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1119 i = i * 10;
1120 if (i - j > i) return 1; /* check for subtract overflow */
1121 i = i - j;
1122 }
1123 }
1124 *ret = i;
1125 return 0;
1126}
1127
1128
1129/* This function reads exactly <len> chars from <s> and converts them to a
1130 * signed integer which it stores into <ret>. It accurately detects any error
1131 * (truncated string, invalid chars, overflows). It is meant to be used in
1132 * applications designed for hostile environments. It returns zero when the
1133 * number has successfully been converted, non-zero otherwise. When an error
1134 * is returned, the <ret> value is left untouched. It is about 3 times slower
1135 * than str2irc().
1136 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001137
1138int strl2llrc(const char *s, int len, long long *ret)
1139{
1140 long long i = 0;
1141 int j;
1142
1143 if (!len)
1144 return 1;
1145
1146 if (*s != '-') {
1147 /* positive number */
1148 while (len-- > 0) {
1149 j = (*s++) - '0';
1150 if (j > 9) return 1; /* invalid char */
1151 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1152 i = i * 10LL;
1153 if (i + j < i) return 1; /* check for addition overflow */
1154 i = i + j;
1155 }
1156 } else {
1157 /* negative number */
1158 s++;
1159 while (--len > 0) {
1160 j = (*s++) - '0';
1161 if (j > 9) return 1; /* invalid char */
1162 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1163 i = i * 10LL;
1164 if (i - j > i) return 1; /* check for subtract overflow */
1165 i = i - j;
1166 }
1167 }
1168 *ret = i;
1169 return 0;
1170}
1171
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001172/* This function parses a time value optionally followed by a unit suffix among
1173 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1174 * expected by the caller. The computation does its best to avoid overflows.
1175 * The value is returned in <ret> if everything is fine, and a NULL is returned
1176 * by the function. In case of error, a pointer to the error is returned and
1177 * <ret> is left untouched. Values are automatically rounded up when needed.
1178 */
1179const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1180{
1181 unsigned imult, idiv;
1182 unsigned omult, odiv;
1183 unsigned value;
1184
1185 omult = odiv = 1;
1186
1187 switch (unit_flags & TIME_UNIT_MASK) {
1188 case TIME_UNIT_US: omult = 1000000; break;
1189 case TIME_UNIT_MS: omult = 1000; break;
1190 case TIME_UNIT_S: break;
1191 case TIME_UNIT_MIN: odiv = 60; break;
1192 case TIME_UNIT_HOUR: odiv = 3600; break;
1193 case TIME_UNIT_DAY: odiv = 86400; break;
1194 default: break;
1195 }
1196
1197 value = 0;
1198
1199 while (1) {
1200 unsigned int j;
1201
1202 j = *text - '0';
1203 if (j > 9)
1204 break;
1205 text++;
1206 value *= 10;
1207 value += j;
1208 }
1209
1210 imult = idiv = 1;
1211 switch (*text) {
1212 case '\0': /* no unit = default unit */
1213 imult = omult = idiv = odiv = 1;
1214 break;
1215 case 's': /* second = unscaled unit */
1216 break;
1217 case 'u': /* microsecond : "us" */
1218 if (text[1] == 's') {
1219 idiv = 1000000;
1220 text++;
1221 }
1222 break;
1223 case 'm': /* millisecond : "ms" or minute: "m" */
1224 if (text[1] == 's') {
1225 idiv = 1000;
1226 text++;
1227 } else
1228 imult = 60;
1229 break;
1230 case 'h': /* hour : "h" */
1231 imult = 3600;
1232 break;
1233 case 'd': /* day : "d" */
1234 imult = 86400;
1235 break;
1236 default:
1237 return text;
1238 break;
1239 }
1240
1241 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1242 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1243 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1244 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1245
1246 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1247 *ret = value;
1248 return NULL;
1249}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001250
Emeric Brun39132b22010-01-04 14:57:24 +01001251/* this function converts the string starting at <text> to an unsigned int
1252 * stored in <ret>. If an error is detected, the pointer to the unexpected
1253 * character is returned. If the conversio is succesful, NULL is returned.
1254 */
1255const char *parse_size_err(const char *text, unsigned *ret) {
1256 unsigned value = 0;
1257
1258 while (1) {
1259 unsigned int j;
1260
1261 j = *text - '0';
1262 if (j > 9)
1263 break;
1264 if (value > ~0U / 10)
1265 return text;
1266 value *= 10;
1267 if (value > (value + j))
1268 return text;
1269 value += j;
1270 text++;
1271 }
1272
1273 switch (*text) {
1274 case '\0':
1275 break;
1276 case 'K':
1277 case 'k':
1278 if (value > ~0U >> 10)
1279 return text;
1280 value = value << 10;
1281 break;
1282 case 'M':
1283 case 'm':
1284 if (value > ~0U >> 20)
1285 return text;
1286 value = value << 20;
1287 break;
1288 case 'G':
1289 case 'g':
1290 if (value > ~0U >> 30)
1291 return text;
1292 value = value << 30;
1293 break;
1294 default:
1295 return text;
1296 }
1297
1298 *ret = value;
1299 return NULL;
1300}
1301
Willy Tarreau946ba592009-05-10 15:41:18 +02001302/* copies at most <n> characters from <src> and always terminates with '\0' */
1303char *my_strndup(const char *src, int n)
1304{
1305 int len = 0;
1306 char *ret;
1307
1308 while (len < n && src[len])
1309 len++;
1310
1311 ret = (char *)malloc(len + 1);
1312 if (!ret)
1313 return ret;
1314 memcpy(ret, src, len);
1315 ret[len] = '\0';
1316 return ret;
1317}
1318
Willy Tarreau482b00d2009-10-04 22:48:42 +02001319/* This function returns the first unused key greater than or equal to <key> in
1320 * ID tree <root>. Zero is returned if no place is found.
1321 */
1322unsigned int get_next_id(struct eb_root *root, unsigned int key)
1323{
1324 struct eb32_node *used;
1325
1326 do {
1327 used = eb32_lookup_ge(root, key);
1328 if (!used || used->key > key)
1329 return key; /* key is available */
1330 key++;
1331 } while (key);
1332 return key;
1333}
1334
Willy Tarreau348238b2010-01-18 15:05:57 +01001335/* This function compares a sample word possibly followed by blanks to another
1336 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1337 * otherwise zero. This intends to be used when checking HTTP headers for some
1338 * values. Note that it validates a word followed only by blanks but does not
1339 * validate a word followed by blanks then other chars.
1340 */
1341int word_match(const char *sample, int slen, const char *word, int wlen)
1342{
1343 if (slen < wlen)
1344 return 0;
1345
1346 while (wlen) {
1347 char c = *sample ^ *word;
1348 if (c && c != ('A' ^ 'a'))
1349 return 0;
1350 sample++;
1351 word++;
1352 slen--;
1353 wlen--;
1354 }
1355
1356 while (slen) {
1357 if (*sample != ' ' && *sample != '\t')
1358 return 0;
1359 sample++;
1360 slen--;
1361 }
1362 return 1;
1363}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001364
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001365/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1366 * is particularly fast because it avoids expensive operations such as
1367 * multiplies, which are optimized away at the end. It requires a properly
1368 * formated address though (3 points).
1369 */
1370unsigned int inetaddr_host(const char *text)
1371{
1372 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1373 register unsigned int dig100, dig10, dig1;
1374 int s;
1375 const char *p, *d;
1376
1377 dig1 = dig10 = dig100 = ascii_zero;
1378 s = 24;
1379
1380 p = text;
1381 while (1) {
1382 if (((unsigned)(*p - '0')) <= 9) {
1383 p++;
1384 continue;
1385 }
1386
1387 /* here, we have a complete byte between <text> and <p> (exclusive) */
1388 if (p == text)
1389 goto end;
1390
1391 d = p - 1;
1392 dig1 |= (unsigned int)(*d << s);
1393 if (d == text)
1394 goto end;
1395
1396 d--;
1397 dig10 |= (unsigned int)(*d << s);
1398 if (d == text)
1399 goto end;
1400
1401 d--;
1402 dig100 |= (unsigned int)(*d << s);
1403 end:
1404 if (!s || *p != '.')
1405 break;
1406
1407 s -= 8;
1408 text = ++p;
1409 }
1410
1411 dig100 -= ascii_zero;
1412 dig10 -= ascii_zero;
1413 dig1 -= ascii_zero;
1414 return ((dig100 * 10) + dig10) * 10 + dig1;
1415}
1416
1417/*
1418 * Idem except the first unparsed character has to be passed in <stop>.
1419 */
1420unsigned int inetaddr_host_lim(const char *text, const char *stop)
1421{
1422 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1423 register unsigned int dig100, dig10, dig1;
1424 int s;
1425 const char *p, *d;
1426
1427 dig1 = dig10 = dig100 = ascii_zero;
1428 s = 24;
1429
1430 p = text;
1431 while (1) {
1432 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1433 p++;
1434 continue;
1435 }
1436
1437 /* here, we have a complete byte between <text> and <p> (exclusive) */
1438 if (p == text)
1439 goto end;
1440
1441 d = p - 1;
1442 dig1 |= (unsigned int)(*d << s);
1443 if (d == text)
1444 goto end;
1445
1446 d--;
1447 dig10 |= (unsigned int)(*d << s);
1448 if (d == text)
1449 goto end;
1450
1451 d--;
1452 dig100 |= (unsigned int)(*d << s);
1453 end:
1454 if (!s || p == stop || *p != '.')
1455 break;
1456
1457 s -= 8;
1458 text = ++p;
1459 }
1460
1461 dig100 -= ascii_zero;
1462 dig10 -= ascii_zero;
1463 dig1 -= ascii_zero;
1464 return ((dig100 * 10) + dig10) * 10 + dig1;
1465}
1466
1467/*
1468 * Idem except the pointer to first unparsed byte is returned into <ret> which
1469 * must not be NULL.
1470 */
Willy Tarreau74172752010-10-15 23:21:42 +02001471unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001472{
1473 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1474 register unsigned int dig100, dig10, dig1;
1475 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001476 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001477
1478 dig1 = dig10 = dig100 = ascii_zero;
1479 s = 24;
1480
1481 p = text;
1482 while (1) {
1483 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1484 p++;
1485 continue;
1486 }
1487
1488 /* here, we have a complete byte between <text> and <p> (exclusive) */
1489 if (p == text)
1490 goto end;
1491
1492 d = p - 1;
1493 dig1 |= (unsigned int)(*d << s);
1494 if (d == text)
1495 goto end;
1496
1497 d--;
1498 dig10 |= (unsigned int)(*d << s);
1499 if (d == text)
1500 goto end;
1501
1502 d--;
1503 dig100 |= (unsigned int)(*d << s);
1504 end:
1505 if (!s || p == stop || *p != '.')
1506 break;
1507
1508 s -= 8;
1509 text = ++p;
1510 }
1511
1512 *ret = p;
1513 dig100 -= ascii_zero;
1514 dig10 -= ascii_zero;
1515 dig1 -= ascii_zero;
1516 return ((dig100 * 10) + dig10) * 10 + dig1;
1517}
1518
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001519/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1520 * or the number of chars read in case of success. Maybe this could be replaced
1521 * by one of the functions above. Also, apparently this function does not support
1522 * hosts above 255 and requires exactly 4 octets.
1523 */
1524int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1525{
1526 const char *addr;
1527 int saw_digit, octets, ch;
1528 u_char tmp[4], *tp;
1529 const char *cp = buf;
1530
1531 saw_digit = 0;
1532 octets = 0;
1533 *(tp = tmp) = 0;
1534
1535 for (addr = buf; addr - buf < len; addr++) {
1536 unsigned char digit = (ch = *addr) - '0';
1537
1538 if (digit > 9 && ch != '.')
1539 break;
1540
1541 if (digit <= 9) {
1542 u_int new = *tp * 10 + digit;
1543
1544 if (new > 255)
1545 return 0;
1546
1547 *tp = new;
1548
1549 if (!saw_digit) {
1550 if (++octets > 4)
1551 return 0;
1552 saw_digit = 1;
1553 }
1554 } else if (ch == '.' && saw_digit) {
1555 if (octets == 4)
1556 return 0;
1557
1558 *++tp = 0;
1559 saw_digit = 0;
1560 } else
1561 return 0;
1562 }
1563
1564 if (octets < 4)
1565 return 0;
1566
1567 memcpy(&dst->s_addr, tmp, 4);
1568 return addr - cp;
1569}
1570
Willy Tarreauacf95772010-06-14 19:09:21 +02001571/* To be used to quote config arg positions. Returns the short string at <ptr>
1572 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1573 * if ptr is NULL or empty. The string is locally allocated.
1574 */
1575const char *quote_arg(const char *ptr)
1576{
1577 static char val[32];
1578 int i;
1579
1580 if (!ptr || !*ptr)
1581 return "end of line";
1582 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001583 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001584 val[i] = *ptr++;
1585 val[i++] = '\'';
1586 val[i] = '\0';
1587 return val;
1588}
1589
Willy Tarreau5b180202010-07-18 10:40:48 +02001590/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1591int get_std_op(const char *str)
1592{
1593 int ret = -1;
1594
1595 if (*str == 'e' && str[1] == 'q')
1596 ret = STD_OP_EQ;
1597 else if (*str == 'n' && str[1] == 'e')
1598 ret = STD_OP_NE;
1599 else if (*str == 'l') {
1600 if (str[1] == 'e') ret = STD_OP_LE;
1601 else if (str[1] == 't') ret = STD_OP_LT;
1602 }
1603 else if (*str == 'g') {
1604 if (str[1] == 'e') ret = STD_OP_GE;
1605 else if (str[1] == 't') ret = STD_OP_GT;
1606 }
1607
1608 if (ret == -1 || str[2] != '\0')
1609 return -1;
1610 return ret;
1611}
1612
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001613/* hash a 32-bit integer to another 32-bit integer */
1614unsigned int full_hash(unsigned int a)
1615{
1616 return __full_hash(a);
1617}
1618
David du Colombier4f92d322011-03-24 11:09:31 +01001619/* Return non-zero if IPv4 address is part of the network,
1620 * otherwise zero.
1621 */
1622int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1623{
1624 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1625}
1626
1627/* Return non-zero if IPv6 address is part of the network,
1628 * otherwise zero.
1629 */
1630int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1631{
1632 int i;
1633
1634 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1635 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1636 (((int *)net)[i] & ((int *)mask)[i]))
1637 return 0;
1638 return 1;
1639}
1640
1641/* RFC 4291 prefix */
1642const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1643 0x00, 0x00, 0x00, 0x00,
1644 0x00, 0x00, 0xFF, 0xFF };
1645
1646/* Map IPv4 adress on IPv6 address, as specified in RFC 3513. */
1647void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1648{
1649 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
1650 memcpy(sin6_addr->s6_addr+12, &sin_addr->s_addr, 4);
1651}
1652
1653/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1654 * Return true if conversion is possible and false otherwise.
1655 */
1656int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1657{
1658 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1659 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1660 sizeof(struct in_addr));
1661 return 1;
1662 }
1663
1664 return 0;
1665}
1666
William Lallemand421f5b52012-02-06 18:15:57 +01001667char *human_time(int t, short hz_div) {
1668 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1669 char *p = rv;
1670 int cnt=2; // print two numbers
1671
1672 if (unlikely(t < 0 || hz_div <= 0)) {
1673 sprintf(p, "?");
1674 return rv;
1675 }
1676
1677 if (unlikely(hz_div > 1))
1678 t /= hz_div;
1679
1680 if (t >= DAY) {
1681 p += sprintf(p, "%dd", t / DAY);
1682 cnt--;
1683 }
1684
1685 if (cnt && t % DAY / HOUR) {
1686 p += sprintf(p, "%dh", t % DAY / HOUR);
1687 cnt--;
1688 }
1689
1690 if (cnt && t % HOUR / MINUTE) {
1691 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1692 cnt--;
1693 }
1694
1695 if ((cnt && t % MINUTE) || !t) // also display '0s'
1696 p += sprintf(p, "%ds", t % MINUTE / SEC);
1697
1698 return rv;
1699}
1700
1701const char *monthname[12] = {
1702 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1703 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1704};
1705
1706/* date2str_log: write a date in the format :
1707 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1708 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1709 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1710 *
1711 * without using sprintf. return a pointer to the last char written (\0) or
1712 * NULL if there isn't enough space.
1713 */
1714char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1715{
1716
1717 if (size < 25) /* the size is fixed: 24 chars + \0 */
1718 return NULL;
1719
1720 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1721 *dst++ = '/';
1722 memcpy(dst, monthname[tm->tm_mon], 3); // month
1723 dst += 3;
1724 *dst++ = '/';
1725 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1726 *dst++ = ':';
1727 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1728 *dst++ = ':';
1729 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1730 *dst++ = ':';
1731 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1732 *dst++ = '.';
1733 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1734 dst += 3; // only the 3 first digits
1735 *dst = '\0';
1736
1737 return dst;
1738}
1739
1740/* gmt2str_log: write a date in the format :
1741 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1742 * return a pointer to the last char written (\0) or
1743 * NULL if there isn't enough space.
1744 */
1745char *gmt2str_log(char *dst, struct tm *tm, size_t size)
1746{
Yuxans Yao4e25b012012-10-19 10:36:09 +08001747 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01001748 return NULL;
1749
1750 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1751 *dst++ = '/';
1752 memcpy(dst, monthname[tm->tm_mon], 3); // month
1753 dst += 3;
1754 *dst++ = '/';
1755 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1756 *dst++ = ':';
1757 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1758 *dst++ = ':';
1759 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1760 *dst++ = ':';
1761 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1762 *dst++ = ' ';
1763 *dst++ = '+';
1764 *dst++ = '0';
1765 *dst++ = '0';
1766 *dst++ = '0';
1767 *dst++ = '0';
1768 *dst = '\0';
1769
1770 return dst;
1771}
1772
Yuxans Yao4e25b012012-10-19 10:36:09 +08001773/* localdate2str_log: write a date in the format :
1774 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
1775 * * return a pointer to the last char written (\0) or
1776 * * NULL if there isn't enough space.
1777 */
1778char *localdate2str_log(char *dst, struct tm *tm, size_t size)
1779{
1780 if (size < 27) /* the size is fixed: 26 chars + \0 */
1781 return NULL;
1782
1783 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1784 *dst++ = '/';
1785 memcpy(dst, monthname[tm->tm_mon], 3); // month
1786 dst += 3;
1787 *dst++ = '/';
1788 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1789 *dst++ = ':';
1790 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1791 *dst++ = ':';
1792 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1793 *dst++ = ':';
1794 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1795 *dst++ = ' ';
1796 memcpy(dst, localtimezone, 5); // timezone
1797 dst += 5;
1798 *dst = '\0';
1799
1800 return dst;
1801}
1802
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001803/* Dynamically allocates a string of the proper length to hold the formatted
1804 * output. NULL is returned on error. The caller is responsible for freeing the
1805 * memory area using free(). The resulting string is returned in <out> if the
1806 * pointer is not NULL. A previous version of <out> might be used to build the
1807 * new string, and it will be freed before returning if it is not NULL, which
1808 * makes it possible to build complex strings from iterative calls without
1809 * having to care about freeing intermediate values, as in the example below :
1810 *
1811 * memprintf(&err, "invalid argument: '%s'", arg);
1812 * ...
1813 * memprintf(&err, "parser said : <%s>\n", *err);
1814 * ...
1815 * free(*err);
1816 *
1817 * This means that <err> must be initialized to NULL before first invocation.
1818 * The return value also holds the allocated string, which eases error checking
1819 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02001820 * passed instead and it will be ignored. The returned message will then also
1821 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001822 *
1823 * It is also convenient to use it without any free except the last one :
1824 * err = NULL;
1825 * if (!fct1(err)) report(*err);
1826 * if (!fct2(err)) report(*err);
1827 * if (!fct3(err)) report(*err);
1828 * free(*err);
1829 */
1830char *memprintf(char **out, const char *format, ...)
1831{
1832 va_list args;
1833 char *ret = NULL;
1834 int allocated = 0;
1835 int needed = 0;
1836
Willy Tarreaueb6cead2012-09-20 19:43:14 +02001837 if (!out)
1838 return NULL;
1839
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001840 do {
1841 /* vsnprintf() will return the required length even when the
1842 * target buffer is NULL. We do this in a loop just in case
1843 * intermediate evaluations get wrong.
1844 */
1845 va_start(args, format);
1846 needed = vsnprintf(ret, allocated, format, args) + 1;
1847 va_end(args);
1848
1849 if (needed <= allocated)
1850 break;
1851
1852 allocated = needed;
1853 ret = realloc(ret, allocated);
1854 } while (ret);
1855
1856 if (needed < 0) {
1857 /* an error was encountered */
1858 free(ret);
1859 ret = NULL;
1860 }
1861
1862 if (out) {
1863 free(*out);
1864 *out = ret;
1865 }
1866
1867 return ret;
1868}
William Lallemand421f5b52012-02-06 18:15:57 +01001869
Willy Tarreau21c705b2012-09-14 11:40:36 +02001870/* Used to add <level> spaces before each line of <out>, unless there is only one line.
1871 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02001872 * freed by the caller. It also supports being passed a NULL which results in the same
1873 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02001874 * Example of use :
1875 * parse(cmd, &err); (callee: memprintf(&err, ...))
1876 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
1877 * free(err);
1878 */
1879char *indent_msg(char **out, int level)
1880{
1881 char *ret, *in, *p;
1882 int needed = 0;
1883 int lf = 0;
1884 int lastlf = 0;
1885 int len;
1886
Willy Tarreau70eec382012-10-10 08:56:47 +02001887 if (!out || !*out)
1888 return NULL;
1889
Willy Tarreau21c705b2012-09-14 11:40:36 +02001890 in = *out - 1;
1891 while ((in = strchr(in + 1, '\n')) != NULL) {
1892 lastlf = in - *out;
1893 lf++;
1894 }
1895
1896 if (!lf) /* single line, no LF, return it as-is */
1897 return *out;
1898
1899 len = strlen(*out);
1900
1901 if (lf == 1 && lastlf == len - 1) {
1902 /* single line, LF at end, strip it and return as-is */
1903 (*out)[lastlf] = 0;
1904 return *out;
1905 }
1906
1907 /* OK now we have at least one LF, we need to process the whole string
1908 * as a multi-line string. What we'll do :
1909 * - prefix with an LF if there is none
1910 * - add <level> spaces before each line
1911 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
1912 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
1913 */
1914
1915 needed = 1 + level * (lf + 1) + len + 1;
1916 p = ret = malloc(needed);
1917 in = *out;
1918
1919 /* skip initial LFs */
1920 while (*in == '\n')
1921 in++;
1922
1923 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
1924 while (*in) {
1925 *p++ = '\n';
1926 memset(p, ' ', level);
1927 p += level;
1928 do {
1929 *p++ = *in++;
1930 } while (*in && *in != '\n');
1931 if (*in)
1932 in++;
1933 }
1934 *p = 0;
1935
1936 free(*out);
1937 *out = ret;
1938
1939 return ret;
1940}
1941
Willy Tarreaubaaee002006-06-26 02:48:02 +02001942/*
1943 * Local variables:
1944 * c-indent-level: 8
1945 * c-basic-offset: 8
1946 * End:
1947 */