blob: fdc91909a84ed9aebfdf86f310f0e8d96546e622 [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
Baruch Siache1651b22020-07-24 07:52:20 +030013#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010014#define _GNU_SOURCE
15#include <dlfcn.h>
16#include <link.h>
17#endif
18
Willy Tarreau2e74c3f2007-12-02 18:45:09 +010019#include <ctype.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020020#include <errno.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020021#include <netdb.h>
Willy Tarreau9a7bea52012-04-27 11:16:50 +020022#include <stdarg.h>
Willy Tarreaudd2f85e2012-09-02 22:34:23 +020023#include <stdio.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020024#include <stdlib.h>
25#include <string.h>
Thierry Fournier93127942016-01-20 18:49:45 +010026#include <time.h>
Willy Tarreau16e01562016-08-09 16:46:18 +020027#include <unistd.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010028#include <sys/socket.h>
Willy Tarreau37101052019-05-20 16:48:20 +020029#include <sys/stat.h>
30#include <sys/types.h>
Willy Tarreau127f9662007-12-06 00:53:51 +010031#include <sys/un.h>
Willy Tarreaubaaee002006-06-26 02:48:02 +020032#include <netinet/in.h>
33#include <arpa/inet.h>
34
Willy Tarreau30053062020-08-20 16:39:14 +020035#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
36#include <sys/auxv.h>
37#endif
38
Willy Tarreau48fbcae2020-06-03 18:09:46 +020039#include <import/eb32sctree.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020040#include <import/eb32tree.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020041
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020042#include <haproxy/api.h>
Willy Tarreauc13ed532020-06-02 10:22:45 +020043#include <haproxy/chunk.h>
Willy Tarreau7c18b542020-06-11 09:23:02 +020044#include <haproxy/dgram.h>
Willy Tarreaueb92deb2020-06-04 10:53:16 +020045#include <haproxy/dns.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020046#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020047#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020048#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020049#include <haproxy/namespace.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020050#include <haproxy/protocol.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010051#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020052#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020053#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020054#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020055#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010056
Thierry Fournier93127942016-01-20 18:49:45 +010057/* This macro returns false if the test __x is false. Many
58 * of the following parsing function must be abort the processing
59 * if it returns 0, so this macro is useful for writing light code.
60 */
61#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
62
Willy Tarreau56adcf22012-12-23 18:00:29 +010063/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020064 * 2^64-1 = 18446744073709551615 or
65 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020066 *
67 * The HTML version needs room for adding the 25 characters
68 * '<span class="rls"></span>' around digits at positions 3N+1 in order
69 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020070 */
Christopher Faulet99bca652017-11-14 16:47:26 +010071THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
72THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020073
Willy Tarreau588297f2014-06-16 15:16:40 +020074/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
75 * to quote strings larger than a max configuration line.
76 */
Christopher Faulet99bca652017-11-14 16:47:26 +010077THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
78THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020079
Willy Tarreaubaaee002006-06-26 02:48:02 +020080/*
William Lallemande7340ec2012-01-24 11:15:39 +010081 * unsigned long long ASCII representation
82 *
83 * return the last char '\0' or NULL if no enough
84 * space in dst
85 */
86char *ulltoa(unsigned long long n, char *dst, size_t size)
87{
88 int i = 0;
89 char *res;
90
91 switch(n) {
92 case 1ULL ... 9ULL:
93 i = 0;
94 break;
95
96 case 10ULL ... 99ULL:
97 i = 1;
98 break;
99
100 case 100ULL ... 999ULL:
101 i = 2;
102 break;
103
104 case 1000ULL ... 9999ULL:
105 i = 3;
106 break;
107
108 case 10000ULL ... 99999ULL:
109 i = 4;
110 break;
111
112 case 100000ULL ... 999999ULL:
113 i = 5;
114 break;
115
116 case 1000000ULL ... 9999999ULL:
117 i = 6;
118 break;
119
120 case 10000000ULL ... 99999999ULL:
121 i = 7;
122 break;
123
124 case 100000000ULL ... 999999999ULL:
125 i = 8;
126 break;
127
128 case 1000000000ULL ... 9999999999ULL:
129 i = 9;
130 break;
131
132 case 10000000000ULL ... 99999999999ULL:
133 i = 10;
134 break;
135
136 case 100000000000ULL ... 999999999999ULL:
137 i = 11;
138 break;
139
140 case 1000000000000ULL ... 9999999999999ULL:
141 i = 12;
142 break;
143
144 case 10000000000000ULL ... 99999999999999ULL:
145 i = 13;
146 break;
147
148 case 100000000000000ULL ... 999999999999999ULL:
149 i = 14;
150 break;
151
152 case 1000000000000000ULL ... 9999999999999999ULL:
153 i = 15;
154 break;
155
156 case 10000000000000000ULL ... 99999999999999999ULL:
157 i = 16;
158 break;
159
160 case 100000000000000000ULL ... 999999999999999999ULL:
161 i = 17;
162 break;
163
164 case 1000000000000000000ULL ... 9999999999999999999ULL:
165 i = 18;
166 break;
167
168 case 10000000000000000000ULL ... ULLONG_MAX:
169 i = 19;
170 break;
171 }
172 if (i + 2 > size) // (i + 1) + '\0'
173 return NULL; // too long
174 res = dst + i + 1;
175 *res = '\0';
176 for (; i >= 0; i--) {
177 dst[i] = n % 10ULL + '0';
178 n /= 10ULL;
179 }
180 return res;
181}
182
183/*
184 * unsigned long ASCII representation
185 *
186 * return the last char '\0' or NULL if no enough
187 * space in dst
188 */
189char *ultoa_o(unsigned long n, char *dst, size_t size)
190{
191 int i = 0;
192 char *res;
193
194 switch (n) {
195 case 0U ... 9UL:
196 i = 0;
197 break;
198
199 case 10U ... 99UL:
200 i = 1;
201 break;
202
203 case 100U ... 999UL:
204 i = 2;
205 break;
206
207 case 1000U ... 9999UL:
208 i = 3;
209 break;
210
211 case 10000U ... 99999UL:
212 i = 4;
213 break;
214
215 case 100000U ... 999999UL:
216 i = 5;
217 break;
218
219 case 1000000U ... 9999999UL:
220 i = 6;
221 break;
222
223 case 10000000U ... 99999999UL:
224 i = 7;
225 break;
226
227 case 100000000U ... 999999999UL:
228 i = 8;
229 break;
230#if __WORDSIZE == 32
231
232 case 1000000000ULL ... ULONG_MAX:
233 i = 9;
234 break;
235
236#elif __WORDSIZE == 64
237
238 case 1000000000ULL ... 9999999999UL:
239 i = 9;
240 break;
241
242 case 10000000000ULL ... 99999999999UL:
243 i = 10;
244 break;
245
246 case 100000000000ULL ... 999999999999UL:
247 i = 11;
248 break;
249
250 case 1000000000000ULL ... 9999999999999UL:
251 i = 12;
252 break;
253
254 case 10000000000000ULL ... 99999999999999UL:
255 i = 13;
256 break;
257
258 case 100000000000000ULL ... 999999999999999UL:
259 i = 14;
260 break;
261
262 case 1000000000000000ULL ... 9999999999999999UL:
263 i = 15;
264 break;
265
266 case 10000000000000000ULL ... 99999999999999999UL:
267 i = 16;
268 break;
269
270 case 100000000000000000ULL ... 999999999999999999UL:
271 i = 17;
272 break;
273
274 case 1000000000000000000ULL ... 9999999999999999999UL:
275 i = 18;
276 break;
277
278 case 10000000000000000000ULL ... ULONG_MAX:
279 i = 19;
280 break;
281
282#endif
283 }
284 if (i + 2 > size) // (i + 1) + '\0'
285 return NULL; // too long
286 res = dst + i + 1;
287 *res = '\0';
288 for (; i >= 0; i--) {
289 dst[i] = n % 10U + '0';
290 n /= 10U;
291 }
292 return res;
293}
294
295/*
296 * signed long ASCII representation
297 *
298 * return the last char '\0' or NULL if no enough
299 * space in dst
300 */
301char *ltoa_o(long int n, char *dst, size_t size)
302{
303 char *pos = dst;
304
305 if (n < 0) {
306 if (size < 3)
307 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
308 *pos = '-';
309 pos++;
310 dst = ultoa_o(-n, pos, size - 1);
311 } else {
312 dst = ultoa_o(n, dst, size);
313 }
314 return dst;
315}
316
317/*
318 * signed long long ASCII representation
319 *
320 * return the last char '\0' or NULL if no enough
321 * space in dst
322 */
323char *lltoa(long long n, char *dst, size_t size)
324{
325 char *pos = dst;
326
327 if (n < 0) {
328 if (size < 3)
329 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
330 *pos = '-';
331 pos++;
332 dst = ulltoa(-n, pos, size - 1);
333 } else {
334 dst = ulltoa(n, dst, size);
335 }
336 return dst;
337}
338
339/*
340 * write a ascii representation of a unsigned into dst,
341 * return a pointer to the last character
342 * Pad the ascii representation with '0', using size.
343 */
344char *utoa_pad(unsigned int n, char *dst, size_t size)
345{
346 int i = 0;
347 char *ret;
348
349 switch(n) {
350 case 0U ... 9U:
351 i = 0;
352 break;
353
354 case 10U ... 99U:
355 i = 1;
356 break;
357
358 case 100U ... 999U:
359 i = 2;
360 break;
361
362 case 1000U ... 9999U:
363 i = 3;
364 break;
365
366 case 10000U ... 99999U:
367 i = 4;
368 break;
369
370 case 100000U ... 999999U:
371 i = 5;
372 break;
373
374 case 1000000U ... 9999999U:
375 i = 6;
376 break;
377
378 case 10000000U ... 99999999U:
379 i = 7;
380 break;
381
382 case 100000000U ... 999999999U:
383 i = 8;
384 break;
385
386 case 1000000000U ... 4294967295U:
387 i = 9;
388 break;
389 }
390 if (i + 2 > size) // (i + 1) + '\0'
391 return NULL; // too long
392 if (i < size)
393 i = size - 2; // padding - '\0'
394
395 ret = dst + i + 1;
396 *ret = '\0';
397 for (; i >= 0; i--) {
398 dst[i] = n % 10U + '0';
399 n /= 10U;
400 }
401 return ret;
402}
403
404/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200405 * copies at most <size-1> chars from <src> to <dst>. Last char is always
406 * set to 0, unless <size> is 0. The number of chars copied is returned
407 * (excluding the terminating zero).
408 * This code has been optimized for size and speed : on x86, it's 45 bytes
409 * long, uses only registers, and consumes only 4 cycles per char.
410 */
411int strlcpy2(char *dst, const char *src, int size)
412{
413 char *orig = dst;
414 if (size) {
415 while (--size && (*dst = *src)) {
416 src++; dst++;
417 }
418 *dst = 0;
419 }
420 return dst - orig;
421}
422
423/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200424 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200425 * the ascii representation for number 'n' in decimal.
426 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100427char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200428{
429 char *pos;
430
Willy Tarreau72d759c2007-10-25 12:14:10 +0200431 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200432 *pos-- = '\0';
433
434 do {
435 *pos-- = '0' + n % 10;
436 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200437 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200438 return pos + 1;
439}
440
Willy Tarreau91092e52007-10-25 16:58:42 +0200441/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200442 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200443 * the ascii representation for number 'n' in decimal.
444 */
445char *lltoa_r(long long int in, char *buffer, int size)
446{
447 char *pos;
448 int neg = 0;
449 unsigned long long int n;
450
451 pos = buffer + size - 1;
452 *pos-- = '\0';
453
454 if (in < 0) {
455 neg = 1;
456 n = -in;
457 }
458 else
459 n = in;
460
461 do {
462 *pos-- = '0' + n % 10;
463 n /= 10;
464 } while (n && pos >= buffer);
465 if (neg && pos > buffer)
466 *pos-- = '-';
467 return pos + 1;
468}
469
470/*
471 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200472 * the ascii representation for signed number 'n' in decimal.
473 */
474char *sltoa_r(long n, char *buffer, int size)
475{
476 char *pos;
477
478 if (n >= 0)
479 return ultoa_r(n, buffer, size);
480
481 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
482 *pos = '-';
483 return pos;
484}
485
486/*
487 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200488 * the ascii representation for number 'n' in decimal, formatted for
489 * HTML output with tags to create visual grouping by 3 digits. The
490 * output needs to support at least 171 characters.
491 */
492const char *ulltoh_r(unsigned long long n, char *buffer, int size)
493{
494 char *start;
495 int digit = 0;
496
497 start = buffer + size;
498 *--start = '\0';
499
500 do {
501 if (digit == 3 && start >= buffer + 7)
502 memcpy(start -= 7, "</span>", 7);
503
504 if (start >= buffer + 1) {
505 *--start = '0' + n % 10;
506 n /= 10;
507 }
508
509 if (digit == 3 && start >= buffer + 18)
510 memcpy(start -= 18, "<span class=\"rls\">", 18);
511
512 if (digit++ == 3)
513 digit = 1;
514 } while (n && start > buffer);
515 return start;
516}
517
518/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200519 * This function simply returns a locally allocated string containing the ascii
520 * representation for number 'n' in decimal, unless n is 0 in which case it
521 * returns the alternate string (or an empty string if the alternate string is
522 * NULL). It use is intended for limits reported in reports, where it's
523 * desirable not to display anything if there is no limit. Warning! it shares
524 * the same vector as ultoa_r().
525 */
526const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
527{
528 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
529}
530
Willy Tarreau588297f2014-06-16 15:16:40 +0200531/* returns a locally allocated string containing the quoted encoding of the
532 * input string. The output may be truncated to QSTR_SIZE chars, but it is
533 * guaranteed that the string will always be properly terminated. Quotes are
534 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
535 * always be at least 4 chars.
536 */
537const char *qstr(const char *str)
538{
539 char *ret = quoted_str[quoted_idx];
540 char *p, *end;
541
542 if (++quoted_idx >= NB_QSTR)
543 quoted_idx = 0;
544
545 p = ret;
546 end = ret + QSTR_SIZE;
547
548 *p++ = '"';
549
550 /* always keep 3 chars to support passing "" and the ending " */
551 while (*str && p < end - 3) {
552 if (*str == '"') {
553 *p++ = '"';
554 *p++ = '"';
555 }
556 else
557 *p++ = *str;
558 str++;
559 }
560 *p++ = '"';
561 return ret;
562}
563
Robert Tsai81ae1952007-12-05 10:47:29 +0100564/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200565 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
566 *
567 * It looks like this one would be a good candidate for inlining, but this is
568 * not interesting because it around 35 bytes long and often called multiple
569 * times within the same function.
570 */
571int ishex(char s)
572{
573 s -= '0';
574 if ((unsigned char)s <= 9)
575 return 1;
576 s -= 'A' - '0';
577 if ((unsigned char)s <= 5)
578 return 1;
579 s -= 'a' - 'A';
580 if ((unsigned char)s <= 5)
581 return 1;
582 return 0;
583}
584
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100585/* rounds <i> down to the closest value having max 2 digits */
586unsigned int round_2dig(unsigned int i)
587{
588 unsigned int mul = 1;
589
590 while (i >= 100) {
591 i /= 10;
592 mul *= 10;
593 }
594 return i * mul;
595}
596
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100597/*
598 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
599 * invalid character is found, a pointer to it is returned. If everything is
600 * fine, NULL is returned.
601 */
602const char *invalid_char(const char *name)
603{
604 if (!*name)
605 return name;
606
607 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100608 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100609 *name != '_' && *name != '-')
610 return name;
611 name++;
612 }
613 return NULL;
614}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200615
616/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200617 * Checks <name> for invalid characters. Valid chars are [_.-] and those
618 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200619 * If an invalid character is found, a pointer to it is returned.
620 * If everything is fine, NULL is returned.
621 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200622static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200623
624 if (!*name)
625 return name;
626
627 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100628 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200629 *name != '_' && *name != '-')
630 return name;
631
632 name++;
633 }
634
635 return NULL;
636}
637
638/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200639 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
640 * If an invalid character is found, a pointer to it is returned.
641 * If everything is fine, NULL is returned.
642 */
643const char *invalid_domainchar(const char *name) {
644 return __invalid_char(name, isalnum);
645}
646
647/*
648 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
649 * If an invalid character is found, a pointer to it is returned.
650 * If everything is fine, NULL is returned.
651 */
652const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200653 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200654}
655
656/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100657 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100658 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
659 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
660 * the function tries to guess the address family from the syntax. If the
661 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100662 * string is assumed to contain only an address, no port. The address can be a
663 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
664 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
665 * The return address will only have the address family and the address set,
666 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100667 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
668 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100669 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200670 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100671struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200672{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100673 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100674 /* max IPv6 length, including brackets and terminating NULL */
675 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100676 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100677
678 /* check IPv6 with square brackets */
679 if (str[0] == '[') {
680 size_t iplength = strlen(str);
681
682 if (iplength < 4) {
683 /* minimal size is 4 when using brackets "[::]" */
684 goto fail;
685 }
686 else if (iplength >= sizeof(tmpip)) {
687 /* IPv6 literal can not be larger than tmpip */
688 goto fail;
689 }
690 else {
691 if (str[iplength - 1] != ']') {
692 /* if address started with bracket, it should end with bracket */
693 goto fail;
694 }
695 else {
696 memcpy(tmpip, str + 1, iplength - 2);
697 tmpip[iplength - 2] = '\0';
698 str = tmpip;
699 }
700 }
701 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100702
Willy Tarreaufab5a432011-03-04 15:31:53 +0100703 /* Any IPv6 address */
704 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100705 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
706 sa->ss_family = AF_INET6;
707 else if (sa->ss_family != AF_INET6)
708 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100709 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100710 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100711 }
712
Willy Tarreau24709282013-03-10 21:32:12 +0100713 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100714 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100715 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
716 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100717 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100718 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100719 }
720
721 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100722 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
723 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100724 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100725 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100726 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100727 }
728
729 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100730 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
731 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100732 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100733 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100734 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100735 }
736
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100737 if (!resolve)
738 return NULL;
739
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200740 if (!dns_hostname_validation(str, NULL))
741 return NULL;
742
David du Colombierd5f43282011-03-17 10:40:16 +0100743#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200744 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100745 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100746 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100747
748 memset(&result, 0, sizeof(result));
749 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100750 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100751 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200752 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100753 hints.ai_protocol = 0;
754
755 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100756 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
757 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100758 else if (sa->ss_family != result->ai_family) {
759 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100760 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100761 }
Willy Tarreau24709282013-03-10 21:32:12 +0100762
David du Colombierd5f43282011-03-17 10:40:16 +0100763 switch (result->ai_family) {
764 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100765 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100766 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100767 success = 1;
768 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100769 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100770 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100771 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100772 success = 1;
773 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100774 }
775 }
776
Sean Carey58ea0392013-02-15 23:39:18 +0100777 if (result)
778 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100779
780 if (success)
781 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100782 }
David du Colombierd5f43282011-03-17 10:40:16 +0100783#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200784 /* try to resolve an IPv4/IPv6 hostname */
785 he = gethostbyname(str);
786 if (he) {
787 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
788 sa->ss_family = he->h_addrtype;
789 else if (sa->ss_family != he->h_addrtype)
790 goto fail;
791
792 switch (sa->ss_family) {
793 case AF_INET:
794 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100795 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200796 return sa;
797 case AF_INET6:
798 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100799 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200800 return sa;
801 }
802 }
803
David du Colombierd5f43282011-03-17 10:40:16 +0100804 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100805 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100806 return NULL;
807}
808
809/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100810 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
811 * range or offset consisting in two integers that the caller will have to
812 * check to find the relevant input format. The following format are supported :
813 *
814 * String format | address | port | low | high
815 * addr | <addr> | 0 | 0 | 0
816 * addr: | <addr> | 0 | 0 | 0
817 * addr:port | <addr> | <port> | <port> | <port>
818 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
819 * addr:+port | <addr> | <port> | 0 | <port>
820 * addr:-port | <addr> |-<port> | <port> | 0
821 *
822 * The detection of a port range or increment by the caller is made by
823 * comparing <low> and <high>. If both are equal, then port 0 means no port
824 * was specified. The caller may pass NULL for <low> and <high> if it is not
825 * interested in retrieving port ranges.
826 *
827 * Note that <addr> above may also be :
828 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
829 * - "*" => family will be AF_INET and address will be INADDR_ANY
830 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
831 * - a host name => family and address will depend on host name resolving.
832 *
Willy Tarreau24709282013-03-10 21:32:12 +0100833 * A prefix may be passed in before the address above to force the family :
834 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
835 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
836 * - "unix@" => force address to be a path to a UNIX socket even if the
837 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200838 * - 'abns@' -> force address to belong to the abstract namespace (Linux
839 * only). These sockets are just like Unix sockets but without
840 * the need for an underlying file system. The address is a
841 * string. Technically it's like a Unix socket with a zero in
842 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100843 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100844 *
mildisff5d5102015-10-26 18:50:08 +0100845 * IPv6 addresses can be declared with or without square brackets. When using
846 * square brackets for IPv6 addresses, the port separator (colon) is optional.
847 * If not using square brackets, and in order to avoid any ambiguity with
848 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
849 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
850 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100851 *
852 * If <pfx> is non-null, it is used as a string prefix before any path-based
853 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100854 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200855 * if <fqdn> is non-null, it will be filled with :
856 * - a pointer to the FQDN of the server name to resolve if there's one, and
857 * that the caller will have to free(),
858 * - NULL if there was an explicit address that doesn't require resolution.
859 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200860 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
861 * still honored so it is possible for the caller to know whether a resolution
862 * failed by clearing this flag and checking if <fqdn> was filled, indicating
863 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200864 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100865 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200866 * the address when cast to sockaddr_in and the address family is
867 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200868 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200869 * The matching protocol will be set into <proto> if non-null.
870 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200871 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
872 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100873 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200874struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
875 struct protocol **proto, char **err,
876 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100877{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100878 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100879 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200880 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100881 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100882 char *port1, *port2;
883 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200884 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200885 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200886 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100887
888 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200889 if (fqdn)
890 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200891
Willy Tarreaudad36a32013-03-11 01:20:04 +0100892 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100893 if (str2 == NULL) {
894 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100895 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100896 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200897
Willy Tarreau9f69f462015-09-08 16:01:25 +0200898 if (!*str2) {
899 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
900 goto out;
901 }
902
Willy Tarreau24709282013-03-10 21:32:12 +0100903 memset(&ss, 0, sizeof(ss));
904
Willy Tarreaue835bd82020-09-16 11:35:47 +0200905 /* prepare the default socket types */
906 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM)
907 sock_type = ctrl_type = SOCK_DGRAM;
908 else
909 sock_type = ctrl_type = SOCK_STREAM;
910
911 if (strncmp(str2, "stream+", 7) == 0) {
912 str2 += 7;
913 sock_type = ctrl_type = SOCK_STREAM;
914 }
915 else if (strncmp(str2, "dgram+", 6) == 0) {
916 str2 += 6;
917 sock_type = ctrl_type = SOCK_DGRAM;
918 }
919
Willy Tarreau24709282013-03-10 21:32:12 +0100920 if (strncmp(str2, "unix@", 5) == 0) {
921 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200922 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100923 ss.ss_family = AF_UNIX;
924 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200925 else if (strncmp(str2, "abns@", 5) == 0) {
926 str2 += 5;
927 abstract = 1;
928 ss.ss_family = AF_UNIX;
929 }
Willy Tarreau24709282013-03-10 21:32:12 +0100930 else if (strncmp(str2, "ipv4@", 5) == 0) {
931 str2 += 5;
932 ss.ss_family = AF_INET;
933 }
934 else if (strncmp(str2, "ipv6@", 5) == 0) {
935 str2 += 5;
936 ss.ss_family = AF_INET6;
937 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200938 else if (strncmp(str2, "udp4@", 5) == 0) {
939 str2 += 5;
940 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200941 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200942 }
943 else if (strncmp(str2, "udp6@", 5) == 0) {
944 str2 += 5;
945 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200946 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200947 }
948 else if (strncmp(str2, "udp@", 4) == 0) {
949 str2 += 4;
950 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200951 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200952 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200953 else if (strncmp(str2, "fd@", 3) == 0) {
954 str2 += 3;
955 ss.ss_family = AF_CUST_EXISTING_FD;
956 }
957 else if (strncmp(str2, "sockpair@", 9) == 0) {
958 str2 += 9;
959 ss.ss_family = AF_CUST_SOCKPAIR;
960 }
Willy Tarreau24709282013-03-10 21:32:12 +0100961 else if (*str2 == '/') {
962 ss.ss_family = AF_UNIX;
963 }
964 else
965 ss.ss_family = AF_UNSPEC;
966
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200967 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200968 struct sockaddr_storage ss2;
969 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200970 char *endptr;
971
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200972 new_fd = strtol(str2, &endptr, 10);
973 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200974 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
975 goto out;
976 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200977
Willy Tarreaua215be22020-09-16 10:14:16 +0200978 /* just verify that it's a socket */
979 addr_len = sizeof(ss2);
980 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
981 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
982 goto out;
983 }
984
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200985 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
986 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200987 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200988 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100989 char *endptr;
990
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200991 new_fd = strtol(str2, &endptr, 10);
992 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100993 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100994 goto out;
995 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200996
Willy Tarreau6edc7222020-09-15 17:41:56 +0200997 if (opts & PA_O_SOCKET_FD) {
998 socklen_t addr_len;
999 int type;
1000
1001 addr_len = sizeof(ss);
1002 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1003 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1004 goto out;
1005 }
1006
1007 addr_len = sizeof(type);
1008 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001009 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001010 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1011 goto out;
1012 }
1013
1014 porta = portl = porth = get_host_port(&ss);
1015 } else if (opts & PA_O_RAW_FD) {
1016 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1017 ((struct sockaddr_in *)&ss)->sin_port = 0;
1018 } else {
1019 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1020 goto out;
1021 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001022 }
1023 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001024 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001025 int prefix_path_len;
1026 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001027 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001028
1029 /* complete unix socket path name during startup or soft-restart is
1030 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1031 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001032 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001033 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001034 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001035
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001036 adr_len = strlen(str2);
1037 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001038 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1039 goto out;
1040 }
1041
Willy Tarreauccfccef2014-05-10 01:49:15 +02001042 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001043 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001044 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001045 memcpy(un->sun_path, pfx, prefix_path_len);
1046 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001047 }
Willy Tarreau24709282013-03-10 21:32:12 +01001048 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001049 char *end = str2 + strlen(str2);
1050 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001051
mildisff5d5102015-10-26 18:50:08 +01001052 /* search for : or ] whatever comes first */
1053 for (chr = end-1; chr > str2; chr--) {
1054 if (*chr == ']' || *chr == ':')
1055 break;
1056 }
1057
1058 if (*chr == ':') {
1059 /* Found a colon before a closing-bracket, must be a port separator.
1060 * This guarantee backward compatibility.
1061 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001062 if (!(opts & PA_O_PORT_OK)) {
1063 memprintf(err, "port specification not permitted here in '%s'", str);
1064 goto out;
1065 }
mildisff5d5102015-10-26 18:50:08 +01001066 *chr++ = '\0';
1067 port1 = chr;
1068 }
1069 else {
1070 /* Either no colon and no closing-bracket
1071 * or directly ending with a closing-bracket.
1072 * However, no port.
1073 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001074 if (opts & PA_O_PORT_MAND) {
1075 memprintf(err, "missing port specification in '%s'", str);
1076 goto out;
1077 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001078 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001079 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001080
Willy Tarreau90807112020-02-25 08:16:33 +01001081 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001082 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001083 if (port2) {
1084 if (!(opts & PA_O_PORT_RANGE)) {
1085 memprintf(err, "port range not permitted here in '%s'", str);
1086 goto out;
1087 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001088 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001089 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001090 else
1091 port2 = port1;
1092 portl = atoi(port1);
1093 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001094
1095 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1096 memprintf(err, "invalid port '%s'", port1);
1097 goto out;
1098 }
1099
1100 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1101 memprintf(err, "invalid port '%s'", port2);
1102 goto out;
1103 }
1104
1105 if (portl > porth) {
1106 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1107 goto out;
1108 }
1109
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001110 porta = portl;
1111 }
1112 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001113 if (!(opts & PA_O_PORT_OFS)) {
1114 memprintf(err, "port offset not permitted here in '%s'", str);
1115 goto out;
1116 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001117 portl = atoi(port1 + 1);
1118 porta = -portl;
1119 }
1120 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001121 if (!(opts & PA_O_PORT_OFS)) {
1122 memprintf(err, "port offset not permitted here in '%s'", str);
1123 goto out;
1124 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001125 porth = atoi(port1 + 1);
1126 porta = porth;
1127 }
1128 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001129 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001130 goto out;
1131 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001132 else if (opts & PA_O_PORT_MAND) {
1133 memprintf(err, "missing port specification in '%s'", str);
1134 goto out;
1135 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001136
1137 /* first try to parse the IP without resolving. If it fails, it
1138 * tells us we need to keep a copy of the FQDN to resolve later
1139 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001140 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001141 */
1142 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001143 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1144 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001145 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1146 goto out;
1147 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001148
Willy Tarreauceccdd72016-11-02 22:27:10 +01001149 if (fqdn) {
1150 if (str2 != back)
1151 memmove(back, str2, strlen(str2) + 1);
1152 *fqdn = back;
1153 back = NULL;
1154 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001155 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001156 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001157 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001158
Willy Tarreaue835bd82020-09-16 11:35:47 +02001159 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1160 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1161 goto out;
1162 }
1163 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1164 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1165 goto out;
1166 }
1167
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001168 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001169 /* Note: if the caller asks for a proto, we must find one,
1170 * except if we return with an fqdn that will resolve later,
1171 * in which case the address is not known yet (this is only
1172 * for servers actually).
1173 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001174 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001175 sock_type == SOCK_DGRAM,
1176 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001177
Willy Tarreau5fc93282020-09-16 18:25:03 +02001178 if (!new_proto && (!fqdn || !*fqdn)) {
1179 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1180 goto out;
1181 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001182
1183 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1184 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1185 goto out;
1186 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001187 }
1188
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001189 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001190 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001191 if (port)
1192 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001193 if (low)
1194 *low = portl;
1195 if (high)
1196 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001197 if (fd)
1198 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001199 if (proto)
1200 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001201 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001202 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001203}
1204
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001205/* converts <str> to a struct in_addr containing a network mask. It can be
1206 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001207 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001208 */
1209int str2mask(const char *str, struct in_addr *mask)
1210{
1211 if (strchr(str, '.') != NULL) { /* dotted notation */
1212 if (!inet_pton(AF_INET, str, mask))
1213 return 0;
1214 }
1215 else { /* mask length */
1216 char *err;
1217 unsigned long len = strtol(str, &err, 10);
1218
1219 if (!*str || (err && *err) || (unsigned)len > 32)
1220 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001221
1222 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001223 }
1224 return 1;
1225}
1226
Tim Duesterhus47185172018-01-25 16:24:49 +01001227/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001228 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001229 * if the conversion succeeds otherwise zero.
1230 */
1231int str2mask6(const char *str, struct in6_addr *mask)
1232{
1233 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1234 if (!inet_pton(AF_INET6, str, mask))
1235 return 0;
1236 }
1237 else { /* mask length */
1238 char *err;
1239 unsigned long len = strtol(str, &err, 10);
1240
1241 if (!*str || (err && *err) || (unsigned)len > 128)
1242 return 0;
1243
1244 len2mask6(len, mask);
1245 }
1246 return 1;
1247}
1248
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001249/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1250 * succeeds otherwise zero.
1251 */
1252int cidr2dotted(int cidr, struct in_addr *mask) {
1253
1254 if (cidr < 0 || cidr > 32)
1255 return 0;
1256
1257 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1258 return 1;
1259}
1260
Thierry Fournier70473a52016-02-17 17:12:14 +01001261/* Convert mask from bit length form to in_addr form.
1262 * This function never fails.
1263 */
1264void len2mask4(int len, struct in_addr *addr)
1265{
1266 if (len >= 32) {
1267 addr->s_addr = 0xffffffff;
1268 return;
1269 }
1270 if (len <= 0) {
1271 addr->s_addr = 0x00000000;
1272 return;
1273 }
1274 addr->s_addr = 0xffffffff << (32 - len);
1275 addr->s_addr = htonl(addr->s_addr);
1276}
1277
1278/* Convert mask from bit length form to in6_addr form.
1279 * This function never fails.
1280 */
1281void len2mask6(int len, struct in6_addr *addr)
1282{
1283 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1284 len -= 32;
1285 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1286 len -= 32;
1287 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1288 len -= 32;
1289 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1290}
1291
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001292/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001293 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001294 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001295 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001296 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1297 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001298int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001299{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001300 __label__ out_free, out_err;
1301 char *c, *s;
1302 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001303
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001304 s = strdup(str);
1305 if (!s)
1306 return 0;
1307
Willy Tarreaubaaee002006-06-26 02:48:02 +02001308 memset(mask, 0, sizeof(*mask));
1309 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001310
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001311 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001312 *c++ = '\0';
1313 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001314 if (!str2mask(c, mask))
1315 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001316 }
1317 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001318 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001319 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001320 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001321 struct hostent *he;
1322
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001323 if (!resolve)
1324 goto out_err;
1325
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001326 if ((he = gethostbyname(s)) == NULL) {
1327 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001328 }
1329 else
1330 *addr = *(struct in_addr *) *(he->h_addr_list);
1331 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001332
1333 ret_val = 1;
1334 out_free:
1335 free(s);
1336 return ret_val;
1337 out_err:
1338 ret_val = 0;
1339 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001340}
1341
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001342
1343/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001344 * converts <str> to two struct in6_addr* which must be pre-allocated.
1345 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001346 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001347 * Returns 1 if OK, 0 if error.
1348 */
1349int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1350{
1351 char *c, *s;
1352 int ret_val = 0;
1353 char *err;
1354 unsigned long len = 128;
1355
1356 s = strdup(str);
1357 if (!s)
1358 return 0;
1359
1360 memset(mask, 0, sizeof(*mask));
1361 memset(addr, 0, sizeof(*addr));
1362
1363 if ((c = strrchr(s, '/')) != NULL) {
1364 *c++ = '\0'; /* c points to the mask */
1365 if (!*c)
1366 goto out_free;
1367
1368 len = strtoul(c, &err, 10);
1369 if ((err && *err) || (unsigned)len > 128)
1370 goto out_free;
1371 }
1372 *mask = len; /* OK we have a valid mask in <len> */
1373
1374 if (!inet_pton(AF_INET6, s, addr))
1375 goto out_free;
1376
1377 ret_val = 1;
1378 out_free:
1379 free(s);
1380 return ret_val;
1381}
1382
1383
1384/*
David du Colombier6f5ccb12011-03-10 22:26:24 +01001385 * Parse IPv4 address found in url.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001386 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001387int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001388{
1389 int saw_digit, octets, ch;
1390 u_char tmp[4], *tp;
1391 const char *cp = addr;
1392
1393 saw_digit = 0;
1394 octets = 0;
1395 *(tp = tmp) = 0;
1396
1397 while (*addr) {
1398 unsigned char digit = (ch = *addr++) - '0';
1399 if (digit > 9 && ch != '.')
1400 break;
1401 if (digit <= 9) {
1402 u_int new = *tp * 10 + digit;
1403 if (new > 255)
1404 return 0;
1405 *tp = new;
1406 if (!saw_digit) {
1407 if (++octets > 4)
1408 return 0;
1409 saw_digit = 1;
1410 }
1411 } else if (ch == '.' && saw_digit) {
1412 if (octets == 4)
1413 return 0;
1414 *++tp = 0;
1415 saw_digit = 0;
1416 } else
1417 return 0;
1418 }
1419
1420 if (octets < 4)
1421 return 0;
1422
1423 memcpy(&dst->s_addr, tmp, 4);
1424 return addr-cp-1;
1425}
1426
1427/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001428 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001429 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001430 * the hostname. Actually only http and https are supported. <out> can be NULL.
1431 * This function returns the consumed length. It is useful if you parse complete
1432 * url like http://host:port/path, because the consumed length corresponds to
1433 * the first character of the path. If the conversion fails, it returns -1.
1434 *
1435 * This function tries to resolve the DNS name if haproxy is in starting mode.
1436 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001437 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001438int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001439{
1440 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001441 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001442 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001443 unsigned long long int http_code = 0;
1444 int default_port;
1445 struct hostent *he;
1446 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001447
1448 /* Firstly, try to find :// pattern */
1449 while (curr < url+ulen && url_code != 0x3a2f2f) {
1450 url_code = ((url_code & 0xffff) << 8);
1451 url_code += (unsigned char)*curr++;
1452 }
1453
1454 /* Secondly, if :// pattern is found, verify parsed stuff
1455 * before pattern is matching our http pattern.
1456 * If so parse ip address and port in uri.
1457 *
1458 * WARNING: Current code doesn't support dynamic async dns resolver.
1459 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001460 if (url_code != 0x3a2f2f)
1461 return -1;
1462
1463 /* Copy scheme, and utrn to lower case. */
1464 while (cp < curr - 3)
1465 http_code = (http_code << 8) + *cp++;
1466 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001467
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001468 /* HTTP or HTTPS url matching */
1469 if (http_code == 0x2020202068747470ULL) {
1470 default_port = 80;
1471 if (out)
1472 out->scheme = SCH_HTTP;
1473 }
1474 else if (http_code == 0x2020206874747073ULL) {
1475 default_port = 443;
1476 if (out)
1477 out->scheme = SCH_HTTPS;
1478 }
1479 else
1480 return -1;
1481
1482 /* If the next char is '[', the host address is IPv6. */
1483 if (*curr == '[') {
1484 curr++;
1485
1486 /* Check trash size */
1487 if (trash.size < ulen)
1488 return -1;
1489
1490 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001491 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001492 for (end = curr;
1493 end < url + ulen && *end != ']';
1494 end++, p++)
1495 *p = *end;
1496 if (*end != ']')
1497 return -1;
1498 *p = '\0';
1499
1500 /* Update out. */
1501 if (out) {
1502 out->host = curr;
1503 out->host_len = end - curr;
1504 }
1505
1506 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001507 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001508 return -1;
1509 end++;
1510
1511 /* Decode port. */
1512 if (*end == ':') {
1513 end++;
1514 default_port = read_uint(&end, url + ulen);
1515 }
1516 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1517 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1518 return end - url;
1519 }
1520 else {
1521 /* We are looking for IP address. If you want to parse and
1522 * resolve hostname found in url, you can use str2sa_range(), but
1523 * be warned this can slow down global daemon performances
1524 * while handling lagging dns responses.
1525 */
1526 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1527 if (ret) {
1528 /* Update out. */
1529 if (out) {
1530 out->host = curr;
1531 out->host_len = ret;
1532 }
1533
1534 curr += ret;
1535
1536 /* Decode port. */
1537 if (*curr == ':') {
1538 curr++;
1539 default_port = read_uint(&curr, url + ulen);
1540 }
1541 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1542
1543 /* Set family. */
1544 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1545 return curr - url;
1546 }
1547 else if (global.mode & MODE_STARTING) {
1548 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1549 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001550 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001551
1552 /* look for : or / or end */
1553 for (end = curr;
1554 end < url + ulen && *end != '/' && *end != ':';
1555 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001556 memcpy(trash.area, curr, end - curr);
1557 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001558
1559 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001560 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001561 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001562 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001563
1564 /* Update out. */
1565 if (out) {
1566 out->host = curr;
1567 out->host_len = end - curr;
1568 }
1569
1570 /* Decode port. */
1571 if (*end == ':') {
1572 end++;
1573 default_port = read_uint(&end, url + ulen);
1574 }
1575
1576 /* Copy IP address, set port and family. */
1577 switch (he->h_addrtype) {
1578 case AF_INET:
1579 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1580 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1581 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1582 return end - url;
1583
1584 case AF_INET6:
1585 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1586 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1587 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1588 return end - url;
1589 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001590 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001591 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001592 return -1;
1593}
1594
Willy Tarreau631f01c2011-09-05 00:36:48 +02001595/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1596 * address family is returned so that it's easy for the caller to adapt to the
1597 * output format. Zero is returned if the address family is not supported. -1
1598 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1599 * supported.
1600 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001601int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001602{
1603
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001604 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001605
1606 if (size < 5)
1607 return 0;
1608 *str = '\0';
1609
1610 switch (addr->ss_family) {
1611 case AF_INET:
1612 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1613 break;
1614 case AF_INET6:
1615 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1616 break;
1617 case AF_UNIX:
1618 memcpy(str, "unix", 5);
1619 return addr->ss_family;
1620 default:
1621 return 0;
1622 }
1623
1624 if (inet_ntop(addr->ss_family, ptr, str, size))
1625 return addr->ss_family;
1626
1627 /* failed */
1628 return -1;
1629}
1630
Simon Horman75ab8bd2014-06-16 09:39:41 +09001631/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1632 * address family is returned so that it's easy for the caller to adapt to the
1633 * output format. Zero is returned if the address family is not supported. -1
1634 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1635 * supported.
1636 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001637int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001638{
1639
1640 uint16_t port;
1641
1642
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001643 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001644 return 0;
1645 *str = '\0';
1646
1647 switch (addr->ss_family) {
1648 case AF_INET:
1649 port = ((struct sockaddr_in *)addr)->sin_port;
1650 break;
1651 case AF_INET6:
1652 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1653 break;
1654 case AF_UNIX:
1655 memcpy(str, "unix", 5);
1656 return addr->ss_family;
1657 default:
1658 return 0;
1659 }
1660
1661 snprintf(str, size, "%u", ntohs(port));
1662 return addr->ss_family;
1663}
1664
Willy Tarreau16e01562016-08-09 16:46:18 +02001665/* check if the given address is local to the system or not. It will return
1666 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1667 * it is. We don't want to iterate over all interfaces for this (and it is not
1668 * portable). So instead we try to bind in UDP to this address on a free non
1669 * privileged port and to connect to the same address, port 0 (connect doesn't
1670 * care). If it succeeds, we own the address. Note that non-inet addresses are
1671 * considered local since they're most likely AF_UNIX.
1672 */
1673int addr_is_local(const struct netns_entry *ns,
1674 const struct sockaddr_storage *orig)
1675{
1676 struct sockaddr_storage addr;
1677 int result;
1678 int fd;
1679
1680 if (!is_inet_addr(orig))
1681 return 1;
1682
1683 memcpy(&addr, orig, sizeof(addr));
1684 set_host_port(&addr, 0);
1685
1686 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1687 if (fd < 0)
1688 return -1;
1689
1690 result = -1;
1691 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1692 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1693 result = 0; // fail, non-local address
1694 else
1695 result = 1; // success, local address
1696 }
1697 else {
1698 if (errno == EADDRNOTAVAIL)
1699 result = 0; // definitely not local :-)
1700 }
1701 close(fd);
1702
1703 return result;
1704}
1705
Willy Tarreaubaaee002006-06-26 02:48:02 +02001706/* will try to encode the string <string> replacing all characters tagged in
1707 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1708 * prefixed by <escape>, and will store the result between <start> (included)
1709 * and <stop> (excluded), and will always terminate the string with a '\0'
1710 * before <stop>. The position of the '\0' is returned if the conversion
1711 * completes. If bytes are missing between <start> and <stop>, then the
1712 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1713 * cannot even be stored so we return <start> without writing the 0.
1714 * The input string must also be zero-terminated.
1715 */
1716const char hextab[16] = "0123456789ABCDEF";
1717char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001718 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001719 const char *string)
1720{
1721 if (start < stop) {
1722 stop--; /* reserve one byte for the final '\0' */
1723 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001724 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001725 *start++ = *string;
1726 else {
1727 if (start + 3 >= stop)
1728 break;
1729 *start++ = escape;
1730 *start++ = hextab[(*string >> 4) & 15];
1731 *start++ = hextab[*string & 15];
1732 }
1733 string++;
1734 }
1735 *start = '\0';
1736 }
1737 return start;
1738}
1739
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001740/*
1741 * Same behavior as encode_string() above, except that it encodes chunk
1742 * <chunk> instead of a string.
1743 */
1744char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001745 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001746 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001747{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001748 char *str = chunk->area;
1749 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001750
1751 if (start < stop) {
1752 stop--; /* reserve one byte for the final '\0' */
1753 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001754 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001755 *start++ = *str;
1756 else {
1757 if (start + 3 >= stop)
1758 break;
1759 *start++ = escape;
1760 *start++ = hextab[(*str >> 4) & 15];
1761 *start++ = hextab[*str & 15];
1762 }
1763 str++;
1764 }
1765 *start = '\0';
1766 }
1767 return start;
1768}
1769
Dragan Dosen0edd1092016-02-12 13:23:02 +01001770/*
1771 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001772 * character. The input <string> must be zero-terminated. The result will
1773 * be stored between <start> (included) and <stop> (excluded). This
1774 * function will always try to terminate the resulting string with a '\0'
1775 * before <stop>, and will return its position if the conversion
1776 * completes.
1777 */
1778char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001779 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001780 const char *string)
1781{
1782 if (start < stop) {
1783 stop--; /* reserve one byte for the final '\0' */
1784 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001785 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001786 *start++ = *string;
1787 else {
1788 if (start + 2 >= stop)
1789 break;
1790 *start++ = escape;
1791 *start++ = *string;
1792 }
1793 string++;
1794 }
1795 *start = '\0';
1796 }
1797 return start;
1798}
1799
1800/*
1801 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001802 * character. <chunk> contains the input to be escaped. The result will be
1803 * stored between <start> (included) and <stop> (excluded). The function
1804 * will always try to terminate the resulting string with a '\0' before
1805 * <stop>, and will return its position if the conversion completes.
1806 */
1807char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001808 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001809 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001810{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001811 char *str = chunk->area;
1812 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001813
1814 if (start < stop) {
1815 stop--; /* reserve one byte for the final '\0' */
1816 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001817 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001818 *start++ = *str;
1819 else {
1820 if (start + 2 >= stop)
1821 break;
1822 *start++ = escape;
1823 *start++ = *str;
1824 }
1825 str++;
1826 }
1827 *start = '\0';
1828 }
1829 return start;
1830}
1831
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001832/* Check a string for using it in a CSV output format. If the string contains
1833 * one of the following four char <">, <,>, CR or LF, the string is
1834 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1835 * <str> is the input string to be escaped. The function assumes that
1836 * the input string is null-terminated.
1837 *
1838 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001839 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001840 * format.
1841 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001842 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001843 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001844 * If <quote> is 1, the converter puts the quotes only if any reserved character
1845 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001846 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001847 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001848 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001849 * The function returns the converted string on its output. If an error
1850 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001851 * for using the function directly as printf() argument.
1852 *
1853 * If the output buffer is too short to contain the input string, the result
1854 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001855 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001856 * This function appends the encoding to the existing output chunk, and it
1857 * guarantees that it starts immediately at the first available character of
1858 * the chunk. Please use csv_enc() instead if you want to replace the output
1859 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001860 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001861const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001862{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001863 char *end = output->area + output->size;
1864 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001865 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001866
Willy Tarreaub631c292016-01-08 10:04:08 +01001867 if (quote == 1) {
1868 /* automatic quoting: first verify if we'll have to quote the string */
1869 if (!strpbrk(str, "\n\r,\""))
1870 quote = 0;
1871 }
1872
1873 if (quote)
1874 *ptr++ = '"';
1875
Willy Tarreau898529b2016-01-06 18:07:04 +01001876 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1877 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001878 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001879 ptr++;
1880 if (ptr >= end - 2) {
1881 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001882 break;
1883 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001884 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001885 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001886 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001887 str++;
1888 }
1889
Willy Tarreaub631c292016-01-08 10:04:08 +01001890 if (quote)
1891 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001892
Willy Tarreau898529b2016-01-06 18:07:04 +01001893 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001894 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001895 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001896}
1897
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001898/* Decode an URL-encoded string in-place. The resulting string might
1899 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001900 * aborted, the string is truncated before the issue and a negative value is
1901 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001902 * If the 'in_form' argument is non-nul the string is assumed to be part of
1903 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1904 * turned to a space. If it's zero, this will only be done after a question
1905 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001906 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001907int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001908{
1909 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001910 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001911
1912 in = string;
1913 out = string;
1914 while (*in) {
1915 switch (*in) {
1916 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001917 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001918 break;
1919 case '%' :
1920 if (!ishex(in[1]) || !ishex(in[2]))
1921 goto end;
1922 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1923 in += 2;
1924 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001925 case '?':
1926 in_form = 1;
1927 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001928 default:
1929 *out++ = *in;
1930 break;
1931 }
1932 in++;
1933 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001934 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001935 end:
1936 *out = 0;
1937 return ret;
1938}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001939
Willy Tarreau6911fa42007-03-04 18:06:08 +01001940unsigned int str2ui(const char *s)
1941{
1942 return __str2ui(s);
1943}
1944
1945unsigned int str2uic(const char *s)
1946{
1947 return __str2uic(s);
1948}
1949
1950unsigned int strl2ui(const char *s, int len)
1951{
1952 return __strl2ui(s, len);
1953}
1954
1955unsigned int strl2uic(const char *s, int len)
1956{
1957 return __strl2uic(s, len);
1958}
1959
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001960unsigned int read_uint(const char **s, const char *end)
1961{
1962 return __read_uint(s, end);
1963}
1964
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001965/* This function reads an unsigned integer from the string pointed to by <s> and
1966 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1967 * function automatically stops at <end>. If the number overflows, the 2^64-1
1968 * value is returned.
1969 */
1970unsigned long long int read_uint64(const char **s, const char *end)
1971{
1972 const char *ptr = *s;
1973 unsigned long long int i = 0, tmp;
1974 unsigned int j;
1975
1976 while (ptr < end) {
1977
1978 /* read next char */
1979 j = *ptr - '0';
1980 if (j > 9)
1981 goto read_uint64_end;
1982
1983 /* add char to the number and check overflow. */
1984 tmp = i * 10;
1985 if (tmp / 10 != i) {
1986 i = ULLONG_MAX;
1987 goto read_uint64_eat;
1988 }
1989 if (ULLONG_MAX - tmp < j) {
1990 i = ULLONG_MAX;
1991 goto read_uint64_eat;
1992 }
1993 i = tmp + j;
1994 ptr++;
1995 }
1996read_uint64_eat:
1997 /* eat each numeric char */
1998 while (ptr < end) {
1999 if ((unsigned int)(*ptr - '0') > 9)
2000 break;
2001 ptr++;
2002 }
2003read_uint64_end:
2004 *s = ptr;
2005 return i;
2006}
2007
2008/* This function reads an integer from the string pointed to by <s> and returns
2009 * it. The <s> pointer is adjusted to point to the first unread char. The function
2010 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2011 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2012 * returned.
2013 */
2014long long int read_int64(const char **s, const char *end)
2015{
2016 unsigned long long int i = 0;
2017 int neg = 0;
2018
2019 /* Look for minus char. */
2020 if (**s == '-') {
2021 neg = 1;
2022 (*s)++;
2023 }
2024 else if (**s == '+')
2025 (*s)++;
2026
2027 /* convert as positive number. */
2028 i = read_uint64(s, end);
2029
2030 if (neg) {
2031 if (i > 0x8000000000000000ULL)
2032 return LLONG_MIN;
2033 return -i;
2034 }
2035 if (i > 0x7fffffffffffffffULL)
2036 return LLONG_MAX;
2037 return i;
2038}
2039
Willy Tarreau6911fa42007-03-04 18:06:08 +01002040/* This one is 7 times faster than strtol() on athlon with checks.
2041 * It returns the value of the number composed of all valid digits read,
2042 * and can process negative numbers too.
2043 */
2044int strl2ic(const char *s, int len)
2045{
2046 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002047 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002048
2049 if (len > 0) {
2050 if (*s != '-') {
2051 /* positive number */
2052 while (len-- > 0) {
2053 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002054 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002055 if (j > 9)
2056 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002057 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002058 }
2059 } else {
2060 /* negative number */
2061 s++;
2062 while (--len > 0) {
2063 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002064 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002065 if (j > 9)
2066 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002067 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002068 }
2069 }
2070 }
2071 return i;
2072}
2073
2074
2075/* This function reads exactly <len> chars from <s> and converts them to a
2076 * signed integer which it stores into <ret>. It accurately detects any error
2077 * (truncated string, invalid chars, overflows). It is meant to be used in
2078 * applications designed for hostile environments. It returns zero when the
2079 * number has successfully been converted, non-zero otherwise. When an error
2080 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2081 * faster than strtol().
2082 */
2083int strl2irc(const char *s, int len, int *ret)
2084{
2085 int i = 0;
2086 int j;
2087
2088 if (!len)
2089 return 1;
2090
2091 if (*s != '-') {
2092 /* positive number */
2093 while (len-- > 0) {
2094 j = (*s++) - '0';
2095 if (j > 9) return 1; /* invalid char */
2096 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2097 i = i * 10;
2098 if (i + j < i) return 1; /* check for addition overflow */
2099 i = i + j;
2100 }
2101 } else {
2102 /* negative number */
2103 s++;
2104 while (--len > 0) {
2105 j = (*s++) - '0';
2106 if (j > 9) return 1; /* invalid char */
2107 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2108 i = i * 10;
2109 if (i - j > i) return 1; /* check for subtract overflow */
2110 i = i - j;
2111 }
2112 }
2113 *ret = i;
2114 return 0;
2115}
2116
2117
2118/* This function reads exactly <len> chars from <s> and converts them to a
2119 * signed integer which it stores into <ret>. It accurately detects any error
2120 * (truncated string, invalid chars, overflows). It is meant to be used in
2121 * applications designed for hostile environments. It returns zero when the
2122 * number has successfully been converted, non-zero otherwise. When an error
2123 * is returned, the <ret> value is left untouched. It is about 3 times slower
2124 * than str2irc().
2125 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002126
2127int strl2llrc(const char *s, int len, long long *ret)
2128{
2129 long long i = 0;
2130 int j;
2131
2132 if (!len)
2133 return 1;
2134
2135 if (*s != '-') {
2136 /* positive number */
2137 while (len-- > 0) {
2138 j = (*s++) - '0';
2139 if (j > 9) return 1; /* invalid char */
2140 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2141 i = i * 10LL;
2142 if (i + j < i) return 1; /* check for addition overflow */
2143 i = i + j;
2144 }
2145 } else {
2146 /* negative number */
2147 s++;
2148 while (--len > 0) {
2149 j = (*s++) - '0';
2150 if (j > 9) return 1; /* invalid char */
2151 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2152 i = i * 10LL;
2153 if (i - j > i) return 1; /* check for subtract overflow */
2154 i = i - j;
2155 }
2156 }
2157 *ret = i;
2158 return 0;
2159}
2160
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002161/* This function is used with pat_parse_dotted_ver(). It converts a string
2162 * composed by two number separated by a dot. Each part must contain in 16 bits
2163 * because internally they will be represented as a 32-bit quantity stored in
2164 * a 64-bit integer. It returns zero when the number has successfully been
2165 * converted, non-zero otherwise. When an error is returned, the <ret> value
2166 * is left untouched.
2167 *
2168 * "1.3" -> 0x0000000000010003
2169 * "65535.65535" -> 0x00000000ffffffff
2170 */
2171int strl2llrc_dotted(const char *text, int len, long long *ret)
2172{
2173 const char *end = &text[len];
2174 const char *p;
2175 long long major, minor;
2176
2177 /* Look for dot. */
2178 for (p = text; p < end; p++)
2179 if (*p == '.')
2180 break;
2181
2182 /* Convert major. */
2183 if (strl2llrc(text, p - text, &major) != 0)
2184 return 1;
2185
2186 /* Check major. */
2187 if (major >= 65536)
2188 return 1;
2189
2190 /* Convert minor. */
2191 minor = 0;
2192 if (p < end)
2193 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2194 return 1;
2195
2196 /* Check minor. */
2197 if (minor >= 65536)
2198 return 1;
2199
2200 /* Compose value. */
2201 *ret = (major << 16) | (minor & 0xffff);
2202 return 0;
2203}
2204
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002205/* This function parses a time value optionally followed by a unit suffix among
2206 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2207 * expected by the caller. The computation does its best to avoid overflows.
2208 * The value is returned in <ret> if everything is fine, and a NULL is returned
2209 * by the function. In case of error, a pointer to the error is returned and
2210 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002211 * Values resulting in values larger than or equal to 2^31 after conversion are
2212 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2213 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002214 */
2215const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2216{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002217 unsigned long long imult, idiv;
2218 unsigned long long omult, odiv;
2219 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002220 const char *str = text;
2221
2222 if (!isdigit((unsigned char)*text))
2223 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002224
2225 omult = odiv = 1;
2226
2227 switch (unit_flags & TIME_UNIT_MASK) {
2228 case TIME_UNIT_US: omult = 1000000; break;
2229 case TIME_UNIT_MS: omult = 1000; break;
2230 case TIME_UNIT_S: break;
2231 case TIME_UNIT_MIN: odiv = 60; break;
2232 case TIME_UNIT_HOUR: odiv = 3600; break;
2233 case TIME_UNIT_DAY: odiv = 86400; break;
2234 default: break;
2235 }
2236
2237 value = 0;
2238
2239 while (1) {
2240 unsigned int j;
2241
2242 j = *text - '0';
2243 if (j > 9)
2244 break;
2245 text++;
2246 value *= 10;
2247 value += j;
2248 }
2249
2250 imult = idiv = 1;
2251 switch (*text) {
2252 case '\0': /* no unit = default unit */
2253 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002254 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002255 case 's': /* second = unscaled unit */
2256 break;
2257 case 'u': /* microsecond : "us" */
2258 if (text[1] == 's') {
2259 idiv = 1000000;
2260 text++;
2261 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002262 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002263 case 'm': /* millisecond : "ms" or minute: "m" */
2264 if (text[1] == 's') {
2265 idiv = 1000;
2266 text++;
2267 } else
2268 imult = 60;
2269 break;
2270 case 'h': /* hour : "h" */
2271 imult = 3600;
2272 break;
2273 case 'd': /* day : "d" */
2274 imult = 86400;
2275 break;
2276 default:
2277 return text;
2278 break;
2279 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002280 if (*(++text) != '\0') {
2281 ha_warning("unexpected character '%c' after the timer value '%s', only "
2282 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2283 " This will be reported as an error in next versions.\n", *text, str);
2284 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002285
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002286 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002287 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2288 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2289 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2290 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2291
Willy Tarreau9faebe32019-06-07 19:00:37 +02002292 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2293 if (result >= 0x80000000)
2294 return PARSE_TIME_OVER;
2295 if (!result && value)
2296 return PARSE_TIME_UNDER;
2297 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002298 return NULL;
2299}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002300
Emeric Brun39132b22010-01-04 14:57:24 +01002301/* this function converts the string starting at <text> to an unsigned int
2302 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002303 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002304 */
2305const char *parse_size_err(const char *text, unsigned *ret) {
2306 unsigned value = 0;
2307
Christopher Faulet82635a02020-12-11 09:30:45 +01002308 if (!isdigit((unsigned char)*text))
2309 return text;
2310
Emeric Brun39132b22010-01-04 14:57:24 +01002311 while (1) {
2312 unsigned int j;
2313
2314 j = *text - '0';
2315 if (j > 9)
2316 break;
2317 if (value > ~0U / 10)
2318 return text;
2319 value *= 10;
2320 if (value > (value + j))
2321 return text;
2322 value += j;
2323 text++;
2324 }
2325
2326 switch (*text) {
2327 case '\0':
2328 break;
2329 case 'K':
2330 case 'k':
2331 if (value > ~0U >> 10)
2332 return text;
2333 value = value << 10;
2334 break;
2335 case 'M':
2336 case 'm':
2337 if (value > ~0U >> 20)
2338 return text;
2339 value = value << 20;
2340 break;
2341 case 'G':
2342 case 'g':
2343 if (value > ~0U >> 30)
2344 return text;
2345 value = value << 30;
2346 break;
2347 default:
2348 return text;
2349 }
2350
Godbach58048a22015-01-28 17:36:16 +08002351 if (*text != '\0' && *++text != '\0')
2352 return text;
2353
Emeric Brun39132b22010-01-04 14:57:24 +01002354 *ret = value;
2355 return NULL;
2356}
2357
Willy Tarreau126d4062013-12-03 17:50:47 +01002358/*
2359 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002360 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002361 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002362 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002363 */
2364int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2365{
2366 int len;
2367 const char *p = source;
2368 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002369 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002370
2371 len = strlen(source);
2372 if (len % 2) {
2373 memprintf(err, "an even number of hex digit is expected");
2374 return 0;
2375 }
2376
2377 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002378
Willy Tarreau126d4062013-12-03 17:50:47 +01002379 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002380 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002381 if (!*binstr) {
2382 memprintf(err, "out of memory while loading string pattern");
2383 return 0;
2384 }
2385 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002386 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002387 else {
2388 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002389 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002390 len, *binstrlen);
2391 return 0;
2392 }
2393 alloc = 0;
2394 }
2395 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002396
2397 i = j = 0;
2398 while (j < len) {
2399 if (!ishex(p[i++]))
2400 goto bad_input;
2401 if (!ishex(p[i++]))
2402 goto bad_input;
2403 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2404 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002405 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002406
2407bad_input:
2408 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002409 if (alloc) {
2410 free(*binstr);
2411 *binstr = NULL;
2412 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002413 return 0;
2414}
2415
Willy Tarreau946ba592009-05-10 15:41:18 +02002416/* copies at most <n> characters from <src> and always terminates with '\0' */
2417char *my_strndup(const char *src, int n)
2418{
2419 int len = 0;
2420 char *ret;
2421
2422 while (len < n && src[len])
2423 len++;
2424
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002425 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002426 if (!ret)
2427 return ret;
2428 memcpy(ret, src, len);
2429 ret[len] = '\0';
2430 return ret;
2431}
2432
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002433/*
2434 * search needle in haystack
2435 * returns the pointer if found, returns NULL otherwise
2436 */
2437const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2438{
2439 const void *c = NULL;
2440 unsigned char f;
2441
2442 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2443 return NULL;
2444
2445 f = *(char *)needle;
2446 c = haystack;
2447 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2448 if ((haystacklen - (c - haystack)) < needlelen)
2449 return NULL;
2450
2451 if (memcmp(c, needle, needlelen) == 0)
2452 return c;
2453 ++c;
2454 }
2455 return NULL;
2456}
2457
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002458/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002459size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2460{
2461 size_t ret = 0;
2462
2463 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2464 str++;
2465 ret++;
2466 }
2467 return ret;
2468}
2469
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002470/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002471size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2472{
2473 size_t ret = 0;
2474
2475 while (ret < len) {
2476 if(memchr(reject, *((int *)str), rejectlen))
2477 return ret;
2478 str++;
2479 ret++;
2480 }
2481 return ret;
2482}
2483
Willy Tarreau482b00d2009-10-04 22:48:42 +02002484/* This function returns the first unused key greater than or equal to <key> in
2485 * ID tree <root>. Zero is returned if no place is found.
2486 */
2487unsigned int get_next_id(struct eb_root *root, unsigned int key)
2488{
2489 struct eb32_node *used;
2490
2491 do {
2492 used = eb32_lookup_ge(root, key);
2493 if (!used || used->key > key)
2494 return key; /* key is available */
2495 key++;
2496 } while (key);
2497 return key;
2498}
2499
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002500/* dump the full tree to <file> in DOT format for debugging purposes. Will
2501 * optionally highlight node <subj> if found, depending on operation <op> :
2502 * 0 : nothing
2503 * >0 : insertion, node/leaf are surrounded in red
2504 * <0 : removal, node/leaf are dashed with no background
2505 * Will optionally add "desc" as a label on the graph if set and non-null.
2506 */
2507void eb32sc_to_file(FILE *file, struct eb_root *root, const struct eb32sc_node *subj, int op, const char *desc)
Willy Tarreaued3cda02017-11-15 15:04:05 +01002508{
2509 struct eb32sc_node *node;
2510 unsigned long scope = -1;
2511
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002512 fprintf(file, "digraph ebtree {\n");
2513
2514 if (desc && *desc) {
2515 fprintf(file,
2516 " fontname=\"fixed\";\n"
2517 " fontsize=8;\n"
2518 " label=\"%s\";\n", desc);
2519 }
2520
Willy Tarreaued3cda02017-11-15 15:04:05 +01002521 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002522 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2523 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002524 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2525 );
2526
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002527 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002528 (long)eb_root_to_node(root),
2529 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002530 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2531
2532 node = eb32sc_first(root, scope);
2533 while (node) {
2534 if (node->node.node_p) {
2535 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002536 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2537 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2538 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002539
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002540 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002541 (long)node,
2542 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002543 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002544
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002545 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002546 (long)node,
2547 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002548 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2549
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002550 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002551 (long)node,
2552 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002553 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2554 }
2555
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002556 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2557 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2558 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002559
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002560 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002561 (long)node,
2562 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002563 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002564 node = eb32sc_next(node, scope);
2565 }
2566 fprintf(file, "}\n");
2567}
2568
Willy Tarreau348238b2010-01-18 15:05:57 +01002569/* This function compares a sample word possibly followed by blanks to another
2570 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2571 * otherwise zero. This intends to be used when checking HTTP headers for some
2572 * values. Note that it validates a word followed only by blanks but does not
2573 * validate a word followed by blanks then other chars.
2574 */
2575int word_match(const char *sample, int slen, const char *word, int wlen)
2576{
2577 if (slen < wlen)
2578 return 0;
2579
2580 while (wlen) {
2581 char c = *sample ^ *word;
2582 if (c && c != ('A' ^ 'a'))
2583 return 0;
2584 sample++;
2585 word++;
2586 slen--;
2587 wlen--;
2588 }
2589
2590 while (slen) {
2591 if (*sample != ' ' && *sample != '\t')
2592 return 0;
2593 sample++;
2594 slen--;
2595 }
2596 return 1;
2597}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002598
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002599/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2600 * is particularly fast because it avoids expensive operations such as
2601 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002602 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002603 */
2604unsigned int inetaddr_host(const char *text)
2605{
2606 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2607 register unsigned int dig100, dig10, dig1;
2608 int s;
2609 const char *p, *d;
2610
2611 dig1 = dig10 = dig100 = ascii_zero;
2612 s = 24;
2613
2614 p = text;
2615 while (1) {
2616 if (((unsigned)(*p - '0')) <= 9) {
2617 p++;
2618 continue;
2619 }
2620
2621 /* here, we have a complete byte between <text> and <p> (exclusive) */
2622 if (p == text)
2623 goto end;
2624
2625 d = p - 1;
2626 dig1 |= (unsigned int)(*d << s);
2627 if (d == text)
2628 goto end;
2629
2630 d--;
2631 dig10 |= (unsigned int)(*d << s);
2632 if (d == text)
2633 goto end;
2634
2635 d--;
2636 dig100 |= (unsigned int)(*d << s);
2637 end:
2638 if (!s || *p != '.')
2639 break;
2640
2641 s -= 8;
2642 text = ++p;
2643 }
2644
2645 dig100 -= ascii_zero;
2646 dig10 -= ascii_zero;
2647 dig1 -= ascii_zero;
2648 return ((dig100 * 10) + dig10) * 10 + dig1;
2649}
2650
2651/*
2652 * Idem except the first unparsed character has to be passed in <stop>.
2653 */
2654unsigned int inetaddr_host_lim(const char *text, const char *stop)
2655{
2656 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2657 register unsigned int dig100, dig10, dig1;
2658 int s;
2659 const char *p, *d;
2660
2661 dig1 = dig10 = dig100 = ascii_zero;
2662 s = 24;
2663
2664 p = text;
2665 while (1) {
2666 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2667 p++;
2668 continue;
2669 }
2670
2671 /* here, we have a complete byte between <text> and <p> (exclusive) */
2672 if (p == text)
2673 goto end;
2674
2675 d = p - 1;
2676 dig1 |= (unsigned int)(*d << s);
2677 if (d == text)
2678 goto end;
2679
2680 d--;
2681 dig10 |= (unsigned int)(*d << s);
2682 if (d == text)
2683 goto end;
2684
2685 d--;
2686 dig100 |= (unsigned int)(*d << s);
2687 end:
2688 if (!s || p == stop || *p != '.')
2689 break;
2690
2691 s -= 8;
2692 text = ++p;
2693 }
2694
2695 dig100 -= ascii_zero;
2696 dig10 -= ascii_zero;
2697 dig1 -= ascii_zero;
2698 return ((dig100 * 10) + dig10) * 10 + dig1;
2699}
2700
2701/*
2702 * Idem except the pointer to first unparsed byte is returned into <ret> which
2703 * must not be NULL.
2704 */
Willy Tarreau74172752010-10-15 23:21:42 +02002705unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002706{
2707 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2708 register unsigned int dig100, dig10, dig1;
2709 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002710 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002711
2712 dig1 = dig10 = dig100 = ascii_zero;
2713 s = 24;
2714
2715 p = text;
2716 while (1) {
2717 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2718 p++;
2719 continue;
2720 }
2721
2722 /* here, we have a complete byte between <text> and <p> (exclusive) */
2723 if (p == text)
2724 goto end;
2725
2726 d = p - 1;
2727 dig1 |= (unsigned int)(*d << s);
2728 if (d == text)
2729 goto end;
2730
2731 d--;
2732 dig10 |= (unsigned int)(*d << s);
2733 if (d == text)
2734 goto end;
2735
2736 d--;
2737 dig100 |= (unsigned int)(*d << s);
2738 end:
2739 if (!s || p == stop || *p != '.')
2740 break;
2741
2742 s -= 8;
2743 text = ++p;
2744 }
2745
2746 *ret = p;
2747 dig100 -= ascii_zero;
2748 dig10 -= ascii_zero;
2749 dig1 -= ascii_zero;
2750 return ((dig100 * 10) + dig10) * 10 + dig1;
2751}
2752
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002753/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2754 * or the number of chars read in case of success. Maybe this could be replaced
2755 * by one of the functions above. Also, apparently this function does not support
2756 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002757 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002758 */
2759int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2760{
2761 const char *addr;
2762 int saw_digit, octets, ch;
2763 u_char tmp[4], *tp;
2764 const char *cp = buf;
2765
2766 saw_digit = 0;
2767 octets = 0;
2768 *(tp = tmp) = 0;
2769
2770 for (addr = buf; addr - buf < len; addr++) {
2771 unsigned char digit = (ch = *addr) - '0';
2772
2773 if (digit > 9 && ch != '.')
2774 break;
2775
2776 if (digit <= 9) {
2777 u_int new = *tp * 10 + digit;
2778
2779 if (new > 255)
2780 return 0;
2781
2782 *tp = new;
2783
2784 if (!saw_digit) {
2785 if (++octets > 4)
2786 return 0;
2787 saw_digit = 1;
2788 }
2789 } else if (ch == '.' && saw_digit) {
2790 if (octets == 4)
2791 return 0;
2792
2793 *++tp = 0;
2794 saw_digit = 0;
2795 } else
2796 return 0;
2797 }
2798
2799 if (octets < 4)
2800 return 0;
2801
2802 memcpy(&dst->s_addr, tmp, 4);
2803 return addr - cp;
2804}
2805
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002806/* This function converts the string in <buf> of the len <len> to
2807 * struct in6_addr <dst> which must be allocated by the caller.
2808 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002809 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002810 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002811int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2812{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002813 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002814 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002815
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002816 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002817 return 0;
2818
2819 memcpy(null_term_ip6, buf, len);
2820 null_term_ip6[len] = '\0';
2821
Willy Tarreau075415a2013-12-12 11:29:39 +01002822 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002823 return 0;
2824
Willy Tarreau075415a2013-12-12 11:29:39 +01002825 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002826 return 1;
2827}
2828
Willy Tarreauacf95772010-06-14 19:09:21 +02002829/* To be used to quote config arg positions. Returns the short string at <ptr>
2830 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2831 * if ptr is NULL or empty. The string is locally allocated.
2832 */
2833const char *quote_arg(const char *ptr)
2834{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002835 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002836 int i;
2837
2838 if (!ptr || !*ptr)
2839 return "end of line";
2840 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002841 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002842 val[i] = *ptr++;
2843 val[i++] = '\'';
2844 val[i] = '\0';
2845 return val;
2846}
2847
Willy Tarreau5b180202010-07-18 10:40:48 +02002848/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2849int get_std_op(const char *str)
2850{
2851 int ret = -1;
2852
2853 if (*str == 'e' && str[1] == 'q')
2854 ret = STD_OP_EQ;
2855 else if (*str == 'n' && str[1] == 'e')
2856 ret = STD_OP_NE;
2857 else if (*str == 'l') {
2858 if (str[1] == 'e') ret = STD_OP_LE;
2859 else if (str[1] == 't') ret = STD_OP_LT;
2860 }
2861 else if (*str == 'g') {
2862 if (str[1] == 'e') ret = STD_OP_GE;
2863 else if (str[1] == 't') ret = STD_OP_GT;
2864 }
2865
2866 if (ret == -1 || str[2] != '\0')
2867 return -1;
2868 return ret;
2869}
2870
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002871/* hash a 32-bit integer to another 32-bit integer */
2872unsigned int full_hash(unsigned int a)
2873{
2874 return __full_hash(a);
2875}
2876
Willy Tarreauf3241112019-02-26 09:56:22 +01002877/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2878 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2879 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2880 * a popcount variant and is described here :
2881 * https://graphics.stanford.edu/~seander/bithacks.html
2882 */
2883unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2884{
2885 unsigned long a, b, c, d;
2886 unsigned int s;
2887 unsigned int t;
2888
2889 a = m - ((m >> 1) & ~0UL/3);
2890 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2891 c = (b + (b >> 4)) & ~0UL/0x11;
2892 d = (c + (c >> 8)) & ~0UL/0x101;
2893
2894 r++; // make r be 1..64
2895
2896 t = 0;
2897 s = LONGBITS;
2898 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002899 unsigned long d2 = (d >> 16) >> 16;
2900 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002901 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2902 }
2903
2904 t = (d >> (s - 16)) & 0xff;
2905 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2906 t = (c >> (s - 8)) & 0xf;
2907 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2908 t = (b >> (s - 4)) & 0x7;
2909 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2910 t = (a >> (s - 2)) & 0x3;
2911 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2912 t = (m >> (s - 1)) & 0x1;
2913 s -= ((t - r) & 256) >> 8;
2914
2915 return s - 1;
2916}
2917
2918/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2919 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2920 * using mask_prep_rank_map() below.
2921 */
2922unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2923 unsigned long a, unsigned long b,
2924 unsigned long c, unsigned long d)
2925{
2926 unsigned int s;
2927 unsigned int t;
2928
2929 r++; // make r be 1..64
2930
2931 t = 0;
2932 s = LONGBITS;
2933 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002934 unsigned long d2 = (d >> 16) >> 16;
2935 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002936 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2937 }
2938
2939 t = (d >> (s - 16)) & 0xff;
2940 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2941 t = (c >> (s - 8)) & 0xf;
2942 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2943 t = (b >> (s - 4)) & 0x7;
2944 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2945 t = (a >> (s - 2)) & 0x3;
2946 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2947 t = (m >> (s - 1)) & 0x1;
2948 s -= ((t - r) & 256) >> 8;
2949
2950 return s - 1;
2951}
2952
2953/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2954 * above.
2955 */
2956void mask_prep_rank_map(unsigned long m,
2957 unsigned long *a, unsigned long *b,
2958 unsigned long *c, unsigned long *d)
2959{
2960 *a = m - ((m >> 1) & ~0UL/3);
2961 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2962 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2963 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2964}
2965
David du Colombier4f92d322011-03-24 11:09:31 +01002966/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002967 * otherwise zero. Note that <addr> may not necessarily be aligned
2968 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002969 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002970int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002971{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002972 struct in_addr addr_copy;
2973
2974 memcpy(&addr_copy, addr, sizeof(addr_copy));
2975 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002976}
2977
2978/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002979 * otherwise zero. Note that <addr> may not necessarily be aligned
2980 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002981 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002982int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002983{
2984 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002985 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002986
Willy Tarreaueec1d382016-07-13 11:59:39 +02002987 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002988 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002989 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002990 (((int *)net)[i] & ((int *)mask)[i]))
2991 return 0;
2992 return 1;
2993}
2994
2995/* RFC 4291 prefix */
2996const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
2997 0x00, 0x00, 0x00, 0x00,
2998 0x00, 0x00, 0xFF, 0xFF };
2999
Joseph Herlant32b83272018-11-15 11:58:28 -08003000/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003001 * Input and output may overlap.
3002 */
David du Colombier4f92d322011-03-24 11:09:31 +01003003void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3004{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003005 struct in_addr tmp_addr;
3006
3007 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003008 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003009 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003010}
3011
Joseph Herlant32b83272018-11-15 11:58:28 -08003012/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003013 * Return true if conversion is possible and false otherwise.
3014 */
3015int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3016{
3017 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3018 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3019 sizeof(struct in_addr));
3020 return 1;
3021 }
3022
3023 return 0;
3024}
3025
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003026/* compare two struct sockaddr_storage and return:
3027 * 0 (true) if the addr is the same in both
3028 * 1 (false) if the addr is not the same in both
3029 * -1 (unable) if one of the addr is not AF_INET*
3030 */
3031int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3032{
3033 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3034 return -1;
3035
3036 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3037 return -1;
3038
3039 if (ss1->ss_family != ss2->ss_family)
3040 return 1;
3041
3042 switch (ss1->ss_family) {
3043 case AF_INET:
3044 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3045 &((struct sockaddr_in *)ss2)->sin_addr,
3046 sizeof(struct in_addr)) != 0;
3047 case AF_INET6:
3048 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3049 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3050 sizeof(struct in6_addr)) != 0;
3051 }
3052
3053 return 1;
3054}
3055
Baptiste Assmann08396c82016-01-31 00:27:17 +01003056/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003057 * The caller must allocate and clear <dest> before calling.
3058 * The source must be in either AF_INET or AF_INET6 family, or the destination
3059 * address will be undefined. If the destination address used to hold a port,
3060 * it is preserved, so that this function can be used to switch to another
3061 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003062 */
3063struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3064{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003065 int prev_port;
3066
3067 prev_port = get_net_port(dest);
3068 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003069 dest->ss_family = source->ss_family;
3070
3071 /* copy new addr and apply it */
3072 switch (source->ss_family) {
3073 case AF_INET:
3074 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003075 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003076 break;
3077 case AF_INET6:
3078 memcpy(((struct sockaddr_in6 *)dest)->sin6_addr.s6_addr, ((struct sockaddr_in6 *)source)->sin6_addr.s6_addr, sizeof(struct in6_addr));
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003079 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003080 break;
3081 }
3082
3083 return dest;
3084}
3085
William Lallemand421f5b52012-02-06 18:15:57 +01003086char *human_time(int t, short hz_div) {
3087 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3088 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003089 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003090 int cnt=2; // print two numbers
3091
3092 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003093 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003094 return rv;
3095 }
3096
3097 if (unlikely(hz_div > 1))
3098 t /= hz_div;
3099
3100 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003101 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003102 cnt--;
3103 }
3104
3105 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003106 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003107 cnt--;
3108 }
3109
3110 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003111 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003112 cnt--;
3113 }
3114
3115 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003116 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003117
3118 return rv;
3119}
3120
3121const char *monthname[12] = {
3122 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3123 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3124};
3125
3126/* date2str_log: write a date in the format :
3127 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3128 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3129 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3130 *
3131 * without using sprintf. return a pointer to the last char written (\0) or
3132 * NULL if there isn't enough space.
3133 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003134char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003135{
3136
3137 if (size < 25) /* the size is fixed: 24 chars + \0 */
3138 return NULL;
3139
3140 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003141 if (!dst)
3142 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003143 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003144
William Lallemand421f5b52012-02-06 18:15:57 +01003145 memcpy(dst, monthname[tm->tm_mon], 3); // month
3146 dst += 3;
3147 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003148
William Lallemand421f5b52012-02-06 18:15:57 +01003149 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003150 if (!dst)
3151 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003152 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003153
William Lallemand421f5b52012-02-06 18:15:57 +01003154 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003155 if (!dst)
3156 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003157 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003158
William Lallemand421f5b52012-02-06 18:15:57 +01003159 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003160 if (!dst)
3161 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003162 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003163
William Lallemand421f5b52012-02-06 18:15:57 +01003164 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003165 if (!dst)
3166 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003167 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003168
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003169 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003170 if (!dst)
3171 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003172 *dst = '\0';
3173
3174 return dst;
3175}
3176
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003177/* Base year used to compute leap years */
3178#define TM_YEAR_BASE 1900
3179
3180/* Return the difference in seconds between two times (leap seconds are ignored).
3181 * Retrieved from glibc 2.18 source code.
3182 */
3183static int my_tm_diff(const struct tm *a, const struct tm *b)
3184{
3185 /* Compute intervening leap days correctly even if year is negative.
3186 * Take care to avoid int overflow in leap day calculations,
3187 * but it's OK to assume that A and B are close to each other.
3188 */
3189 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3190 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3191 int a100 = a4 / 25 - (a4 % 25 < 0);
3192 int b100 = b4 / 25 - (b4 % 25 < 0);
3193 int a400 = a100 >> 2;
3194 int b400 = b100 >> 2;
3195 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3196 int years = a->tm_year - b->tm_year;
3197 int days = (365 * years + intervening_leap_days
3198 + (a->tm_yday - b->tm_yday));
3199 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3200 + (a->tm_min - b->tm_min))
3201 + (a->tm_sec - b->tm_sec));
3202}
3203
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003204/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003205 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003206 * The string returned has the same format as returned by strftime(... "%z", tm).
3207 * Offsets are kept in an internal cache for better performances.
3208 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003209const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003210{
3211 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003212 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003213
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003214 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003215 struct tm tm_gmt;
3216 int diff;
3217 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003218
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003219 /* Pretend DST not active if its status is unknown */
3220 if (isdst < 0)
3221 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003222
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003223 /* Fetch the offset and initialize it if needed */
3224 gmt_offset = gmt_offsets[isdst & 0x01];
3225 if (unlikely(!*gmt_offset)) {
3226 get_gmtime(t, &tm_gmt);
3227 diff = my_tm_diff(tm, &tm_gmt);
3228 if (diff < 0) {
3229 diff = -diff;
3230 *gmt_offset = '-';
3231 } else {
3232 *gmt_offset = '+';
3233 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003234 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003235 diff /= 60; /* Convert to minutes */
3236 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3237 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003238
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003239 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003240}
3241
William Lallemand421f5b52012-02-06 18:15:57 +01003242/* gmt2str_log: write a date in the format :
3243 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3244 * return a pointer to the last char written (\0) or
3245 * NULL if there isn't enough space.
3246 */
3247char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3248{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003249 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003250 return NULL;
3251
3252 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003253 if (!dst)
3254 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003255 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003256
William Lallemand421f5b52012-02-06 18:15:57 +01003257 memcpy(dst, monthname[tm->tm_mon], 3); // month
3258 dst += 3;
3259 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003260
William Lallemand421f5b52012-02-06 18:15:57 +01003261 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003262 if (!dst)
3263 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003264 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003265
William Lallemand421f5b52012-02-06 18:15:57 +01003266 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003267 if (!dst)
3268 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003269 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003270
William Lallemand421f5b52012-02-06 18:15:57 +01003271 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003272 if (!dst)
3273 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003274 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003275
William Lallemand421f5b52012-02-06 18:15:57 +01003276 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003277 if (!dst)
3278 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003279 *dst++ = ' ';
3280 *dst++ = '+';
3281 *dst++ = '0';
3282 *dst++ = '0';
3283 *dst++ = '0';
3284 *dst++ = '0';
3285 *dst = '\0';
3286
3287 return dst;
3288}
3289
Yuxans Yao4e25b012012-10-19 10:36:09 +08003290/* localdate2str_log: write a date in the format :
3291 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003292 * Both t and tm must represent the same time.
3293 * return a pointer to the last char written (\0) or
3294 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003295 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003296char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003297{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003298 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003299 if (size < 27) /* the size is fixed: 26 chars + \0 */
3300 return NULL;
3301
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003302 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003303
Yuxans Yao4e25b012012-10-19 10:36:09 +08003304 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003305 if (!dst)
3306 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003307 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003308
Yuxans Yao4e25b012012-10-19 10:36:09 +08003309 memcpy(dst, monthname[tm->tm_mon], 3); // month
3310 dst += 3;
3311 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003312
Yuxans Yao4e25b012012-10-19 10:36:09 +08003313 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003314 if (!dst)
3315 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003316 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003317
Yuxans Yao4e25b012012-10-19 10:36:09 +08003318 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003319 if (!dst)
3320 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003321 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003322
Yuxans Yao4e25b012012-10-19 10:36:09 +08003323 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003324 if (!dst)
3325 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003326 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003327
Yuxans Yao4e25b012012-10-19 10:36:09 +08003328 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003329 if (!dst)
3330 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003331 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003332
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003333 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003334 dst += 5;
3335 *dst = '\0';
3336
3337 return dst;
3338}
3339
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003340/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3341 * It is meant as a portable replacement for timegm() for use with valid inputs.
3342 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3343 */
3344time_t my_timegm(const struct tm *tm)
3345{
3346 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3347 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3348 * sum of the extra N days for elapsed months. The sum of all these N
3349 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3350 * in a 5-bit word. This means that with 60 bits we can represent a
3351 * matrix of all these values at once, which is fast and efficient to
3352 * access. The extra February day for leap years is not counted here.
3353 *
3354 * Jan : none = 0 (0)
3355 * Feb : Jan = 3 (3)
3356 * Mar : Jan..Feb = 3 (3 + 0)
3357 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3358 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3359 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3360 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3361 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3362 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3363 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3364 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3365 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3366 */
3367 uint64_t extra =
3368 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3369 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3370 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3371 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3372
3373 unsigned int y = tm->tm_year + 1900;
3374 unsigned int m = tm->tm_mon;
3375 unsigned long days = 0;
3376
3377 /* days since 1/1/1970 for full years */
3378 days += days_since_zero(y) - days_since_zero(1970);
3379
3380 /* days for full months in the current year */
3381 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3382
3383 /* count + 1 after March for leap years. A leap year is a year multiple
3384 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3385 * is leap, 1900 isn't, 1904 is.
3386 */
3387 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3388 days++;
3389
3390 days += tm->tm_mday - 1;
3391 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3392}
3393
Thierry Fournier93127942016-01-20 18:49:45 +01003394/* This function check a char. It returns true and updates
3395 * <date> and <len> pointer to the new position if the
3396 * character is found.
3397 */
3398static inline int parse_expect_char(const char **date, int *len, char c)
3399{
3400 if (*len < 1 || **date != c)
3401 return 0;
3402 (*len)--;
3403 (*date)++;
3404 return 1;
3405}
3406
3407/* This function expects a string <str> of len <l>. It return true and updates.
3408 * <date> and <len> if the string matches, otherwise, it returns false.
3409 */
3410static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3411{
3412 if (*len < l || strncmp(*date, str, l) != 0)
3413 return 0;
3414 (*len) -= l;
3415 (*date) += l;
3416 return 1;
3417}
3418
3419/* This macro converts 3 chars name in integer. */
3420#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3421
3422/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3423 * / %x54.75.65 ; "Tue", case-sensitive
3424 * / %x57.65.64 ; "Wed", case-sensitive
3425 * / %x54.68.75 ; "Thu", case-sensitive
3426 * / %x46.72.69 ; "Fri", case-sensitive
3427 * / %x53.61.74 ; "Sat", case-sensitive
3428 * / %x53.75.6E ; "Sun", case-sensitive
3429 *
3430 * This array must be alphabetically sorted
3431 */
3432static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3433{
3434 if (*len < 3)
3435 return 0;
3436 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3437 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3438 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3439 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3440 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3441 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3442 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3443 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3444 default: return 0;
3445 }
3446 *len -= 3;
3447 *date += 3;
3448 return 1;
3449}
3450
3451/* month = %x4A.61.6E ; "Jan", case-sensitive
3452 * / %x46.65.62 ; "Feb", case-sensitive
3453 * / %x4D.61.72 ; "Mar", case-sensitive
3454 * / %x41.70.72 ; "Apr", case-sensitive
3455 * / %x4D.61.79 ; "May", case-sensitive
3456 * / %x4A.75.6E ; "Jun", case-sensitive
3457 * / %x4A.75.6C ; "Jul", case-sensitive
3458 * / %x41.75.67 ; "Aug", case-sensitive
3459 * / %x53.65.70 ; "Sep", case-sensitive
3460 * / %x4F.63.74 ; "Oct", case-sensitive
3461 * / %x4E.6F.76 ; "Nov", case-sensitive
3462 * / %x44.65.63 ; "Dec", case-sensitive
3463 *
3464 * This array must be alphabetically sorted
3465 */
3466static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3467{
3468 if (*len < 3)
3469 return 0;
3470 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3471 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3472 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3473 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3474 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3475 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3476 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3477 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3478 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3479 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3480 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3481 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3482 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3483 default: return 0;
3484 }
3485 *len -= 3;
3486 *date += 3;
3487 return 1;
3488}
3489
3490/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3491 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3492 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3493 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3494 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3495 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3496 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3497 *
3498 * This array must be alphabetically sorted
3499 */
3500static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3501{
3502 if (*len < 6) /* Minimum length. */
3503 return 0;
3504 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3505 case STR2I3('M','o','n'):
3506 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3507 tm->tm_wday = 1;
3508 return 1;
3509 case STR2I3('T','u','e'):
3510 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3511 tm->tm_wday = 2;
3512 return 1;
3513 case STR2I3('W','e','d'):
3514 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3515 tm->tm_wday = 3;
3516 return 1;
3517 case STR2I3('T','h','u'):
3518 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3519 tm->tm_wday = 4;
3520 return 1;
3521 case STR2I3('F','r','i'):
3522 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3523 tm->tm_wday = 5;
3524 return 1;
3525 case STR2I3('S','a','t'):
3526 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3527 tm->tm_wday = 6;
3528 return 1;
3529 case STR2I3('S','u','n'):
3530 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3531 tm->tm_wday = 7;
3532 return 1;
3533 }
3534 return 0;
3535}
3536
3537/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3538static inline int parse_digit(const char **date, int *len, int *digit)
3539{
3540 if (*len < 1 || **date < '0' || **date > '9')
3541 return 0;
3542 *digit = (**date - '0');
3543 (*date)++;
3544 (*len)--;
3545 return 1;
3546}
3547
3548/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3549static inline int parse_2digit(const char **date, int *len, int *digit)
3550{
3551 int value;
3552
3553 RET0_UNLESS(parse_digit(date, len, &value));
3554 (*digit) = value * 10;
3555 RET0_UNLESS(parse_digit(date, len, &value));
3556 (*digit) += value;
3557
3558 return 1;
3559}
3560
3561/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3562static inline int parse_4digit(const char **date, int *len, int *digit)
3563{
3564 int value;
3565
3566 RET0_UNLESS(parse_digit(date, len, &value));
3567 (*digit) = value * 1000;
3568
3569 RET0_UNLESS(parse_digit(date, len, &value));
3570 (*digit) += value * 100;
3571
3572 RET0_UNLESS(parse_digit(date, len, &value));
3573 (*digit) += value * 10;
3574
3575 RET0_UNLESS(parse_digit(date, len, &value));
3576 (*digit) += value;
3577
3578 return 1;
3579}
3580
3581/* time-of-day = hour ":" minute ":" second
3582 * ; 00:00:00 - 23:59:60 (leap second)
3583 *
3584 * hour = 2DIGIT
3585 * minute = 2DIGIT
3586 * second = 2DIGIT
3587 */
3588static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3589{
3590 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3591 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3592 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3593 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3594 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3595 return 1;
3596}
3597
3598/* From RFC7231
3599 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3600 *
3601 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3602 * ; fixed length/zone/capitalization subset of the format
3603 * ; see Section 3.3 of [RFC5322]
3604 *
3605 *
3606 * date1 = day SP month SP year
3607 * ; e.g., 02 Jun 1982
3608 *
3609 * day = 2DIGIT
3610 * year = 4DIGIT
3611 *
3612 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3613 *
3614 * time-of-day = hour ":" minute ":" second
3615 * ; 00:00:00 - 23:59:60 (leap second)
3616 *
3617 * hour = 2DIGIT
3618 * minute = 2DIGIT
3619 * second = 2DIGIT
3620 *
3621 * DIGIT = decimal 0-9
3622 */
3623int parse_imf_date(const char *date, int len, struct tm *tm)
3624{
David Carlier327298c2016-11-20 10:42:38 +00003625 /* tm_gmtoff, if present, ought to be zero'ed */
3626 memset(tm, 0, sizeof(*tm));
3627
Thierry Fournier93127942016-01-20 18:49:45 +01003628 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3629 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3630 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3631 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3632 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3633 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3634 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3635 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3636 tm->tm_year -= 1900;
3637 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3638 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3639 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3640 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3641 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003642 return 1;
3643}
3644
3645/* From RFC7231
3646 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3647 *
3648 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3649 * date2 = day "-" month "-" 2DIGIT
3650 * ; e.g., 02-Jun-82
3651 *
3652 * day = 2DIGIT
3653 */
3654int parse_rfc850_date(const char *date, int len, struct tm *tm)
3655{
3656 int year;
3657
David Carlier327298c2016-11-20 10:42:38 +00003658 /* tm_gmtoff, if present, ought to be zero'ed */
3659 memset(tm, 0, sizeof(*tm));
3660
Thierry Fournier93127942016-01-20 18:49:45 +01003661 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3662 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3663 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3664 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3665 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3666 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3667 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3668
3669 /* year = 2DIGIT
3670 *
3671 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3672 * two-digit year, MUST interpret a timestamp that appears to be more
3673 * than 50 years in the future as representing the most recent year in
3674 * the past that had the same last two digits.
3675 */
3676 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3677
3678 /* expect SP */
3679 if (!parse_expect_char(&date, &len, ' ')) {
3680 /* Maybe we have the date with 4 digits. */
3681 RET0_UNLESS(parse_2digit(&date, &len, &year));
3682 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3683 /* expect SP */
3684 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3685 } else {
3686 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3687 * tm_year is the number of year since 1900, so for +1900, we
3688 * do nothing, and for +2000, we add 100.
3689 */
3690 if (tm->tm_year <= 60)
3691 tm->tm_year += 100;
3692 }
3693
3694 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3695 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3696 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3697 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003698
3699 return 1;
3700}
3701
3702/* From RFC7231
3703 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3704 *
3705 * asctime-date = day-name SP date3 SP time-of-day SP year
3706 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3707 * ; e.g., Jun 2
3708 *
3709 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3710 * whitespace in an HTTP-date beyond that specifically included as SP in
3711 * the grammar.
3712 */
3713int parse_asctime_date(const char *date, int len, struct tm *tm)
3714{
David Carlier327298c2016-11-20 10:42:38 +00003715 /* tm_gmtoff, if present, ought to be zero'ed */
3716 memset(tm, 0, sizeof(*tm));
3717
Thierry Fournier93127942016-01-20 18:49:45 +01003718 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3719 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3720 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3721 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3722
3723 /* expect SP and 1DIGIT or 2DIGIT */
3724 if (parse_expect_char(&date, &len, ' '))
3725 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3726 else
3727 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3728
3729 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3730 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3731 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3732 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3733 tm->tm_year -= 1900;
3734 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003735 return 1;
3736}
3737
3738/* From RFC7231
3739 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3740 *
3741 * HTTP-date = IMF-fixdate / obs-date
3742 * obs-date = rfc850-date / asctime-date
3743 *
3744 * parses an HTTP date in the RFC format and is accepted
3745 * alternatives. <date> is the strinf containing the date,
3746 * len is the len of the string. <tm> is filled with the
3747 * parsed time. We must considers this time as GMT.
3748 */
3749int parse_http_date(const char *date, int len, struct tm *tm)
3750{
3751 if (parse_imf_date(date, len, tm))
3752 return 1;
3753
3754 if (parse_rfc850_date(date, len, tm))
3755 return 1;
3756
3757 if (parse_asctime_date(date, len, tm))
3758 return 1;
3759
3760 return 0;
3761}
3762
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003763/* Dynamically allocates a string of the proper length to hold the formatted
3764 * output. NULL is returned on error. The caller is responsible for freeing the
3765 * memory area using free(). The resulting string is returned in <out> if the
3766 * pointer is not NULL. A previous version of <out> might be used to build the
3767 * new string, and it will be freed before returning if it is not NULL, which
3768 * makes it possible to build complex strings from iterative calls without
3769 * having to care about freeing intermediate values, as in the example below :
3770 *
3771 * memprintf(&err, "invalid argument: '%s'", arg);
3772 * ...
3773 * memprintf(&err, "parser said : <%s>\n", *err);
3774 * ...
3775 * free(*err);
3776 *
3777 * This means that <err> must be initialized to NULL before first invocation.
3778 * The return value also holds the allocated string, which eases error checking
3779 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003780 * passed instead and it will be ignored. The returned message will then also
3781 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003782 *
3783 * It is also convenient to use it without any free except the last one :
3784 * err = NULL;
3785 * if (!fct1(err)) report(*err);
3786 * if (!fct2(err)) report(*err);
3787 * if (!fct3(err)) report(*err);
3788 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003789 *
3790 * memprintf relies on memvprintf. This last version can be called from any
3791 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003792 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003793char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003794{
3795 va_list args;
3796 char *ret = NULL;
3797 int allocated = 0;
3798 int needed = 0;
3799
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003800 if (!out)
3801 return NULL;
3802
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003803 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003804 char buf1;
3805
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003806 /* vsnprintf() will return the required length even when the
3807 * target buffer is NULL. We do this in a loop just in case
3808 * intermediate evaluations get wrong.
3809 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003810 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003811 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003812 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003813 if (needed < allocated) {
3814 /* Note: on Solaris 8, the first iteration always
3815 * returns -1 if allocated is zero, so we force a
3816 * retry.
3817 */
3818 if (!allocated)
3819 needed = 0;
3820 else
3821 break;
3822 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003823
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003824 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003825 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003826 } while (ret);
3827
3828 if (needed < 0) {
3829 /* an error was encountered */
3830 free(ret);
3831 ret = NULL;
3832 }
3833
3834 if (out) {
3835 free(*out);
3836 *out = ret;
3837 }
3838
3839 return ret;
3840}
William Lallemand421f5b52012-02-06 18:15:57 +01003841
Christopher Faulet93a518f2017-10-24 11:25:33 +02003842char *memprintf(char **out, const char *format, ...)
3843{
3844 va_list args;
3845 char *ret = NULL;
3846
3847 va_start(args, format);
3848 ret = memvprintf(out, format, args);
3849 va_end(args);
3850
3851 return ret;
3852}
3853
Willy Tarreau21c705b2012-09-14 11:40:36 +02003854/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3855 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003856 * freed by the caller. It also supports being passed a NULL which results in the same
3857 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003858 * Example of use :
3859 * parse(cmd, &err); (callee: memprintf(&err, ...))
3860 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3861 * free(err);
3862 */
3863char *indent_msg(char **out, int level)
3864{
3865 char *ret, *in, *p;
3866 int needed = 0;
3867 int lf = 0;
3868 int lastlf = 0;
3869 int len;
3870
Willy Tarreau70eec382012-10-10 08:56:47 +02003871 if (!out || !*out)
3872 return NULL;
3873
Willy Tarreau21c705b2012-09-14 11:40:36 +02003874 in = *out - 1;
3875 while ((in = strchr(in + 1, '\n')) != NULL) {
3876 lastlf = in - *out;
3877 lf++;
3878 }
3879
3880 if (!lf) /* single line, no LF, return it as-is */
3881 return *out;
3882
3883 len = strlen(*out);
3884
3885 if (lf == 1 && lastlf == len - 1) {
3886 /* single line, LF at end, strip it and return as-is */
3887 (*out)[lastlf] = 0;
3888 return *out;
3889 }
3890
3891 /* OK now we have at least one LF, we need to process the whole string
3892 * as a multi-line string. What we'll do :
3893 * - prefix with an LF if there is none
3894 * - add <level> spaces before each line
3895 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3896 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3897 */
3898
3899 needed = 1 + level * (lf + 1) + len + 1;
3900 p = ret = malloc(needed);
3901 in = *out;
3902
3903 /* skip initial LFs */
3904 while (*in == '\n')
3905 in++;
3906
3907 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3908 while (*in) {
3909 *p++ = '\n';
3910 memset(p, ' ', level);
3911 p += level;
3912 do {
3913 *p++ = *in++;
3914 } while (*in && *in != '\n');
3915 if (*in)
3916 in++;
3917 }
3918 *p = 0;
3919
3920 free(*out);
3921 *out = ret;
3922
3923 return ret;
3924}
3925
Willy Tarreaua2c99112019-08-21 13:17:37 +02003926/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3927 * and end of lines replaced with <eol> if not 0. The first line to indent has
3928 * to be indicated in <first> (starts at zero), so that it is possible to skip
3929 * indenting the first line if it has to be appended after an existing message.
3930 * Empty strings are never indented, and NULL strings are considered empty both
3931 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3932 * character, non-zero otherwise.
3933 */
3934int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3935{
3936 int bol, lf;
3937 int pfxlen = pfx ? strlen(pfx) : 0;
3938
3939 if (!in)
3940 return 0;
3941
3942 bol = 1;
3943 lf = 0;
3944 while (*in) {
3945 if (bol && pfxlen) {
3946 if (first > 0)
3947 first--;
3948 else
3949 b_putblk(out, pfx, pfxlen);
3950 bol = 0;
3951 }
3952
3953 lf = (*in == '\n');
3954 bol |= lf;
3955 b_putchr(out, (lf && eol) ? eol : *in);
3956 in++;
3957 }
3958 return lf;
3959}
3960
Willy Tarreau9d22e562019-03-29 18:49:09 +01003961/* removes environment variable <name> from the environment as found in
3962 * environ. This is only provided as an alternative for systems without
3963 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003964 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003965 * <name> and to replace the matching pointers with the last pointer of
3966 * the array (since variables are not ordered).
3967 * It always returns 0 (success).
3968 */
3969int my_unsetenv(const char *name)
3970{
3971 extern char **environ;
3972 char **p = environ;
3973 int vars;
3974 int next;
3975 int len;
3976
3977 len = strlen(name);
3978 for (vars = 0; p[vars]; vars++)
3979 ;
3980 next = 0;
3981 while (next < vars) {
3982 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3983 next++;
3984 continue;
3985 }
3986 if (next < vars - 1)
3987 p[next] = p[vars - 1];
3988 p[--vars] = NULL;
3989 }
3990 return 0;
3991}
3992
Willy Tarreaudad36a32013-03-11 01:20:04 +01003993/* Convert occurrences of environment variables in the input string to their
3994 * corresponding value. A variable is identified as a series of alphanumeric
3995 * characters or underscores following a '$' sign. The <in> string must be
3996 * free()able. NULL returns NULL. The resulting string might be reallocated if
3997 * some expansion is made. Variable names may also be enclosed into braces if
3998 * needed (eg: to concatenate alphanum characters).
3999 */
4000char *env_expand(char *in)
4001{
4002 char *txt_beg;
4003 char *out;
4004 char *txt_end;
4005 char *var_beg;
4006 char *var_end;
4007 char *value;
4008 char *next;
4009 int out_len;
4010 int val_len;
4011
4012 if (!in)
4013 return in;
4014
4015 value = out = NULL;
4016 out_len = 0;
4017
4018 txt_beg = in;
4019 do {
4020 /* look for next '$' sign in <in> */
4021 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4022
4023 if (!*txt_end && !out) /* end and no expansion performed */
4024 return in;
4025
4026 val_len = 0;
4027 next = txt_end;
4028 if (*txt_end == '$') {
4029 char save;
4030
4031 var_beg = txt_end + 1;
4032 if (*var_beg == '{')
4033 var_beg++;
4034
4035 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004036 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004037 var_end++;
4038 }
4039
4040 next = var_end;
4041 if (*var_end == '}' && (var_beg > txt_end + 1))
4042 next++;
4043
4044 /* get value of the variable name at this location */
4045 save = *var_end;
4046 *var_end = '\0';
4047 value = getenv(var_beg);
4048 *var_end = save;
4049 val_len = value ? strlen(value) : 0;
4050 }
4051
Hubert Verstraete831962e2016-06-28 22:44:26 +02004052 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004053 if (txt_end > txt_beg) {
4054 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4055 out_len += txt_end - txt_beg;
4056 }
4057 if (val_len) {
4058 memcpy(out + out_len, value, val_len);
4059 out_len += val_len;
4060 }
4061 out[out_len] = 0;
4062 txt_beg = next;
4063 } while (*txt_beg);
4064
4065 /* here we know that <out> was allocated and that we don't need <in> anymore */
4066 free(in);
4067 return out;
4068}
4069
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004070
4071/* same as strstr() but case-insensitive and with limit length */
4072const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4073{
4074 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004075 unsigned int slen, plen;
4076 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004077
4078 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4079 return NULL;
4080
4081 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4082 return str1;
4083
4084 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4085 return NULL;
4086
4087 for (tmp1 = 0, start = (char *)str1, pptr = (char *)str2, slen = len_str1, plen = len_str2; slen >= plen; start++, slen--) {
Willy Tarreauf278eec2020-07-05 21:46:32 +02004088 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004089 start++;
4090 slen--;
4091 tmp1++;
4092
4093 if (tmp1 >= len_str1)
4094 return NULL;
4095
4096 /* if pattern longer than string */
4097 if (slen < plen)
4098 return NULL;
4099 }
4100
4101 sptr = start;
4102 pptr = (char *)str2;
4103
4104 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004105 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004106 sptr++;
4107 pptr++;
4108 tmp2++;
4109
4110 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4111 return start;
4112 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4113 return NULL;
4114 }
4115 }
4116 return NULL;
4117}
4118
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004119/* This function read the next valid utf8 char.
4120 * <s> is the byte srray to be decode, <len> is its length.
4121 * The function returns decoded char encoded like this:
4122 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4123 * are the length read. The decoded character is stored in <c>.
4124 */
4125unsigned char utf8_next(const char *s, int len, unsigned int *c)
4126{
4127 const unsigned char *p = (unsigned char *)s;
4128 int dec;
4129 unsigned char code = UTF8_CODE_OK;
4130
4131 if (len < 1)
4132 return UTF8_CODE_OK;
4133
4134 /* Check the type of UTF8 sequence
4135 *
4136 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4137 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4138 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4139 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4140 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4141 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4142 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4143 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4144 */
4145 switch (*p) {
4146 case 0x00 ... 0x7f:
4147 *c = *p;
4148 return UTF8_CODE_OK | 1;
4149
4150 case 0x80 ... 0xbf:
4151 *c = *p;
4152 return UTF8_CODE_BADSEQ | 1;
4153
4154 case 0xc0 ... 0xdf:
4155 if (len < 2) {
4156 *c = *p;
4157 return UTF8_CODE_BADSEQ | 1;
4158 }
4159 *c = *p & 0x1f;
4160 dec = 1;
4161 break;
4162
4163 case 0xe0 ... 0xef:
4164 if (len < 3) {
4165 *c = *p;
4166 return UTF8_CODE_BADSEQ | 1;
4167 }
4168 *c = *p & 0x0f;
4169 dec = 2;
4170 break;
4171
4172 case 0xf0 ... 0xf7:
4173 if (len < 4) {
4174 *c = *p;
4175 return UTF8_CODE_BADSEQ | 1;
4176 }
4177 *c = *p & 0x07;
4178 dec = 3;
4179 break;
4180
4181 case 0xf8 ... 0xfb:
4182 if (len < 5) {
4183 *c = *p;
4184 return UTF8_CODE_BADSEQ | 1;
4185 }
4186 *c = *p & 0x03;
4187 dec = 4;
4188 break;
4189
4190 case 0xfc ... 0xfd:
4191 if (len < 6) {
4192 *c = *p;
4193 return UTF8_CODE_BADSEQ | 1;
4194 }
4195 *c = *p & 0x01;
4196 dec = 5;
4197 break;
4198
4199 case 0xfe ... 0xff:
4200 default:
4201 *c = *p;
4202 return UTF8_CODE_BADSEQ | 1;
4203 }
4204
4205 p++;
4206
4207 while (dec > 0) {
4208
4209 /* need 0x10 for the 2 first bits */
4210 if ( ( *p & 0xc0 ) != 0x80 )
4211 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4212
4213 /* add data at char */
4214 *c = ( *c << 6 ) | ( *p & 0x3f );
4215
4216 dec--;
4217 p++;
4218 }
4219
4220 /* Check ovelong encoding.
4221 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4222 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4223 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4224 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004225 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004226 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4227 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4228 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4229 code |= UTF8_CODE_OVERLONG;
4230
4231 /* Check invalid UTF8 range. */
4232 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4233 (*c >= 0xfffe && *c <= 0xffff))
4234 code |= UTF8_CODE_INVRANGE;
4235
4236 return code | ((p-(unsigned char *)s)&0x0f);
4237}
4238
Maxime de Roucydc887852016-05-13 23:52:54 +02004239/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4240 * On failure : return 0 and <err> filled with an error message.
4241 * The caller is responsible for freeing the <err> and <str> copy
4242 * memory area using free()
4243 */
4244int list_append_word(struct list *li, const char *str, char **err)
4245{
4246 struct wordlist *wl;
4247
4248 wl = calloc(1, sizeof(*wl));
4249 if (!wl) {
4250 memprintf(err, "out of memory");
4251 goto fail_wl;
4252 }
4253
4254 wl->s = strdup(str);
4255 if (!wl->s) {
4256 memprintf(err, "out of memory");
4257 goto fail_wl_s;
4258 }
4259
4260 LIST_ADDQ(li, &wl->list);
4261
4262 return 1;
4263
4264fail_wl_s:
4265 free(wl->s);
4266fail_wl:
4267 free(wl);
4268 return 0;
4269}
4270
Willy Tarreau37101052019-05-20 16:48:20 +02004271/* indicates if a memory location may safely be read or not. The trick consists
4272 * in performing a harmless syscall using this location as an input and letting
4273 * the operating system report whether it's OK or not. For this we have the
4274 * stat() syscall, which will return EFAULT when the memory location supposed
4275 * to contain the file name is not readable. If it is readable it will then
4276 * either return 0 if the area contains an existing file name, or -1 with
4277 * another code. This must not be abused, and some audit systems might detect
4278 * this as abnormal activity. It's used only for unsafe dumps.
4279 */
4280int may_access(const void *ptr)
4281{
4282 struct stat buf;
4283
4284 if (stat(ptr, &buf) == 0)
4285 return 1;
4286 if (errno == EFAULT)
4287 return 0;
4288 return 1;
4289}
4290
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004291/* print a string of text buffer to <out>. The format is :
4292 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4293 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4294 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4295 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004296int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004297{
4298 unsigned char c;
4299 int ptr = 0;
4300
4301 while (buf[ptr] && ptr < bsize) {
4302 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004303 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004304 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004305 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004306 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004307 }
4308 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004309 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004310 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004311 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004312 switch (c) {
4313 case ' ': c = ' '; break;
4314 case '\t': c = 't'; break;
4315 case '\n': c = 'n'; break;
4316 case '\r': c = 'r'; break;
4317 case '\e': c = 'e'; break;
4318 case '\\': c = '\\'; break;
4319 case '=': c = '='; break;
4320 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004321 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004322 }
4323 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004324 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004325 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004326 out->area[out->data++] = '\\';
4327 out->area[out->data++] = 'x';
4328 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4329 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004330 }
4331 ptr++;
4332 }
4333
4334 return ptr;
4335}
4336
4337/* print a buffer in hexa.
4338 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4339 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004340int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004341{
4342 unsigned char c;
4343 int ptr = 0;
4344
4345 while (ptr < bsize) {
4346 c = buf[ptr];
4347
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004348 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004349 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004350 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4351 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004352
4353 ptr++;
4354 }
4355 return ptr;
4356}
4357
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004358/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4359 * prepending each line with prefix <pfx>. The output is *not* initialized.
4360 * The output will not wrap pas the buffer's end so it is more optimal if the
4361 * caller makes sure the buffer is aligned first. A trailing zero will always
4362 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004363 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4364 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004365 */
Willy Tarreau37101052019-05-20 16:48:20 +02004366void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004367{
4368 const unsigned char *d = buf;
4369 int i, j, start;
4370
4371 d = (const unsigned char *)(((unsigned long)buf) & -16);
4372 start = ((unsigned long)buf) & 15;
4373
4374 for (i = 0; i < start + len; i += 16) {
4375 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4376
Willy Tarreau37101052019-05-20 16:48:20 +02004377 // 0: unchecked, 1: checked safe, 2: danger
4378 unsafe = !!unsafe;
4379 if (unsafe && !may_access(d + i))
4380 unsafe = 2;
4381
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004382 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004383 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004384 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004385 else if (unsafe > 1)
4386 chunk_strcat(out, "** ");
4387 else
4388 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004389
4390 if (j == 7)
4391 chunk_strcat(out, "- ");
4392 }
4393 chunk_strcat(out, " ");
4394 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004395 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004396 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004397 else if (unsafe > 1)
4398 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004399 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004400 chunk_appendf(out, "%c", d[i + j]);
4401 else
4402 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004403 }
4404 chunk_strcat(out, "\n");
4405 }
4406}
4407
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004408/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4409 * enclosed in brackets after the address itself, formatted on 14 chars
4410 * including the "0x" prefix. This is meant to be used as a prefix for code
4411 * areas. For example:
4412 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4413 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4414 * is emitted. A NULL <pfx> will be considered empty.
4415 */
4416void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4417{
4418 int ok = 0;
4419 int i;
4420
4421 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4422
4423 for (i = 0; i < n; i++) {
4424 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4425 ok = may_access(addr + i);
4426 if (ok)
4427 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4428 else
4429 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4430 }
4431}
4432
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004433/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4434 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4435 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4436 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4437 * lines are respected within the limit of 70 output chars. Lines that are
4438 * continuation of a previous truncated line begin with "+" instead of " "
4439 * after the offset. The new pointer is returned.
4440 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004441int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004442 int *line, int ptr)
4443{
4444 int end;
4445 unsigned char c;
4446
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004447 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004448 if (end > out->size)
4449 return ptr;
4450
4451 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4452
4453 while (ptr < len && ptr < bsize) {
4454 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004455 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004456 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004457 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004458 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004459 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004460 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004461 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004462 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004463 switch (c) {
4464 case '\t': c = 't'; break;
4465 case '\n': c = 'n'; break;
4466 case '\r': c = 'r'; break;
4467 case '\e': c = 'e'; break;
4468 case '\\': c = '\\'; break;
4469 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004470 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004471 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004472 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004473 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004474 out->area[out->data++] = '\\';
4475 out->area[out->data++] = 'x';
4476 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4477 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004478 }
4479 if (buf[ptr++] == '\n') {
4480 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004481 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004482 *line = ptr;
4483 return ptr;
4484 }
4485 }
4486 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004487 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004488 return ptr;
4489}
4490
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004491/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004492 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4493 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004494 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004495void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4496 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004497{
Willy Tarreau73459792017-04-11 07:58:08 +02004498 unsigned int i;
4499 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004500
4501 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4502 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004503 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004504 for (j = 0; j < 8; j++) {
4505 if (b + j >= 0 && b + j < len)
4506 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4507 else
4508 fprintf(out, " ");
4509 }
4510
4511 if (b + j >= 0 && b + j < len)
4512 fputc('-', out);
4513 else
4514 fputc(' ', out);
4515
4516 for (j = 8; j < 16; j++) {
4517 if (b + j >= 0 && b + j < len)
4518 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4519 else
4520 fprintf(out, " ");
4521 }
4522
4523 fprintf(out, " ");
4524 for (j = 0; j < 16; j++) {
4525 if (b + j >= 0 && b + j < len) {
4526 if (isprint((unsigned char)buf[b + j]))
4527 fputc((unsigned char)buf[b + j], out);
4528 else
4529 fputc('.', out);
4530 }
4531 else
4532 fputc(' ', out);
4533 }
4534 fputc('\n', out);
4535 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004536}
4537
Willy Tarreaubb869862020-04-16 10:52:41 +02004538/* Tries to report the executable path name on platforms supporting this. If
4539 * not found or not possible, returns NULL.
4540 */
4541const char *get_exec_path()
4542{
4543 const char *ret = NULL;
4544
4545#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4546 long execfn = getauxval(AT_EXECFN);
4547
4548 if (execfn && execfn != ENOENT)
4549 ret = (const char *)execfn;
4550#endif
4551 return ret;
4552}
4553
Baruch Siache1651b22020-07-24 07:52:20 +03004554#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004555/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4556 * also returns the symbol size in <size>, otherwise returns 0 there.
4557 */
4558static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4559{
4560 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004561#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004562 const ElfW(Sym) *sym;
4563
4564 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4565 if (ret)
4566 *size = sym ? sym->st_size : 0;
4567#else
4568 ret = dladdr(addr, dli);
4569 *size = 0;
4570#endif
4571 return ret;
4572}
4573#endif
4574
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004575/* Tries to append to buffer <buf> some indications about the symbol at address
4576 * <addr> using the following form:
4577 * lib:+0xoffset (unresolvable address from lib's base)
4578 * main+0xoffset (unresolvable address from main (+/-))
4579 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4580 * name (resolved exact exec address)
4581 * lib:name (resolved exact lib address)
4582 * name+0xoffset/0xsize (resolved address within exec symbol)
4583 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4584 *
4585 * The file name (lib or executable) is limited to what lies between the last
4586 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4587 * the output if not null. The file is not dumped when it's the same as the one
Baruch Siache1651b22020-07-24 07:52:20 +03004588 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004589 *
4590 * The symbol's base address is returned, or NULL when unresolved, in order to
4591 * allow the caller to match it against known ones.
4592 */
Willy Tarreau0c439d82020-07-05 20:26:04 +02004593const void *resolve_sym_name(struct buffer *buf, const char *pfx, void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004594{
4595 const struct {
4596 const void *func;
4597 const char *name;
4598 } fcts[] = {
4599 { .func = process_stream, .name = "process_stream" },
4600 { .func = task_run_applet, .name = "task_run_applet" },
4601 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004602 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004603 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4604 { .func = listener_accept, .name = "listener_accept" },
4605 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4606 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4607#ifdef USE_LUA
4608 { .func = hlua_process_task, .name = "hlua_process_task" },
4609#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004610#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004611 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4612 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4613#endif
4614 };
4615
Baruch Siache1651b22020-07-24 07:52:20 +03004616#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004617 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004618 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004619 const char *fname, *p;
4620#endif
4621 int i;
4622
4623 if (pfx)
4624 chunk_appendf(buf, "%s", pfx);
4625
4626 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4627 if (addr == fcts[i].func) {
4628 chunk_appendf(buf, "%s", fcts[i].name);
4629 return addr;
4630 }
4631 }
4632
Baruch Siache1651b22020-07-24 07:52:20 +03004633#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004634 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004635 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004636 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004637
4638 /* 1. prefix the library name if it's not the same object as the one
4639 * that contains the main function. The name is picked between last '/'
4640 * and first following '.'.
4641 */
4642 if (!dladdr(main, &dli_main))
4643 dli_main.dli_fbase = NULL;
4644
4645 if (dli_main.dli_fbase != dli.dli_fbase) {
4646 fname = dli.dli_fname;
4647 p = strrchr(fname, '/');
4648 if (p++)
4649 fname = p;
4650 p = strchr(fname, '.');
4651 if (!p)
4652 p = fname + strlen(fname);
4653
4654 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4655 }
4656
4657 /* 2. symbol name */
4658 if (dli.dli_sname) {
4659 /* known, dump it and return symbol's address (exact or relative) */
4660 chunk_appendf(buf, "%s", dli.dli_sname);
4661 if (addr != dli.dli_saddr) {
4662 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004663 if (size)
4664 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004665 }
4666 return dli.dli_saddr;
4667 }
4668 else if (dli_main.dli_fbase != dli.dli_fbase) {
4669 /* unresolved symbol from a known library, report relative offset */
4670 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4671 return NULL;
4672 }
Baruch Siache1651b22020-07-24 07:52:20 +03004673#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004674 unknown:
4675 /* unresolved symbol from the main file, report relative offset to main */
4676 if ((void*)addr < (void*)main)
4677 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4678 else
4679 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4680 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004681}
4682
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004683/*
4684 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004685 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004686 *
4687 * First, initializes the value with <sz> as address to 0 and initializes the
4688 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4689 * address updating <sz> pointed value to the size of this array.
4690 *
4691 * Returns 1 if succeeded, 0 if not.
4692 */
4693int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4694{
4695 unsigned int *n;
4696 const char *s, *end;
4697
4698 s = str;
4699 *sz = 0;
4700 end = str + strlen(str);
4701 *nums = n = NULL;
4702
4703 while (1) {
4704 unsigned int r;
4705
4706 if (s >= end)
4707 break;
4708
4709 r = read_uint(&s, end);
4710 /* Expected characters after having read an uint: '\0' or '.',
4711 * if '.', must not be terminal.
4712 */
4713 if (*s != '\0'&& (*s++ != '.' || s == end))
4714 return 0;
4715
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004716 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004717 if (!n)
4718 return 0;
4719
4720 n[(*sz)++] = r;
4721 }
4722 *nums = n;
4723
4724 return 1;
4725}
4726
Willy Tarreau4d589e72019-08-23 19:02:26 +02004727
4728/* returns the number of bytes needed to encode <v> as a varint. An inline
4729 * version exists for use with constants (__varint_bytes()).
4730 */
4731int varint_bytes(uint64_t v)
4732{
4733 int len = 1;
4734
4735 if (v >= 240) {
4736 v = (v - 240) >> 4;
4737 while (1) {
4738 len++;
4739 if (v < 128)
4740 break;
4741 v = (v - 128) >> 7;
4742 }
4743 }
4744 return len;
4745}
4746
Willy Tarreau52bf8392020-03-08 00:42:37 +01004747
4748/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004749static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004750
4751/* This is a thread-safe implementation of xoroshiro128** described below:
4752 * http://prng.di.unimi.it/
4753 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4754 * supports fast jumps and passes all common quality tests. It is thread-safe,
4755 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4756 * local lock on other ones.
4757 */
4758uint64_t ha_random64()
4759{
4760 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004761 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4762 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004763
4764#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4765 static HA_SPINLOCK_T rand_lock;
4766
4767 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4768#endif
4769
4770 old[0] = ha_random_state[0];
4771 old[1] = ha_random_state[1];
4772
4773#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4774 do {
4775#endif
4776 result = rotl64(old[0] * 5, 7) * 9;
4777 new[1] = old[0] ^ old[1];
4778 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4779 new[1] = rotl64(new[1], 37); // c
4780
4781#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4782 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4783#else
4784 ha_random_state[0] = new[0];
4785 ha_random_state[1] = new[1];
4786#if defined(USE_THREAD)
4787 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4788#endif
4789#endif
4790 return result;
4791}
4792
4793/* seeds the random state using up to <len> bytes from <seed>, starting with
4794 * the first non-zero byte.
4795 */
4796void ha_random_seed(const unsigned char *seed, size_t len)
4797{
4798 size_t pos;
4799
4800 /* the seed must not be all zeroes, so we pre-fill it with alternating
4801 * bits and overwrite part of them with the block starting at the first
4802 * non-zero byte from the seed.
4803 */
4804 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4805
4806 for (pos = 0; pos < len; pos++)
4807 if (seed[pos] != 0)
4808 break;
4809
4810 if (pos == len)
4811 return;
4812
4813 seed += pos;
4814 len -= pos;
4815
4816 if (len > sizeof(ha_random_state))
4817 len = sizeof(ha_random_state);
4818
4819 memcpy(ha_random_state, seed, len);
4820}
4821
4822/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4823 * and is equivalent to calling ha_random64() as many times. It is used to
4824 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4825 * different generators (i.e. different processes after a fork). The <dist>
4826 * argument is the distance to jump to and is used in a loop so it rather not
4827 * be too large if the processing time is a concern.
4828 *
4829 * BEWARE: this function is NOT thread-safe and must not be called during
4830 * concurrent accesses to ha_random64().
4831 */
4832void ha_random_jump96(uint32_t dist)
4833{
4834 while (dist--) {
4835 uint64_t s0 = 0;
4836 uint64_t s1 = 0;
4837 int b;
4838
4839 for (b = 0; b < 64; b++) {
4840 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4841 s0 ^= ha_random_state[0];
4842 s1 ^= ha_random_state[1];
4843 }
4844 ha_random64();
4845 }
4846
4847 for (b = 0; b < 64; b++) {
4848 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4849 s0 ^= ha_random_state[0];
4850 s1 ^= ha_random_state[1];
4851 }
4852 ha_random64();
4853 }
4854 ha_random_state[0] = s0;
4855 ha_random_state[1] = s1;
4856 }
4857}
4858
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004859/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4860 * bytes large.
4861 */
4862void ha_generate_uuid(struct buffer *output)
4863{
4864 uint32_t rnd[4];
4865 uint64_t last;
4866
4867 last = ha_random64();
4868 rnd[0] = last;
4869 rnd[1] = last >> 32;
4870
4871 last = ha_random64();
4872 rnd[2] = last;
4873 rnd[3] = last >> 32;
4874
4875 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4876 rnd[0],
4877 rnd[1] & 0xFFFF,
4878 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4879 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4880 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4881}
4882
4883
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004884/* only used by parse_line() below. It supports writing in place provided that
4885 * <in> is updated to the next location before calling it. In that case, the
4886 * char at <in> may be overwritten.
4887 */
4888#define EMIT_CHAR(x) \
4889 do { \
4890 char __c = (char)(x); \
4891 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4892 err |= PARSE_ERR_OVERLAP; \
4893 if (outpos >= outmax) \
4894 err |= PARSE_ERR_TOOLARGE; \
4895 if (!err) \
4896 out[outpos] = __c; \
4897 outpos++; \
4898 } while (0)
4899
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004900/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004901 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4902 * extraneous ones are not emitted but <outlen> is updated so that the caller
4903 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4904 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004905 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4906 * it is guaranteed that at least one arg will point to the zero. It is safe
4907 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004908 *
4909 * <out> may overlap with <in> provided that it never goes further, in which
4910 * case the parser will accept to perform in-place parsing and unquoting/
4911 * unescaping but only if environment variables do not lead to expansion that
4912 * causes overlapping, otherwise the input string being destroyed, the error
4913 * will not be recoverable. Note that even during out-of-place <in> will
4914 * experience temporary modifications in-place for variable resolution and must
4915 * be writable, and will also receive zeroes to delimit words when using
4916 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4917 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4918 * starting point of the first invalid character sequence or unmatched
4919 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4920 * error reporting might be difficult since zeroes will have been inserted into
4921 * the string. One solution for the caller may consist in replacing all args
4922 * delimiters with spaces in this case.
4923 */
4924uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4925{
4926 char *quote = NULL;
4927 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02004928 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004929 unsigned char hex1, hex2;
4930 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004931 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004932 size_t outpos = 0;
4933 int squote = 0;
4934 int dquote = 0;
4935 int arg = 0;
4936 uint32_t err = 0;
4937
4938 *nbargs = 0;
4939 *outlen = 0;
4940
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004941 /* argsmax may be -1 here, protecting args[] from any write */
4942 if (arg < argsmax)
4943 args[arg] = out;
4944
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004945 while (1) {
4946 if (*in >= '-' && *in != '\\') {
4947 /* speedup: directly send all regular chars starting
4948 * with '-', '.', '/', alnum etc...
4949 */
4950 EMIT_CHAR(*in++);
4951 continue;
4952 }
4953 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4954 /* end of line */
4955 break;
4956 }
4957 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4958 /* comment */
4959 break;
4960 }
4961 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4962 if (dquote) {
4963 dquote = 0;
4964 quote = NULL;
4965 }
4966 else {
4967 dquote = 1;
4968 quote = in;
4969 }
4970 in++;
4971 continue;
4972 }
4973 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4974 if (squote) {
4975 squote = 0;
4976 quote = NULL;
4977 }
4978 else {
4979 squote = 1;
4980 quote = in;
4981 }
4982 in++;
4983 continue;
4984 }
4985 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4986 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4987 * C equivalent value but only when they have a special meaning and within
4988 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4989 */
4990 char tosend = *in;
4991
4992 switch (in[1]) {
4993 case ' ':
4994 case '\\':
4995 tosend = in[1];
4996 in++;
4997 break;
4998
4999 case 't':
5000 tosend = '\t';
5001 in++;
5002 break;
5003
5004 case 'n':
5005 tosend = '\n';
5006 in++;
5007 break;
5008
5009 case 'r':
5010 tosend = '\r';
5011 in++;
5012 break;
5013
5014 case '#':
5015 /* escaping of "#" only if comments are supported */
5016 if (opts & PARSE_OPT_SHARP)
5017 in++;
5018 tosend = *in;
5019 break;
5020
5021 case '\'':
5022 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5023 if (opts & PARSE_OPT_SQUOTE && !squote)
5024 in++;
5025 tosend = *in;
5026 break;
5027
5028 case '"':
5029 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5030 if (opts & PARSE_OPT_DQUOTE && !squote)
5031 in++;
5032 tosend = *in;
5033 break;
5034
5035 case '$':
5036 /* escaping of '$' only inside double quotes and only if env supported */
5037 if (opts & PARSE_OPT_ENV && dquote)
5038 in++;
5039 tosend = *in;
5040 break;
5041
5042 case 'x':
5043 if (!ishex(in[2]) || !ishex(in[3])) {
5044 /* invalid or incomplete hex sequence */
5045 err |= PARSE_ERR_HEX;
5046 if (errptr)
5047 *errptr = in;
5048 goto leave;
5049 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005050 hex1 = toupper((unsigned char)in[2]) - '0';
5051 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005052 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5053 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5054 tosend = (hex1 << 4) + hex2;
5055 in += 3;
5056 break;
5057
5058 default:
5059 /* other combinations are not escape sequences */
5060 break;
5061 }
5062
5063 in++;
5064 EMIT_CHAR(tosend);
5065 }
5066 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5067 /* a non-escaped space is an argument separator */
5068 while (isspace((unsigned char)*in))
5069 in++;
5070 EMIT_CHAR(0);
5071 arg++;
5072 if (arg < argsmax)
5073 args[arg] = out + outpos;
5074 else
5075 err |= PARSE_ERR_TOOMANY;
5076 }
5077 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5078 /* environment variables are evaluated anywhere, or only
5079 * inside double quotes if they are supported.
5080 */
5081 char *var_name;
5082 char save_char;
5083 char *value;
5084
5085 in++;
5086
5087 if (*in == '{')
5088 brace = in++;
5089
5090 if (!isalpha((unsigned char)*in) && *in != '_') {
5091 /* unacceptable character in variable name */
5092 err |= PARSE_ERR_VARNAME;
5093 if (errptr)
5094 *errptr = in;
5095 goto leave;
5096 }
5097
5098 var_name = in;
5099 while (isalnum((unsigned char)*in) || *in == '_')
5100 in++;
5101
5102 save_char = *in;
5103 *in = '\0';
5104 value = getenv(var_name);
5105 *in = save_char;
5106
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005107 /* support for '[*]' sequence to force word expansion,
5108 * only available inside braces */
5109 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5110 word_expand = in++;
5111
5112 if (*in++ != '*' || *in++ != ']') {
5113 err |= PARSE_ERR_WRONG_EXPAND;
5114 if (errptr)
5115 *errptr = word_expand;
5116 goto leave;
5117 }
5118 }
5119
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005120 if (brace) {
5121 if (*in != '}') {
5122 /* unmatched brace */
5123 err |= PARSE_ERR_BRACE;
5124 if (errptr)
5125 *errptr = brace;
5126 goto leave;
5127 }
5128 in++;
5129 brace = NULL;
5130 }
5131
5132 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005133 while (*value) {
5134 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005135 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005136 EMIT_CHAR(0);
5137 ++arg;
5138 if (arg < argsmax)
5139 args[arg] = out + outpos;
5140 else
5141 err |= PARSE_ERR_TOOMANY;
5142
5143 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005144 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005145 ;
5146 } else {
5147 EMIT_CHAR(*value++);
5148 }
5149 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005150 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005151 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005152 }
5153 else {
5154 /* any other regular char */
5155 EMIT_CHAR(*in++);
5156 }
5157 }
5158
5159 /* end of output string */
5160 EMIT_CHAR(0);
5161 arg++;
5162
5163 if (quote) {
5164 /* unmatched quote */
5165 err |= PARSE_ERR_QUOTE;
5166 if (errptr)
5167 *errptr = quote;
5168 goto leave;
5169 }
5170 leave:
5171 *nbargs = arg;
5172 *outlen = outpos;
5173
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005174 /* empty all trailing args by making them point to the trailing zero,
5175 * at least the last one in any case.
5176 */
5177 if (arg > argsmax)
5178 arg = argsmax;
5179
5180 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005181 args[arg++] = out + outpos - 1;
5182
5183 return err;
5184}
5185#undef EMIT_CHAR
5186
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005187/* This is used to sanitize an input line that's about to be used for error reporting.
5188 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5189 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5190 * If non-printable chars are present in the output. It returns the new offset <pos>
5191 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5192 * be at least 6 to support two "..." otherwise the result is undefined. The line
5193 * itself must have at least 7 chars allocated for the same reason.
5194 */
5195size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5196{
5197 size_t shift = 0;
5198 char *out = line;
5199 char *in = line;
5200 char *end = line + width;
5201
5202 if (pos >= width) {
5203 /* if we have to shift, we'll be out of context, so let's
5204 * try to put <pos> at the center of width.
5205 */
5206 shift = pos - width / 2;
5207 in += shift + 3;
5208 end = out + width - 3;
5209 out[0] = out[1] = out[2] = '.';
5210 out += 3;
5211 }
5212
5213 while (out < end && *in) {
5214 if (isspace((unsigned char)*in))
5215 *out++ = ' ';
5216 else if (isprint((unsigned char)*in))
5217 *out++ = *in;
5218 else
5219 *out++ = '?';
5220 in++;
5221 }
5222
5223 if (end < line + width) {
5224 out[0] = out[1] = out[2] = '.';
5225 out += 3;
5226 }
5227
5228 *out++ = 0;
5229 return pos - shift;
5230}
5231
Willy Tarreaubaaee002006-06-26 02:48:02 +02005232/*
5233 * Local variables:
5234 * c-indent-level: 8
5235 * c-basic-offset: 8
5236 * End:
5237 */