blob: 28c2b9a5a0dbd96b54057906651602636112aec1 [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
Thierry FOURNIERe059ec92014-03-17 12:01:13 +010024#include <common/chunk.h>
Willy Tarreaue3ba5f02006-06-29 18:54:54 +020025#include <common/config.h>
Willy Tarreau2dd0d472006-06-29 17:53:05 +020026#include <common/standard.h>
Thierry FOURNIER9f95e402014-03-21 14:51:46 +010027#include <types/global.h>
Willy Tarreau45cb4fb2009-10-26 21:10:04 +010028#include <eb32tree.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020029
Willy Tarreau56adcf22012-12-23 18:00:29 +010030/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020031 * 2^64-1 = 18446744073709551615 or
32 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020033 *
34 * The HTML version needs room for adding the 25 characters
35 * '<span class="rls"></span>' around digits at positions 3N+1 in order
36 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020037 */
Willy Tarreau56adcf22012-12-23 18:00:29 +010038char itoa_str[NB_ITOA_STR][171];
39int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020040
Willy Tarreau588297f2014-06-16 15:16:40 +020041/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
42 * to quote strings larger than a max configuration line.
43 */
44char quoted_str[NB_QSTR][QSTR_SIZE + 1];
45int quoted_idx = 0;
46
Willy Tarreaubaaee002006-06-26 02:48:02 +020047/*
William Lallemande7340ec2012-01-24 11:15:39 +010048 * unsigned long long ASCII representation
49 *
50 * return the last char '\0' or NULL if no enough
51 * space in dst
52 */
53char *ulltoa(unsigned long long n, char *dst, size_t size)
54{
55 int i = 0;
56 char *res;
57
58 switch(n) {
59 case 1ULL ... 9ULL:
60 i = 0;
61 break;
62
63 case 10ULL ... 99ULL:
64 i = 1;
65 break;
66
67 case 100ULL ... 999ULL:
68 i = 2;
69 break;
70
71 case 1000ULL ... 9999ULL:
72 i = 3;
73 break;
74
75 case 10000ULL ... 99999ULL:
76 i = 4;
77 break;
78
79 case 100000ULL ... 999999ULL:
80 i = 5;
81 break;
82
83 case 1000000ULL ... 9999999ULL:
84 i = 6;
85 break;
86
87 case 10000000ULL ... 99999999ULL:
88 i = 7;
89 break;
90
91 case 100000000ULL ... 999999999ULL:
92 i = 8;
93 break;
94
95 case 1000000000ULL ... 9999999999ULL:
96 i = 9;
97 break;
98
99 case 10000000000ULL ... 99999999999ULL:
100 i = 10;
101 break;
102
103 case 100000000000ULL ... 999999999999ULL:
104 i = 11;
105 break;
106
107 case 1000000000000ULL ... 9999999999999ULL:
108 i = 12;
109 break;
110
111 case 10000000000000ULL ... 99999999999999ULL:
112 i = 13;
113 break;
114
115 case 100000000000000ULL ... 999999999999999ULL:
116 i = 14;
117 break;
118
119 case 1000000000000000ULL ... 9999999999999999ULL:
120 i = 15;
121 break;
122
123 case 10000000000000000ULL ... 99999999999999999ULL:
124 i = 16;
125 break;
126
127 case 100000000000000000ULL ... 999999999999999999ULL:
128 i = 17;
129 break;
130
131 case 1000000000000000000ULL ... 9999999999999999999ULL:
132 i = 18;
133 break;
134
135 case 10000000000000000000ULL ... ULLONG_MAX:
136 i = 19;
137 break;
138 }
139 if (i + 2 > size) // (i + 1) + '\0'
140 return NULL; // too long
141 res = dst + i + 1;
142 *res = '\0';
143 for (; i >= 0; i--) {
144 dst[i] = n % 10ULL + '0';
145 n /= 10ULL;
146 }
147 return res;
148}
149
150/*
151 * unsigned long ASCII representation
152 *
153 * return the last char '\0' or NULL if no enough
154 * space in dst
155 */
156char *ultoa_o(unsigned long n, char *dst, size_t size)
157{
158 int i = 0;
159 char *res;
160
161 switch (n) {
162 case 0U ... 9UL:
163 i = 0;
164 break;
165
166 case 10U ... 99UL:
167 i = 1;
168 break;
169
170 case 100U ... 999UL:
171 i = 2;
172 break;
173
174 case 1000U ... 9999UL:
175 i = 3;
176 break;
177
178 case 10000U ... 99999UL:
179 i = 4;
180 break;
181
182 case 100000U ... 999999UL:
183 i = 5;
184 break;
185
186 case 1000000U ... 9999999UL:
187 i = 6;
188 break;
189
190 case 10000000U ... 99999999UL:
191 i = 7;
192 break;
193
194 case 100000000U ... 999999999UL:
195 i = 8;
196 break;
197#if __WORDSIZE == 32
198
199 case 1000000000ULL ... ULONG_MAX:
200 i = 9;
201 break;
202
203#elif __WORDSIZE == 64
204
205 case 1000000000ULL ... 9999999999UL:
206 i = 9;
207 break;
208
209 case 10000000000ULL ... 99999999999UL:
210 i = 10;
211 break;
212
213 case 100000000000ULL ... 999999999999UL:
214 i = 11;
215 break;
216
217 case 1000000000000ULL ... 9999999999999UL:
218 i = 12;
219 break;
220
221 case 10000000000000ULL ... 99999999999999UL:
222 i = 13;
223 break;
224
225 case 100000000000000ULL ... 999999999999999UL:
226 i = 14;
227 break;
228
229 case 1000000000000000ULL ... 9999999999999999UL:
230 i = 15;
231 break;
232
233 case 10000000000000000ULL ... 99999999999999999UL:
234 i = 16;
235 break;
236
237 case 100000000000000000ULL ... 999999999999999999UL:
238 i = 17;
239 break;
240
241 case 1000000000000000000ULL ... 9999999999999999999UL:
242 i = 18;
243 break;
244
245 case 10000000000000000000ULL ... ULONG_MAX:
246 i = 19;
247 break;
248
249#endif
250 }
251 if (i + 2 > size) // (i + 1) + '\0'
252 return NULL; // too long
253 res = dst + i + 1;
254 *res = '\0';
255 for (; i >= 0; i--) {
256 dst[i] = n % 10U + '0';
257 n /= 10U;
258 }
259 return res;
260}
261
262/*
263 * signed long ASCII representation
264 *
265 * return the last char '\0' or NULL if no enough
266 * space in dst
267 */
268char *ltoa_o(long int n, char *dst, size_t size)
269{
270 char *pos = dst;
271
272 if (n < 0) {
273 if (size < 3)
274 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
275 *pos = '-';
276 pos++;
277 dst = ultoa_o(-n, pos, size - 1);
278 } else {
279 dst = ultoa_o(n, dst, size);
280 }
281 return dst;
282}
283
284/*
285 * signed long long ASCII representation
286 *
287 * return the last char '\0' or NULL if no enough
288 * space in dst
289 */
290char *lltoa(long long n, char *dst, size_t size)
291{
292 char *pos = dst;
293
294 if (n < 0) {
295 if (size < 3)
296 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
297 *pos = '-';
298 pos++;
299 dst = ulltoa(-n, pos, size - 1);
300 } else {
301 dst = ulltoa(n, dst, size);
302 }
303 return dst;
304}
305
306/*
307 * write a ascii representation of a unsigned into dst,
308 * return a pointer to the last character
309 * Pad the ascii representation with '0', using size.
310 */
311char *utoa_pad(unsigned int n, char *dst, size_t size)
312{
313 int i = 0;
314 char *ret;
315
316 switch(n) {
317 case 0U ... 9U:
318 i = 0;
319 break;
320
321 case 10U ... 99U:
322 i = 1;
323 break;
324
325 case 100U ... 999U:
326 i = 2;
327 break;
328
329 case 1000U ... 9999U:
330 i = 3;
331 break;
332
333 case 10000U ... 99999U:
334 i = 4;
335 break;
336
337 case 100000U ... 999999U:
338 i = 5;
339 break;
340
341 case 1000000U ... 9999999U:
342 i = 6;
343 break;
344
345 case 10000000U ... 99999999U:
346 i = 7;
347 break;
348
349 case 100000000U ... 999999999U:
350 i = 8;
351 break;
352
353 case 1000000000U ... 4294967295U:
354 i = 9;
355 break;
356 }
357 if (i + 2 > size) // (i + 1) + '\0'
358 return NULL; // too long
359 if (i < size)
360 i = size - 2; // padding - '\0'
361
362 ret = dst + i + 1;
363 *ret = '\0';
364 for (; i >= 0; i--) {
365 dst[i] = n % 10U + '0';
366 n /= 10U;
367 }
368 return ret;
369}
370
371/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200372 * copies at most <size-1> chars from <src> to <dst>. Last char is always
373 * set to 0, unless <size> is 0. The number of chars copied is returned
374 * (excluding the terminating zero).
375 * This code has been optimized for size and speed : on x86, it's 45 bytes
376 * long, uses only registers, and consumes only 4 cycles per char.
377 */
378int strlcpy2(char *dst, const char *src, int size)
379{
380 char *orig = dst;
381 if (size) {
382 while (--size && (*dst = *src)) {
383 src++; dst++;
384 }
385 *dst = 0;
386 }
387 return dst - orig;
388}
389
390/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200391 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200392 * the ascii representation for number 'n' in decimal.
393 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100394char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200395{
396 char *pos;
397
Willy Tarreau72d759c2007-10-25 12:14:10 +0200398 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200399 *pos-- = '\0';
400
401 do {
402 *pos-- = '0' + n % 10;
403 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200404 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200405 return pos + 1;
406}
407
Willy Tarreau91092e52007-10-25 16:58:42 +0200408/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200409 * This function simply returns a locally allocated string containing
410 * the ascii representation for number 'n' in decimal, formatted for
411 * HTML output with tags to create visual grouping by 3 digits. The
412 * output needs to support at least 171 characters.
413 */
414const char *ulltoh_r(unsigned long long n, char *buffer, int size)
415{
416 char *start;
417 int digit = 0;
418
419 start = buffer + size;
420 *--start = '\0';
421
422 do {
423 if (digit == 3 && start >= buffer + 7)
424 memcpy(start -= 7, "</span>", 7);
425
426 if (start >= buffer + 1) {
427 *--start = '0' + n % 10;
428 n /= 10;
429 }
430
431 if (digit == 3 && start >= buffer + 18)
432 memcpy(start -= 18, "<span class=\"rls\">", 18);
433
434 if (digit++ == 3)
435 digit = 1;
436 } while (n && start > buffer);
437 return start;
438}
439
440/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200441 * This function simply returns a locally allocated string containing the ascii
442 * representation for number 'n' in decimal, unless n is 0 in which case it
443 * returns the alternate string (or an empty string if the alternate string is
444 * NULL). It use is intended for limits reported in reports, where it's
445 * desirable not to display anything if there is no limit. Warning! it shares
446 * the same vector as ultoa_r().
447 */
448const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
449{
450 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
451}
452
Willy Tarreau588297f2014-06-16 15:16:40 +0200453/* returns a locally allocated string containing the quoted encoding of the
454 * input string. The output may be truncated to QSTR_SIZE chars, but it is
455 * guaranteed that the string will always be properly terminated. Quotes are
456 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
457 * always be at least 4 chars.
458 */
459const char *qstr(const char *str)
460{
461 char *ret = quoted_str[quoted_idx];
462 char *p, *end;
463
464 if (++quoted_idx >= NB_QSTR)
465 quoted_idx = 0;
466
467 p = ret;
468 end = ret + QSTR_SIZE;
469
470 *p++ = '"';
471
472 /* always keep 3 chars to support passing "" and the ending " */
473 while (*str && p < end - 3) {
474 if (*str == '"') {
475 *p++ = '"';
476 *p++ = '"';
477 }
478 else
479 *p++ = *str;
480 str++;
481 }
482 *p++ = '"';
483 return ret;
484}
485
Robert Tsai81ae1952007-12-05 10:47:29 +0100486/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200487 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
488 *
489 * It looks like this one would be a good candidate for inlining, but this is
490 * not interesting because it around 35 bytes long and often called multiple
491 * times within the same function.
492 */
493int ishex(char s)
494{
495 s -= '0';
496 if ((unsigned char)s <= 9)
497 return 1;
498 s -= 'A' - '0';
499 if ((unsigned char)s <= 5)
500 return 1;
501 s -= 'a' - 'A';
502 if ((unsigned char)s <= 5)
503 return 1;
504 return 0;
505}
506
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100507/*
508 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
509 * invalid character is found, a pointer to it is returned. If everything is
510 * fine, NULL is returned.
511 */
512const char *invalid_char(const char *name)
513{
514 if (!*name)
515 return name;
516
517 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100518 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100519 *name != '_' && *name != '-')
520 return name;
521 name++;
522 }
523 return NULL;
524}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200525
526/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200527 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
528 * If an invalid character is found, a pointer to it is returned.
529 * If everything is fine, NULL is returned.
530 */
531const char *invalid_domainchar(const char *name) {
532
533 if (!*name)
534 return name;
535
536 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100537 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200538 *name != '_' && *name != '-')
539 return name;
540
541 name++;
542 }
543
544 return NULL;
545}
546
547/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100548 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100549 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
550 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
551 * the function tries to guess the address family from the syntax. If the
552 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100553 * string is assumed to contain only an address, no port. The address can be a
554 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
555 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
556 * The return address will only have the address family and the address set,
557 * all other fields remain zero. The string is not supposed to be modified.
558 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200559 */
Willy Tarreau24709282013-03-10 21:32:12 +0100560static struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200561{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100562 struct hostent *he;
563
Willy Tarreaufab5a432011-03-04 15:31:53 +0100564 /* Any IPv6 address */
565 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100566 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
567 sa->ss_family = AF_INET6;
568 else if (sa->ss_family != AF_INET6)
569 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100570 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100571 }
572
Willy Tarreau24709282013-03-10 21:32:12 +0100573 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100574 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100575 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
576 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100577 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100578 }
579
580 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100581 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
582 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100583 sa->ss_family = AF_INET6;
584 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100585 }
586
587 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100588 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
589 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100590 sa->ss_family = AF_INET;
591 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100592 }
593
David du Colombierd5f43282011-03-17 10:40:16 +0100594#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200595 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100596 struct addrinfo hints, *result;
597
598 memset(&result, 0, sizeof(result));
599 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100600 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100601 hints.ai_socktype = SOCK_DGRAM;
602 hints.ai_flags = AI_PASSIVE;
603 hints.ai_protocol = 0;
604
605 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100606 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
607 sa->ss_family = result->ai_family;
608 else if (sa->ss_family != result->ai_family)
609 goto fail;
610
David du Colombierd5f43282011-03-17 10:40:16 +0100611 switch (result->ai_family) {
612 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100613 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
614 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100615 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100616 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
617 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100618 }
619 }
620
Sean Carey58ea0392013-02-15 23:39:18 +0100621 if (result)
622 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100623 }
David du Colombierd5f43282011-03-17 10:40:16 +0100624#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200625 /* try to resolve an IPv4/IPv6 hostname */
626 he = gethostbyname(str);
627 if (he) {
628 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
629 sa->ss_family = he->h_addrtype;
630 else if (sa->ss_family != he->h_addrtype)
631 goto fail;
632
633 switch (sa->ss_family) {
634 case AF_INET:
635 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
636 return sa;
637 case AF_INET6:
638 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
639 return sa;
640 }
641 }
642
David du Colombierd5f43282011-03-17 10:40:16 +0100643 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100644 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100645 return NULL;
646}
647
648/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100649 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
650 * range or offset consisting in two integers that the caller will have to
651 * check to find the relevant input format. The following format are supported :
652 *
653 * String format | address | port | low | high
654 * addr | <addr> | 0 | 0 | 0
655 * addr: | <addr> | 0 | 0 | 0
656 * addr:port | <addr> | <port> | <port> | <port>
657 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
658 * addr:+port | <addr> | <port> | 0 | <port>
659 * addr:-port | <addr> |-<port> | <port> | 0
660 *
661 * The detection of a port range or increment by the caller is made by
662 * comparing <low> and <high>. If both are equal, then port 0 means no port
663 * was specified. The caller may pass NULL for <low> and <high> if it is not
664 * interested in retrieving port ranges.
665 *
666 * Note that <addr> above may also be :
667 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
668 * - "*" => family will be AF_INET and address will be INADDR_ANY
669 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
670 * - a host name => family and address will depend on host name resolving.
671 *
Willy Tarreau24709282013-03-10 21:32:12 +0100672 * A prefix may be passed in before the address above to force the family :
673 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
674 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
675 * - "unix@" => force address to be a path to a UNIX socket even if the
676 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200677 * - 'abns@' -> force address to belong to the abstract namespace (Linux
678 * only). These sockets are just like Unix sockets but without
679 * the need for an underlying file system. The address is a
680 * string. Technically it's like a Unix socket with a zero in
681 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100682 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100683 *
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100684 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
685 * is mandatory after the IP address even when no port is specified. NULL is
686 * returned if the address cannot be parsed. The <low> and <high> ports are
Willy Tarreau24709282013-03-10 21:32:12 +0100687 * always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100688 *
689 * If <pfx> is non-null, it is used as a string prefix before any path-based
690 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100691 *
692 * When a file descriptor is passed, its value is put into the s_addr part of
693 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100694 */
Willy Tarreaud393a622013-03-04 18:22:00 +0100695struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100696{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100697 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100698 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100699 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100700 char *port1, *port2;
701 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200702 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100703
704 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200705
Willy Tarreaudad36a32013-03-11 01:20:04 +0100706 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100707 if (str2 == NULL) {
708 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100709 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100710 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200711
Willy Tarreau36456072015-09-08 16:01:25 +0200712 if (!*str2) {
713 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
714 goto out;
715 }
716
Willy Tarreau24709282013-03-10 21:32:12 +0100717 memset(&ss, 0, sizeof(ss));
718
719 if (strncmp(str2, "unix@", 5) == 0) {
720 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200721 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100722 ss.ss_family = AF_UNIX;
723 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200724 else if (strncmp(str2, "abns@", 5) == 0) {
725 str2 += 5;
726 abstract = 1;
727 ss.ss_family = AF_UNIX;
728 }
Willy Tarreau24709282013-03-10 21:32:12 +0100729 else if (strncmp(str2, "ipv4@", 5) == 0) {
730 str2 += 5;
731 ss.ss_family = AF_INET;
732 }
733 else if (strncmp(str2, "ipv6@", 5) == 0) {
734 str2 += 5;
735 ss.ss_family = AF_INET6;
736 }
737 else if (*str2 == '/') {
738 ss.ss_family = AF_UNIX;
739 }
740 else
741 ss.ss_family = AF_UNSPEC;
742
Willy Tarreau40aa0702013-03-10 23:51:38 +0100743 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
744 char *endptr;
745
746 str2 += 3;
747 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
748
749 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100750 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100751 goto out;
752 }
753
754 /* we return AF_UNSPEC if we use a file descriptor number */
755 ss.ss_family = AF_UNSPEC;
756 }
757 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100758 int prefix_path_len;
759 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200760 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100761
762 /* complete unix socket path name during startup or soft-restart is
763 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
764 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200765 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100766 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
767 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
768
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200769 adr_len = strlen(str2);
770 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100771 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
772 goto out;
773 }
774
Willy Tarreauccfccef2014-05-10 01:49:15 +0200775 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
776 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200777 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100778 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200779 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100780 }
Willy Tarreau24709282013-03-10 21:32:12 +0100781 else { /* IPv4 and IPv6 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100782 port1 = strrchr(str2, ':');
783 if (port1)
784 *port1++ = '\0';
785 else
786 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200787
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100788 if (str2ip(str2, &ss) == NULL) {
789 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
790 goto out;
791 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100792
Willy Tarreaua39d1992013-04-01 20:37:42 +0200793 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100794 port2 = strchr(port1, '-');
795 if (port2)
796 *port2++ = '\0';
797 else
798 port2 = port1;
799 portl = atoi(port1);
800 porth = atoi(port2);
801 porta = portl;
802 }
803 else if (*port1 == '-') { /* negative offset */
804 portl = atoi(port1 + 1);
805 porta = -portl;
806 }
807 else if (*port1 == '+') { /* positive offset */
808 porth = atoi(port1 + 1);
809 porta = porth;
810 }
811 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100812 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100813 goto out;
814 }
815 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100816 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100817
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100818 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100819 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100820 if (low)
821 *low = portl;
822 if (high)
823 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100824 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100825 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200826}
827
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100828/* converts <str> to a struct in_addr containing a network mask. It can be
829 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
830 * if the conversion succeeds otherwise non-zero.
831 */
832int str2mask(const char *str, struct in_addr *mask)
833{
834 if (strchr(str, '.') != NULL) { /* dotted notation */
835 if (!inet_pton(AF_INET, str, mask))
836 return 0;
837 }
838 else { /* mask length */
839 char *err;
840 unsigned long len = strtol(str, &err, 10);
841
842 if (!*str || (err && *err) || (unsigned)len > 32)
843 return 0;
844 if (len)
845 mask->s_addr = htonl(~0UL << (32 - len));
846 else
847 mask->s_addr = 0;
848 }
849 return 1;
850}
851
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100852/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
853 * succeeds otherwise zero.
854 */
855int cidr2dotted(int cidr, struct in_addr *mask) {
856
857 if (cidr < 0 || cidr > 32)
858 return 0;
859
860 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
861 return 1;
862}
863
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200864/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200865 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200866 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
867 * is optionnal and either in the dotted or CIDR notation.
868 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
869 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100870int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200871{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200872 __label__ out_free, out_err;
873 char *c, *s;
874 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200875
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200876 s = strdup(str);
877 if (!s)
878 return 0;
879
Willy Tarreaubaaee002006-06-26 02:48:02 +0200880 memset(mask, 0, sizeof(*mask));
881 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200882
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200883 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200884 *c++ = '\0';
885 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100886 if (!str2mask(c, mask))
887 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200888 }
889 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100890 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200891 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200892 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200893 struct hostent *he;
894
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100895 if (!resolve)
896 goto out_err;
897
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200898 if ((he = gethostbyname(s)) == NULL) {
899 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200900 }
901 else
902 *addr = *(struct in_addr *) *(he->h_addr_list);
903 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200904
905 ret_val = 1;
906 out_free:
907 free(s);
908 return ret_val;
909 out_err:
910 ret_val = 0;
911 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200912}
913
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100914
915/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200916 * converts <str> to two struct in6_addr* which must be pre-allocated.
917 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
918 * is an optionnal number of bits (128 being the default).
919 * Returns 1 if OK, 0 if error.
920 */
921int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
922{
923 char *c, *s;
924 int ret_val = 0;
925 char *err;
926 unsigned long len = 128;
927
928 s = strdup(str);
929 if (!s)
930 return 0;
931
932 memset(mask, 0, sizeof(*mask));
933 memset(addr, 0, sizeof(*addr));
934
935 if ((c = strrchr(s, '/')) != NULL) {
936 *c++ = '\0'; /* c points to the mask */
937 if (!*c)
938 goto out_free;
939
940 len = strtoul(c, &err, 10);
941 if ((err && *err) || (unsigned)len > 128)
942 goto out_free;
943 }
944 *mask = len; /* OK we have a valid mask in <len> */
945
946 if (!inet_pton(AF_INET6, s, addr))
947 goto out_free;
948
949 ret_val = 1;
950 out_free:
951 free(s);
952 return ret_val;
953}
954
955
956/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100957 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100958 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100959int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100960{
961 int saw_digit, octets, ch;
962 u_char tmp[4], *tp;
963 const char *cp = addr;
964
965 saw_digit = 0;
966 octets = 0;
967 *(tp = tmp) = 0;
968
969 while (*addr) {
970 unsigned char digit = (ch = *addr++) - '0';
971 if (digit > 9 && ch != '.')
972 break;
973 if (digit <= 9) {
974 u_int new = *tp * 10 + digit;
975 if (new > 255)
976 return 0;
977 *tp = new;
978 if (!saw_digit) {
979 if (++octets > 4)
980 return 0;
981 saw_digit = 1;
982 }
983 } else if (ch == '.' && saw_digit) {
984 if (octets == 4)
985 return 0;
986 *++tp = 0;
987 saw_digit = 0;
988 } else
989 return 0;
990 }
991
992 if (octets < 4)
993 return 0;
994
995 memcpy(&dst->s_addr, tmp, 4);
996 return addr-cp-1;
997}
998
999/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001000 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
1001 * <out> contain the code of the dectected scheme, the start and length of
1002 * the hostname. Actually only http and https are supported. <out> can be NULL.
1003 * This function returns the consumed length. It is useful if you parse complete
1004 * url like http://host:port/path, because the consumed length corresponds to
1005 * the first character of the path. If the conversion fails, it returns -1.
1006 *
1007 * This function tries to resolve the DNS name if haproxy is in starting mode.
1008 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001009 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001010int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001011{
1012 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001013 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001014 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001015 unsigned long long int http_code = 0;
1016 int default_port;
1017 struct hostent *he;
1018 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001019
1020 /* Firstly, try to find :// pattern */
1021 while (curr < url+ulen && url_code != 0x3a2f2f) {
1022 url_code = ((url_code & 0xffff) << 8);
1023 url_code += (unsigned char)*curr++;
1024 }
1025
1026 /* Secondly, if :// pattern is found, verify parsed stuff
1027 * before pattern is matching our http pattern.
1028 * If so parse ip address and port in uri.
1029 *
1030 * WARNING: Current code doesn't support dynamic async dns resolver.
1031 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001032 if (url_code != 0x3a2f2f)
1033 return -1;
1034
1035 /* Copy scheme, and utrn to lower case. */
1036 while (cp < curr - 3)
1037 http_code = (http_code << 8) + *cp++;
1038 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001039
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001040 /* HTTP or HTTPS url matching */
1041 if (http_code == 0x2020202068747470ULL) {
1042 default_port = 80;
1043 if (out)
1044 out->scheme = SCH_HTTP;
1045 }
1046 else if (http_code == 0x2020206874747073ULL) {
1047 default_port = 443;
1048 if (out)
1049 out->scheme = SCH_HTTPS;
1050 }
1051 else
1052 return -1;
1053
1054 /* If the next char is '[', the host address is IPv6. */
1055 if (*curr == '[') {
1056 curr++;
1057
1058 /* Check trash size */
1059 if (trash.size < ulen)
1060 return -1;
1061
1062 /* Look for ']' and copy the address in a trash buffer. */
1063 p = trash.str;
1064 for (end = curr;
1065 end < url + ulen && *end != ']';
1066 end++, p++)
1067 *p = *end;
1068 if (*end != ']')
1069 return -1;
1070 *p = '\0';
1071
1072 /* Update out. */
1073 if (out) {
1074 out->host = curr;
1075 out->host_len = end - curr;
1076 }
1077
1078 /* Try IPv6 decoding. */
1079 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1080 return -1;
1081 end++;
1082
1083 /* Decode port. */
1084 if (*end == ':') {
1085 end++;
1086 default_port = read_uint(&end, url + ulen);
1087 }
1088 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1089 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1090 return end - url;
1091 }
1092 else {
1093 /* We are looking for IP address. If you want to parse and
1094 * resolve hostname found in url, you can use str2sa_range(), but
1095 * be warned this can slow down global daemon performances
1096 * while handling lagging dns responses.
1097 */
1098 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1099 if (ret) {
1100 /* Update out. */
1101 if (out) {
1102 out->host = curr;
1103 out->host_len = ret;
1104 }
1105
1106 curr += ret;
1107
1108 /* Decode port. */
1109 if (*curr == ':') {
1110 curr++;
1111 default_port = read_uint(&curr, url + ulen);
1112 }
1113 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1114
1115 /* Set family. */
1116 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1117 return curr - url;
1118 }
1119 else if (global.mode & MODE_STARTING) {
1120 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1121 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001122 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001123
1124 /* look for : or / or end */
1125 for (end = curr;
1126 end < url + ulen && *end != '/' && *end != ':';
1127 end++);
1128 memcpy(trash.str, curr, end - curr);
1129 trash.str[end - curr] = '\0';
1130
1131 /* try to resolve an IPv4/IPv6 hostname */
1132 he = gethostbyname(trash.str);
1133 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001134 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001135
1136 /* Update out. */
1137 if (out) {
1138 out->host = curr;
1139 out->host_len = end - curr;
1140 }
1141
1142 /* Decode port. */
1143 if (*end == ':') {
1144 end++;
1145 default_port = read_uint(&end, url + ulen);
1146 }
1147
1148 /* Copy IP address, set port and family. */
1149 switch (he->h_addrtype) {
1150 case AF_INET:
1151 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1152 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1153 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1154 return end - url;
1155
1156 case AF_INET6:
1157 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1158 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1159 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1160 return end - url;
1161 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001162 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001163 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001164 return -1;
1165}
1166
Willy Tarreau631f01c2011-09-05 00:36:48 +02001167/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1168 * address family is returned so that it's easy for the caller to adapt to the
1169 * output format. Zero is returned if the address family is not supported. -1
1170 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1171 * supported.
1172 */
1173int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1174{
1175
1176 void *ptr;
1177
1178 if (size < 5)
1179 return 0;
1180 *str = '\0';
1181
1182 switch (addr->ss_family) {
1183 case AF_INET:
1184 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1185 break;
1186 case AF_INET6:
1187 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1188 break;
1189 case AF_UNIX:
1190 memcpy(str, "unix", 5);
1191 return addr->ss_family;
1192 default:
1193 return 0;
1194 }
1195
1196 if (inet_ntop(addr->ss_family, ptr, str, size))
1197 return addr->ss_family;
1198
1199 /* failed */
1200 return -1;
1201}
1202
Simon Horman75ab8bd2014-06-16 09:39:41 +09001203/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1204 * address family is returned so that it's easy for the caller to adapt to the
1205 * output format. Zero is returned if the address family is not supported. -1
1206 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1207 * supported.
1208 */
1209int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1210{
1211
1212 uint16_t port;
1213
1214
1215 if (size < 5)
1216 return 0;
1217 *str = '\0';
1218
1219 switch (addr->ss_family) {
1220 case AF_INET:
1221 port = ((struct sockaddr_in *)addr)->sin_port;
1222 break;
1223 case AF_INET6:
1224 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1225 break;
1226 case AF_UNIX:
1227 memcpy(str, "unix", 5);
1228 return addr->ss_family;
1229 default:
1230 return 0;
1231 }
1232
1233 snprintf(str, size, "%u", ntohs(port));
1234 return addr->ss_family;
1235}
1236
Willy Tarreaubaaee002006-06-26 02:48:02 +02001237/* will try to encode the string <string> replacing all characters tagged in
1238 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1239 * prefixed by <escape>, and will store the result between <start> (included)
1240 * and <stop> (excluded), and will always terminate the string with a '\0'
1241 * before <stop>. The position of the '\0' is returned if the conversion
1242 * completes. If bytes are missing between <start> and <stop>, then the
1243 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1244 * cannot even be stored so we return <start> without writing the 0.
1245 * The input string must also be zero-terminated.
1246 */
1247const char hextab[16] = "0123456789ABCDEF";
1248char *encode_string(char *start, char *stop,
1249 const char escape, const fd_set *map,
1250 const char *string)
1251{
1252 if (start < stop) {
1253 stop--; /* reserve one byte for the final '\0' */
1254 while (start < stop && *string != '\0') {
1255 if (!FD_ISSET((unsigned char)(*string), map))
1256 *start++ = *string;
1257 else {
1258 if (start + 3 >= stop)
1259 break;
1260 *start++ = escape;
1261 *start++ = hextab[(*string >> 4) & 15];
1262 *start++ = hextab[*string & 15];
1263 }
1264 string++;
1265 }
1266 *start = '\0';
1267 }
1268 return start;
1269}
1270
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001271/*
1272 * Same behavior as encode_string() above, except that it encodes chunk
1273 * <chunk> instead of a string.
1274 */
1275char *encode_chunk(char *start, char *stop,
1276 const char escape, const fd_set *map,
1277 const struct chunk *chunk)
1278{
1279 char *str = chunk->str;
1280 char *end = chunk->str + chunk->len;
1281
1282 if (start < stop) {
1283 stop--; /* reserve one byte for the final '\0' */
1284 while (start < stop && str < end) {
1285 if (!FD_ISSET((unsigned char)(*str), map))
1286 *start++ = *str;
1287 else {
1288 if (start + 3 >= stop)
1289 break;
1290 *start++ = escape;
1291 *start++ = hextab[(*str >> 4) & 15];
1292 *start++ = hextab[*str & 15];
1293 }
1294 str++;
1295 }
1296 *start = '\0';
1297 }
1298 return start;
1299}
1300
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001301/* Decode an URL-encoded string in-place. The resulting string might
1302 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001303 * aborted, the string is truncated before the issue and a negative value is
1304 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001305 */
1306int url_decode(char *string)
1307{
1308 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001309 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001310
1311 in = string;
1312 out = string;
1313 while (*in) {
1314 switch (*in) {
1315 case '+' :
1316 *out++ = ' ';
1317 break;
1318 case '%' :
1319 if (!ishex(in[1]) || !ishex(in[2]))
1320 goto end;
1321 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1322 in += 2;
1323 break;
1324 default:
1325 *out++ = *in;
1326 break;
1327 }
1328 in++;
1329 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001330 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001331 end:
1332 *out = 0;
1333 return ret;
1334}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001335
Willy Tarreau6911fa42007-03-04 18:06:08 +01001336unsigned int str2ui(const char *s)
1337{
1338 return __str2ui(s);
1339}
1340
1341unsigned int str2uic(const char *s)
1342{
1343 return __str2uic(s);
1344}
1345
1346unsigned int strl2ui(const char *s, int len)
1347{
1348 return __strl2ui(s, len);
1349}
1350
1351unsigned int strl2uic(const char *s, int len)
1352{
1353 return __strl2uic(s, len);
1354}
1355
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001356unsigned int read_uint(const char **s, const char *end)
1357{
1358 return __read_uint(s, end);
1359}
1360
Willy Tarreau6911fa42007-03-04 18:06:08 +01001361/* This one is 7 times faster than strtol() on athlon with checks.
1362 * It returns the value of the number composed of all valid digits read,
1363 * and can process negative numbers too.
1364 */
1365int strl2ic(const char *s, int len)
1366{
1367 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001368 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001369
1370 if (len > 0) {
1371 if (*s != '-') {
1372 /* positive number */
1373 while (len-- > 0) {
1374 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001375 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001376 if (j > 9)
1377 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001378 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001379 }
1380 } else {
1381 /* negative number */
1382 s++;
1383 while (--len > 0) {
1384 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001385 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001386 if (j > 9)
1387 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001388 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001389 }
1390 }
1391 }
1392 return i;
1393}
1394
1395
1396/* This function reads exactly <len> chars from <s> and converts them to a
1397 * signed integer which it stores into <ret>. It accurately detects any error
1398 * (truncated string, invalid chars, overflows). It is meant to be used in
1399 * applications designed for hostile environments. It returns zero when the
1400 * number has successfully been converted, non-zero otherwise. When an error
1401 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1402 * faster than strtol().
1403 */
1404int strl2irc(const char *s, int len, int *ret)
1405{
1406 int i = 0;
1407 int j;
1408
1409 if (!len)
1410 return 1;
1411
1412 if (*s != '-') {
1413 /* positive number */
1414 while (len-- > 0) {
1415 j = (*s++) - '0';
1416 if (j > 9) return 1; /* invalid char */
1417 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1418 i = i * 10;
1419 if (i + j < i) return 1; /* check for addition overflow */
1420 i = i + j;
1421 }
1422 } else {
1423 /* negative number */
1424 s++;
1425 while (--len > 0) {
1426 j = (*s++) - '0';
1427 if (j > 9) return 1; /* invalid char */
1428 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1429 i = i * 10;
1430 if (i - j > i) return 1; /* check for subtract overflow */
1431 i = i - j;
1432 }
1433 }
1434 *ret = i;
1435 return 0;
1436}
1437
1438
1439/* This function reads exactly <len> chars from <s> and converts them to a
1440 * signed integer which it stores into <ret>. It accurately detects any error
1441 * (truncated string, invalid chars, overflows). It is meant to be used in
1442 * applications designed for hostile environments. It returns zero when the
1443 * number has successfully been converted, non-zero otherwise. When an error
1444 * is returned, the <ret> value is left untouched. It is about 3 times slower
1445 * than str2irc().
1446 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001447
1448int strl2llrc(const char *s, int len, long long *ret)
1449{
1450 long long i = 0;
1451 int j;
1452
1453 if (!len)
1454 return 1;
1455
1456 if (*s != '-') {
1457 /* positive number */
1458 while (len-- > 0) {
1459 j = (*s++) - '0';
1460 if (j > 9) return 1; /* invalid char */
1461 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1462 i = i * 10LL;
1463 if (i + j < i) return 1; /* check for addition overflow */
1464 i = i + j;
1465 }
1466 } else {
1467 /* negative number */
1468 s++;
1469 while (--len > 0) {
1470 j = (*s++) - '0';
1471 if (j > 9) return 1; /* invalid char */
1472 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1473 i = i * 10LL;
1474 if (i - j > i) return 1; /* check for subtract overflow */
1475 i = i - j;
1476 }
1477 }
1478 *ret = i;
1479 return 0;
1480}
1481
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001482/* This function is used with pat_parse_dotted_ver(). It converts a string
1483 * composed by two number separated by a dot. Each part must contain in 16 bits
1484 * because internally they will be represented as a 32-bit quantity stored in
1485 * a 64-bit integer. It returns zero when the number has successfully been
1486 * converted, non-zero otherwise. When an error is returned, the <ret> value
1487 * is left untouched.
1488 *
1489 * "1.3" -> 0x0000000000010003
1490 * "65535.65535" -> 0x00000000ffffffff
1491 */
1492int strl2llrc_dotted(const char *text, int len, long long *ret)
1493{
1494 const char *end = &text[len];
1495 const char *p;
1496 long long major, minor;
1497
1498 /* Look for dot. */
1499 for (p = text; p < end; p++)
1500 if (*p == '.')
1501 break;
1502
1503 /* Convert major. */
1504 if (strl2llrc(text, p - text, &major) != 0)
1505 return 1;
1506
1507 /* Check major. */
1508 if (major >= 65536)
1509 return 1;
1510
1511 /* Convert minor. */
1512 minor = 0;
1513 if (p < end)
1514 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1515 return 1;
1516
1517 /* Check minor. */
1518 if (minor >= 65536)
1519 return 1;
1520
1521 /* Compose value. */
1522 *ret = (major << 16) | (minor & 0xffff);
1523 return 0;
1524}
1525
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001526/* This function parses a time value optionally followed by a unit suffix among
1527 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1528 * expected by the caller. The computation does its best to avoid overflows.
1529 * The value is returned in <ret> if everything is fine, and a NULL is returned
1530 * by the function. In case of error, a pointer to the error is returned and
1531 * <ret> is left untouched. Values are automatically rounded up when needed.
1532 */
1533const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1534{
1535 unsigned imult, idiv;
1536 unsigned omult, odiv;
1537 unsigned value;
1538
1539 omult = odiv = 1;
1540
1541 switch (unit_flags & TIME_UNIT_MASK) {
1542 case TIME_UNIT_US: omult = 1000000; break;
1543 case TIME_UNIT_MS: omult = 1000; break;
1544 case TIME_UNIT_S: break;
1545 case TIME_UNIT_MIN: odiv = 60; break;
1546 case TIME_UNIT_HOUR: odiv = 3600; break;
1547 case TIME_UNIT_DAY: odiv = 86400; break;
1548 default: break;
1549 }
1550
1551 value = 0;
1552
1553 while (1) {
1554 unsigned int j;
1555
1556 j = *text - '0';
1557 if (j > 9)
1558 break;
1559 text++;
1560 value *= 10;
1561 value += j;
1562 }
1563
1564 imult = idiv = 1;
1565 switch (*text) {
1566 case '\0': /* no unit = default unit */
1567 imult = omult = idiv = odiv = 1;
1568 break;
1569 case 's': /* second = unscaled unit */
1570 break;
1571 case 'u': /* microsecond : "us" */
1572 if (text[1] == 's') {
1573 idiv = 1000000;
1574 text++;
1575 }
1576 break;
1577 case 'm': /* millisecond : "ms" or minute: "m" */
1578 if (text[1] == 's') {
1579 idiv = 1000;
1580 text++;
1581 } else
1582 imult = 60;
1583 break;
1584 case 'h': /* hour : "h" */
1585 imult = 3600;
1586 break;
1587 case 'd': /* day : "d" */
1588 imult = 86400;
1589 break;
1590 default:
1591 return text;
1592 break;
1593 }
1594
1595 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1596 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1597 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1598 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1599
1600 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1601 *ret = value;
1602 return NULL;
1603}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001604
Emeric Brun39132b22010-01-04 14:57:24 +01001605/* this function converts the string starting at <text> to an unsigned int
1606 * stored in <ret>. If an error is detected, the pointer to the unexpected
1607 * character is returned. If the conversio is succesful, NULL is returned.
1608 */
1609const char *parse_size_err(const char *text, unsigned *ret) {
1610 unsigned value = 0;
1611
1612 while (1) {
1613 unsigned int j;
1614
1615 j = *text - '0';
1616 if (j > 9)
1617 break;
1618 if (value > ~0U / 10)
1619 return text;
1620 value *= 10;
1621 if (value > (value + j))
1622 return text;
1623 value += j;
1624 text++;
1625 }
1626
1627 switch (*text) {
1628 case '\0':
1629 break;
1630 case 'K':
1631 case 'k':
1632 if (value > ~0U >> 10)
1633 return text;
1634 value = value << 10;
1635 break;
1636 case 'M':
1637 case 'm':
1638 if (value > ~0U >> 20)
1639 return text;
1640 value = value << 20;
1641 break;
1642 case 'G':
1643 case 'g':
1644 if (value > ~0U >> 30)
1645 return text;
1646 value = value << 30;
1647 break;
1648 default:
1649 return text;
1650 }
1651
1652 *ret = value;
1653 return NULL;
1654}
1655
Willy Tarreau126d4062013-12-03 17:50:47 +01001656/*
1657 * Parse binary string written in hexadecimal (source) and store the decoded
1658 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1659 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001660 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001661 */
1662int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1663{
1664 int len;
1665 const char *p = source;
1666 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001667 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001668
1669 len = strlen(source);
1670 if (len % 2) {
1671 memprintf(err, "an even number of hex digit is expected");
1672 return 0;
1673 }
1674
1675 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001676
Willy Tarreau126d4062013-12-03 17:50:47 +01001677 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001678 *binstr = calloc(len, sizeof(char));
1679 if (!*binstr) {
1680 memprintf(err, "out of memory while loading string pattern");
1681 return 0;
1682 }
1683 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001684 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001685 else {
1686 if (*binstrlen < len) {
1687 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1688 len, *binstrlen);
1689 return 0;
1690 }
1691 alloc = 0;
1692 }
1693 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001694
1695 i = j = 0;
1696 while (j < len) {
1697 if (!ishex(p[i++]))
1698 goto bad_input;
1699 if (!ishex(p[i++]))
1700 goto bad_input;
1701 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1702 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001703 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001704
1705bad_input:
1706 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich171d9a52016-03-03 20:40:37 +01001707 if (alloc) {
1708 free(*binstr);
1709 *binstr = NULL;
1710 }
Willy Tarreau126d4062013-12-03 17:50:47 +01001711 return 0;
1712}
1713
Willy Tarreau946ba592009-05-10 15:41:18 +02001714/* copies at most <n> characters from <src> and always terminates with '\0' */
1715char *my_strndup(const char *src, int n)
1716{
1717 int len = 0;
1718 char *ret;
1719
1720 while (len < n && src[len])
1721 len++;
1722
1723 ret = (char *)malloc(len + 1);
1724 if (!ret)
1725 return ret;
1726 memcpy(ret, src, len);
1727 ret[len] = '\0';
1728 return ret;
1729}
1730
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001731/*
1732 * search needle in haystack
1733 * returns the pointer if found, returns NULL otherwise
1734 */
1735const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1736{
1737 const void *c = NULL;
1738 unsigned char f;
1739
1740 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1741 return NULL;
1742
1743 f = *(char *)needle;
1744 c = haystack;
1745 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1746 if ((haystacklen - (c - haystack)) < needlelen)
1747 return NULL;
1748
1749 if (memcmp(c, needle, needlelen) == 0)
1750 return c;
1751 ++c;
1752 }
1753 return NULL;
1754}
1755
Willy Tarreau482b00d2009-10-04 22:48:42 +02001756/* This function returns the first unused key greater than or equal to <key> in
1757 * ID tree <root>. Zero is returned if no place is found.
1758 */
1759unsigned int get_next_id(struct eb_root *root, unsigned int key)
1760{
1761 struct eb32_node *used;
1762
1763 do {
1764 used = eb32_lookup_ge(root, key);
1765 if (!used || used->key > key)
1766 return key; /* key is available */
1767 key++;
1768 } while (key);
1769 return key;
1770}
1771
Willy Tarreau348238b2010-01-18 15:05:57 +01001772/* This function compares a sample word possibly followed by blanks to another
1773 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1774 * otherwise zero. This intends to be used when checking HTTP headers for some
1775 * values. Note that it validates a word followed only by blanks but does not
1776 * validate a word followed by blanks then other chars.
1777 */
1778int word_match(const char *sample, int slen, const char *word, int wlen)
1779{
1780 if (slen < wlen)
1781 return 0;
1782
1783 while (wlen) {
1784 char c = *sample ^ *word;
1785 if (c && c != ('A' ^ 'a'))
1786 return 0;
1787 sample++;
1788 word++;
1789 slen--;
1790 wlen--;
1791 }
1792
1793 while (slen) {
1794 if (*sample != ' ' && *sample != '\t')
1795 return 0;
1796 sample++;
1797 slen--;
1798 }
1799 return 1;
1800}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001801
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001802/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1803 * is particularly fast because it avoids expensive operations such as
1804 * multiplies, which are optimized away at the end. It requires a properly
1805 * formated address though (3 points).
1806 */
1807unsigned int inetaddr_host(const char *text)
1808{
1809 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1810 register unsigned int dig100, dig10, dig1;
1811 int s;
1812 const char *p, *d;
1813
1814 dig1 = dig10 = dig100 = ascii_zero;
1815 s = 24;
1816
1817 p = text;
1818 while (1) {
1819 if (((unsigned)(*p - '0')) <= 9) {
1820 p++;
1821 continue;
1822 }
1823
1824 /* here, we have a complete byte between <text> and <p> (exclusive) */
1825 if (p == text)
1826 goto end;
1827
1828 d = p - 1;
1829 dig1 |= (unsigned int)(*d << s);
1830 if (d == text)
1831 goto end;
1832
1833 d--;
1834 dig10 |= (unsigned int)(*d << s);
1835 if (d == text)
1836 goto end;
1837
1838 d--;
1839 dig100 |= (unsigned int)(*d << s);
1840 end:
1841 if (!s || *p != '.')
1842 break;
1843
1844 s -= 8;
1845 text = ++p;
1846 }
1847
1848 dig100 -= ascii_zero;
1849 dig10 -= ascii_zero;
1850 dig1 -= ascii_zero;
1851 return ((dig100 * 10) + dig10) * 10 + dig1;
1852}
1853
1854/*
1855 * Idem except the first unparsed character has to be passed in <stop>.
1856 */
1857unsigned int inetaddr_host_lim(const char *text, const char *stop)
1858{
1859 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1860 register unsigned int dig100, dig10, dig1;
1861 int s;
1862 const char *p, *d;
1863
1864 dig1 = dig10 = dig100 = ascii_zero;
1865 s = 24;
1866
1867 p = text;
1868 while (1) {
1869 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1870 p++;
1871 continue;
1872 }
1873
1874 /* here, we have a complete byte between <text> and <p> (exclusive) */
1875 if (p == text)
1876 goto end;
1877
1878 d = p - 1;
1879 dig1 |= (unsigned int)(*d << s);
1880 if (d == text)
1881 goto end;
1882
1883 d--;
1884 dig10 |= (unsigned int)(*d << s);
1885 if (d == text)
1886 goto end;
1887
1888 d--;
1889 dig100 |= (unsigned int)(*d << s);
1890 end:
1891 if (!s || p == stop || *p != '.')
1892 break;
1893
1894 s -= 8;
1895 text = ++p;
1896 }
1897
1898 dig100 -= ascii_zero;
1899 dig10 -= ascii_zero;
1900 dig1 -= ascii_zero;
1901 return ((dig100 * 10) + dig10) * 10 + dig1;
1902}
1903
1904/*
1905 * Idem except the pointer to first unparsed byte is returned into <ret> which
1906 * must not be NULL.
1907 */
Willy Tarreau74172752010-10-15 23:21:42 +02001908unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001909{
1910 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1911 register unsigned int dig100, dig10, dig1;
1912 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001913 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001914
1915 dig1 = dig10 = dig100 = ascii_zero;
1916 s = 24;
1917
1918 p = text;
1919 while (1) {
1920 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1921 p++;
1922 continue;
1923 }
1924
1925 /* here, we have a complete byte between <text> and <p> (exclusive) */
1926 if (p == text)
1927 goto end;
1928
1929 d = p - 1;
1930 dig1 |= (unsigned int)(*d << s);
1931 if (d == text)
1932 goto end;
1933
1934 d--;
1935 dig10 |= (unsigned int)(*d << s);
1936 if (d == text)
1937 goto end;
1938
1939 d--;
1940 dig100 |= (unsigned int)(*d << s);
1941 end:
1942 if (!s || p == stop || *p != '.')
1943 break;
1944
1945 s -= 8;
1946 text = ++p;
1947 }
1948
1949 *ret = p;
1950 dig100 -= ascii_zero;
1951 dig10 -= ascii_zero;
1952 dig1 -= ascii_zero;
1953 return ((dig100 * 10) + dig10) * 10 + dig1;
1954}
1955
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001956/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1957 * or the number of chars read in case of success. Maybe this could be replaced
1958 * by one of the functions above. Also, apparently this function does not support
1959 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001960 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001961 */
1962int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1963{
1964 const char *addr;
1965 int saw_digit, octets, ch;
1966 u_char tmp[4], *tp;
1967 const char *cp = buf;
1968
1969 saw_digit = 0;
1970 octets = 0;
1971 *(tp = tmp) = 0;
1972
1973 for (addr = buf; addr - buf < len; addr++) {
1974 unsigned char digit = (ch = *addr) - '0';
1975
1976 if (digit > 9 && ch != '.')
1977 break;
1978
1979 if (digit <= 9) {
1980 u_int new = *tp * 10 + digit;
1981
1982 if (new > 255)
1983 return 0;
1984
1985 *tp = new;
1986
1987 if (!saw_digit) {
1988 if (++octets > 4)
1989 return 0;
1990 saw_digit = 1;
1991 }
1992 } else if (ch == '.' && saw_digit) {
1993 if (octets == 4)
1994 return 0;
1995
1996 *++tp = 0;
1997 saw_digit = 0;
1998 } else
1999 return 0;
2000 }
2001
2002 if (octets < 4)
2003 return 0;
2004
2005 memcpy(&dst->s_addr, tmp, 4);
2006 return addr - cp;
2007}
2008
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002009/* This function converts the string in <buf> of the len <len> to
2010 * struct in6_addr <dst> which must be allocated by the caller.
2011 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002012 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002013 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002014int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2015{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002016 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002017 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002018
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002019 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002020 return 0;
2021
2022 memcpy(null_term_ip6, buf, len);
2023 null_term_ip6[len] = '\0';
2024
Willy Tarreau075415a2013-12-12 11:29:39 +01002025 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002026 return 0;
2027
Willy Tarreau075415a2013-12-12 11:29:39 +01002028 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002029 return 1;
2030}
2031
Willy Tarreauacf95772010-06-14 19:09:21 +02002032/* To be used to quote config arg positions. Returns the short string at <ptr>
2033 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2034 * if ptr is NULL or empty. The string is locally allocated.
2035 */
2036const char *quote_arg(const char *ptr)
2037{
2038 static char val[32];
2039 int i;
2040
2041 if (!ptr || !*ptr)
2042 return "end of line";
2043 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002044 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002045 val[i] = *ptr++;
2046 val[i++] = '\'';
2047 val[i] = '\0';
2048 return val;
2049}
2050
Willy Tarreau5b180202010-07-18 10:40:48 +02002051/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2052int get_std_op(const char *str)
2053{
2054 int ret = -1;
2055
2056 if (*str == 'e' && str[1] == 'q')
2057 ret = STD_OP_EQ;
2058 else if (*str == 'n' && str[1] == 'e')
2059 ret = STD_OP_NE;
2060 else if (*str == 'l') {
2061 if (str[1] == 'e') ret = STD_OP_LE;
2062 else if (str[1] == 't') ret = STD_OP_LT;
2063 }
2064 else if (*str == 'g') {
2065 if (str[1] == 'e') ret = STD_OP_GE;
2066 else if (str[1] == 't') ret = STD_OP_GT;
2067 }
2068
2069 if (ret == -1 || str[2] != '\0')
2070 return -1;
2071 return ret;
2072}
2073
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002074/* hash a 32-bit integer to another 32-bit integer */
2075unsigned int full_hash(unsigned int a)
2076{
2077 return __full_hash(a);
2078}
2079
David du Colombier4f92d322011-03-24 11:09:31 +01002080/* Return non-zero if IPv4 address is part of the network,
2081 * otherwise zero.
2082 */
2083int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
2084{
2085 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
2086}
2087
2088/* Return non-zero if IPv6 address is part of the network,
2089 * otherwise zero.
2090 */
2091int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
2092{
2093 int i;
2094
2095 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2096 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2097 (((int *)net)[i] & ((int *)mask)[i]))
2098 return 0;
2099 return 1;
2100}
2101
2102/* RFC 4291 prefix */
2103const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2104 0x00, 0x00, 0x00, 0x00,
2105 0x00, 0x00, 0xFF, 0xFF };
2106
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002107/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2108 * Input and output may overlap.
2109 */
David du Colombier4f92d322011-03-24 11:09:31 +01002110void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2111{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002112 struct in_addr tmp_addr;
2113
2114 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002115 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002116 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002117}
2118
2119/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2120 * Return true if conversion is possible and false otherwise.
2121 */
2122int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2123{
2124 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2125 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2126 sizeof(struct in_addr));
2127 return 1;
2128 }
2129
2130 return 0;
2131}
2132
William Lallemand421f5b52012-02-06 18:15:57 +01002133char *human_time(int t, short hz_div) {
2134 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2135 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002136 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002137 int cnt=2; // print two numbers
2138
2139 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002140 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002141 return rv;
2142 }
2143
2144 if (unlikely(hz_div > 1))
2145 t /= hz_div;
2146
2147 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002148 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002149 cnt--;
2150 }
2151
2152 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002153 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002154 cnt--;
2155 }
2156
2157 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002158 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002159 cnt--;
2160 }
2161
2162 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002163 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002164
2165 return rv;
2166}
2167
2168const char *monthname[12] = {
2169 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2170 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2171};
2172
2173/* date2str_log: write a date in the format :
2174 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2175 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2176 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2177 *
2178 * without using sprintf. return a pointer to the last char written (\0) or
2179 * NULL if there isn't enough space.
2180 */
2181char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2182{
2183
2184 if (size < 25) /* the size is fixed: 24 chars + \0 */
2185 return NULL;
2186
2187 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2188 *dst++ = '/';
2189 memcpy(dst, monthname[tm->tm_mon], 3); // month
2190 dst += 3;
2191 *dst++ = '/';
2192 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2193 *dst++ = ':';
2194 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2195 *dst++ = ':';
2196 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2197 *dst++ = ':';
2198 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2199 *dst++ = '.';
2200 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2201 dst += 3; // only the 3 first digits
2202 *dst = '\0';
2203
2204 return dst;
2205}
2206
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002207/* Base year used to compute leap years */
2208#define TM_YEAR_BASE 1900
2209
2210/* Return the difference in seconds between two times (leap seconds are ignored).
2211 * Retrieved from glibc 2.18 source code.
2212 */
2213static int my_tm_diff(const struct tm *a, const struct tm *b)
2214{
2215 /* Compute intervening leap days correctly even if year is negative.
2216 * Take care to avoid int overflow in leap day calculations,
2217 * but it's OK to assume that A and B are close to each other.
2218 */
2219 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
2220 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
2221 int a100 = a4 / 25 - (a4 % 25 < 0);
2222 int b100 = b4 / 25 - (b4 % 25 < 0);
2223 int a400 = a100 >> 2;
2224 int b400 = b100 >> 2;
2225 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
2226 int years = a->tm_year - b->tm_year;
2227 int days = (365 * years + intervening_leap_days
2228 + (a->tm_yday - b->tm_yday));
2229 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
2230 + (a->tm_min - b->tm_min))
2231 + (a->tm_sec - b->tm_sec));
2232}
2233
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002234/* Return the GMT offset for a specific local time.
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002235 * Both t and tm must represent the same time.
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002236 * The string returned has the same format as returned by strftime(... "%z", tm).
2237 * Offsets are kept in an internal cache for better performances.
2238 */
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002239const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002240{
2241 /* Cache offsets from GMT (depending on whether DST is active or not) */
2242 static char gmt_offsets[2][5+1] = { "", "" };
2243
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002244 char *gmt_offset;
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002245 struct tm tm_gmt;
2246 int diff;
2247 int isdst = tm->tm_isdst;
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002248
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002249 /* Pretend DST not active if its status is unknown */
2250 if (isdst < 0)
2251 isdst = 0;
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002252
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002253 /* Fetch the offset and initialize it if needed */
2254 gmt_offset = gmt_offsets[isdst & 0x01];
2255 if (unlikely(!*gmt_offset)) {
2256 get_gmtime(t, &tm_gmt);
2257 diff = my_tm_diff(tm, &tm_gmt);
2258 if (diff < 0) {
2259 diff = -diff;
2260 *gmt_offset = '-';
2261 } else {
2262 *gmt_offset = '+';
2263 }
2264 diff /= 60; /* Convert to minutes */
2265 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
2266 }
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002267
2268 return gmt_offset;
2269}
2270
William Lallemand421f5b52012-02-06 18:15:57 +01002271/* gmt2str_log: write a date in the format :
2272 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2273 * return a pointer to the last char written (\0) or
2274 * NULL if there isn't enough space.
2275 */
2276char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2277{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002278 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002279 return NULL;
2280
2281 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2282 *dst++ = '/';
2283 memcpy(dst, monthname[tm->tm_mon], 3); // month
2284 dst += 3;
2285 *dst++ = '/';
2286 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2287 *dst++ = ':';
2288 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2289 *dst++ = ':';
2290 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2291 *dst++ = ':';
2292 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2293 *dst++ = ' ';
2294 *dst++ = '+';
2295 *dst++ = '0';
2296 *dst++ = '0';
2297 *dst++ = '0';
2298 *dst++ = '0';
2299 *dst = '\0';
2300
2301 return dst;
2302}
2303
Yuxans Yao4e25b012012-10-19 10:36:09 +08002304/* localdate2str_log: write a date in the format :
2305 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002306 * Both t and tm must represent the same time.
2307 * return a pointer to the last char written (\0) or
2308 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08002309 */
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002310char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08002311{
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002312 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08002313 if (size < 27) /* the size is fixed: 26 chars + \0 */
2314 return NULL;
2315
Benoit GARNIER517cdce2016-03-27 03:04:16 +02002316 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002317
Yuxans Yao4e25b012012-10-19 10:36:09 +08002318 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2319 *dst++ = '/';
2320 memcpy(dst, monthname[tm->tm_mon], 3); // month
2321 dst += 3;
2322 *dst++ = '/';
2323 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2324 *dst++ = ':';
2325 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2326 *dst++ = ':';
2327 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2328 *dst++ = ':';
2329 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2330 *dst++ = ' ';
Benoit GARNIER5237ace2016-03-27 11:08:03 +02002331 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08002332 dst += 5;
2333 *dst = '\0';
2334
2335 return dst;
2336}
2337
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002338/* Dynamically allocates a string of the proper length to hold the formatted
2339 * output. NULL is returned on error. The caller is responsible for freeing the
2340 * memory area using free(). The resulting string is returned in <out> if the
2341 * pointer is not NULL. A previous version of <out> might be used to build the
2342 * new string, and it will be freed before returning if it is not NULL, which
2343 * makes it possible to build complex strings from iterative calls without
2344 * having to care about freeing intermediate values, as in the example below :
2345 *
2346 * memprintf(&err, "invalid argument: '%s'", arg);
2347 * ...
2348 * memprintf(&err, "parser said : <%s>\n", *err);
2349 * ...
2350 * free(*err);
2351 *
2352 * This means that <err> must be initialized to NULL before first invocation.
2353 * The return value also holds the allocated string, which eases error checking
2354 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002355 * passed instead and it will be ignored. The returned message will then also
2356 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002357 *
2358 * It is also convenient to use it without any free except the last one :
2359 * err = NULL;
2360 * if (!fct1(err)) report(*err);
2361 * if (!fct2(err)) report(*err);
2362 * if (!fct3(err)) report(*err);
2363 * free(*err);
2364 */
2365char *memprintf(char **out, const char *format, ...)
2366{
2367 va_list args;
2368 char *ret = NULL;
2369 int allocated = 0;
2370 int needed = 0;
2371
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002372 if (!out)
2373 return NULL;
2374
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002375 do {
2376 /* vsnprintf() will return the required length even when the
2377 * target buffer is NULL. We do this in a loop just in case
2378 * intermediate evaluations get wrong.
2379 */
2380 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002381 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002382 va_end(args);
2383
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002384 if (needed < allocated) {
2385 /* Note: on Solaris 8, the first iteration always
2386 * returns -1 if allocated is zero, so we force a
2387 * retry.
2388 */
2389 if (!allocated)
2390 needed = 0;
2391 else
2392 break;
2393 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002394
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002395 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002396 ret = realloc(ret, allocated);
2397 } while (ret);
2398
2399 if (needed < 0) {
2400 /* an error was encountered */
2401 free(ret);
2402 ret = NULL;
2403 }
2404
2405 if (out) {
2406 free(*out);
2407 *out = ret;
2408 }
2409
2410 return ret;
2411}
William Lallemand421f5b52012-02-06 18:15:57 +01002412
Willy Tarreau21c705b2012-09-14 11:40:36 +02002413/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2414 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002415 * freed by the caller. It also supports being passed a NULL which results in the same
2416 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002417 * Example of use :
2418 * parse(cmd, &err); (callee: memprintf(&err, ...))
2419 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2420 * free(err);
2421 */
2422char *indent_msg(char **out, int level)
2423{
2424 char *ret, *in, *p;
2425 int needed = 0;
2426 int lf = 0;
2427 int lastlf = 0;
2428 int len;
2429
Willy Tarreau70eec382012-10-10 08:56:47 +02002430 if (!out || !*out)
2431 return NULL;
2432
Willy Tarreau21c705b2012-09-14 11:40:36 +02002433 in = *out - 1;
2434 while ((in = strchr(in + 1, '\n')) != NULL) {
2435 lastlf = in - *out;
2436 lf++;
2437 }
2438
2439 if (!lf) /* single line, no LF, return it as-is */
2440 return *out;
2441
2442 len = strlen(*out);
2443
2444 if (lf == 1 && lastlf == len - 1) {
2445 /* single line, LF at end, strip it and return as-is */
2446 (*out)[lastlf] = 0;
2447 return *out;
2448 }
2449
2450 /* OK now we have at least one LF, we need to process the whole string
2451 * as a multi-line string. What we'll do :
2452 * - prefix with an LF if there is none
2453 * - add <level> spaces before each line
2454 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2455 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2456 */
2457
2458 needed = 1 + level * (lf + 1) + len + 1;
2459 p = ret = malloc(needed);
2460 in = *out;
2461
2462 /* skip initial LFs */
2463 while (*in == '\n')
2464 in++;
2465
2466 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2467 while (*in) {
2468 *p++ = '\n';
2469 memset(p, ' ', level);
2470 p += level;
2471 do {
2472 *p++ = *in++;
2473 } while (*in && *in != '\n');
2474 if (*in)
2475 in++;
2476 }
2477 *p = 0;
2478
2479 free(*out);
2480 *out = ret;
2481
2482 return ret;
2483}
2484
Willy Tarreaudad36a32013-03-11 01:20:04 +01002485/* Convert occurrences of environment variables in the input string to their
2486 * corresponding value. A variable is identified as a series of alphanumeric
2487 * characters or underscores following a '$' sign. The <in> string must be
2488 * free()able. NULL returns NULL. The resulting string might be reallocated if
2489 * some expansion is made. Variable names may also be enclosed into braces if
2490 * needed (eg: to concatenate alphanum characters).
2491 */
2492char *env_expand(char *in)
2493{
2494 char *txt_beg;
2495 char *out;
2496 char *txt_end;
2497 char *var_beg;
2498 char *var_end;
2499 char *value;
2500 char *next;
2501 int out_len;
2502 int val_len;
2503
2504 if (!in)
2505 return in;
2506
2507 value = out = NULL;
2508 out_len = 0;
2509
2510 txt_beg = in;
2511 do {
2512 /* look for next '$' sign in <in> */
2513 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2514
2515 if (!*txt_end && !out) /* end and no expansion performed */
2516 return in;
2517
2518 val_len = 0;
2519 next = txt_end;
2520 if (*txt_end == '$') {
2521 char save;
2522
2523 var_beg = txt_end + 1;
2524 if (*var_beg == '{')
2525 var_beg++;
2526
2527 var_end = var_beg;
2528 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2529 var_end++;
2530 }
2531
2532 next = var_end;
2533 if (*var_end == '}' && (var_beg > txt_end + 1))
2534 next++;
2535
2536 /* get value of the variable name at this location */
2537 save = *var_end;
2538 *var_end = '\0';
2539 value = getenv(var_beg);
2540 *var_end = save;
2541 val_len = value ? strlen(value) : 0;
2542 }
2543
2544 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2545 if (txt_end > txt_beg) {
2546 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2547 out_len += txt_end - txt_beg;
2548 }
2549 if (val_len) {
2550 memcpy(out + out_len, value, val_len);
2551 out_len += val_len;
2552 }
2553 out[out_len] = 0;
2554 txt_beg = next;
2555 } while (*txt_beg);
2556
2557 /* here we know that <out> was allocated and that we don't need <in> anymore */
2558 free(in);
2559 return out;
2560}
2561
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002562
2563/* same as strstr() but case-insensitive and with limit length */
2564const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2565{
2566 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02002567 unsigned int slen, plen;
2568 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002569
2570 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2571 return NULL;
2572
2573 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2574 return str1;
2575
2576 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2577 return NULL;
2578
2579 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2580 while (toupper(*start) != toupper(*str2)) {
2581 start++;
2582 slen--;
2583 tmp1++;
2584
2585 if (tmp1 >= len_str1)
2586 return NULL;
2587
2588 /* if pattern longer than string */
2589 if (slen < plen)
2590 return NULL;
2591 }
2592
2593 sptr = start;
2594 pptr = (char *)str2;
2595
2596 tmp2 = 0;
2597 while (toupper(*sptr) == toupper(*pptr)) {
2598 sptr++;
2599 pptr++;
2600 tmp2++;
2601
2602 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2603 return start;
2604 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2605 return NULL;
2606 }
2607 }
2608 return NULL;
2609}
2610
Willy Tarreaubaaee002006-06-26 02:48:02 +02002611/*
2612 * Local variables:
2613 * c-indent-level: 8
2614 * c-basic-offset: 8
2615 * End:
2616 */