blob: c670be0ac0124a48a4e620c5112b3dc491cbe531 [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 Tarreau24709282013-03-10 21:32:12 +0100508 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
509 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
510 * the function tries to guess the address family from the syntax. If the
511 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100512 * string is assumed to contain only an address, no port. The address can be a
513 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
514 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
515 * The return address will only have the address family and the address set,
516 * all other fields remain zero. The string is not supposed to be modified.
517 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200518 */
Willy Tarreau24709282013-03-10 21:32:12 +0100519static struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200520{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100521 struct hostent *he;
522
Willy Tarreaufab5a432011-03-04 15:31:53 +0100523 /* Any IPv6 address */
524 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100525 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
526 sa->ss_family = AF_INET6;
527 else if (sa->ss_family != AF_INET6)
528 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100529 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100530 }
531
Willy Tarreau24709282013-03-10 21:32:12 +0100532 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100533 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100534 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
535 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100536 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100537 }
538
539 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100540 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
541 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100542 sa->ss_family = AF_INET6;
543 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100544 }
545
546 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100547 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
548 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100549 sa->ss_family = AF_INET;
550 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100551 }
552
553 /* try to resolve an IPv4/IPv6 hostname */
554 he = gethostbyname(str);
555 if (he) {
Willy Tarreau24709282013-03-10 21:32:12 +0100556 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
557 sa->ss_family = he->h_addrtype;
558 else if (sa->ss_family != he->h_addrtype)
559 goto fail;
560
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100561 switch (sa->ss_family) {
Willy Tarreaufab5a432011-03-04 15:31:53 +0100562 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100563 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
564 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100565 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100566 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
567 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100568 }
David du Colombierd5f43282011-03-17 10:40:16 +0100569 }
570#ifdef USE_GETADDRINFO
571 else {
572 struct addrinfo hints, *result;
573
574 memset(&result, 0, sizeof(result));
575 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100576 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100577 hints.ai_socktype = SOCK_DGRAM;
578 hints.ai_flags = AI_PASSIVE;
579 hints.ai_protocol = 0;
580
581 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100582 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
583 sa->ss_family = result->ai_family;
584 else if (sa->ss_family != result->ai_family)
585 goto fail;
586
David du Colombierd5f43282011-03-17 10:40:16 +0100587 switch (result->ai_family) {
588 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100589 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
590 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100591 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100592 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
593 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100594 }
595 }
596
Sean Carey58ea0392013-02-15 23:39:18 +0100597 if (result)
598 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100599 }
David du Colombierd5f43282011-03-17 10:40:16 +0100600#endif
601 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100602 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100603 return NULL;
604}
605
606/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100607 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
608 * range or offset consisting in two integers that the caller will have to
609 * check to find the relevant input format. The following format are supported :
610 *
611 * String format | address | port | low | high
612 * addr | <addr> | 0 | 0 | 0
613 * addr: | <addr> | 0 | 0 | 0
614 * addr:port | <addr> | <port> | <port> | <port>
615 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
616 * addr:+port | <addr> | <port> | 0 | <port>
617 * addr:-port | <addr> |-<port> | <port> | 0
618 *
619 * The detection of a port range or increment by the caller is made by
620 * comparing <low> and <high>. If both are equal, then port 0 means no port
621 * was specified. The caller may pass NULL for <low> and <high> if it is not
622 * interested in retrieving port ranges.
623 *
624 * Note that <addr> above may also be :
625 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
626 * - "*" => family will be AF_INET and address will be INADDR_ANY
627 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
628 * - a host name => family and address will depend on host name resolving.
629 *
Willy Tarreau24709282013-03-10 21:32:12 +0100630 * A prefix may be passed in before the address above to force the family :
631 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
632 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
633 * - "unix@" => force address to be a path to a UNIX socket even if the
634 * path does not start with a '/'
635 *
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100636 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
637 * is mandatory after the IP address even when no port is specified. NULL is
638 * returned if the address cannot be parsed. The <low> and <high> ports are
Willy Tarreau24709282013-03-10 21:32:12 +0100639 * always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100640 *
641 * If <pfx> is non-null, it is used as a string prefix before any path-based
642 * address (typically the path to a unix socket).
Willy Tarreaufab5a432011-03-04 15:31:53 +0100643 */
Willy Tarreaud393a622013-03-04 18:22:00 +0100644struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100645{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100646 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100647 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100648 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100649 char *port1, *port2;
650 int portl, porth, porta;
651
652 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200653
Willy Tarreau24709282013-03-10 21:32:12 +0100654 str2 = back = strdup(str);
Willy Tarreaudf350f12013-03-01 20:22:54 +0100655 if (str2 == NULL) {
656 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100657 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100658 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200659
Willy Tarreau24709282013-03-10 21:32:12 +0100660 memset(&ss, 0, sizeof(ss));
661
662 if (strncmp(str2, "unix@", 5) == 0) {
663 str2 += 5;
664 ss.ss_family = AF_UNIX;
665 }
666 else if (strncmp(str2, "ipv4@", 5) == 0) {
667 str2 += 5;
668 ss.ss_family = AF_INET;
669 }
670 else if (strncmp(str2, "ipv6@", 5) == 0) {
671 str2 += 5;
672 ss.ss_family = AF_INET6;
673 }
674 else if (*str2 == '/') {
675 ss.ss_family = AF_UNIX;
676 }
677 else
678 ss.ss_family = AF_UNSPEC;
679
680 if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100681 int prefix_path_len;
682 int max_path_len;
683
684 /* complete unix socket path name during startup or soft-restart is
685 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
686 */
687 prefix_path_len = pfx ? strlen(pfx) : 0;
688 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
689 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
690
691 if (strlen(str2) > max_path_len) {
692 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
693 goto out;
694 }
695
Willy Tarreau15586382013-03-04 19:48:14 +0100696 if (pfx) {
697 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
698 strcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len, str2);
699 }
700 else {
701 strcpy(((struct sockaddr_un *)&ss)->sun_path, str2);
702 }
Willy Tarreau15586382013-03-04 19:48:14 +0100703 }
Willy Tarreau24709282013-03-10 21:32:12 +0100704 else { /* IPv4 and IPv6 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100705 port1 = strrchr(str2, ':');
706 if (port1)
707 *port1++ = '\0';
708 else
709 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200710
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100711 if (str2ip(str2, &ss) == NULL) {
712 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
713 goto out;
714 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100715
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100716 if (isdigit(*port1)) { /* single port or range */
717 port2 = strchr(port1, '-');
718 if (port2)
719 *port2++ = '\0';
720 else
721 port2 = port1;
722 portl = atoi(port1);
723 porth = atoi(port2);
724 porta = portl;
725 }
726 else if (*port1 == '-') { /* negative offset */
727 portl = atoi(port1 + 1);
728 porta = -portl;
729 }
730 else if (*port1 == '+') { /* positive offset */
731 porth = atoi(port1 + 1);
732 porta = porth;
733 }
734 else if (*port1) { /* other any unexpected char */
735 memprintf(err, "invalid character '%c' in port number '%s'\n", *port1, port1);
736 goto out;
737 }
738 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100739 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100740
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100741 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100742 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100743 if (low)
744 *low = portl;
745 if (high)
746 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100747 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100748 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200749}
750
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100751/* converts <str> to a struct in_addr containing a network mask. It can be
752 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
753 * if the conversion succeeds otherwise non-zero.
754 */
755int str2mask(const char *str, struct in_addr *mask)
756{
757 if (strchr(str, '.') != NULL) { /* dotted notation */
758 if (!inet_pton(AF_INET, str, mask))
759 return 0;
760 }
761 else { /* mask length */
762 char *err;
763 unsigned long len = strtol(str, &err, 10);
764
765 if (!*str || (err && *err) || (unsigned)len > 32)
766 return 0;
767 if (len)
768 mask->s_addr = htonl(~0UL << (32 - len));
769 else
770 mask->s_addr = 0;
771 }
772 return 1;
773}
774
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200775/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200776 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200777 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
778 * is optionnal and either in the dotted or CIDR notation.
779 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
780 */
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200781int str2net(const char *str, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200782{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200783 __label__ out_free, out_err;
784 char *c, *s;
785 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200786
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200787 s = strdup(str);
788 if (!s)
789 return 0;
790
Willy Tarreaubaaee002006-06-26 02:48:02 +0200791 memset(mask, 0, sizeof(*mask));
792 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200793
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200794 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200795 *c++ = '\0';
796 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100797 if (!str2mask(c, mask))
798 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200799 }
800 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100801 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200802 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200803 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200804 struct hostent *he;
805
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200806 if ((he = gethostbyname(s)) == NULL) {
807 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200808 }
809 else
810 *addr = *(struct in_addr *) *(he->h_addr_list);
811 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200812
813 ret_val = 1;
814 out_free:
815 free(s);
816 return ret_val;
817 out_err:
818 ret_val = 0;
819 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200820}
821
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100822
823/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200824 * converts <str> to two struct in6_addr* which must be pre-allocated.
825 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
826 * is an optionnal number of bits (128 being the default).
827 * Returns 1 if OK, 0 if error.
828 */
829int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
830{
831 char *c, *s;
832 int ret_val = 0;
833 char *err;
834 unsigned long len = 128;
835
836 s = strdup(str);
837 if (!s)
838 return 0;
839
840 memset(mask, 0, sizeof(*mask));
841 memset(addr, 0, sizeof(*addr));
842
843 if ((c = strrchr(s, '/')) != NULL) {
844 *c++ = '\0'; /* c points to the mask */
845 if (!*c)
846 goto out_free;
847
848 len = strtoul(c, &err, 10);
849 if ((err && *err) || (unsigned)len > 128)
850 goto out_free;
851 }
852 *mask = len; /* OK we have a valid mask in <len> */
853
854 if (!inet_pton(AF_INET6, s, addr))
855 goto out_free;
856
857 ret_val = 1;
858 out_free:
859 free(s);
860 return ret_val;
861}
862
863
864/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100865 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100866 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100867int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100868{
869 int saw_digit, octets, ch;
870 u_char tmp[4], *tp;
871 const char *cp = addr;
872
873 saw_digit = 0;
874 octets = 0;
875 *(tp = tmp) = 0;
876
877 while (*addr) {
878 unsigned char digit = (ch = *addr++) - '0';
879 if (digit > 9 && ch != '.')
880 break;
881 if (digit <= 9) {
882 u_int new = *tp * 10 + digit;
883 if (new > 255)
884 return 0;
885 *tp = new;
886 if (!saw_digit) {
887 if (++octets > 4)
888 return 0;
889 saw_digit = 1;
890 }
891 } else if (ch == '.' && saw_digit) {
892 if (octets == 4)
893 return 0;
894 *++tp = 0;
895 saw_digit = 0;
896 } else
897 return 0;
898 }
899
900 if (octets < 4)
901 return 0;
902
903 memcpy(&dst->s_addr, tmp, 4);
904 return addr-cp-1;
905}
906
907/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100908 * Resolve destination server from URL. Convert <str> to a sockaddr_storage*.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100909 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100910int url2sa(const char *url, int ulen, struct sockaddr_storage *addr)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100911{
912 const char *curr = url, *cp = url;
913 int ret, url_code = 0;
914 unsigned int http_code = 0;
915
916 /* Cleanup the room */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100917
918 /* FIXME: assume IPv4 only for now */
919 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
920 ((struct sockaddr_in *)addr)->sin_addr.s_addr = 0;
921 ((struct sockaddr_in *)addr)->sin_port = 0;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100922
923 /* Firstly, try to find :// pattern */
924 while (curr < url+ulen && url_code != 0x3a2f2f) {
925 url_code = ((url_code & 0xffff) << 8);
926 url_code += (unsigned char)*curr++;
927 }
928
929 /* Secondly, if :// pattern is found, verify parsed stuff
930 * before pattern is matching our http pattern.
931 * If so parse ip address and port in uri.
932 *
933 * WARNING: Current code doesn't support dynamic async dns resolver.
934 */
935 if (url_code == 0x3a2f2f) {
936 while (cp < curr - 3)
937 http_code = (http_code << 8) + *cp++;
938 http_code |= 0x20202020; /* Turn everything to lower case */
939
940 /* HTTP url matching */
941 if (http_code == 0x68747470) {
942 /* We are looking for IP address. If you want to parse and
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100943 * resolve hostname found in url, you can use str2sa_range(), but
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100944 * be warned this can slow down global daemon performances
945 * while handling lagging dns responses.
946 */
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200947 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100948 if (!ret)
949 return -1;
950 curr += ret;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100951 ((struct sockaddr_in *)addr)->sin_port = (*curr == ':') ? str2uic(++curr) : 80;
Cyril Bonté9ccf6612012-10-24 23:47:47 +0200952 ((struct sockaddr_in *)addr)->sin_port = htons(((struct sockaddr_in *)addr)->sin_port);
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100953 }
954 return 0;
955 }
956
957 return -1;
958}
959
Willy Tarreau631f01c2011-09-05 00:36:48 +0200960/* Tries to convert a sockaddr_storage address to text form. Upon success, the
961 * address family is returned so that it's easy for the caller to adapt to the
962 * output format. Zero is returned if the address family is not supported. -1
963 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
964 * supported.
965 */
966int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
967{
968
969 void *ptr;
970
971 if (size < 5)
972 return 0;
973 *str = '\0';
974
975 switch (addr->ss_family) {
976 case AF_INET:
977 ptr = &((struct sockaddr_in *)addr)->sin_addr;
978 break;
979 case AF_INET6:
980 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
981 break;
982 case AF_UNIX:
983 memcpy(str, "unix", 5);
984 return addr->ss_family;
985 default:
986 return 0;
987 }
988
989 if (inet_ntop(addr->ss_family, ptr, str, size))
990 return addr->ss_family;
991
992 /* failed */
993 return -1;
994}
995
Willy Tarreaubaaee002006-06-26 02:48:02 +0200996/* will try to encode the string <string> replacing all characters tagged in
997 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
998 * prefixed by <escape>, and will store the result between <start> (included)
999 * and <stop> (excluded), and will always terminate the string with a '\0'
1000 * before <stop>. The position of the '\0' is returned if the conversion
1001 * completes. If bytes are missing between <start> and <stop>, then the
1002 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1003 * cannot even be stored so we return <start> without writing the 0.
1004 * The input string must also be zero-terminated.
1005 */
1006const char hextab[16] = "0123456789ABCDEF";
1007char *encode_string(char *start, char *stop,
1008 const char escape, const fd_set *map,
1009 const char *string)
1010{
1011 if (start < stop) {
1012 stop--; /* reserve one byte for the final '\0' */
1013 while (start < stop && *string != '\0') {
1014 if (!FD_ISSET((unsigned char)(*string), map))
1015 *start++ = *string;
1016 else {
1017 if (start + 3 >= stop)
1018 break;
1019 *start++ = escape;
1020 *start++ = hextab[(*string >> 4) & 15];
1021 *start++ = hextab[*string & 15];
1022 }
1023 string++;
1024 }
1025 *start = '\0';
1026 }
1027 return start;
1028}
1029
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001030/* Decode an URL-encoded string in-place. The resulting string might
1031 * be shorter. If some forbidden characters are found, the conversion is
1032 * aborted, the string is truncated before the issue and non-zero is returned,
1033 * otherwise the operation returns non-zero indicating success.
1034 */
1035int url_decode(char *string)
1036{
1037 char *in, *out;
1038 int ret = 0;
1039
1040 in = string;
1041 out = string;
1042 while (*in) {
1043 switch (*in) {
1044 case '+' :
1045 *out++ = ' ';
1046 break;
1047 case '%' :
1048 if (!ishex(in[1]) || !ishex(in[2]))
1049 goto end;
1050 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1051 in += 2;
1052 break;
1053 default:
1054 *out++ = *in;
1055 break;
1056 }
1057 in++;
1058 }
1059 ret = 1; /* success */
1060 end:
1061 *out = 0;
1062 return ret;
1063}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001064
Willy Tarreau6911fa42007-03-04 18:06:08 +01001065unsigned int str2ui(const char *s)
1066{
1067 return __str2ui(s);
1068}
1069
1070unsigned int str2uic(const char *s)
1071{
1072 return __str2uic(s);
1073}
1074
1075unsigned int strl2ui(const char *s, int len)
1076{
1077 return __strl2ui(s, len);
1078}
1079
1080unsigned int strl2uic(const char *s, int len)
1081{
1082 return __strl2uic(s, len);
1083}
1084
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001085unsigned int read_uint(const char **s, const char *end)
1086{
1087 return __read_uint(s, end);
1088}
1089
Willy Tarreau6911fa42007-03-04 18:06:08 +01001090/* This one is 7 times faster than strtol() on athlon with checks.
1091 * It returns the value of the number composed of all valid digits read,
1092 * and can process negative numbers too.
1093 */
1094int strl2ic(const char *s, int len)
1095{
1096 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001097 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001098
1099 if (len > 0) {
1100 if (*s != '-') {
1101 /* positive number */
1102 while (len-- > 0) {
1103 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001104 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001105 if (j > 9)
1106 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001107 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001108 }
1109 } else {
1110 /* negative number */
1111 s++;
1112 while (--len > 0) {
1113 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001114 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001115 if (j > 9)
1116 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001117 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001118 }
1119 }
1120 }
1121 return i;
1122}
1123
1124
1125/* This function reads exactly <len> chars from <s> and converts them to a
1126 * signed integer which it stores into <ret>. It accurately detects any error
1127 * (truncated string, invalid chars, overflows). It is meant to be used in
1128 * applications designed for hostile environments. It returns zero when the
1129 * number has successfully been converted, non-zero otherwise. When an error
1130 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1131 * faster than strtol().
1132 */
1133int strl2irc(const char *s, int len, int *ret)
1134{
1135 int i = 0;
1136 int j;
1137
1138 if (!len)
1139 return 1;
1140
1141 if (*s != '-') {
1142 /* positive number */
1143 while (len-- > 0) {
1144 j = (*s++) - '0';
1145 if (j > 9) return 1; /* invalid char */
1146 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1147 i = i * 10;
1148 if (i + j < i) return 1; /* check for addition overflow */
1149 i = i + j;
1150 }
1151 } else {
1152 /* negative number */
1153 s++;
1154 while (--len > 0) {
1155 j = (*s++) - '0';
1156 if (j > 9) return 1; /* invalid char */
1157 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1158 i = i * 10;
1159 if (i - j > i) return 1; /* check for subtract overflow */
1160 i = i - j;
1161 }
1162 }
1163 *ret = i;
1164 return 0;
1165}
1166
1167
1168/* This function reads exactly <len> chars from <s> and converts them to a
1169 * signed integer which it stores into <ret>. It accurately detects any error
1170 * (truncated string, invalid chars, overflows). It is meant to be used in
1171 * applications designed for hostile environments. It returns zero when the
1172 * number has successfully been converted, non-zero otherwise. When an error
1173 * is returned, the <ret> value is left untouched. It is about 3 times slower
1174 * than str2irc().
1175 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001176
1177int strl2llrc(const char *s, int len, long long *ret)
1178{
1179 long long i = 0;
1180 int j;
1181
1182 if (!len)
1183 return 1;
1184
1185 if (*s != '-') {
1186 /* positive number */
1187 while (len-- > 0) {
1188 j = (*s++) - '0';
1189 if (j > 9) return 1; /* invalid char */
1190 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1191 i = i * 10LL;
1192 if (i + j < i) return 1; /* check for addition overflow */
1193 i = i + j;
1194 }
1195 } else {
1196 /* negative number */
1197 s++;
1198 while (--len > 0) {
1199 j = (*s++) - '0';
1200 if (j > 9) return 1; /* invalid char */
1201 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1202 i = i * 10LL;
1203 if (i - j > i) return 1; /* check for subtract overflow */
1204 i = i - j;
1205 }
1206 }
1207 *ret = i;
1208 return 0;
1209}
1210
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001211/* This function parses a time value optionally followed by a unit suffix among
1212 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1213 * expected by the caller. The computation does its best to avoid overflows.
1214 * The value is returned in <ret> if everything is fine, and a NULL is returned
1215 * by the function. In case of error, a pointer to the error is returned and
1216 * <ret> is left untouched. Values are automatically rounded up when needed.
1217 */
1218const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1219{
1220 unsigned imult, idiv;
1221 unsigned omult, odiv;
1222 unsigned value;
1223
1224 omult = odiv = 1;
1225
1226 switch (unit_flags & TIME_UNIT_MASK) {
1227 case TIME_UNIT_US: omult = 1000000; break;
1228 case TIME_UNIT_MS: omult = 1000; break;
1229 case TIME_UNIT_S: break;
1230 case TIME_UNIT_MIN: odiv = 60; break;
1231 case TIME_UNIT_HOUR: odiv = 3600; break;
1232 case TIME_UNIT_DAY: odiv = 86400; break;
1233 default: break;
1234 }
1235
1236 value = 0;
1237
1238 while (1) {
1239 unsigned int j;
1240
1241 j = *text - '0';
1242 if (j > 9)
1243 break;
1244 text++;
1245 value *= 10;
1246 value += j;
1247 }
1248
1249 imult = idiv = 1;
1250 switch (*text) {
1251 case '\0': /* no unit = default unit */
1252 imult = omult = idiv = odiv = 1;
1253 break;
1254 case 's': /* second = unscaled unit */
1255 break;
1256 case 'u': /* microsecond : "us" */
1257 if (text[1] == 's') {
1258 idiv = 1000000;
1259 text++;
1260 }
1261 break;
1262 case 'm': /* millisecond : "ms" or minute: "m" */
1263 if (text[1] == 's') {
1264 idiv = 1000;
1265 text++;
1266 } else
1267 imult = 60;
1268 break;
1269 case 'h': /* hour : "h" */
1270 imult = 3600;
1271 break;
1272 case 'd': /* day : "d" */
1273 imult = 86400;
1274 break;
1275 default:
1276 return text;
1277 break;
1278 }
1279
1280 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1281 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1282 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1283 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1284
1285 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1286 *ret = value;
1287 return NULL;
1288}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001289
Emeric Brun39132b22010-01-04 14:57:24 +01001290/* this function converts the string starting at <text> to an unsigned int
1291 * stored in <ret>. If an error is detected, the pointer to the unexpected
1292 * character is returned. If the conversio is succesful, NULL is returned.
1293 */
1294const char *parse_size_err(const char *text, unsigned *ret) {
1295 unsigned value = 0;
1296
1297 while (1) {
1298 unsigned int j;
1299
1300 j = *text - '0';
1301 if (j > 9)
1302 break;
1303 if (value > ~0U / 10)
1304 return text;
1305 value *= 10;
1306 if (value > (value + j))
1307 return text;
1308 value += j;
1309 text++;
1310 }
1311
1312 switch (*text) {
1313 case '\0':
1314 break;
1315 case 'K':
1316 case 'k':
1317 if (value > ~0U >> 10)
1318 return text;
1319 value = value << 10;
1320 break;
1321 case 'M':
1322 case 'm':
1323 if (value > ~0U >> 20)
1324 return text;
1325 value = value << 20;
1326 break;
1327 case 'G':
1328 case 'g':
1329 if (value > ~0U >> 30)
1330 return text;
1331 value = value << 30;
1332 break;
1333 default:
1334 return text;
1335 }
1336
1337 *ret = value;
1338 return NULL;
1339}
1340
Willy Tarreau946ba592009-05-10 15:41:18 +02001341/* copies at most <n> characters from <src> and always terminates with '\0' */
1342char *my_strndup(const char *src, int n)
1343{
1344 int len = 0;
1345 char *ret;
1346
1347 while (len < n && src[len])
1348 len++;
1349
1350 ret = (char *)malloc(len + 1);
1351 if (!ret)
1352 return ret;
1353 memcpy(ret, src, len);
1354 ret[len] = '\0';
1355 return ret;
1356}
1357
Willy Tarreau482b00d2009-10-04 22:48:42 +02001358/* This function returns the first unused key greater than or equal to <key> in
1359 * ID tree <root>. Zero is returned if no place is found.
1360 */
1361unsigned int get_next_id(struct eb_root *root, unsigned int key)
1362{
1363 struct eb32_node *used;
1364
1365 do {
1366 used = eb32_lookup_ge(root, key);
1367 if (!used || used->key > key)
1368 return key; /* key is available */
1369 key++;
1370 } while (key);
1371 return key;
1372}
1373
Willy Tarreau348238b2010-01-18 15:05:57 +01001374/* This function compares a sample word possibly followed by blanks to another
1375 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1376 * otherwise zero. This intends to be used when checking HTTP headers for some
1377 * values. Note that it validates a word followed only by blanks but does not
1378 * validate a word followed by blanks then other chars.
1379 */
1380int word_match(const char *sample, int slen, const char *word, int wlen)
1381{
1382 if (slen < wlen)
1383 return 0;
1384
1385 while (wlen) {
1386 char c = *sample ^ *word;
1387 if (c && c != ('A' ^ 'a'))
1388 return 0;
1389 sample++;
1390 word++;
1391 slen--;
1392 wlen--;
1393 }
1394
1395 while (slen) {
1396 if (*sample != ' ' && *sample != '\t')
1397 return 0;
1398 sample++;
1399 slen--;
1400 }
1401 return 1;
1402}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001403
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001404/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1405 * is particularly fast because it avoids expensive operations such as
1406 * multiplies, which are optimized away at the end. It requires a properly
1407 * formated address though (3 points).
1408 */
1409unsigned int inetaddr_host(const char *text)
1410{
1411 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1412 register unsigned int dig100, dig10, dig1;
1413 int s;
1414 const char *p, *d;
1415
1416 dig1 = dig10 = dig100 = ascii_zero;
1417 s = 24;
1418
1419 p = text;
1420 while (1) {
1421 if (((unsigned)(*p - '0')) <= 9) {
1422 p++;
1423 continue;
1424 }
1425
1426 /* here, we have a complete byte between <text> and <p> (exclusive) */
1427 if (p == text)
1428 goto end;
1429
1430 d = p - 1;
1431 dig1 |= (unsigned int)(*d << s);
1432 if (d == text)
1433 goto end;
1434
1435 d--;
1436 dig10 |= (unsigned int)(*d << s);
1437 if (d == text)
1438 goto end;
1439
1440 d--;
1441 dig100 |= (unsigned int)(*d << s);
1442 end:
1443 if (!s || *p != '.')
1444 break;
1445
1446 s -= 8;
1447 text = ++p;
1448 }
1449
1450 dig100 -= ascii_zero;
1451 dig10 -= ascii_zero;
1452 dig1 -= ascii_zero;
1453 return ((dig100 * 10) + dig10) * 10 + dig1;
1454}
1455
1456/*
1457 * Idem except the first unparsed character has to be passed in <stop>.
1458 */
1459unsigned int inetaddr_host_lim(const char *text, const char *stop)
1460{
1461 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1462 register unsigned int dig100, dig10, dig1;
1463 int s;
1464 const char *p, *d;
1465
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 dig100 -= ascii_zero;
1501 dig10 -= ascii_zero;
1502 dig1 -= ascii_zero;
1503 return ((dig100 * 10) + dig10) * 10 + dig1;
1504}
1505
1506/*
1507 * Idem except the pointer to first unparsed byte is returned into <ret> which
1508 * must not be NULL.
1509 */
Willy Tarreau74172752010-10-15 23:21:42 +02001510unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001511{
1512 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1513 register unsigned int dig100, dig10, dig1;
1514 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001515 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001516
1517 dig1 = dig10 = dig100 = ascii_zero;
1518 s = 24;
1519
1520 p = text;
1521 while (1) {
1522 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1523 p++;
1524 continue;
1525 }
1526
1527 /* here, we have a complete byte between <text> and <p> (exclusive) */
1528 if (p == text)
1529 goto end;
1530
1531 d = p - 1;
1532 dig1 |= (unsigned int)(*d << s);
1533 if (d == text)
1534 goto end;
1535
1536 d--;
1537 dig10 |= (unsigned int)(*d << s);
1538 if (d == text)
1539 goto end;
1540
1541 d--;
1542 dig100 |= (unsigned int)(*d << s);
1543 end:
1544 if (!s || p == stop || *p != '.')
1545 break;
1546
1547 s -= 8;
1548 text = ++p;
1549 }
1550
1551 *ret = p;
1552 dig100 -= ascii_zero;
1553 dig10 -= ascii_zero;
1554 dig1 -= ascii_zero;
1555 return ((dig100 * 10) + dig10) * 10 + dig1;
1556}
1557
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001558/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1559 * or the number of chars read in case of success. Maybe this could be replaced
1560 * by one of the functions above. Also, apparently this function does not support
1561 * hosts above 255 and requires exactly 4 octets.
1562 */
1563int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1564{
1565 const char *addr;
1566 int saw_digit, octets, ch;
1567 u_char tmp[4], *tp;
1568 const char *cp = buf;
1569
1570 saw_digit = 0;
1571 octets = 0;
1572 *(tp = tmp) = 0;
1573
1574 for (addr = buf; addr - buf < len; addr++) {
1575 unsigned char digit = (ch = *addr) - '0';
1576
1577 if (digit > 9 && ch != '.')
1578 break;
1579
1580 if (digit <= 9) {
1581 u_int new = *tp * 10 + digit;
1582
1583 if (new > 255)
1584 return 0;
1585
1586 *tp = new;
1587
1588 if (!saw_digit) {
1589 if (++octets > 4)
1590 return 0;
1591 saw_digit = 1;
1592 }
1593 } else if (ch == '.' && saw_digit) {
1594 if (octets == 4)
1595 return 0;
1596
1597 *++tp = 0;
1598 saw_digit = 0;
1599 } else
1600 return 0;
1601 }
1602
1603 if (octets < 4)
1604 return 0;
1605
1606 memcpy(&dst->s_addr, tmp, 4);
1607 return addr - cp;
1608}
1609
Willy Tarreauacf95772010-06-14 19:09:21 +02001610/* To be used to quote config arg positions. Returns the short string at <ptr>
1611 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1612 * if ptr is NULL or empty. The string is locally allocated.
1613 */
1614const char *quote_arg(const char *ptr)
1615{
1616 static char val[32];
1617 int i;
1618
1619 if (!ptr || !*ptr)
1620 return "end of line";
1621 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001622 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001623 val[i] = *ptr++;
1624 val[i++] = '\'';
1625 val[i] = '\0';
1626 return val;
1627}
1628
Willy Tarreau5b180202010-07-18 10:40:48 +02001629/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
1630int get_std_op(const char *str)
1631{
1632 int ret = -1;
1633
1634 if (*str == 'e' && str[1] == 'q')
1635 ret = STD_OP_EQ;
1636 else if (*str == 'n' && str[1] == 'e')
1637 ret = STD_OP_NE;
1638 else if (*str == 'l') {
1639 if (str[1] == 'e') ret = STD_OP_LE;
1640 else if (str[1] == 't') ret = STD_OP_LT;
1641 }
1642 else if (*str == 'g') {
1643 if (str[1] == 'e') ret = STD_OP_GE;
1644 else if (str[1] == 't') ret = STD_OP_GT;
1645 }
1646
1647 if (ret == -1 || str[2] != '\0')
1648 return -1;
1649 return ret;
1650}
1651
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01001652/* hash a 32-bit integer to another 32-bit integer */
1653unsigned int full_hash(unsigned int a)
1654{
1655 return __full_hash(a);
1656}
1657
David du Colombier4f92d322011-03-24 11:09:31 +01001658/* Return non-zero if IPv4 address is part of the network,
1659 * otherwise zero.
1660 */
1661int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
1662{
1663 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
1664}
1665
1666/* Return non-zero if IPv6 address is part of the network,
1667 * otherwise zero.
1668 */
1669int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
1670{
1671 int i;
1672
1673 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
1674 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
1675 (((int *)net)[i] & ((int *)mask)[i]))
1676 return 0;
1677 return 1;
1678}
1679
1680/* RFC 4291 prefix */
1681const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
1682 0x00, 0x00, 0x00, 0x00,
1683 0x00, 0x00, 0xFF, 0xFF };
1684
1685/* Map IPv4 adress on IPv6 address, as specified in RFC 3513. */
1686void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
1687{
1688 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
1689 memcpy(sin6_addr->s6_addr+12, &sin_addr->s_addr, 4);
1690}
1691
1692/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
1693 * Return true if conversion is possible and false otherwise.
1694 */
1695int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
1696{
1697 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
1698 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
1699 sizeof(struct in_addr));
1700 return 1;
1701 }
1702
1703 return 0;
1704}
1705
William Lallemand421f5b52012-02-06 18:15:57 +01001706char *human_time(int t, short hz_div) {
1707 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
1708 char *p = rv;
1709 int cnt=2; // print two numbers
1710
1711 if (unlikely(t < 0 || hz_div <= 0)) {
1712 sprintf(p, "?");
1713 return rv;
1714 }
1715
1716 if (unlikely(hz_div > 1))
1717 t /= hz_div;
1718
1719 if (t >= DAY) {
1720 p += sprintf(p, "%dd", t / DAY);
1721 cnt--;
1722 }
1723
1724 if (cnt && t % DAY / HOUR) {
1725 p += sprintf(p, "%dh", t % DAY / HOUR);
1726 cnt--;
1727 }
1728
1729 if (cnt && t % HOUR / MINUTE) {
1730 p += sprintf(p, "%dm", t % HOUR / MINUTE);
1731 cnt--;
1732 }
1733
1734 if ((cnt && t % MINUTE) || !t) // also display '0s'
1735 p += sprintf(p, "%ds", t % MINUTE / SEC);
1736
1737 return rv;
1738}
1739
1740const char *monthname[12] = {
1741 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1742 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1743};
1744
1745/* date2str_log: write a date in the format :
1746 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
1747 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
1748 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
1749 *
1750 * without using sprintf. return a pointer to the last char written (\0) or
1751 * NULL if there isn't enough space.
1752 */
1753char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
1754{
1755
1756 if (size < 25) /* the size is fixed: 24 chars + \0 */
1757 return NULL;
1758
1759 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1760 *dst++ = '/';
1761 memcpy(dst, monthname[tm->tm_mon], 3); // month
1762 dst += 3;
1763 *dst++ = '/';
1764 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1765 *dst++ = ':';
1766 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1767 *dst++ = ':';
1768 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1769 *dst++ = ':';
1770 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1771 *dst++ = '.';
1772 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
1773 dst += 3; // only the 3 first digits
1774 *dst = '\0';
1775
1776 return dst;
1777}
1778
1779/* gmt2str_log: write a date in the format :
1780 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
1781 * return a pointer to the last char written (\0) or
1782 * NULL if there isn't enough space.
1783 */
1784char *gmt2str_log(char *dst, struct tm *tm, size_t size)
1785{
Yuxans Yao4e25b012012-10-19 10:36:09 +08001786 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01001787 return NULL;
1788
1789 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1790 *dst++ = '/';
1791 memcpy(dst, monthname[tm->tm_mon], 3); // month
1792 dst += 3;
1793 *dst++ = '/';
1794 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1795 *dst++ = ':';
1796 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1797 *dst++ = ':';
1798 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1799 *dst++ = ':';
1800 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1801 *dst++ = ' ';
1802 *dst++ = '+';
1803 *dst++ = '0';
1804 *dst++ = '0';
1805 *dst++ = '0';
1806 *dst++ = '0';
1807 *dst = '\0';
1808
1809 return dst;
1810}
1811
Yuxans Yao4e25b012012-10-19 10:36:09 +08001812/* localdate2str_log: write a date in the format :
1813 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
1814 * * return a pointer to the last char written (\0) or
1815 * * NULL if there isn't enough space.
1816 */
1817char *localdate2str_log(char *dst, struct tm *tm, size_t size)
1818{
1819 if (size < 27) /* the size is fixed: 26 chars + \0 */
1820 return NULL;
1821
1822 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
1823 *dst++ = '/';
1824 memcpy(dst, monthname[tm->tm_mon], 3); // month
1825 dst += 3;
1826 *dst++ = '/';
1827 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
1828 *dst++ = ':';
1829 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
1830 *dst++ = ':';
1831 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
1832 *dst++ = ':';
1833 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
1834 *dst++ = ' ';
1835 memcpy(dst, localtimezone, 5); // timezone
1836 dst += 5;
1837 *dst = '\0';
1838
1839 return dst;
1840}
1841
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001842/* Dynamically allocates a string of the proper length to hold the formatted
1843 * output. NULL is returned on error. The caller is responsible for freeing the
1844 * memory area using free(). The resulting string is returned in <out> if the
1845 * pointer is not NULL. A previous version of <out> might be used to build the
1846 * new string, and it will be freed before returning if it is not NULL, which
1847 * makes it possible to build complex strings from iterative calls without
1848 * having to care about freeing intermediate values, as in the example below :
1849 *
1850 * memprintf(&err, "invalid argument: '%s'", arg);
1851 * ...
1852 * memprintf(&err, "parser said : <%s>\n", *err);
1853 * ...
1854 * free(*err);
1855 *
1856 * This means that <err> must be initialized to NULL before first invocation.
1857 * The return value also holds the allocated string, which eases error checking
1858 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02001859 * passed instead and it will be ignored. The returned message will then also
1860 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001861 *
1862 * It is also convenient to use it without any free except the last one :
1863 * err = NULL;
1864 * if (!fct1(err)) report(*err);
1865 * if (!fct2(err)) report(*err);
1866 * if (!fct3(err)) report(*err);
1867 * free(*err);
1868 */
1869char *memprintf(char **out, const char *format, ...)
1870{
1871 va_list args;
1872 char *ret = NULL;
1873 int allocated = 0;
1874 int needed = 0;
1875
Willy Tarreaueb6cead2012-09-20 19:43:14 +02001876 if (!out)
1877 return NULL;
1878
Willy Tarreau9a7bea52012-04-27 11:16:50 +02001879 do {
1880 /* vsnprintf() will return the required length even when the
1881 * target buffer is NULL. We do this in a loop just in case
1882 * intermediate evaluations get wrong.
1883 */
1884 va_start(args, format);
1885 needed = vsnprintf(ret, allocated, format, args) + 1;
1886 va_end(args);
1887
1888 if (needed <= allocated)
1889 break;
1890
1891 allocated = needed;
1892 ret = realloc(ret, allocated);
1893 } while (ret);
1894
1895 if (needed < 0) {
1896 /* an error was encountered */
1897 free(ret);
1898 ret = NULL;
1899 }
1900
1901 if (out) {
1902 free(*out);
1903 *out = ret;
1904 }
1905
1906 return ret;
1907}
William Lallemand421f5b52012-02-06 18:15:57 +01001908
Willy Tarreau21c705b2012-09-14 11:40:36 +02001909/* Used to add <level> spaces before each line of <out>, unless there is only one line.
1910 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02001911 * freed by the caller. It also supports being passed a NULL which results in the same
1912 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02001913 * Example of use :
1914 * parse(cmd, &err); (callee: memprintf(&err, ...))
1915 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
1916 * free(err);
1917 */
1918char *indent_msg(char **out, int level)
1919{
1920 char *ret, *in, *p;
1921 int needed = 0;
1922 int lf = 0;
1923 int lastlf = 0;
1924 int len;
1925
Willy Tarreau70eec382012-10-10 08:56:47 +02001926 if (!out || !*out)
1927 return NULL;
1928
Willy Tarreau21c705b2012-09-14 11:40:36 +02001929 in = *out - 1;
1930 while ((in = strchr(in + 1, '\n')) != NULL) {
1931 lastlf = in - *out;
1932 lf++;
1933 }
1934
1935 if (!lf) /* single line, no LF, return it as-is */
1936 return *out;
1937
1938 len = strlen(*out);
1939
1940 if (lf == 1 && lastlf == len - 1) {
1941 /* single line, LF at end, strip it and return as-is */
1942 (*out)[lastlf] = 0;
1943 return *out;
1944 }
1945
1946 /* OK now we have at least one LF, we need to process the whole string
1947 * as a multi-line string. What we'll do :
1948 * - prefix with an LF if there is none
1949 * - add <level> spaces before each line
1950 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
1951 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
1952 */
1953
1954 needed = 1 + level * (lf + 1) + len + 1;
1955 p = ret = malloc(needed);
1956 in = *out;
1957
1958 /* skip initial LFs */
1959 while (*in == '\n')
1960 in++;
1961
1962 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
1963 while (*in) {
1964 *p++ = '\n';
1965 memset(p, ' ', level);
1966 p += level;
1967 do {
1968 *p++ = *in++;
1969 } while (*in && *in != '\n');
1970 if (*in)
1971 in++;
1972 }
1973 *p = 0;
1974
1975 free(*out);
1976 *out = ret;
1977
1978 return ret;
1979}
1980
Willy Tarreaubaaee002006-06-26 02:48:02 +02001981/*
1982 * Local variables:
1983 * c-indent-level: 8
1984 * c-basic-offset: 8
1985 * End:
1986 */