blob: b0c5fe6eb23488cf7a576b02a117cf3359cc678a [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
41/*
William Lallemande7340ec2012-01-24 11:15:39 +010042 * unsigned long long ASCII representation
43 *
44 * return the last char '\0' or NULL if no enough
45 * space in dst
46 */
47char *ulltoa(unsigned long long n, char *dst, size_t size)
48{
49 int i = 0;
50 char *res;
51
52 switch(n) {
53 case 1ULL ... 9ULL:
54 i = 0;
55 break;
56
57 case 10ULL ... 99ULL:
58 i = 1;
59 break;
60
61 case 100ULL ... 999ULL:
62 i = 2;
63 break;
64
65 case 1000ULL ... 9999ULL:
66 i = 3;
67 break;
68
69 case 10000ULL ... 99999ULL:
70 i = 4;
71 break;
72
73 case 100000ULL ... 999999ULL:
74 i = 5;
75 break;
76
77 case 1000000ULL ... 9999999ULL:
78 i = 6;
79 break;
80
81 case 10000000ULL ... 99999999ULL:
82 i = 7;
83 break;
84
85 case 100000000ULL ... 999999999ULL:
86 i = 8;
87 break;
88
89 case 1000000000ULL ... 9999999999ULL:
90 i = 9;
91 break;
92
93 case 10000000000ULL ... 99999999999ULL:
94 i = 10;
95 break;
96
97 case 100000000000ULL ... 999999999999ULL:
98 i = 11;
99 break;
100
101 case 1000000000000ULL ... 9999999999999ULL:
102 i = 12;
103 break;
104
105 case 10000000000000ULL ... 99999999999999ULL:
106 i = 13;
107 break;
108
109 case 100000000000000ULL ... 999999999999999ULL:
110 i = 14;
111 break;
112
113 case 1000000000000000ULL ... 9999999999999999ULL:
114 i = 15;
115 break;
116
117 case 10000000000000000ULL ... 99999999999999999ULL:
118 i = 16;
119 break;
120
121 case 100000000000000000ULL ... 999999999999999999ULL:
122 i = 17;
123 break;
124
125 case 1000000000000000000ULL ... 9999999999999999999ULL:
126 i = 18;
127 break;
128
129 case 10000000000000000000ULL ... ULLONG_MAX:
130 i = 19;
131 break;
132 }
133 if (i + 2 > size) // (i + 1) + '\0'
134 return NULL; // too long
135 res = dst + i + 1;
136 *res = '\0';
137 for (; i >= 0; i--) {
138 dst[i] = n % 10ULL + '0';
139 n /= 10ULL;
140 }
141 return res;
142}
143
144/*
145 * unsigned long ASCII representation
146 *
147 * return the last char '\0' or NULL if no enough
148 * space in dst
149 */
150char *ultoa_o(unsigned long n, char *dst, size_t size)
151{
152 int i = 0;
153 char *res;
154
155 switch (n) {
156 case 0U ... 9UL:
157 i = 0;
158 break;
159
160 case 10U ... 99UL:
161 i = 1;
162 break;
163
164 case 100U ... 999UL:
165 i = 2;
166 break;
167
168 case 1000U ... 9999UL:
169 i = 3;
170 break;
171
172 case 10000U ... 99999UL:
173 i = 4;
174 break;
175
176 case 100000U ... 999999UL:
177 i = 5;
178 break;
179
180 case 1000000U ... 9999999UL:
181 i = 6;
182 break;
183
184 case 10000000U ... 99999999UL:
185 i = 7;
186 break;
187
188 case 100000000U ... 999999999UL:
189 i = 8;
190 break;
191#if __WORDSIZE == 32
192
193 case 1000000000ULL ... ULONG_MAX:
194 i = 9;
195 break;
196
197#elif __WORDSIZE == 64
198
199 case 1000000000ULL ... 9999999999UL:
200 i = 9;
201 break;
202
203 case 10000000000ULL ... 99999999999UL:
204 i = 10;
205 break;
206
207 case 100000000000ULL ... 999999999999UL:
208 i = 11;
209 break;
210
211 case 1000000000000ULL ... 9999999999999UL:
212 i = 12;
213 break;
214
215 case 10000000000000ULL ... 99999999999999UL:
216 i = 13;
217 break;
218
219 case 100000000000000ULL ... 999999999999999UL:
220 i = 14;
221 break;
222
223 case 1000000000000000ULL ... 9999999999999999UL:
224 i = 15;
225 break;
226
227 case 10000000000000000ULL ... 99999999999999999UL:
228 i = 16;
229 break;
230
231 case 100000000000000000ULL ... 999999999999999999UL:
232 i = 17;
233 break;
234
235 case 1000000000000000000ULL ... 9999999999999999999UL:
236 i = 18;
237 break;
238
239 case 10000000000000000000ULL ... ULONG_MAX:
240 i = 19;
241 break;
242
243#endif
244 }
245 if (i + 2 > size) // (i + 1) + '\0'
246 return NULL; // too long
247 res = dst + i + 1;
248 *res = '\0';
249 for (; i >= 0; i--) {
250 dst[i] = n % 10U + '0';
251 n /= 10U;
252 }
253 return res;
254}
255
256/*
257 * signed long ASCII representation
258 *
259 * return the last char '\0' or NULL if no enough
260 * space in dst
261 */
262char *ltoa_o(long int n, char *dst, size_t size)
263{
264 char *pos = dst;
265
266 if (n < 0) {
267 if (size < 3)
268 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
269 *pos = '-';
270 pos++;
271 dst = ultoa_o(-n, pos, size - 1);
272 } else {
273 dst = ultoa_o(n, dst, size);
274 }
275 return dst;
276}
277
278/*
279 * signed long long ASCII representation
280 *
281 * return the last char '\0' or NULL if no enough
282 * space in dst
283 */
284char *lltoa(long long n, char *dst, size_t size)
285{
286 char *pos = dst;
287
288 if (n < 0) {
289 if (size < 3)
290 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
291 *pos = '-';
292 pos++;
293 dst = ulltoa(-n, pos, size - 1);
294 } else {
295 dst = ulltoa(n, dst, size);
296 }
297 return dst;
298}
299
300/*
301 * write a ascii representation of a unsigned into dst,
302 * return a pointer to the last character
303 * Pad the ascii representation with '0', using size.
304 */
305char *utoa_pad(unsigned int n, char *dst, size_t size)
306{
307 int i = 0;
308 char *ret;
309
310 switch(n) {
311 case 0U ... 9U:
312 i = 0;
313 break;
314
315 case 10U ... 99U:
316 i = 1;
317 break;
318
319 case 100U ... 999U:
320 i = 2;
321 break;
322
323 case 1000U ... 9999U:
324 i = 3;
325 break;
326
327 case 10000U ... 99999U:
328 i = 4;
329 break;
330
331 case 100000U ... 999999U:
332 i = 5;
333 break;
334
335 case 1000000U ... 9999999U:
336 i = 6;
337 break;
338
339 case 10000000U ... 99999999U:
340 i = 7;
341 break;
342
343 case 100000000U ... 999999999U:
344 i = 8;
345 break;
346
347 case 1000000000U ... 4294967295U:
348 i = 9;
349 break;
350 }
351 if (i + 2 > size) // (i + 1) + '\0'
352 return NULL; // too long
353 if (i < size)
354 i = size - 2; // padding - '\0'
355
356 ret = dst + i + 1;
357 *ret = '\0';
358 for (; i >= 0; i--) {
359 dst[i] = n % 10U + '0';
360 n /= 10U;
361 }
362 return ret;
363}
364
365/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200366 * copies at most <size-1> chars from <src> to <dst>. Last char is always
367 * set to 0, unless <size> is 0. The number of chars copied is returned
368 * (excluding the terminating zero).
369 * This code has been optimized for size and speed : on x86, it's 45 bytes
370 * long, uses only registers, and consumes only 4 cycles per char.
371 */
372int strlcpy2(char *dst, const char *src, int size)
373{
374 char *orig = dst;
375 if (size) {
376 while (--size && (*dst = *src)) {
377 src++; dst++;
378 }
379 *dst = 0;
380 }
381 return dst - orig;
382}
383
384/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200385 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200386 * the ascii representation for number 'n' in decimal.
387 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100388char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200389{
390 char *pos;
391
Willy Tarreau72d759c2007-10-25 12:14:10 +0200392 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200393 *pos-- = '\0';
394
395 do {
396 *pos-- = '0' + n % 10;
397 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200398 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200399 return pos + 1;
400}
401
Willy Tarreau91092e52007-10-25 16:58:42 +0200402/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200403 * This function simply returns a locally allocated string containing
404 * the ascii representation for number 'n' in decimal, formatted for
405 * HTML output with tags to create visual grouping by 3 digits. The
406 * output needs to support at least 171 characters.
407 */
408const char *ulltoh_r(unsigned long long n, char *buffer, int size)
409{
410 char *start;
411 int digit = 0;
412
413 start = buffer + size;
414 *--start = '\0';
415
416 do {
417 if (digit == 3 && start >= buffer + 7)
418 memcpy(start -= 7, "</span>", 7);
419
420 if (start >= buffer + 1) {
421 *--start = '0' + n % 10;
422 n /= 10;
423 }
424
425 if (digit == 3 && start >= buffer + 18)
426 memcpy(start -= 18, "<span class=\"rls\">", 18);
427
428 if (digit++ == 3)
429 digit = 1;
430 } while (n && start > buffer);
431 return start;
432}
433
434/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200435 * This function simply returns a locally allocated string containing the ascii
436 * representation for number 'n' in decimal, unless n is 0 in which case it
437 * returns the alternate string (or an empty string if the alternate string is
438 * NULL). It use is intended for limits reported in reports, where it's
439 * desirable not to display anything if there is no limit. Warning! it shares
440 * the same vector as ultoa_r().
441 */
442const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
443{
444 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
445}
446
Robert Tsai81ae1952007-12-05 10:47:29 +0100447/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200448 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
449 *
450 * It looks like this one would be a good candidate for inlining, but this is
451 * not interesting because it around 35 bytes long and often called multiple
452 * times within the same function.
453 */
454int ishex(char s)
455{
456 s -= '0';
457 if ((unsigned char)s <= 9)
458 return 1;
459 s -= 'A' - '0';
460 if ((unsigned char)s <= 5)
461 return 1;
462 s -= 'a' - 'A';
463 if ((unsigned char)s <= 5)
464 return 1;
465 return 0;
466}
467
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100468/*
469 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
470 * invalid character is found, a pointer to it is returned. If everything is
471 * fine, NULL is returned.
472 */
473const char *invalid_char(const char *name)
474{
475 if (!*name)
476 return name;
477
478 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100479 if (!isalnum((int)(unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100480 *name != '_' && *name != '-')
481 return name;
482 name++;
483 }
484 return NULL;
485}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200486
487/*
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200488 * Checks <domainname> for invalid characters. Valid chars are [A-Za-z0-9_.-].
489 * If an invalid character is found, a pointer to it is returned.
490 * If everything is fine, NULL is returned.
491 */
492const char *invalid_domainchar(const char *name) {
493
494 if (!*name)
495 return name;
496
497 while (*name) {
Willy Tarreau88e05812010-03-03 00:16:00 +0100498 if (!isalnum((int)(unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200499 *name != '_' && *name != '-')
500 return name;
501
502 name++;
503 }
504
505 return NULL;
506}
507
508/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100509 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100510 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
511 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
512 * the function tries to guess the address family from the syntax. If the
513 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100514 * string is assumed to contain only an address, no port. The address can be a
515 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
516 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
517 * The return address will only have the address family and the address set,
518 * all other fields remain zero. The string is not supposed to be modified.
519 * The IPv6 '::' address is IN6ADDR_ANY.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200520 */
Willy Tarreau24709282013-03-10 21:32:12 +0100521static struct sockaddr_storage *str2ip(const char *str, struct sockaddr_storage *sa)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200522{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100523 struct hostent *he;
524
Willy Tarreaufab5a432011-03-04 15:31:53 +0100525 /* Any IPv6 address */
526 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100527 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
528 sa->ss_family = AF_INET6;
529 else if (sa->ss_family != AF_INET6)
530 goto fail;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100531 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100532 }
533
Willy Tarreau24709282013-03-10 21:32:12 +0100534 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100535 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100536 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
537 sa->ss_family = AF_INET;
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100538 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100539 }
540
541 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100542 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
543 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100544 sa->ss_family = AF_INET6;
545 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100546 }
547
548 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100549 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
550 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100551 sa->ss_family = AF_INET;
552 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100553 }
554
David du Colombierd5f43282011-03-17 10:40:16 +0100555#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200556 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100557 struct addrinfo hints, *result;
558
559 memset(&result, 0, sizeof(result));
560 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100561 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100562 hints.ai_socktype = SOCK_DGRAM;
563 hints.ai_flags = AI_PASSIVE;
564 hints.ai_protocol = 0;
565
566 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100567 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
568 sa->ss_family = result->ai_family;
569 else if (sa->ss_family != result->ai_family)
570 goto fail;
571
David du Colombierd5f43282011-03-17 10:40:16 +0100572 switch (result->ai_family) {
573 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100574 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
575 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100576 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100577 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
578 return sa;
David du Colombierd5f43282011-03-17 10:40:16 +0100579 }
580 }
581
Sean Carey58ea0392013-02-15 23:39:18 +0100582 if (result)
583 freeaddrinfo(result);
Willy Tarreaufab5a432011-03-04 15:31:53 +0100584 }
David du Colombierd5f43282011-03-17 10:40:16 +0100585#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200586 /* try to resolve an IPv4/IPv6 hostname */
587 he = gethostbyname(str);
588 if (he) {
589 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
590 sa->ss_family = he->h_addrtype;
591 else if (sa->ss_family != he->h_addrtype)
592 goto fail;
593
594 switch (sa->ss_family) {
595 case AF_INET:
596 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
597 return sa;
598 case AF_INET6:
599 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
600 return sa;
601 }
602 }
603
David du Colombierd5f43282011-03-17 10:40:16 +0100604 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100605 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100606 return NULL;
607}
608
609/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100610 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
611 * range or offset consisting in two integers that the caller will have to
612 * check to find the relevant input format. The following format are supported :
613 *
614 * String format | address | port | low | high
615 * addr | <addr> | 0 | 0 | 0
616 * addr: | <addr> | 0 | 0 | 0
617 * addr:port | <addr> | <port> | <port> | <port>
618 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
619 * addr:+port | <addr> | <port> | 0 | <port>
620 * addr:-port | <addr> |-<port> | <port> | 0
621 *
622 * The detection of a port range or increment by the caller is made by
623 * comparing <low> and <high>. If both are equal, then port 0 means no port
624 * was specified. The caller may pass NULL for <low> and <high> if it is not
625 * interested in retrieving port ranges.
626 *
627 * Note that <addr> above may also be :
628 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
629 * - "*" => family will be AF_INET and address will be INADDR_ANY
630 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
631 * - a host name => family and address will depend on host name resolving.
632 *
Willy Tarreau24709282013-03-10 21:32:12 +0100633 * A prefix may be passed in before the address above to force the family :
634 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
635 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
636 * - "unix@" => force address to be a path to a UNIX socket even if the
637 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200638 * - 'abns@' -> force address to belong to the abstract namespace (Linux
639 * only). These sockets are just like Unix sockets but without
640 * the need for an underlying file system. The address is a
641 * string. Technically it's like a Unix socket with a zero in
642 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100643 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100644 *
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100645 * Also note that in order to avoid any ambiguity with IPv6 addresses, the ':'
646 * is mandatory after the IP address even when no port is specified. NULL is
647 * returned if the address cannot be parsed. The <low> and <high> ports are
Willy Tarreau24709282013-03-10 21:32:12 +0100648 * always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100649 *
650 * If <pfx> is non-null, it is used as a string prefix before any path-based
651 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100652 *
653 * When a file descriptor is passed, its value is put into the s_addr part of
654 * the address when cast to sockaddr_in and the address family is AF_UNSPEC.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100655 */
Willy Tarreaud393a622013-03-04 18:22:00 +0100656struct sockaddr_storage *str2sa_range(const char *str, int *low, int *high, char **err, const char *pfx)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100657{
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100658 static struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100659 struct sockaddr_storage *ret = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100660 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100661 char *port1, *port2;
662 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200663 int abstract = 0;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100664
665 portl = porth = porta = 0;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200666
Willy Tarreaudad36a32013-03-11 01:20:04 +0100667 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100668 if (str2 == NULL) {
669 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100670 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100671 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200672
Willy Tarreau24709282013-03-10 21:32:12 +0100673 memset(&ss, 0, sizeof(ss));
674
675 if (strncmp(str2, "unix@", 5) == 0) {
676 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200677 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100678 ss.ss_family = AF_UNIX;
679 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200680 else if (strncmp(str2, "abns@", 5) == 0) {
681 str2 += 5;
682 abstract = 1;
683 ss.ss_family = AF_UNIX;
684 }
Willy Tarreau24709282013-03-10 21:32:12 +0100685 else if (strncmp(str2, "ipv4@", 5) == 0) {
686 str2 += 5;
687 ss.ss_family = AF_INET;
688 }
689 else if (strncmp(str2, "ipv6@", 5) == 0) {
690 str2 += 5;
691 ss.ss_family = AF_INET6;
692 }
693 else if (*str2 == '/') {
694 ss.ss_family = AF_UNIX;
695 }
696 else
697 ss.ss_family = AF_UNSPEC;
698
Willy Tarreau40aa0702013-03-10 23:51:38 +0100699 if (ss.ss_family == AF_UNSPEC && strncmp(str2, "fd@", 3) == 0) {
700 char *endptr;
701
702 str2 += 3;
703 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = strtol(str2, &endptr, 10);
704
705 if (!*str2 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100706 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100707 goto out;
708 }
709
710 /* we return AF_UNSPEC if we use a file descriptor number */
711 ss.ss_family = AF_UNSPEC;
712 }
713 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau15586382013-03-04 19:48:14 +0100714 int prefix_path_len;
715 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200716 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +0100717
718 /* complete unix socket path name during startup or soft-restart is
719 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
720 */
Willy Tarreauccfccef2014-05-10 01:49:15 +0200721 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau15586382013-03-04 19:48:14 +0100722 max_path_len = (sizeof(((struct sockaddr_un *)&ss)->sun_path) - 1) -
723 (prefix_path_len ? prefix_path_len + 1 + 5 + 1 + 3 : 0);
724
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200725 adr_len = strlen(str2);
726 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +0100727 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
728 goto out;
729 }
730
Willy Tarreauccfccef2014-05-10 01:49:15 +0200731 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
732 memset(((struct sockaddr_un *)&ss)->sun_path, 0, sizeof(((struct sockaddr_un *)&ss)->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +0200733 if (prefix_path_len)
Willy Tarreau15586382013-03-04 19:48:14 +0100734 memcpy(((struct sockaddr_un *)&ss)->sun_path, pfx, prefix_path_len);
Willy Tarreauccfccef2014-05-10 01:49:15 +0200735 memcpy(((struct sockaddr_un *)&ss)->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +0100736 }
Willy Tarreau24709282013-03-10 21:32:12 +0100737 else { /* IPv4 and IPv6 */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100738 port1 = strrchr(str2, ':');
739 if (port1)
740 *port1++ = '\0';
741 else
742 port1 = "";
Willy Tarreaubaaee002006-06-26 02:48:02 +0200743
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100744 if (str2ip(str2, &ss) == NULL) {
745 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
746 goto out;
747 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100748
Willy Tarreaua39d1992013-04-01 20:37:42 +0200749 if (isdigit((int)(unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100750 port2 = strchr(port1, '-');
751 if (port2)
752 *port2++ = '\0';
753 else
754 port2 = port1;
755 portl = atoi(port1);
756 porth = atoi(port2);
757 porta = portl;
758 }
759 else if (*port1 == '-') { /* negative offset */
760 portl = atoi(port1 + 1);
761 porta = -portl;
762 }
763 else if (*port1 == '+') { /* positive offset */
764 porth = atoi(port1 + 1);
765 porta = porth;
766 }
767 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +0100768 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100769 goto out;
770 }
771 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +0100772 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100773
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100774 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +0100775 out:
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100776 if (low)
777 *low = portl;
778 if (high)
779 *high = porth;
Willy Tarreau24709282013-03-10 21:32:12 +0100780 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100781 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200782}
783
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100784/* converts <str> to a struct in_addr containing a network mask. It can be
785 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
786 * if the conversion succeeds otherwise non-zero.
787 */
788int str2mask(const char *str, struct in_addr *mask)
789{
790 if (strchr(str, '.') != NULL) { /* dotted notation */
791 if (!inet_pton(AF_INET, str, mask))
792 return 0;
793 }
794 else { /* mask length */
795 char *err;
796 unsigned long len = strtol(str, &err, 10);
797
798 if (!*str || (err && *err) || (unsigned)len > 32)
799 return 0;
800 if (len)
801 mask->s_addr = htonl(~0UL << (32 - len));
802 else
803 mask->s_addr = 0;
804 }
805 return 1;
806}
807
Thierry FOURNIERb0504632013-12-14 15:39:02 +0100808/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
809 * succeeds otherwise zero.
810 */
811int cidr2dotted(int cidr, struct in_addr *mask) {
812
813 if (cidr < 0 || cidr > 32)
814 return 0;
815
816 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
817 return 1;
818}
819
Willy Tarreauc6f4ce82009-06-10 11:09:37 +0200820/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +0200821 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200822 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
823 * is optionnal and either in the dotted or CIDR notation.
824 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
825 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100826int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200827{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200828 __label__ out_free, out_err;
829 char *c, *s;
830 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200831
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200832 s = strdup(str);
833 if (!s)
834 return 0;
835
Willy Tarreaubaaee002006-06-26 02:48:02 +0200836 memset(mask, 0, sizeof(*mask));
837 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +0200838
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200839 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200840 *c++ = '\0';
841 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +0100842 if (!str2mask(c, mask))
843 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200844 }
845 else {
Willy Tarreauebd61602006-12-30 11:54:15 +0100846 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200847 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200848 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +0200849 struct hostent *he;
850
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +0100851 if (!resolve)
852 goto out_err;
853
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200854 if ((he = gethostbyname(s)) == NULL) {
855 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200856 }
857 else
858 *addr = *(struct in_addr *) *(he->h_addr_list);
859 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +0200860
861 ret_val = 1;
862 out_free:
863 free(s);
864 return ret_val;
865 out_err:
866 ret_val = 0;
867 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200868}
869
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100870
871/*
Willy Tarreau6d20e282012-04-27 22:49:47 +0200872 * converts <str> to two struct in6_addr* which must be pre-allocated.
873 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
874 * is an optionnal number of bits (128 being the default).
875 * Returns 1 if OK, 0 if error.
876 */
877int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
878{
879 char *c, *s;
880 int ret_val = 0;
881 char *err;
882 unsigned long len = 128;
883
884 s = strdup(str);
885 if (!s)
886 return 0;
887
888 memset(mask, 0, sizeof(*mask));
889 memset(addr, 0, sizeof(*addr));
890
891 if ((c = strrchr(s, '/')) != NULL) {
892 *c++ = '\0'; /* c points to the mask */
893 if (!*c)
894 goto out_free;
895
896 len = strtoul(c, &err, 10);
897 if ((err && *err) || (unsigned)len > 128)
898 goto out_free;
899 }
900 *mask = len; /* OK we have a valid mask in <len> */
901
902 if (!inet_pton(AF_INET6, s, addr))
903 goto out_free;
904
905 ret_val = 1;
906 out_free:
907 free(s);
908 return ret_val;
909}
910
911
912/*
David du Colombier6f5ccb12011-03-10 22:26:24 +0100913 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100914 */
David du Colombier6f5ccb12011-03-10 22:26:24 +0100915int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100916{
917 int saw_digit, octets, ch;
918 u_char tmp[4], *tp;
919 const char *cp = addr;
920
921 saw_digit = 0;
922 octets = 0;
923 *(tp = tmp) = 0;
924
925 while (*addr) {
926 unsigned char digit = (ch = *addr++) - '0';
927 if (digit > 9 && ch != '.')
928 break;
929 if (digit <= 9) {
930 u_int new = *tp * 10 + digit;
931 if (new > 255)
932 return 0;
933 *tp = new;
934 if (!saw_digit) {
935 if (++octets > 4)
936 return 0;
937 saw_digit = 1;
938 }
939 } else if (ch == '.' && saw_digit) {
940 if (octets == 4)
941 return 0;
942 *++tp = 0;
943 saw_digit = 0;
944 } else
945 return 0;
946 }
947
948 if (octets < 4)
949 return 0;
950
951 memcpy(&dst->s_addr, tmp, 4);
952 return addr-cp-1;
953}
954
955/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100956 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
957 * <out> contain the code of the dectected scheme, the start and length of
958 * the hostname. Actually only http and https are supported. <out> can be NULL.
959 * This function returns the consumed length. It is useful if you parse complete
960 * url like http://host:port/path, because the consumed length corresponds to
961 * the first character of the path. If the conversion fails, it returns -1.
962 *
963 * This function tries to resolve the DNS name if haproxy is in starting mode.
964 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100965 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100966int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100967{
968 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100969 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100970 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100971 unsigned long long int http_code = 0;
972 int default_port;
973 struct hostent *he;
974 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100975
976 /* Firstly, try to find :// pattern */
977 while (curr < url+ulen && url_code != 0x3a2f2f) {
978 url_code = ((url_code & 0xffff) << 8);
979 url_code += (unsigned char)*curr++;
980 }
981
982 /* Secondly, if :// pattern is found, verify parsed stuff
983 * before pattern is matching our http pattern.
984 * If so parse ip address and port in uri.
985 *
986 * WARNING: Current code doesn't support dynamic async dns resolver.
987 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100988 if (url_code != 0x3a2f2f)
989 return -1;
990
991 /* Copy scheme, and utrn to lower case. */
992 while (cp < curr - 3)
993 http_code = (http_code << 8) + *cp++;
994 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +0100995
Thierry FOURNIER9f95e402014-03-21 14:51:46 +0100996 /* HTTP or HTTPS url matching */
997 if (http_code == 0x2020202068747470ULL) {
998 default_port = 80;
999 if (out)
1000 out->scheme = SCH_HTTP;
1001 }
1002 else if (http_code == 0x2020206874747073ULL) {
1003 default_port = 443;
1004 if (out)
1005 out->scheme = SCH_HTTPS;
1006 }
1007 else
1008 return -1;
1009
1010 /* If the next char is '[', the host address is IPv6. */
1011 if (*curr == '[') {
1012 curr++;
1013
1014 /* Check trash size */
1015 if (trash.size < ulen)
1016 return -1;
1017
1018 /* Look for ']' and copy the address in a trash buffer. */
1019 p = trash.str;
1020 for (end = curr;
1021 end < url + ulen && *end != ']';
1022 end++, p++)
1023 *p = *end;
1024 if (*end != ']')
1025 return -1;
1026 *p = '\0';
1027
1028 /* Update out. */
1029 if (out) {
1030 out->host = curr;
1031 out->host_len = end - curr;
1032 }
1033
1034 /* Try IPv6 decoding. */
1035 if (!inet_pton(AF_INET6, trash.str, &((struct sockaddr_in6 *)addr)->sin6_addr))
1036 return -1;
1037 end++;
1038
1039 /* Decode port. */
1040 if (*end == ':') {
1041 end++;
1042 default_port = read_uint(&end, url + ulen);
1043 }
1044 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1045 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1046 return end - url;
1047 }
1048 else {
1049 /* We are looking for IP address. If you want to parse and
1050 * resolve hostname found in url, you can use str2sa_range(), but
1051 * be warned this can slow down global daemon performances
1052 * while handling lagging dns responses.
1053 */
1054 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1055 if (ret) {
1056 /* Update out. */
1057 if (out) {
1058 out->host = curr;
1059 out->host_len = ret;
1060 }
1061
1062 curr += ret;
1063
1064 /* Decode port. */
1065 if (*curr == ':') {
1066 curr++;
1067 default_port = read_uint(&curr, url + ulen);
1068 }
1069 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1070
1071 /* Set family. */
1072 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1073 return curr - url;
1074 }
1075 else if (global.mode & MODE_STARTING) {
1076 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1077 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001078 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001079
1080 /* look for : or / or end */
1081 for (end = curr;
1082 end < url + ulen && *end != '/' && *end != ':';
1083 end++);
1084 memcpy(trash.str, curr, end - curr);
1085 trash.str[end - curr] = '\0';
1086
1087 /* try to resolve an IPv4/IPv6 hostname */
1088 he = gethostbyname(trash.str);
1089 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001090 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001091
1092 /* Update out. */
1093 if (out) {
1094 out->host = curr;
1095 out->host_len = end - curr;
1096 }
1097
1098 /* Decode port. */
1099 if (*end == ':') {
1100 end++;
1101 default_port = read_uint(&end, url + ulen);
1102 }
1103
1104 /* Copy IP address, set port and family. */
1105 switch (he->h_addrtype) {
1106 case AF_INET:
1107 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1108 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1109 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1110 return end - url;
1111
1112 case AF_INET6:
1113 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1114 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1115 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1116 return end - url;
1117 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001118 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001119 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001120 return -1;
1121}
1122
Willy Tarreau631f01c2011-09-05 00:36:48 +02001123/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1124 * address family is returned so that it's easy for the caller to adapt to the
1125 * output format. Zero is returned if the address family is not supported. -1
1126 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1127 * supported.
1128 */
1129int addr_to_str(struct sockaddr_storage *addr, char *str, int size)
1130{
1131
1132 void *ptr;
1133
1134 if (size < 5)
1135 return 0;
1136 *str = '\0';
1137
1138 switch (addr->ss_family) {
1139 case AF_INET:
1140 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1141 break;
1142 case AF_INET6:
1143 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1144 break;
1145 case AF_UNIX:
1146 memcpy(str, "unix", 5);
1147 return addr->ss_family;
1148 default:
1149 return 0;
1150 }
1151
1152 if (inet_ntop(addr->ss_family, ptr, str, size))
1153 return addr->ss_family;
1154
1155 /* failed */
1156 return -1;
1157}
1158
Simon Horman75ab8bd2014-06-16 09:39:41 +09001159/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1160 * address family is returned so that it's easy for the caller to adapt to the
1161 * output format. Zero is returned if the address family is not supported. -1
1162 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1163 * supported.
1164 */
1165int port_to_str(struct sockaddr_storage *addr, char *str, int size)
1166{
1167
1168 uint16_t port;
1169
1170
1171 if (size < 5)
1172 return 0;
1173 *str = '\0';
1174
1175 switch (addr->ss_family) {
1176 case AF_INET:
1177 port = ((struct sockaddr_in *)addr)->sin_port;
1178 break;
1179 case AF_INET6:
1180 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1181 break;
1182 case AF_UNIX:
1183 memcpy(str, "unix", 5);
1184 return addr->ss_family;
1185 default:
1186 return 0;
1187 }
1188
1189 snprintf(str, size, "%u", ntohs(port));
1190 return addr->ss_family;
1191}
1192
Willy Tarreaubaaee002006-06-26 02:48:02 +02001193/* will try to encode the string <string> replacing all characters tagged in
1194 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1195 * prefixed by <escape>, and will store the result between <start> (included)
1196 * and <stop> (excluded), and will always terminate the string with a '\0'
1197 * before <stop>. The position of the '\0' is returned if the conversion
1198 * completes. If bytes are missing between <start> and <stop>, then the
1199 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1200 * cannot even be stored so we return <start> without writing the 0.
1201 * The input string must also be zero-terminated.
1202 */
1203const char hextab[16] = "0123456789ABCDEF";
1204char *encode_string(char *start, char *stop,
1205 const char escape, const fd_set *map,
1206 const char *string)
1207{
1208 if (start < stop) {
1209 stop--; /* reserve one byte for the final '\0' */
1210 while (start < stop && *string != '\0') {
1211 if (!FD_ISSET((unsigned char)(*string), map))
1212 *start++ = *string;
1213 else {
1214 if (start + 3 >= stop)
1215 break;
1216 *start++ = escape;
1217 *start++ = hextab[(*string >> 4) & 15];
1218 *start++ = hextab[*string & 15];
1219 }
1220 string++;
1221 }
1222 *start = '\0';
1223 }
1224 return start;
1225}
1226
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001227/*
1228 * Same behavior as encode_string() above, except that it encodes chunk
1229 * <chunk> instead of a string.
1230 */
1231char *encode_chunk(char *start, char *stop,
1232 const char escape, const fd_set *map,
1233 const struct chunk *chunk)
1234{
1235 char *str = chunk->str;
1236 char *end = chunk->str + chunk->len;
1237
1238 if (start < stop) {
1239 stop--; /* reserve one byte for the final '\0' */
1240 while (start < stop && str < end) {
1241 if (!FD_ISSET((unsigned char)(*str), map))
1242 *start++ = *str;
1243 else {
1244 if (start + 3 >= stop)
1245 break;
1246 *start++ = escape;
1247 *start++ = hextab[(*str >> 4) & 15];
1248 *start++ = hextab[*str & 15];
1249 }
1250 str++;
1251 }
1252 *start = '\0';
1253 }
1254 return start;
1255}
1256
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001257/* Decode an URL-encoded string in-place. The resulting string might
1258 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001259 * aborted, the string is truncated before the issue and a negative value is
1260 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001261 */
1262int url_decode(char *string)
1263{
1264 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001265 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001266
1267 in = string;
1268 out = string;
1269 while (*in) {
1270 switch (*in) {
1271 case '+' :
1272 *out++ = ' ';
1273 break;
1274 case '%' :
1275 if (!ishex(in[1]) || !ishex(in[2]))
1276 goto end;
1277 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1278 in += 2;
1279 break;
1280 default:
1281 *out++ = *in;
1282 break;
1283 }
1284 in++;
1285 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001286 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001287 end:
1288 *out = 0;
1289 return ret;
1290}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001291
Willy Tarreau6911fa42007-03-04 18:06:08 +01001292unsigned int str2ui(const char *s)
1293{
1294 return __str2ui(s);
1295}
1296
1297unsigned int str2uic(const char *s)
1298{
1299 return __str2uic(s);
1300}
1301
1302unsigned int strl2ui(const char *s, int len)
1303{
1304 return __strl2ui(s, len);
1305}
1306
1307unsigned int strl2uic(const char *s, int len)
1308{
1309 return __strl2uic(s, len);
1310}
1311
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001312unsigned int read_uint(const char **s, const char *end)
1313{
1314 return __read_uint(s, end);
1315}
1316
Willy Tarreau6911fa42007-03-04 18:06:08 +01001317/* This one is 7 times faster than strtol() on athlon with checks.
1318 * It returns the value of the number composed of all valid digits read,
1319 * and can process negative numbers too.
1320 */
1321int strl2ic(const char *s, int len)
1322{
1323 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001324 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001325
1326 if (len > 0) {
1327 if (*s != '-') {
1328 /* positive number */
1329 while (len-- > 0) {
1330 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001331 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001332 if (j > 9)
1333 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001334 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001335 }
1336 } else {
1337 /* negative number */
1338 s++;
1339 while (--len > 0) {
1340 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001341 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001342 if (j > 9)
1343 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02001344 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01001345 }
1346 }
1347 }
1348 return i;
1349}
1350
1351
1352/* This function reads exactly <len> chars from <s> and converts them to a
1353 * signed integer which it stores into <ret>. It accurately detects any error
1354 * (truncated string, invalid chars, overflows). It is meant to be used in
1355 * applications designed for hostile environments. It returns zero when the
1356 * number has successfully been converted, non-zero otherwise. When an error
1357 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
1358 * faster than strtol().
1359 */
1360int strl2irc(const char *s, int len, int *ret)
1361{
1362 int i = 0;
1363 int j;
1364
1365 if (!len)
1366 return 1;
1367
1368 if (*s != '-') {
1369 /* positive number */
1370 while (len-- > 0) {
1371 j = (*s++) - '0';
1372 if (j > 9) return 1; /* invalid char */
1373 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
1374 i = i * 10;
1375 if (i + j < i) return 1; /* check for addition overflow */
1376 i = i + j;
1377 }
1378 } else {
1379 /* negative number */
1380 s++;
1381 while (--len > 0) {
1382 j = (*s++) - '0';
1383 if (j > 9) return 1; /* invalid char */
1384 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
1385 i = i * 10;
1386 if (i - j > i) return 1; /* check for subtract overflow */
1387 i = i - j;
1388 }
1389 }
1390 *ret = i;
1391 return 0;
1392}
1393
1394
1395/* This function reads exactly <len> chars from <s> and converts them to a
1396 * signed integer which it stores into <ret>. It accurately detects any error
1397 * (truncated string, invalid chars, overflows). It is meant to be used in
1398 * applications designed for hostile environments. It returns zero when the
1399 * number has successfully been converted, non-zero otherwise. When an error
1400 * is returned, the <ret> value is left untouched. It is about 3 times slower
1401 * than str2irc().
1402 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01001403
1404int strl2llrc(const char *s, int len, long long *ret)
1405{
1406 long long 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 > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
1418 i = i * 10LL;
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 < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
1429 i = i * 10LL;
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
Thierry FOURNIER511e9472014-01-23 17:40:34 +01001438/* This function is used with pat_parse_dotted_ver(). It converts a string
1439 * composed by two number separated by a dot. Each part must contain in 16 bits
1440 * because internally they will be represented as a 32-bit quantity stored in
1441 * a 64-bit integer. It returns zero when the number has successfully been
1442 * converted, non-zero otherwise. When an error is returned, the <ret> value
1443 * is left untouched.
1444 *
1445 * "1.3" -> 0x0000000000010003
1446 * "65535.65535" -> 0x00000000ffffffff
1447 */
1448int strl2llrc_dotted(const char *text, int len, long long *ret)
1449{
1450 const char *end = &text[len];
1451 const char *p;
1452 long long major, minor;
1453
1454 /* Look for dot. */
1455 for (p = text; p < end; p++)
1456 if (*p == '.')
1457 break;
1458
1459 /* Convert major. */
1460 if (strl2llrc(text, p - text, &major) != 0)
1461 return 1;
1462
1463 /* Check major. */
1464 if (major >= 65536)
1465 return 1;
1466
1467 /* Convert minor. */
1468 minor = 0;
1469 if (p < end)
1470 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
1471 return 1;
1472
1473 /* Check minor. */
1474 if (minor >= 65536)
1475 return 1;
1476
1477 /* Compose value. */
1478 *ret = (major << 16) | (minor & 0xffff);
1479 return 0;
1480}
1481
Willy Tarreaua0d37b62007-12-02 22:00:35 +01001482/* This function parses a time value optionally followed by a unit suffix among
1483 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
1484 * expected by the caller. The computation does its best to avoid overflows.
1485 * The value is returned in <ret> if everything is fine, and a NULL is returned
1486 * by the function. In case of error, a pointer to the error is returned and
1487 * <ret> is left untouched. Values are automatically rounded up when needed.
1488 */
1489const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
1490{
1491 unsigned imult, idiv;
1492 unsigned omult, odiv;
1493 unsigned value;
1494
1495 omult = odiv = 1;
1496
1497 switch (unit_flags & TIME_UNIT_MASK) {
1498 case TIME_UNIT_US: omult = 1000000; break;
1499 case TIME_UNIT_MS: omult = 1000; break;
1500 case TIME_UNIT_S: break;
1501 case TIME_UNIT_MIN: odiv = 60; break;
1502 case TIME_UNIT_HOUR: odiv = 3600; break;
1503 case TIME_UNIT_DAY: odiv = 86400; break;
1504 default: break;
1505 }
1506
1507 value = 0;
1508
1509 while (1) {
1510 unsigned int j;
1511
1512 j = *text - '0';
1513 if (j > 9)
1514 break;
1515 text++;
1516 value *= 10;
1517 value += j;
1518 }
1519
1520 imult = idiv = 1;
1521 switch (*text) {
1522 case '\0': /* no unit = default unit */
1523 imult = omult = idiv = odiv = 1;
1524 break;
1525 case 's': /* second = unscaled unit */
1526 break;
1527 case 'u': /* microsecond : "us" */
1528 if (text[1] == 's') {
1529 idiv = 1000000;
1530 text++;
1531 }
1532 break;
1533 case 'm': /* millisecond : "ms" or minute: "m" */
1534 if (text[1] == 's') {
1535 idiv = 1000;
1536 text++;
1537 } else
1538 imult = 60;
1539 break;
1540 case 'h': /* hour : "h" */
1541 imult = 3600;
1542 break;
1543 case 'd': /* day : "d" */
1544 imult = 86400;
1545 break;
1546 default:
1547 return text;
1548 break;
1549 }
1550
1551 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
1552 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
1553 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
1554 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
1555
1556 value = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
1557 *ret = value;
1558 return NULL;
1559}
Willy Tarreau6911fa42007-03-04 18:06:08 +01001560
Emeric Brun39132b22010-01-04 14:57:24 +01001561/* this function converts the string starting at <text> to an unsigned int
1562 * stored in <ret>. If an error is detected, the pointer to the unexpected
1563 * character is returned. If the conversio is succesful, NULL is returned.
1564 */
1565const char *parse_size_err(const char *text, unsigned *ret) {
1566 unsigned value = 0;
1567
1568 while (1) {
1569 unsigned int j;
1570
1571 j = *text - '0';
1572 if (j > 9)
1573 break;
1574 if (value > ~0U / 10)
1575 return text;
1576 value *= 10;
1577 if (value > (value + j))
1578 return text;
1579 value += j;
1580 text++;
1581 }
1582
1583 switch (*text) {
1584 case '\0':
1585 break;
1586 case 'K':
1587 case 'k':
1588 if (value > ~0U >> 10)
1589 return text;
1590 value = value << 10;
1591 break;
1592 case 'M':
1593 case 'm':
1594 if (value > ~0U >> 20)
1595 return text;
1596 value = value << 20;
1597 break;
1598 case 'G':
1599 case 'g':
1600 if (value > ~0U >> 30)
1601 return text;
1602 value = value << 30;
1603 break;
1604 default:
1605 return text;
1606 }
1607
1608 *ret = value;
1609 return NULL;
1610}
1611
Willy Tarreau126d4062013-12-03 17:50:47 +01001612/*
1613 * Parse binary string written in hexadecimal (source) and store the decoded
1614 * result into binstr and set binstrlen to the lengh of binstr. Memory for
1615 * binstr is allocated by the function. In case of error, returns 0 with an
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001616 * error message in err. In succes case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01001617 */
1618int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
1619{
1620 int len;
1621 const char *p = source;
1622 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001623 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01001624
1625 len = strlen(source);
1626 if (len % 2) {
1627 memprintf(err, "an even number of hex digit is expected");
1628 return 0;
1629 }
1630
1631 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001632
Willy Tarreau126d4062013-12-03 17:50:47 +01001633 if (!*binstr) {
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001634 *binstr = calloc(len, sizeof(char));
1635 if (!*binstr) {
1636 memprintf(err, "out of memory while loading string pattern");
1637 return 0;
1638 }
1639 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001640 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001641 else {
1642 if (*binstrlen < len) {
1643 memprintf(err, "no space avalaible in the buffer. expect %d, provides %d",
1644 len, *binstrlen);
1645 return 0;
1646 }
1647 alloc = 0;
1648 }
1649 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01001650
1651 i = j = 0;
1652 while (j < len) {
1653 if (!ishex(p[i++]))
1654 goto bad_input;
1655 if (!ishex(p[i++]))
1656 goto bad_input;
1657 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
1658 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01001659 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01001660
1661bad_input:
1662 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Thierry FOURNIER9645d422013-12-06 19:59:28 +01001663 if (alloc)
1664 free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01001665 return 0;
1666}
1667
Willy Tarreau946ba592009-05-10 15:41:18 +02001668/* copies at most <n> characters from <src> and always terminates with '\0' */
1669char *my_strndup(const char *src, int n)
1670{
1671 int len = 0;
1672 char *ret;
1673
1674 while (len < n && src[len])
1675 len++;
1676
1677 ret = (char *)malloc(len + 1);
1678 if (!ret)
1679 return ret;
1680 memcpy(ret, src, len);
1681 ret[len] = '\0';
1682 return ret;
1683}
1684
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02001685/*
1686 * search needle in haystack
1687 * returns the pointer if found, returns NULL otherwise
1688 */
1689const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
1690{
1691 const void *c = NULL;
1692 unsigned char f;
1693
1694 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
1695 return NULL;
1696
1697 f = *(char *)needle;
1698 c = haystack;
1699 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
1700 if ((haystacklen - (c - haystack)) < needlelen)
1701 return NULL;
1702
1703 if (memcmp(c, needle, needlelen) == 0)
1704 return c;
1705 ++c;
1706 }
1707 return NULL;
1708}
1709
Willy Tarreau482b00d2009-10-04 22:48:42 +02001710/* This function returns the first unused key greater than or equal to <key> in
1711 * ID tree <root>. Zero is returned if no place is found.
1712 */
1713unsigned int get_next_id(struct eb_root *root, unsigned int key)
1714{
1715 struct eb32_node *used;
1716
1717 do {
1718 used = eb32_lookup_ge(root, key);
1719 if (!used || used->key > key)
1720 return key; /* key is available */
1721 key++;
1722 } while (key);
1723 return key;
1724}
1725
Willy Tarreau348238b2010-01-18 15:05:57 +01001726/* This function compares a sample word possibly followed by blanks to another
1727 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
1728 * otherwise zero. This intends to be used when checking HTTP headers for some
1729 * values. Note that it validates a word followed only by blanks but does not
1730 * validate a word followed by blanks then other chars.
1731 */
1732int word_match(const char *sample, int slen, const char *word, int wlen)
1733{
1734 if (slen < wlen)
1735 return 0;
1736
1737 while (wlen) {
1738 char c = *sample ^ *word;
1739 if (c && c != ('A' ^ 'a'))
1740 return 0;
1741 sample++;
1742 word++;
1743 slen--;
1744 wlen--;
1745 }
1746
1747 while (slen) {
1748 if (*sample != ' ' && *sample != '\t')
1749 return 0;
1750 sample++;
1751 slen--;
1752 }
1753 return 1;
1754}
Willy Tarreau482b00d2009-10-04 22:48:42 +02001755
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001756/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
1757 * is particularly fast because it avoids expensive operations such as
1758 * multiplies, which are optimized away at the end. It requires a properly
1759 * formated address though (3 points).
1760 */
1761unsigned int inetaddr_host(const char *text)
1762{
1763 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1764 register unsigned int dig100, dig10, dig1;
1765 int s;
1766 const char *p, *d;
1767
1768 dig1 = dig10 = dig100 = ascii_zero;
1769 s = 24;
1770
1771 p = text;
1772 while (1) {
1773 if (((unsigned)(*p - '0')) <= 9) {
1774 p++;
1775 continue;
1776 }
1777
1778 /* here, we have a complete byte between <text> and <p> (exclusive) */
1779 if (p == text)
1780 goto end;
1781
1782 d = p - 1;
1783 dig1 |= (unsigned int)(*d << s);
1784 if (d == text)
1785 goto end;
1786
1787 d--;
1788 dig10 |= (unsigned int)(*d << s);
1789 if (d == text)
1790 goto end;
1791
1792 d--;
1793 dig100 |= (unsigned int)(*d << s);
1794 end:
1795 if (!s || *p != '.')
1796 break;
1797
1798 s -= 8;
1799 text = ++p;
1800 }
1801
1802 dig100 -= ascii_zero;
1803 dig10 -= ascii_zero;
1804 dig1 -= ascii_zero;
1805 return ((dig100 * 10) + dig10) * 10 + dig1;
1806}
1807
1808/*
1809 * Idem except the first unparsed character has to be passed in <stop>.
1810 */
1811unsigned int inetaddr_host_lim(const char *text, const char *stop)
1812{
1813 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1814 register unsigned int dig100, dig10, dig1;
1815 int s;
1816 const char *p, *d;
1817
1818 dig1 = dig10 = dig100 = ascii_zero;
1819 s = 24;
1820
1821 p = text;
1822 while (1) {
1823 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1824 p++;
1825 continue;
1826 }
1827
1828 /* here, we have a complete byte between <text> and <p> (exclusive) */
1829 if (p == text)
1830 goto end;
1831
1832 d = p - 1;
1833 dig1 |= (unsigned int)(*d << s);
1834 if (d == text)
1835 goto end;
1836
1837 d--;
1838 dig10 |= (unsigned int)(*d << s);
1839 if (d == text)
1840 goto end;
1841
1842 d--;
1843 dig100 |= (unsigned int)(*d << s);
1844 end:
1845 if (!s || p == stop || *p != '.')
1846 break;
1847
1848 s -= 8;
1849 text = ++p;
1850 }
1851
1852 dig100 -= ascii_zero;
1853 dig10 -= ascii_zero;
1854 dig1 -= ascii_zero;
1855 return ((dig100 * 10) + dig10) * 10 + dig1;
1856}
1857
1858/*
1859 * Idem except the pointer to first unparsed byte is returned into <ret> which
1860 * must not be NULL.
1861 */
Willy Tarreau74172752010-10-15 23:21:42 +02001862unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001863{
1864 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
1865 register unsigned int dig100, dig10, dig1;
1866 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02001867 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02001868
1869 dig1 = dig10 = dig100 = ascii_zero;
1870 s = 24;
1871
1872 p = text;
1873 while (1) {
1874 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
1875 p++;
1876 continue;
1877 }
1878
1879 /* here, we have a complete byte between <text> and <p> (exclusive) */
1880 if (p == text)
1881 goto end;
1882
1883 d = p - 1;
1884 dig1 |= (unsigned int)(*d << s);
1885 if (d == text)
1886 goto end;
1887
1888 d--;
1889 dig10 |= (unsigned int)(*d << s);
1890 if (d == text)
1891 goto end;
1892
1893 d--;
1894 dig100 |= (unsigned int)(*d << s);
1895 end:
1896 if (!s || p == stop || *p != '.')
1897 break;
1898
1899 s -= 8;
1900 text = ++p;
1901 }
1902
1903 *ret = p;
1904 dig100 -= ascii_zero;
1905 dig10 -= ascii_zero;
1906 dig1 -= ascii_zero;
1907 return ((dig100 * 10) + dig10) * 10 + dig1;
1908}
1909
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001910/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
1911 * or the number of chars read in case of success. Maybe this could be replaced
1912 * by one of the functions above. Also, apparently this function does not support
1913 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01001914 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02001915 */
1916int buf2ip(const char *buf, size_t len, struct in_addr *dst)
1917{
1918 const char *addr;
1919 int saw_digit, octets, ch;
1920 u_char tmp[4], *tp;
1921 const char *cp = buf;
1922
1923 saw_digit = 0;
1924 octets = 0;
1925 *(tp = tmp) = 0;
1926
1927 for (addr = buf; addr - buf < len; addr++) {
1928 unsigned char digit = (ch = *addr) - '0';
1929
1930 if (digit > 9 && ch != '.')
1931 break;
1932
1933 if (digit <= 9) {
1934 u_int new = *tp * 10 + digit;
1935
1936 if (new > 255)
1937 return 0;
1938
1939 *tp = new;
1940
1941 if (!saw_digit) {
1942 if (++octets > 4)
1943 return 0;
1944 saw_digit = 1;
1945 }
1946 } else if (ch == '.' && saw_digit) {
1947 if (octets == 4)
1948 return 0;
1949
1950 *++tp = 0;
1951 saw_digit = 0;
1952 } else
1953 return 0;
1954 }
1955
1956 if (octets < 4)
1957 return 0;
1958
1959 memcpy(&dst->s_addr, tmp, 4);
1960 return addr - cp;
1961}
1962
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001963/* This function converts the string in <buf> of the len <len> to
1964 * struct in6_addr <dst> which must be allocated by the caller.
1965 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01001966 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001967 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001968int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
1969{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001970 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01001971 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001972
Thierry FOURNIERcd659912013-12-11 12:33:54 +01001973 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001974 return 0;
1975
1976 memcpy(null_term_ip6, buf, len);
1977 null_term_ip6[len] = '\0';
1978
Willy Tarreau075415a2013-12-12 11:29:39 +01001979 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001980 return 0;
1981
Willy Tarreau075415a2013-12-12 11:29:39 +01001982 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01001983 return 1;
1984}
1985
Willy Tarreauacf95772010-06-14 19:09:21 +02001986/* To be used to quote config arg positions. Returns the short string at <ptr>
1987 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
1988 * if ptr is NULL or empty. The string is locally allocated.
1989 */
1990const char *quote_arg(const char *ptr)
1991{
1992 static char val[32];
1993 int i;
1994
1995 if (!ptr || !*ptr)
1996 return "end of line";
1997 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01001998 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02001999 val[i] = *ptr++;
2000 val[i++] = '\'';
2001 val[i] = '\0';
2002 return val;
2003}
2004
Willy Tarreau5b180202010-07-18 10:40:48 +02002005/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2006int get_std_op(const char *str)
2007{
2008 int ret = -1;
2009
2010 if (*str == 'e' && str[1] == 'q')
2011 ret = STD_OP_EQ;
2012 else if (*str == 'n' && str[1] == 'e')
2013 ret = STD_OP_NE;
2014 else if (*str == 'l') {
2015 if (str[1] == 'e') ret = STD_OP_LE;
2016 else if (str[1] == 't') ret = STD_OP_LT;
2017 }
2018 else if (*str == 'g') {
2019 if (str[1] == 'e') ret = STD_OP_GE;
2020 else if (str[1] == 't') ret = STD_OP_GT;
2021 }
2022
2023 if (ret == -1 || str[2] != '\0')
2024 return -1;
2025 return ret;
2026}
2027
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002028/* hash a 32-bit integer to another 32-bit integer */
2029unsigned int full_hash(unsigned int a)
2030{
2031 return __full_hash(a);
2032}
2033
David du Colombier4f92d322011-03-24 11:09:31 +01002034/* Return non-zero if IPv4 address is part of the network,
2035 * otherwise zero.
2036 */
2037int in_net_ipv4(struct in_addr *addr, struct in_addr *mask, struct in_addr *net)
2038{
2039 return((addr->s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
2040}
2041
2042/* Return non-zero if IPv6 address is part of the network,
2043 * otherwise zero.
2044 */
2045int in_net_ipv6(struct in6_addr *addr, struct in6_addr *mask, struct in6_addr *net)
2046{
2047 int i;
2048
2049 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
2050 if (((((int *)addr)[i] & ((int *)mask)[i])) !=
2051 (((int *)net)[i] & ((int *)mask)[i]))
2052 return 0;
2053 return 1;
2054}
2055
2056/* RFC 4291 prefix */
2057const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2058 0x00, 0x00, 0x00, 0x00,
2059 0x00, 0x00, 0xFF, 0xFF };
2060
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002061/* Map IPv4 adress on IPv6 address, as specified in RFC 3513.
2062 * Input and output may overlap.
2063 */
David du Colombier4f92d322011-03-24 11:09:31 +01002064void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
2065{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002066 struct in_addr tmp_addr;
2067
2068 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01002069 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01002070 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01002071}
2072
2073/* Map IPv6 adress on IPv4 address, as specified in RFC 3513.
2074 * Return true if conversion is possible and false otherwise.
2075 */
2076int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
2077{
2078 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
2079 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
2080 sizeof(struct in_addr));
2081 return 1;
2082 }
2083
2084 return 0;
2085}
2086
William Lallemand421f5b52012-02-06 18:15:57 +01002087char *human_time(int t, short hz_div) {
2088 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
2089 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02002090 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01002091 int cnt=2; // print two numbers
2092
2093 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002094 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01002095 return rv;
2096 }
2097
2098 if (unlikely(hz_div > 1))
2099 t /= hz_div;
2100
2101 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002102 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01002103 cnt--;
2104 }
2105
2106 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002107 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01002108 cnt--;
2109 }
2110
2111 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02002112 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01002113 cnt--;
2114 }
2115
2116 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02002117 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01002118
2119 return rv;
2120}
2121
2122const char *monthname[12] = {
2123 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
2124 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
2125};
2126
2127/* date2str_log: write a date in the format :
2128 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
2129 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
2130 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
2131 *
2132 * without using sprintf. return a pointer to the last char written (\0) or
2133 * NULL if there isn't enough space.
2134 */
2135char *date2str_log(char *dst, struct tm *tm, struct timeval *date, size_t size)
2136{
2137
2138 if (size < 25) /* the size is fixed: 24 chars + \0 */
2139 return NULL;
2140
2141 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2142 *dst++ = '/';
2143 memcpy(dst, monthname[tm->tm_mon], 3); // month
2144 dst += 3;
2145 *dst++ = '/';
2146 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2147 *dst++ = ':';
2148 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2149 *dst++ = ':';
2150 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2151 *dst++ = ':';
2152 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2153 *dst++ = '.';
2154 utoa_pad((unsigned int)(date->tv_usec/1000), dst, 4); // millisecondes
2155 dst += 3; // only the 3 first digits
2156 *dst = '\0';
2157
2158 return dst;
2159}
2160
2161/* gmt2str_log: write a date in the format :
2162 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
2163 * return a pointer to the last char written (\0) or
2164 * NULL if there isn't enough space.
2165 */
2166char *gmt2str_log(char *dst, struct tm *tm, size_t size)
2167{
Yuxans Yao4e25b012012-10-19 10:36:09 +08002168 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01002169 return NULL;
2170
2171 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2172 *dst++ = '/';
2173 memcpy(dst, monthname[tm->tm_mon], 3); // month
2174 dst += 3;
2175 *dst++ = '/';
2176 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2177 *dst++ = ':';
2178 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2179 *dst++ = ':';
2180 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2181 *dst++ = ':';
2182 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2183 *dst++ = ' ';
2184 *dst++ = '+';
2185 *dst++ = '0';
2186 *dst++ = '0';
2187 *dst++ = '0';
2188 *dst++ = '0';
2189 *dst = '\0';
2190
2191 return dst;
2192}
2193
Yuxans Yao4e25b012012-10-19 10:36:09 +08002194/* localdate2str_log: write a date in the format :
2195 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
2196 * * return a pointer to the last char written (\0) or
2197 * * NULL if there isn't enough space.
2198 */
2199char *localdate2str_log(char *dst, struct tm *tm, size_t size)
2200{
2201 if (size < 27) /* the size is fixed: 26 chars + \0 */
2202 return NULL;
2203
2204 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
2205 *dst++ = '/';
2206 memcpy(dst, monthname[tm->tm_mon], 3); // month
2207 dst += 3;
2208 *dst++ = '/';
2209 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
2210 *dst++ = ':';
2211 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
2212 *dst++ = ':';
2213 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
2214 *dst++ = ':';
2215 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
2216 *dst++ = ' ';
2217 memcpy(dst, localtimezone, 5); // timezone
2218 dst += 5;
2219 *dst = '\0';
2220
2221 return dst;
2222}
2223
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002224/* Dynamically allocates a string of the proper length to hold the formatted
2225 * output. NULL is returned on error. The caller is responsible for freeing the
2226 * memory area using free(). The resulting string is returned in <out> if the
2227 * pointer is not NULL. A previous version of <out> might be used to build the
2228 * new string, and it will be freed before returning if it is not NULL, which
2229 * makes it possible to build complex strings from iterative calls without
2230 * having to care about freeing intermediate values, as in the example below :
2231 *
2232 * memprintf(&err, "invalid argument: '%s'", arg);
2233 * ...
2234 * memprintf(&err, "parser said : <%s>\n", *err);
2235 * ...
2236 * free(*err);
2237 *
2238 * This means that <err> must be initialized to NULL before first invocation.
2239 * The return value also holds the allocated string, which eases error checking
2240 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002241 * passed instead and it will be ignored. The returned message will then also
2242 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002243 *
2244 * It is also convenient to use it without any free except the last one :
2245 * err = NULL;
2246 * if (!fct1(err)) report(*err);
2247 * if (!fct2(err)) report(*err);
2248 * if (!fct3(err)) report(*err);
2249 * free(*err);
2250 */
2251char *memprintf(char **out, const char *format, ...)
2252{
2253 va_list args;
2254 char *ret = NULL;
2255 int allocated = 0;
2256 int needed = 0;
2257
Willy Tarreaueb6cead2012-09-20 19:43:14 +02002258 if (!out)
2259 return NULL;
2260
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002261 do {
2262 /* vsnprintf() will return the required length even when the
2263 * target buffer is NULL. We do this in a loop just in case
2264 * intermediate evaluations get wrong.
2265 */
2266 va_start(args, format);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002267 needed = vsnprintf(ret, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002268 va_end(args);
2269
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002270 if (needed < allocated) {
2271 /* Note: on Solaris 8, the first iteration always
2272 * returns -1 if allocated is zero, so we force a
2273 * retry.
2274 */
2275 if (!allocated)
2276 needed = 0;
2277 else
2278 break;
2279 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002280
Willy Tarreau1b2fed62013-04-01 22:48:54 +02002281 allocated = needed + 1;
Willy Tarreau9a7bea52012-04-27 11:16:50 +02002282 ret = realloc(ret, allocated);
2283 } while (ret);
2284
2285 if (needed < 0) {
2286 /* an error was encountered */
2287 free(ret);
2288 ret = NULL;
2289 }
2290
2291 if (out) {
2292 free(*out);
2293 *out = ret;
2294 }
2295
2296 return ret;
2297}
William Lallemand421f5b52012-02-06 18:15:57 +01002298
Willy Tarreau21c705b2012-09-14 11:40:36 +02002299/* Used to add <level> spaces before each line of <out>, unless there is only one line.
2300 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02002301 * freed by the caller. It also supports being passed a NULL which results in the same
2302 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02002303 * Example of use :
2304 * parse(cmd, &err); (callee: memprintf(&err, ...))
2305 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
2306 * free(err);
2307 */
2308char *indent_msg(char **out, int level)
2309{
2310 char *ret, *in, *p;
2311 int needed = 0;
2312 int lf = 0;
2313 int lastlf = 0;
2314 int len;
2315
Willy Tarreau70eec382012-10-10 08:56:47 +02002316 if (!out || !*out)
2317 return NULL;
2318
Willy Tarreau21c705b2012-09-14 11:40:36 +02002319 in = *out - 1;
2320 while ((in = strchr(in + 1, '\n')) != NULL) {
2321 lastlf = in - *out;
2322 lf++;
2323 }
2324
2325 if (!lf) /* single line, no LF, return it as-is */
2326 return *out;
2327
2328 len = strlen(*out);
2329
2330 if (lf == 1 && lastlf == len - 1) {
2331 /* single line, LF at end, strip it and return as-is */
2332 (*out)[lastlf] = 0;
2333 return *out;
2334 }
2335
2336 /* OK now we have at least one LF, we need to process the whole string
2337 * as a multi-line string. What we'll do :
2338 * - prefix with an LF if there is none
2339 * - add <level> spaces before each line
2340 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
2341 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
2342 */
2343
2344 needed = 1 + level * (lf + 1) + len + 1;
2345 p = ret = malloc(needed);
2346 in = *out;
2347
2348 /* skip initial LFs */
2349 while (*in == '\n')
2350 in++;
2351
2352 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
2353 while (*in) {
2354 *p++ = '\n';
2355 memset(p, ' ', level);
2356 p += level;
2357 do {
2358 *p++ = *in++;
2359 } while (*in && *in != '\n');
2360 if (*in)
2361 in++;
2362 }
2363 *p = 0;
2364
2365 free(*out);
2366 *out = ret;
2367
2368 return ret;
2369}
2370
Willy Tarreaudad36a32013-03-11 01:20:04 +01002371/* Convert occurrences of environment variables in the input string to their
2372 * corresponding value. A variable is identified as a series of alphanumeric
2373 * characters or underscores following a '$' sign. The <in> string must be
2374 * free()able. NULL returns NULL. The resulting string might be reallocated if
2375 * some expansion is made. Variable names may also be enclosed into braces if
2376 * needed (eg: to concatenate alphanum characters).
2377 */
2378char *env_expand(char *in)
2379{
2380 char *txt_beg;
2381 char *out;
2382 char *txt_end;
2383 char *var_beg;
2384 char *var_end;
2385 char *value;
2386 char *next;
2387 int out_len;
2388 int val_len;
2389
2390 if (!in)
2391 return in;
2392
2393 value = out = NULL;
2394 out_len = 0;
2395
2396 txt_beg = in;
2397 do {
2398 /* look for next '$' sign in <in> */
2399 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
2400
2401 if (!*txt_end && !out) /* end and no expansion performed */
2402 return in;
2403
2404 val_len = 0;
2405 next = txt_end;
2406 if (*txt_end == '$') {
2407 char save;
2408
2409 var_beg = txt_end + 1;
2410 if (*var_beg == '{')
2411 var_beg++;
2412
2413 var_end = var_beg;
2414 while (isalnum((int)(unsigned char)*var_end) || *var_end == '_') {
2415 var_end++;
2416 }
2417
2418 next = var_end;
2419 if (*var_end == '}' && (var_beg > txt_end + 1))
2420 next++;
2421
2422 /* get value of the variable name at this location */
2423 save = *var_end;
2424 *var_end = '\0';
2425 value = getenv(var_beg);
2426 *var_end = save;
2427 val_len = value ? strlen(value) : 0;
2428 }
2429
2430 out = realloc(out, out_len + (txt_end - txt_beg) + val_len + 1);
2431 if (txt_end > txt_beg) {
2432 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
2433 out_len += txt_end - txt_beg;
2434 }
2435 if (val_len) {
2436 memcpy(out + out_len, value, val_len);
2437 out_len += val_len;
2438 }
2439 out[out_len] = 0;
2440 txt_beg = next;
2441 } while (*txt_beg);
2442
2443 /* here we know that <out> was allocated and that we don't need <in> anymore */
2444 free(in);
2445 return out;
2446}
2447
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002448
2449/* same as strstr() but case-insensitive and with limit length */
2450const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
2451{
2452 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02002453 unsigned int slen, plen;
2454 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02002455
2456 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
2457 return NULL;
2458
2459 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
2460 return str1;
2461
2462 if (len_str1 < len_str2) // pattern is longer than string => search is not found
2463 return NULL;
2464
2465 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
2466 while (toupper(*start) != toupper(*str2)) {
2467 start++;
2468 slen--;
2469 tmp1++;
2470
2471 if (tmp1 >= len_str1)
2472 return NULL;
2473
2474 /* if pattern longer than string */
2475 if (slen < plen)
2476 return NULL;
2477 }
2478
2479 sptr = start;
2480 pptr = (char *)str2;
2481
2482 tmp2 = 0;
2483 while (toupper(*sptr) == toupper(*pptr)) {
2484 sptr++;
2485 pptr++;
2486 tmp2++;
2487
2488 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
2489 return start;
2490 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
2491 return NULL;
2492 }
2493 }
2494 return NULL;
2495}
2496
Willy Tarreaubaaee002006-06-26 02:48:02 +02002497/*
2498 * Local variables:
2499 * c-indent-level: 8
2500 * c-basic-offset: 8
2501 * End:
2502 */