blob: 5d67bd7de5f02e0ff9f6f91c3c4865e19bc5af0c [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 Tarreau209108d2020-06-04 20:30:20 +020051#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020052#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020053#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020054#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010055
Thierry Fournier93127942016-01-20 18:49:45 +010056/* This macro returns false if the test __x is false. Many
57 * of the following parsing function must be abort the processing
58 * if it returns 0, so this macro is useful for writing light code.
59 */
60#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
61
Willy Tarreau56adcf22012-12-23 18:00:29 +010062/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020063 * 2^64-1 = 18446744073709551615 or
64 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020065 *
66 * The HTML version needs room for adding the 25 characters
67 * '<span class="rls"></span>' around digits at positions 3N+1 in order
68 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020069 */
Christopher Faulet99bca652017-11-14 16:47:26 +010070THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
71THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020072
Willy Tarreau588297f2014-06-16 15:16:40 +020073/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
74 * to quote strings larger than a max configuration line.
75 */
Christopher Faulet99bca652017-11-14 16:47:26 +010076THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
77THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020078
Willy Tarreaubaaee002006-06-26 02:48:02 +020079/*
William Lallemande7340ec2012-01-24 11:15:39 +010080 * unsigned long long ASCII representation
81 *
82 * return the last char '\0' or NULL if no enough
83 * space in dst
84 */
85char *ulltoa(unsigned long long n, char *dst, size_t size)
86{
87 int i = 0;
88 char *res;
89
90 switch(n) {
91 case 1ULL ... 9ULL:
92 i = 0;
93 break;
94
95 case 10ULL ... 99ULL:
96 i = 1;
97 break;
98
99 case 100ULL ... 999ULL:
100 i = 2;
101 break;
102
103 case 1000ULL ... 9999ULL:
104 i = 3;
105 break;
106
107 case 10000ULL ... 99999ULL:
108 i = 4;
109 break;
110
111 case 100000ULL ... 999999ULL:
112 i = 5;
113 break;
114
115 case 1000000ULL ... 9999999ULL:
116 i = 6;
117 break;
118
119 case 10000000ULL ... 99999999ULL:
120 i = 7;
121 break;
122
123 case 100000000ULL ... 999999999ULL:
124 i = 8;
125 break;
126
127 case 1000000000ULL ... 9999999999ULL:
128 i = 9;
129 break;
130
131 case 10000000000ULL ... 99999999999ULL:
132 i = 10;
133 break;
134
135 case 100000000000ULL ... 999999999999ULL:
136 i = 11;
137 break;
138
139 case 1000000000000ULL ... 9999999999999ULL:
140 i = 12;
141 break;
142
143 case 10000000000000ULL ... 99999999999999ULL:
144 i = 13;
145 break;
146
147 case 100000000000000ULL ... 999999999999999ULL:
148 i = 14;
149 break;
150
151 case 1000000000000000ULL ... 9999999999999999ULL:
152 i = 15;
153 break;
154
155 case 10000000000000000ULL ... 99999999999999999ULL:
156 i = 16;
157 break;
158
159 case 100000000000000000ULL ... 999999999999999999ULL:
160 i = 17;
161 break;
162
163 case 1000000000000000000ULL ... 9999999999999999999ULL:
164 i = 18;
165 break;
166
167 case 10000000000000000000ULL ... ULLONG_MAX:
168 i = 19;
169 break;
170 }
171 if (i + 2 > size) // (i + 1) + '\0'
172 return NULL; // too long
173 res = dst + i + 1;
174 *res = '\0';
175 for (; i >= 0; i--) {
176 dst[i] = n % 10ULL + '0';
177 n /= 10ULL;
178 }
179 return res;
180}
181
182/*
183 * unsigned long ASCII representation
184 *
185 * return the last char '\0' or NULL if no enough
186 * space in dst
187 */
188char *ultoa_o(unsigned long n, char *dst, size_t size)
189{
190 int i = 0;
191 char *res;
192
193 switch (n) {
194 case 0U ... 9UL:
195 i = 0;
196 break;
197
198 case 10U ... 99UL:
199 i = 1;
200 break;
201
202 case 100U ... 999UL:
203 i = 2;
204 break;
205
206 case 1000U ... 9999UL:
207 i = 3;
208 break;
209
210 case 10000U ... 99999UL:
211 i = 4;
212 break;
213
214 case 100000U ... 999999UL:
215 i = 5;
216 break;
217
218 case 1000000U ... 9999999UL:
219 i = 6;
220 break;
221
222 case 10000000U ... 99999999UL:
223 i = 7;
224 break;
225
226 case 100000000U ... 999999999UL:
227 i = 8;
228 break;
229#if __WORDSIZE == 32
230
231 case 1000000000ULL ... ULONG_MAX:
232 i = 9;
233 break;
234
235#elif __WORDSIZE == 64
236
237 case 1000000000ULL ... 9999999999UL:
238 i = 9;
239 break;
240
241 case 10000000000ULL ... 99999999999UL:
242 i = 10;
243 break;
244
245 case 100000000000ULL ... 999999999999UL:
246 i = 11;
247 break;
248
249 case 1000000000000ULL ... 9999999999999UL:
250 i = 12;
251 break;
252
253 case 10000000000000ULL ... 99999999999999UL:
254 i = 13;
255 break;
256
257 case 100000000000000ULL ... 999999999999999UL:
258 i = 14;
259 break;
260
261 case 1000000000000000ULL ... 9999999999999999UL:
262 i = 15;
263 break;
264
265 case 10000000000000000ULL ... 99999999999999999UL:
266 i = 16;
267 break;
268
269 case 100000000000000000ULL ... 999999999999999999UL:
270 i = 17;
271 break;
272
273 case 1000000000000000000ULL ... 9999999999999999999UL:
274 i = 18;
275 break;
276
277 case 10000000000000000000ULL ... ULONG_MAX:
278 i = 19;
279 break;
280
281#endif
282 }
283 if (i + 2 > size) // (i + 1) + '\0'
284 return NULL; // too long
285 res = dst + i + 1;
286 *res = '\0';
287 for (; i >= 0; i--) {
288 dst[i] = n % 10U + '0';
289 n /= 10U;
290 }
291 return res;
292}
293
294/*
295 * signed long ASCII representation
296 *
297 * return the last char '\0' or NULL if no enough
298 * space in dst
299 */
300char *ltoa_o(long int n, char *dst, size_t size)
301{
302 char *pos = dst;
303
304 if (n < 0) {
305 if (size < 3)
306 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
307 *pos = '-';
308 pos++;
309 dst = ultoa_o(-n, pos, size - 1);
310 } else {
311 dst = ultoa_o(n, dst, size);
312 }
313 return dst;
314}
315
316/*
317 * signed long long ASCII representation
318 *
319 * return the last char '\0' or NULL if no enough
320 * space in dst
321 */
322char *lltoa(long long n, char *dst, size_t size)
323{
324 char *pos = dst;
325
326 if (n < 0) {
327 if (size < 3)
328 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
329 *pos = '-';
330 pos++;
331 dst = ulltoa(-n, pos, size - 1);
332 } else {
333 dst = ulltoa(n, dst, size);
334 }
335 return dst;
336}
337
338/*
339 * write a ascii representation of a unsigned into dst,
340 * return a pointer to the last character
341 * Pad the ascii representation with '0', using size.
342 */
343char *utoa_pad(unsigned int n, char *dst, size_t size)
344{
345 int i = 0;
346 char *ret;
347
348 switch(n) {
349 case 0U ... 9U:
350 i = 0;
351 break;
352
353 case 10U ... 99U:
354 i = 1;
355 break;
356
357 case 100U ... 999U:
358 i = 2;
359 break;
360
361 case 1000U ... 9999U:
362 i = 3;
363 break;
364
365 case 10000U ... 99999U:
366 i = 4;
367 break;
368
369 case 100000U ... 999999U:
370 i = 5;
371 break;
372
373 case 1000000U ... 9999999U:
374 i = 6;
375 break;
376
377 case 10000000U ... 99999999U:
378 i = 7;
379 break;
380
381 case 100000000U ... 999999999U:
382 i = 8;
383 break;
384
385 case 1000000000U ... 4294967295U:
386 i = 9;
387 break;
388 }
389 if (i + 2 > size) // (i + 1) + '\0'
390 return NULL; // too long
391 if (i < size)
392 i = size - 2; // padding - '\0'
393
394 ret = dst + i + 1;
395 *ret = '\0';
396 for (; i >= 0; i--) {
397 dst[i] = n % 10U + '0';
398 n /= 10U;
399 }
400 return ret;
401}
402
403/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200404 * copies at most <size-1> chars from <src> to <dst>. Last char is always
405 * set to 0, unless <size> is 0. The number of chars copied is returned
406 * (excluding the terminating zero).
407 * This code has been optimized for size and speed : on x86, it's 45 bytes
408 * long, uses only registers, and consumes only 4 cycles per char.
409 */
410int strlcpy2(char *dst, const char *src, int size)
411{
412 char *orig = dst;
413 if (size) {
414 while (--size && (*dst = *src)) {
415 src++; dst++;
416 }
417 *dst = 0;
418 }
419 return dst - orig;
420}
421
422/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200423 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200424 * the ascii representation for number 'n' in decimal.
425 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100426char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200427{
428 char *pos;
429
Willy Tarreau72d759c2007-10-25 12:14:10 +0200430 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200431 *pos-- = '\0';
432
433 do {
434 *pos-- = '0' + n % 10;
435 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200436 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200437 return pos + 1;
438}
439
Willy Tarreau91092e52007-10-25 16:58:42 +0200440/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200441 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200442 * the ascii representation for number 'n' in decimal.
443 */
444char *lltoa_r(long long int in, char *buffer, int size)
445{
446 char *pos;
447 int neg = 0;
448 unsigned long long int n;
449
450 pos = buffer + size - 1;
451 *pos-- = '\0';
452
453 if (in < 0) {
454 neg = 1;
455 n = -in;
456 }
457 else
458 n = in;
459
460 do {
461 *pos-- = '0' + n % 10;
462 n /= 10;
463 } while (n && pos >= buffer);
464 if (neg && pos > buffer)
465 *pos-- = '-';
466 return pos + 1;
467}
468
469/*
470 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200471 * the ascii representation for signed number 'n' in decimal.
472 */
473char *sltoa_r(long n, char *buffer, int size)
474{
475 char *pos;
476
477 if (n >= 0)
478 return ultoa_r(n, buffer, size);
479
480 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
481 *pos = '-';
482 return pos;
483}
484
485/*
486 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200487 * the ascii representation for number 'n' in decimal, formatted for
488 * HTML output with tags to create visual grouping by 3 digits. The
489 * output needs to support at least 171 characters.
490 */
491const char *ulltoh_r(unsigned long long n, char *buffer, int size)
492{
493 char *start;
494 int digit = 0;
495
496 start = buffer + size;
497 *--start = '\0';
498
499 do {
500 if (digit == 3 && start >= buffer + 7)
501 memcpy(start -= 7, "</span>", 7);
502
503 if (start >= buffer + 1) {
504 *--start = '0' + n % 10;
505 n /= 10;
506 }
507
508 if (digit == 3 && start >= buffer + 18)
509 memcpy(start -= 18, "<span class=\"rls\">", 18);
510
511 if (digit++ == 3)
512 digit = 1;
513 } while (n && start > buffer);
514 return start;
515}
516
517/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200518 * This function simply returns a locally allocated string containing the ascii
519 * representation for number 'n' in decimal, unless n is 0 in which case it
520 * returns the alternate string (or an empty string if the alternate string is
521 * NULL). It use is intended for limits reported in reports, where it's
522 * desirable not to display anything if there is no limit. Warning! it shares
523 * the same vector as ultoa_r().
524 */
525const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
526{
527 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
528}
529
Willy Tarreau588297f2014-06-16 15:16:40 +0200530/* returns a locally allocated string containing the quoted encoding of the
531 * input string. The output may be truncated to QSTR_SIZE chars, but it is
532 * guaranteed that the string will always be properly terminated. Quotes are
533 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
534 * always be at least 4 chars.
535 */
536const char *qstr(const char *str)
537{
538 char *ret = quoted_str[quoted_idx];
539 char *p, *end;
540
541 if (++quoted_idx >= NB_QSTR)
542 quoted_idx = 0;
543
544 p = ret;
545 end = ret + QSTR_SIZE;
546
547 *p++ = '"';
548
549 /* always keep 3 chars to support passing "" and the ending " */
550 while (*str && p < end - 3) {
551 if (*str == '"') {
552 *p++ = '"';
553 *p++ = '"';
554 }
555 else
556 *p++ = *str;
557 str++;
558 }
559 *p++ = '"';
560 return ret;
561}
562
Robert Tsai81ae1952007-12-05 10:47:29 +0100563/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200564 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
565 *
566 * It looks like this one would be a good candidate for inlining, but this is
567 * not interesting because it around 35 bytes long and often called multiple
568 * times within the same function.
569 */
570int ishex(char s)
571{
572 s -= '0';
573 if ((unsigned char)s <= 9)
574 return 1;
575 s -= 'A' - '0';
576 if ((unsigned char)s <= 5)
577 return 1;
578 s -= 'a' - 'A';
579 if ((unsigned char)s <= 5)
580 return 1;
581 return 0;
582}
583
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100584/* rounds <i> down to the closest value having max 2 digits */
585unsigned int round_2dig(unsigned int i)
586{
587 unsigned int mul = 1;
588
589 while (i >= 100) {
590 i /= 10;
591 mul *= 10;
592 }
593 return i * mul;
594}
595
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100596/*
597 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
598 * invalid character is found, a pointer to it is returned. If everything is
599 * fine, NULL is returned.
600 */
601const char *invalid_char(const char *name)
602{
603 if (!*name)
604 return name;
605
606 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100607 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100608 *name != '_' && *name != '-')
609 return name;
610 name++;
611 }
612 return NULL;
613}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200614
615/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200616 * Checks <name> for invalid characters. Valid chars are [_.-] and those
617 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200618 * If an invalid character is found, a pointer to it is returned.
619 * If everything is fine, NULL is returned.
620 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200621static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200622
623 if (!*name)
624 return name;
625
626 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100627 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200628 *name != '_' && *name != '-')
629 return name;
630
631 name++;
632 }
633
634 return NULL;
635}
636
637/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200638 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
639 * If an invalid character is found, a pointer to it is returned.
640 * If everything is fine, NULL is returned.
641 */
642const char *invalid_domainchar(const char *name) {
643 return __invalid_char(name, isalnum);
644}
645
646/*
647 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
648 * If an invalid character is found, a pointer to it is returned.
649 * If everything is fine, NULL is returned.
650 */
651const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200652 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200653}
654
655/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100656 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100657 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
658 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
659 * the function tries to guess the address family from the syntax. If the
660 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100661 * string is assumed to contain only an address, no port. The address can be a
662 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
663 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
664 * The return address will only have the address family and the address set,
665 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100666 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
667 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100668 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200669 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100670struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200671{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100672 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100673 /* max IPv6 length, including brackets and terminating NULL */
674 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100675 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100676
677 /* check IPv6 with square brackets */
678 if (str[0] == '[') {
679 size_t iplength = strlen(str);
680
681 if (iplength < 4) {
682 /* minimal size is 4 when using brackets "[::]" */
683 goto fail;
684 }
685 else if (iplength >= sizeof(tmpip)) {
686 /* IPv6 literal can not be larger than tmpip */
687 goto fail;
688 }
689 else {
690 if (str[iplength - 1] != ']') {
691 /* if address started with bracket, it should end with bracket */
692 goto fail;
693 }
694 else {
695 memcpy(tmpip, str + 1, iplength - 2);
696 tmpip[iplength - 2] = '\0';
697 str = tmpip;
698 }
699 }
700 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100701
Willy Tarreaufab5a432011-03-04 15:31:53 +0100702 /* Any IPv6 address */
703 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100704 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
705 sa->ss_family = AF_INET6;
706 else if (sa->ss_family != AF_INET6)
707 goto fail;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100708 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100709 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100710 }
711
Willy Tarreau24709282013-03-10 21:32:12 +0100712 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100713 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100714 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
715 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100716 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100717 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100718 }
719
720 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100721 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
722 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100723 sa->ss_family = AF_INET6;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100724 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100725 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100726 }
727
728 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100729 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
730 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100731 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100732 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100733 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100734 }
735
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100736 if (!resolve)
737 return NULL;
738
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200739 if (!dns_hostname_validation(str, NULL))
740 return NULL;
741
David du Colombierd5f43282011-03-17 10:40:16 +0100742#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200743 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100744 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100745 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100746
747 memset(&result, 0, sizeof(result));
748 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100749 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100750 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200751 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100752 hints.ai_protocol = 0;
753
754 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100755 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
756 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100757 else if (sa->ss_family != result->ai_family) {
758 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100759 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100760 }
Willy Tarreau24709282013-03-10 21:32:12 +0100761
David du Colombierd5f43282011-03-17 10:40:16 +0100762 switch (result->ai_family) {
763 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100764 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100765 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100766 success = 1;
767 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100768 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100769 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100770 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100771 success = 1;
772 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100773 }
774 }
775
Sean Carey58ea0392013-02-15 23:39:18 +0100776 if (result)
777 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100778
779 if (success)
780 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100781 }
David du Colombierd5f43282011-03-17 10:40:16 +0100782#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200783 /* try to resolve an IPv4/IPv6 hostname */
784 he = gethostbyname(str);
785 if (he) {
786 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
787 sa->ss_family = he->h_addrtype;
788 else if (sa->ss_family != he->h_addrtype)
789 goto fail;
790
791 switch (sa->ss_family) {
792 case AF_INET:
793 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100794 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200795 return sa;
796 case AF_INET6:
797 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100798 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200799 return sa;
800 }
801 }
802
David du Colombierd5f43282011-03-17 10:40:16 +0100803 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100804 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100805 return NULL;
806}
807
808/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100809 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
810 * range or offset consisting in two integers that the caller will have to
811 * check to find the relevant input format. The following format are supported :
812 *
813 * String format | address | port | low | high
814 * addr | <addr> | 0 | 0 | 0
815 * addr: | <addr> | 0 | 0 | 0
816 * addr:port | <addr> | <port> | <port> | <port>
817 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
818 * addr:+port | <addr> | <port> | 0 | <port>
819 * addr:-port | <addr> |-<port> | <port> | 0
820 *
821 * The detection of a port range or increment by the caller is made by
822 * comparing <low> and <high>. If both are equal, then port 0 means no port
823 * was specified. The caller may pass NULL for <low> and <high> if it is not
824 * interested in retrieving port ranges.
825 *
826 * Note that <addr> above may also be :
827 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
828 * - "*" => family will be AF_INET and address will be INADDR_ANY
829 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
830 * - a host name => family and address will depend on host name resolving.
831 *
Willy Tarreau24709282013-03-10 21:32:12 +0100832 * A prefix may be passed in before the address above to force the family :
833 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
834 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
835 * - "unix@" => force address to be a path to a UNIX socket even if the
836 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200837 * - 'abns@' -> force address to belong to the abstract namespace (Linux
838 * only). These sockets are just like Unix sockets but without
839 * the need for an underlying file system. The address is a
840 * string. Technically it's like a Unix socket with a zero in
841 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100842 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100843 *
mildisff5d5102015-10-26 18:50:08 +0100844 * IPv6 addresses can be declared with or without square brackets. When using
845 * square brackets for IPv6 addresses, the port separator (colon) is optional.
846 * If not using square brackets, and in order to avoid any ambiguity with
847 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
848 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
849 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100850 *
851 * If <pfx> is non-null, it is used as a string prefix before any path-based
852 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100853 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200854 * if <fqdn> is non-null, it will be filled with :
855 * - a pointer to the FQDN of the server name to resolve if there's one, and
856 * that the caller will have to free(),
857 * - NULL if there was an explicit address that doesn't require resolution.
858 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200859 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
860 * still honored so it is possible for the caller to know whether a resolution
861 * failed by clearing this flag and checking if <fqdn> was filled, indicating
862 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200863 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100864 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200865 * the address when cast to sockaddr_in and the address family is
866 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200867 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200868 * The matching protocol will be set into <proto> if non-null.
869 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200870 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
871 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100872 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200873struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
874 struct protocol **proto, char **err,
875 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100876{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100877 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100878 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200879 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100880 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100881 char *port1, *port2;
882 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200883 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200884 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200885 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100886
887 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200888 if (fqdn)
889 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200890
Willy Tarreaudad36a32013-03-11 01:20:04 +0100891 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100892 if (str2 == NULL) {
893 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100894 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100895 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200896
Willy Tarreau9f69f462015-09-08 16:01:25 +0200897 if (!*str2) {
898 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
899 goto out;
900 }
901
Willy Tarreau24709282013-03-10 21:32:12 +0100902 memset(&ss, 0, sizeof(ss));
903
Willy Tarreaue835bd82020-09-16 11:35:47 +0200904 /* prepare the default socket types */
905 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM)
906 sock_type = ctrl_type = SOCK_DGRAM;
907 else
908 sock_type = ctrl_type = SOCK_STREAM;
909
910 if (strncmp(str2, "stream+", 7) == 0) {
911 str2 += 7;
912 sock_type = ctrl_type = SOCK_STREAM;
913 }
914 else if (strncmp(str2, "dgram+", 6) == 0) {
915 str2 += 6;
916 sock_type = ctrl_type = SOCK_DGRAM;
917 }
918
Willy Tarreau24709282013-03-10 21:32:12 +0100919 if (strncmp(str2, "unix@", 5) == 0) {
920 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200921 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100922 ss.ss_family = AF_UNIX;
923 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200924 else if (strncmp(str2, "abns@", 5) == 0) {
925 str2 += 5;
926 abstract = 1;
927 ss.ss_family = AF_UNIX;
928 }
Willy Tarreau24709282013-03-10 21:32:12 +0100929 else if (strncmp(str2, "ipv4@", 5) == 0) {
930 str2 += 5;
931 ss.ss_family = AF_INET;
932 }
933 else if (strncmp(str2, "ipv6@", 5) == 0) {
934 str2 += 5;
935 ss.ss_family = AF_INET6;
936 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200937 else if (strncmp(str2, "udp4@", 5) == 0) {
938 str2 += 5;
939 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200940 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200941 }
942 else if (strncmp(str2, "udp6@", 5) == 0) {
943 str2 += 5;
944 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200945 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200946 }
947 else if (strncmp(str2, "udp@", 4) == 0) {
948 str2 += 4;
949 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200950 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200951 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200952 else if (strncmp(str2, "fd@", 3) == 0) {
953 str2 += 3;
954 ss.ss_family = AF_CUST_EXISTING_FD;
955 }
956 else if (strncmp(str2, "sockpair@", 9) == 0) {
957 str2 += 9;
958 ss.ss_family = AF_CUST_SOCKPAIR;
959 }
Willy Tarreau24709282013-03-10 21:32:12 +0100960 else if (*str2 == '/') {
961 ss.ss_family = AF_UNIX;
962 }
963 else
964 ss.ss_family = AF_UNSPEC;
965
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200966 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +0200967 struct sockaddr_storage ss2;
968 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200969 char *endptr;
970
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200971 new_fd = strtol(str2, &endptr, 10);
972 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +0200973 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
974 goto out;
975 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200976
Willy Tarreaua215be22020-09-16 10:14:16 +0200977 /* just verify that it's a socket */
978 addr_len = sizeof(ss2);
979 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
980 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
981 goto out;
982 }
983
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200984 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
985 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +0200986 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +0200987 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +0100988 char *endptr;
989
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200990 new_fd = strtol(str2, &endptr, 10);
991 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +0100992 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +0100993 goto out;
994 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200995
Willy Tarreau6edc7222020-09-15 17:41:56 +0200996 if (opts & PA_O_SOCKET_FD) {
997 socklen_t addr_len;
998 int type;
999
1000 addr_len = sizeof(ss);
1001 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1002 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1003 goto out;
1004 }
1005
1006 addr_len = sizeof(type);
1007 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001008 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001009 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1010 goto out;
1011 }
1012
1013 porta = portl = porth = get_host_port(&ss);
1014 } else if (opts & PA_O_RAW_FD) {
1015 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1016 ((struct sockaddr_in *)&ss)->sin_port = 0;
1017 } else {
1018 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1019 goto out;
1020 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001021 }
1022 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001023 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001024 int prefix_path_len;
1025 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001026 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001027
1028 /* complete unix socket path name during startup or soft-restart is
1029 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1030 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001031 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001032 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001033 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001034
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001035 adr_len = strlen(str2);
1036 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001037 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1038 goto out;
1039 }
1040
Willy Tarreauccfccef2014-05-10 01:49:15 +02001041 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001042 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001043 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001044 memcpy(un->sun_path, pfx, prefix_path_len);
1045 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001046 }
Willy Tarreau24709282013-03-10 21:32:12 +01001047 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001048 char *end = str2 + strlen(str2);
1049 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001050
mildisff5d5102015-10-26 18:50:08 +01001051 /* search for : or ] whatever comes first */
1052 for (chr = end-1; chr > str2; chr--) {
1053 if (*chr == ']' || *chr == ':')
1054 break;
1055 }
1056
1057 if (*chr == ':') {
1058 /* Found a colon before a closing-bracket, must be a port separator.
1059 * This guarantee backward compatibility.
1060 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001061 if (!(opts & PA_O_PORT_OK)) {
1062 memprintf(err, "port specification not permitted here in '%s'", str);
1063 goto out;
1064 }
mildisff5d5102015-10-26 18:50:08 +01001065 *chr++ = '\0';
1066 port1 = chr;
1067 }
1068 else {
1069 /* Either no colon and no closing-bracket
1070 * or directly ending with a closing-bracket.
1071 * However, no port.
1072 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001073 if (opts & PA_O_PORT_MAND) {
1074 memprintf(err, "missing port specification in '%s'", str);
1075 goto out;
1076 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001077 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001078 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001079
Willy Tarreau90807112020-02-25 08:16:33 +01001080 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001081 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001082 if (port2) {
1083 if (!(opts & PA_O_PORT_RANGE)) {
1084 memprintf(err, "port range not permitted here in '%s'", str);
1085 goto out;
1086 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001087 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001088 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001089 else
1090 port2 = port1;
1091 portl = atoi(port1);
1092 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001093
1094 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1095 memprintf(err, "invalid port '%s'", port1);
1096 goto out;
1097 }
1098
1099 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1100 memprintf(err, "invalid port '%s'", port2);
1101 goto out;
1102 }
1103
1104 if (portl > porth) {
1105 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1106 goto out;
1107 }
1108
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001109 porta = portl;
1110 }
1111 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001112 if (!(opts & PA_O_PORT_OFS)) {
1113 memprintf(err, "port offset not permitted here in '%s'", str);
1114 goto out;
1115 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001116 portl = atoi(port1 + 1);
1117 porta = -portl;
1118 }
1119 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001120 if (!(opts & PA_O_PORT_OFS)) {
1121 memprintf(err, "port offset not permitted here in '%s'", str);
1122 goto out;
1123 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001124 porth = atoi(port1 + 1);
1125 porta = porth;
1126 }
1127 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001128 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001129 goto out;
1130 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001131 else if (opts & PA_O_PORT_MAND) {
1132 memprintf(err, "missing port specification in '%s'", str);
1133 goto out;
1134 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001135
1136 /* first try to parse the IP without resolving. If it fails, it
1137 * tells us we need to keep a copy of the FQDN to resolve later
1138 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001139 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001140 */
1141 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001142 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1143 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001144 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1145 goto out;
1146 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001147
Willy Tarreauceccdd72016-11-02 22:27:10 +01001148 if (fqdn) {
1149 if (str2 != back)
1150 memmove(back, str2, strlen(str2) + 1);
1151 *fqdn = back;
1152 back = NULL;
1153 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001154 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001155 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001156 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001157
Willy Tarreaue835bd82020-09-16 11:35:47 +02001158 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1159 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1160 goto out;
1161 }
1162 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1163 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1164 goto out;
1165 }
1166
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001167 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001168 /* Note: if the caller asks for a proto, we must find one,
1169 * except if we return with an fqdn that will resolve later,
1170 * in which case the address is not known yet (this is only
1171 * for servers actually).
1172 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001173 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001174 sock_type == SOCK_DGRAM,
1175 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001176
Willy Tarreau5fc93282020-09-16 18:25:03 +02001177 if (!new_proto && (!fqdn || !*fqdn)) {
1178 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1179 goto out;
1180 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001181
1182 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1183 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1184 goto out;
1185 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001186 }
1187
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001188 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001189 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001190 if (port)
1191 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001192 if (low)
1193 *low = portl;
1194 if (high)
1195 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001196 if (fd)
1197 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001198 if (proto)
1199 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001200 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001201 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001202}
1203
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001204/* converts <str> to a struct in_addr containing a network mask. It can be
1205 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001206 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001207 */
1208int str2mask(const char *str, struct in_addr *mask)
1209{
1210 if (strchr(str, '.') != NULL) { /* dotted notation */
1211 if (!inet_pton(AF_INET, str, mask))
1212 return 0;
1213 }
1214 else { /* mask length */
1215 char *err;
1216 unsigned long len = strtol(str, &err, 10);
1217
1218 if (!*str || (err && *err) || (unsigned)len > 32)
1219 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001220
1221 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001222 }
1223 return 1;
1224}
1225
Tim Duesterhus47185172018-01-25 16:24:49 +01001226/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001227 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001228 * if the conversion succeeds otherwise zero.
1229 */
1230int str2mask6(const char *str, struct in6_addr *mask)
1231{
1232 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1233 if (!inet_pton(AF_INET6, str, mask))
1234 return 0;
1235 }
1236 else { /* mask length */
1237 char *err;
1238 unsigned long len = strtol(str, &err, 10);
1239
1240 if (!*str || (err && *err) || (unsigned)len > 128)
1241 return 0;
1242
1243 len2mask6(len, mask);
1244 }
1245 return 1;
1246}
1247
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001248/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1249 * succeeds otherwise zero.
1250 */
1251int cidr2dotted(int cidr, struct in_addr *mask) {
1252
1253 if (cidr < 0 || cidr > 32)
1254 return 0;
1255
1256 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1257 return 1;
1258}
1259
Thierry Fournier70473a52016-02-17 17:12:14 +01001260/* Convert mask from bit length form to in_addr form.
1261 * This function never fails.
1262 */
1263void len2mask4(int len, struct in_addr *addr)
1264{
1265 if (len >= 32) {
1266 addr->s_addr = 0xffffffff;
1267 return;
1268 }
1269 if (len <= 0) {
1270 addr->s_addr = 0x00000000;
1271 return;
1272 }
1273 addr->s_addr = 0xffffffff << (32 - len);
1274 addr->s_addr = htonl(addr->s_addr);
1275}
1276
1277/* Convert mask from bit length form to in6_addr form.
1278 * This function never fails.
1279 */
1280void len2mask6(int len, struct in6_addr *addr)
1281{
1282 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1283 len -= 32;
1284 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1285 len -= 32;
1286 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1287 len -= 32;
1288 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1289}
1290
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001291/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001292 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001293 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001294 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001295 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1296 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001297int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001298{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001299 __label__ out_free, out_err;
1300 char *c, *s;
1301 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001302
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001303 s = strdup(str);
1304 if (!s)
1305 return 0;
1306
Willy Tarreaubaaee002006-06-26 02:48:02 +02001307 memset(mask, 0, sizeof(*mask));
1308 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001309
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001310 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001311 *c++ = '\0';
1312 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001313 if (!str2mask(c, mask))
1314 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001315 }
1316 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001317 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001318 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001319 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001320 struct hostent *he;
1321
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001322 if (!resolve)
1323 goto out_err;
1324
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001325 if ((he = gethostbyname(s)) == NULL) {
1326 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001327 }
1328 else
1329 *addr = *(struct in_addr *) *(he->h_addr_list);
1330 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001331
1332 ret_val = 1;
1333 out_free:
1334 free(s);
1335 return ret_val;
1336 out_err:
1337 ret_val = 0;
1338 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001339}
1340
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001341
1342/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001343 * converts <str> to two struct in6_addr* which must be pre-allocated.
1344 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001345 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001346 * Returns 1 if OK, 0 if error.
1347 */
1348int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1349{
1350 char *c, *s;
1351 int ret_val = 0;
1352 char *err;
1353 unsigned long len = 128;
1354
1355 s = strdup(str);
1356 if (!s)
1357 return 0;
1358
1359 memset(mask, 0, sizeof(*mask));
1360 memset(addr, 0, sizeof(*addr));
1361
1362 if ((c = strrchr(s, '/')) != NULL) {
1363 *c++ = '\0'; /* c points to the mask */
1364 if (!*c)
1365 goto out_free;
1366
1367 len = strtoul(c, &err, 10);
1368 if ((err && *err) || (unsigned)len > 128)
1369 goto out_free;
1370 }
1371 *mask = len; /* OK we have a valid mask in <len> */
1372
1373 if (!inet_pton(AF_INET6, s, addr))
1374 goto out_free;
1375
1376 ret_val = 1;
1377 out_free:
1378 free(s);
1379 return ret_val;
1380}
1381
1382
1383/*
Willy Tarreau4d61bdb2021-03-25 11:34:40 +01001384 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1385 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1386 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001387 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001388int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001389{
1390 int saw_digit, octets, ch;
1391 u_char tmp[4], *tp;
1392 const char *cp = addr;
1393
1394 saw_digit = 0;
1395 octets = 0;
1396 *(tp = tmp) = 0;
1397
1398 while (*addr) {
Willy Tarreau4d61bdb2021-03-25 11:34:40 +01001399 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001400 if (digit > 9 && ch != '.')
1401 break;
Willy Tarreau4d61bdb2021-03-25 11:34:40 +01001402 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001403 if (digit <= 9) {
1404 u_int new = *tp * 10 + digit;
1405 if (new > 255)
1406 return 0;
1407 *tp = new;
1408 if (!saw_digit) {
1409 if (++octets > 4)
1410 return 0;
1411 saw_digit = 1;
1412 }
1413 } else if (ch == '.' && saw_digit) {
1414 if (octets == 4)
1415 return 0;
1416 *++tp = 0;
1417 saw_digit = 0;
1418 } else
1419 return 0;
1420 }
1421
1422 if (octets < 4)
1423 return 0;
1424
1425 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau4d61bdb2021-03-25 11:34:40 +01001426 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001427}
1428
1429/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001430 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001431 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001432 * the hostname. Actually only http and https are supported. <out> can be NULL.
1433 * This function returns the consumed length. It is useful if you parse complete
1434 * url like http://host:port/path, because the consumed length corresponds to
1435 * the first character of the path. If the conversion fails, it returns -1.
1436 *
1437 * This function tries to resolve the DNS name if haproxy is in starting mode.
1438 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001439 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001440int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001441{
1442 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001443 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001444 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001445 unsigned long long int http_code = 0;
1446 int default_port;
1447 struct hostent *he;
1448 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001449
1450 /* Firstly, try to find :// pattern */
1451 while (curr < url+ulen && url_code != 0x3a2f2f) {
1452 url_code = ((url_code & 0xffff) << 8);
1453 url_code += (unsigned char)*curr++;
1454 }
1455
1456 /* Secondly, if :// pattern is found, verify parsed stuff
1457 * before pattern is matching our http pattern.
1458 * If so parse ip address and port in uri.
1459 *
1460 * WARNING: Current code doesn't support dynamic async dns resolver.
1461 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001462 if (url_code != 0x3a2f2f)
1463 return -1;
1464
1465 /* Copy scheme, and utrn to lower case. */
1466 while (cp < curr - 3)
1467 http_code = (http_code << 8) + *cp++;
1468 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001469
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001470 /* HTTP or HTTPS url matching */
1471 if (http_code == 0x2020202068747470ULL) {
1472 default_port = 80;
1473 if (out)
1474 out->scheme = SCH_HTTP;
1475 }
1476 else if (http_code == 0x2020206874747073ULL) {
1477 default_port = 443;
1478 if (out)
1479 out->scheme = SCH_HTTPS;
1480 }
1481 else
1482 return -1;
1483
1484 /* If the next char is '[', the host address is IPv6. */
1485 if (*curr == '[') {
1486 curr++;
1487
1488 /* Check trash size */
1489 if (trash.size < ulen)
1490 return -1;
1491
1492 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001493 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001494 for (end = curr;
1495 end < url + ulen && *end != ']';
1496 end++, p++)
1497 *p = *end;
1498 if (*end != ']')
1499 return -1;
1500 *p = '\0';
1501
1502 /* Update out. */
1503 if (out) {
1504 out->host = curr;
1505 out->host_len = end - curr;
1506 }
1507
1508 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001509 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001510 return -1;
1511 end++;
1512
1513 /* Decode port. */
1514 if (*end == ':') {
1515 end++;
1516 default_port = read_uint(&end, url + ulen);
1517 }
1518 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1519 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1520 return end - url;
1521 }
1522 else {
1523 /* We are looking for IP address. If you want to parse and
1524 * resolve hostname found in url, you can use str2sa_range(), but
1525 * be warned this can slow down global daemon performances
1526 * while handling lagging dns responses.
1527 */
1528 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1529 if (ret) {
1530 /* Update out. */
1531 if (out) {
1532 out->host = curr;
1533 out->host_len = ret;
1534 }
1535
1536 curr += ret;
1537
1538 /* Decode port. */
1539 if (*curr == ':') {
1540 curr++;
1541 default_port = read_uint(&curr, url + ulen);
1542 }
1543 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1544
1545 /* Set family. */
1546 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1547 return curr - url;
1548 }
1549 else if (global.mode & MODE_STARTING) {
1550 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1551 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001552 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001553
1554 /* look for : or / or end */
1555 for (end = curr;
1556 end < url + ulen && *end != '/' && *end != ':';
1557 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001558 memcpy(trash.area, curr, end - curr);
1559 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001560
1561 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001562 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001563 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001564 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001565
1566 /* Update out. */
1567 if (out) {
1568 out->host = curr;
1569 out->host_len = end - curr;
1570 }
1571
1572 /* Decode port. */
1573 if (*end == ':') {
1574 end++;
1575 default_port = read_uint(&end, url + ulen);
1576 }
1577
1578 /* Copy IP address, set port and family. */
1579 switch (he->h_addrtype) {
1580 case AF_INET:
1581 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1582 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1583 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1584 return end - url;
1585
1586 case AF_INET6:
1587 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1588 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1589 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1590 return end - url;
1591 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001592 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001593 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001594 return -1;
1595}
1596
Willy Tarreau631f01c2011-09-05 00:36:48 +02001597/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1598 * address family is returned so that it's easy for the caller to adapt to the
1599 * output format. Zero is returned if the address family is not supported. -1
1600 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1601 * supported.
1602 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001603int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001604{
1605
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001606 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001607
1608 if (size < 5)
1609 return 0;
1610 *str = '\0';
1611
1612 switch (addr->ss_family) {
1613 case AF_INET:
1614 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1615 break;
1616 case AF_INET6:
1617 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1618 break;
1619 case AF_UNIX:
1620 memcpy(str, "unix", 5);
1621 return addr->ss_family;
1622 default:
1623 return 0;
1624 }
1625
1626 if (inet_ntop(addr->ss_family, ptr, str, size))
1627 return addr->ss_family;
1628
1629 /* failed */
1630 return -1;
1631}
1632
Simon Horman75ab8bd2014-06-16 09:39:41 +09001633/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1634 * address family is returned so that it's easy for the caller to adapt to the
1635 * output format. Zero is returned if the address family is not supported. -1
1636 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1637 * supported.
1638 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001639int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001640{
1641
1642 uint16_t port;
1643
1644
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001645 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001646 return 0;
1647 *str = '\0';
1648
1649 switch (addr->ss_family) {
1650 case AF_INET:
1651 port = ((struct sockaddr_in *)addr)->sin_port;
1652 break;
1653 case AF_INET6:
1654 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1655 break;
1656 case AF_UNIX:
1657 memcpy(str, "unix", 5);
1658 return addr->ss_family;
1659 default:
1660 return 0;
1661 }
1662
1663 snprintf(str, size, "%u", ntohs(port));
1664 return addr->ss_family;
1665}
1666
Willy Tarreau16e01562016-08-09 16:46:18 +02001667/* check if the given address is local to the system or not. It will return
1668 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1669 * it is. We don't want to iterate over all interfaces for this (and it is not
1670 * portable). So instead we try to bind in UDP to this address on a free non
1671 * privileged port and to connect to the same address, port 0 (connect doesn't
1672 * care). If it succeeds, we own the address. Note that non-inet addresses are
1673 * considered local since they're most likely AF_UNIX.
1674 */
1675int addr_is_local(const struct netns_entry *ns,
1676 const struct sockaddr_storage *orig)
1677{
1678 struct sockaddr_storage addr;
1679 int result;
1680 int fd;
1681
1682 if (!is_inet_addr(orig))
1683 return 1;
1684
1685 memcpy(&addr, orig, sizeof(addr));
1686 set_host_port(&addr, 0);
1687
1688 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1689 if (fd < 0)
1690 return -1;
1691
1692 result = -1;
1693 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1694 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1695 result = 0; // fail, non-local address
1696 else
1697 result = 1; // success, local address
1698 }
1699 else {
1700 if (errno == EADDRNOTAVAIL)
1701 result = 0; // definitely not local :-)
1702 }
1703 close(fd);
1704
1705 return result;
1706}
1707
Willy Tarreaubaaee002006-06-26 02:48:02 +02001708/* will try to encode the string <string> replacing all characters tagged in
1709 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1710 * prefixed by <escape>, and will store the result between <start> (included)
1711 * and <stop> (excluded), and will always terminate the string with a '\0'
1712 * before <stop>. The position of the '\0' is returned if the conversion
1713 * completes. If bytes are missing between <start> and <stop>, then the
1714 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1715 * cannot even be stored so we return <start> without writing the 0.
1716 * The input string must also be zero-terminated.
1717 */
1718const char hextab[16] = "0123456789ABCDEF";
1719char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001720 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001721 const char *string)
1722{
1723 if (start < stop) {
1724 stop--; /* reserve one byte for the final '\0' */
1725 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001726 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001727 *start++ = *string;
1728 else {
1729 if (start + 3 >= stop)
1730 break;
1731 *start++ = escape;
1732 *start++ = hextab[(*string >> 4) & 15];
1733 *start++ = hextab[*string & 15];
1734 }
1735 string++;
1736 }
1737 *start = '\0';
1738 }
1739 return start;
1740}
1741
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001742/*
1743 * Same behavior as encode_string() above, except that it encodes chunk
1744 * <chunk> instead of a string.
1745 */
1746char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001747 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001748 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001749{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001750 char *str = chunk->area;
1751 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001752
1753 if (start < stop) {
1754 stop--; /* reserve one byte for the final '\0' */
1755 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001756 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001757 *start++ = *str;
1758 else {
1759 if (start + 3 >= stop)
1760 break;
1761 *start++ = escape;
1762 *start++ = hextab[(*str >> 4) & 15];
1763 *start++ = hextab[*str & 15];
1764 }
1765 str++;
1766 }
1767 *start = '\0';
1768 }
1769 return start;
1770}
1771
Dragan Dosen0edd1092016-02-12 13:23:02 +01001772/*
1773 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001774 * character. The input <string> must be zero-terminated. The result will
1775 * be stored between <start> (included) and <stop> (excluded). This
1776 * function will always try to terminate the resulting string with a '\0'
1777 * before <stop>, and will return its position if the conversion
1778 * completes.
1779 */
1780char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001781 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001782 const char *string)
1783{
1784 if (start < stop) {
1785 stop--; /* reserve one byte for the final '\0' */
1786 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001787 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001788 *start++ = *string;
1789 else {
1790 if (start + 2 >= stop)
1791 break;
1792 *start++ = escape;
1793 *start++ = *string;
1794 }
1795 string++;
1796 }
1797 *start = '\0';
1798 }
1799 return start;
1800}
1801
1802/*
1803 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001804 * character. <chunk> contains the input to be escaped. The result will be
1805 * stored between <start> (included) and <stop> (excluded). The function
1806 * will always try to terminate the resulting string with a '\0' before
1807 * <stop>, and will return its position if the conversion completes.
1808 */
1809char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001810 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001811 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001812{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001813 char *str = chunk->area;
1814 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001815
1816 if (start < stop) {
1817 stop--; /* reserve one byte for the final '\0' */
1818 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001819 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001820 *start++ = *str;
1821 else {
1822 if (start + 2 >= stop)
1823 break;
1824 *start++ = escape;
1825 *start++ = *str;
1826 }
1827 str++;
1828 }
1829 *start = '\0';
1830 }
1831 return start;
1832}
1833
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001834/* Check a string for using it in a CSV output format. If the string contains
1835 * one of the following four char <">, <,>, CR or LF, the string is
1836 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1837 * <str> is the input string to be escaped. The function assumes that
1838 * the input string is null-terminated.
1839 *
1840 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001841 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001842 * format.
1843 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001844 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001845 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001846 * If <quote> is 1, the converter puts the quotes only if any reserved character
1847 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001848 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001849 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001850 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001851 * The function returns the converted string on its output. If an error
1852 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001853 * for using the function directly as printf() argument.
1854 *
1855 * If the output buffer is too short to contain the input string, the result
1856 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001857 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001858 * This function appends the encoding to the existing output chunk, and it
1859 * guarantees that it starts immediately at the first available character of
1860 * the chunk. Please use csv_enc() instead if you want to replace the output
1861 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001862 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001863const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001864{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001865 char *end = output->area + output->size;
1866 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001867 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001868
Willy Tarreaub631c292016-01-08 10:04:08 +01001869 if (quote == 1) {
1870 /* automatic quoting: first verify if we'll have to quote the string */
1871 if (!strpbrk(str, "\n\r,\""))
1872 quote = 0;
1873 }
1874
1875 if (quote)
1876 *ptr++ = '"';
1877
Willy Tarreau898529b2016-01-06 18:07:04 +01001878 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1879 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001880 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001881 ptr++;
1882 if (ptr >= end - 2) {
1883 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001884 break;
1885 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001886 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001887 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001888 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001889 str++;
1890 }
1891
Willy Tarreaub631c292016-01-08 10:04:08 +01001892 if (quote)
1893 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001894
Willy Tarreau898529b2016-01-06 18:07:04 +01001895 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001896 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001897 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001898}
1899
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001900/* Decode an URL-encoded string in-place. The resulting string might
1901 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001902 * aborted, the string is truncated before the issue and a negative value is
1903 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001904 * If the 'in_form' argument is non-nul the string is assumed to be part of
1905 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
1906 * turned to a space. If it's zero, this will only be done after a question
1907 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001908 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001909int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001910{
1911 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001912 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001913
1914 in = string;
1915 out = string;
1916 while (*in) {
1917 switch (*in) {
1918 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001919 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001920 break;
1921 case '%' :
1922 if (!ishex(in[1]) || !ishex(in[2]))
1923 goto end;
1924 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
1925 in += 2;
1926 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02001927 case '?':
1928 in_form = 1;
1929 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001930 default:
1931 *out++ = *in;
1932 break;
1933 }
1934 in++;
1935 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001936 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001937 end:
1938 *out = 0;
1939 return ret;
1940}
Willy Tarreaubaaee002006-06-26 02:48:02 +02001941
Willy Tarreau6911fa42007-03-04 18:06:08 +01001942unsigned int str2ui(const char *s)
1943{
1944 return __str2ui(s);
1945}
1946
1947unsigned int str2uic(const char *s)
1948{
1949 return __str2uic(s);
1950}
1951
1952unsigned int strl2ui(const char *s, int len)
1953{
1954 return __strl2ui(s, len);
1955}
1956
1957unsigned int strl2uic(const char *s, int len)
1958{
1959 return __strl2uic(s, len);
1960}
1961
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02001962unsigned int read_uint(const char **s, const char *end)
1963{
1964 return __read_uint(s, end);
1965}
1966
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02001967/* This function reads an unsigned integer from the string pointed to by <s> and
1968 * returns it. The <s> pointer is adjusted to point to the first unread char. The
1969 * function automatically stops at <end>. If the number overflows, the 2^64-1
1970 * value is returned.
1971 */
1972unsigned long long int read_uint64(const char **s, const char *end)
1973{
1974 const char *ptr = *s;
1975 unsigned long long int i = 0, tmp;
1976 unsigned int j;
1977
1978 while (ptr < end) {
1979
1980 /* read next char */
1981 j = *ptr - '0';
1982 if (j > 9)
1983 goto read_uint64_end;
1984
1985 /* add char to the number and check overflow. */
1986 tmp = i * 10;
1987 if (tmp / 10 != i) {
1988 i = ULLONG_MAX;
1989 goto read_uint64_eat;
1990 }
1991 if (ULLONG_MAX - tmp < j) {
1992 i = ULLONG_MAX;
1993 goto read_uint64_eat;
1994 }
1995 i = tmp + j;
1996 ptr++;
1997 }
1998read_uint64_eat:
1999 /* eat each numeric char */
2000 while (ptr < end) {
2001 if ((unsigned int)(*ptr - '0') > 9)
2002 break;
2003 ptr++;
2004 }
2005read_uint64_end:
2006 *s = ptr;
2007 return i;
2008}
2009
2010/* This function reads an integer from the string pointed to by <s> and returns
2011 * it. The <s> pointer is adjusted to point to the first unread char. The function
2012 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2013 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2014 * returned.
2015 */
2016long long int read_int64(const char **s, const char *end)
2017{
2018 unsigned long long int i = 0;
2019 int neg = 0;
2020
2021 /* Look for minus char. */
2022 if (**s == '-') {
2023 neg = 1;
2024 (*s)++;
2025 }
2026 else if (**s == '+')
2027 (*s)++;
2028
2029 /* convert as positive number. */
2030 i = read_uint64(s, end);
2031
2032 if (neg) {
2033 if (i > 0x8000000000000000ULL)
2034 return LLONG_MIN;
2035 return -i;
2036 }
2037 if (i > 0x7fffffffffffffffULL)
2038 return LLONG_MAX;
2039 return i;
2040}
2041
Willy Tarreau6911fa42007-03-04 18:06:08 +01002042/* This one is 7 times faster than strtol() on athlon with checks.
2043 * It returns the value of the number composed of all valid digits read,
2044 * and can process negative numbers too.
2045 */
2046int strl2ic(const char *s, int len)
2047{
2048 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002049 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002050
2051 if (len > 0) {
2052 if (*s != '-') {
2053 /* positive number */
2054 while (len-- > 0) {
2055 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002056 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002057 if (j > 9)
2058 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002059 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002060 }
2061 } else {
2062 /* negative number */
2063 s++;
2064 while (--len > 0) {
2065 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002066 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002067 if (j > 9)
2068 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002069 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002070 }
2071 }
2072 }
2073 return i;
2074}
2075
2076
2077/* This function reads exactly <len> chars from <s> and converts them to a
2078 * signed integer which it stores into <ret>. It accurately detects any error
2079 * (truncated string, invalid chars, overflows). It is meant to be used in
2080 * applications designed for hostile environments. It returns zero when the
2081 * number has successfully been converted, non-zero otherwise. When an error
2082 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2083 * faster than strtol().
2084 */
2085int strl2irc(const char *s, int len, int *ret)
2086{
2087 int i = 0;
2088 int j;
2089
2090 if (!len)
2091 return 1;
2092
2093 if (*s != '-') {
2094 /* positive number */
2095 while (len-- > 0) {
2096 j = (*s++) - '0';
2097 if (j > 9) return 1; /* invalid char */
2098 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2099 i = i * 10;
2100 if (i + j < i) return 1; /* check for addition overflow */
2101 i = i + j;
2102 }
2103 } else {
2104 /* negative number */
2105 s++;
2106 while (--len > 0) {
2107 j = (*s++) - '0';
2108 if (j > 9) return 1; /* invalid char */
2109 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2110 i = i * 10;
2111 if (i - j > i) return 1; /* check for subtract overflow */
2112 i = i - j;
2113 }
2114 }
2115 *ret = i;
2116 return 0;
2117}
2118
2119
2120/* This function reads exactly <len> chars from <s> and converts them to a
2121 * signed integer which it stores into <ret>. It accurately detects any error
2122 * (truncated string, invalid chars, overflows). It is meant to be used in
2123 * applications designed for hostile environments. It returns zero when the
2124 * number has successfully been converted, non-zero otherwise. When an error
2125 * is returned, the <ret> value is left untouched. It is about 3 times slower
2126 * than str2irc().
2127 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002128
2129int strl2llrc(const char *s, int len, long long *ret)
2130{
2131 long long i = 0;
2132 int j;
2133
2134 if (!len)
2135 return 1;
2136
2137 if (*s != '-') {
2138 /* positive number */
2139 while (len-- > 0) {
2140 j = (*s++) - '0';
2141 if (j > 9) return 1; /* invalid char */
2142 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2143 i = i * 10LL;
2144 if (i + j < i) return 1; /* check for addition overflow */
2145 i = i + j;
2146 }
2147 } else {
2148 /* negative number */
2149 s++;
2150 while (--len > 0) {
2151 j = (*s++) - '0';
2152 if (j > 9) return 1; /* invalid char */
2153 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2154 i = i * 10LL;
2155 if (i - j > i) return 1; /* check for subtract overflow */
2156 i = i - j;
2157 }
2158 }
2159 *ret = i;
2160 return 0;
2161}
2162
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002163/* This function is used with pat_parse_dotted_ver(). It converts a string
2164 * composed by two number separated by a dot. Each part must contain in 16 bits
2165 * because internally they will be represented as a 32-bit quantity stored in
2166 * a 64-bit integer. It returns zero when the number has successfully been
2167 * converted, non-zero otherwise. When an error is returned, the <ret> value
2168 * is left untouched.
2169 *
2170 * "1.3" -> 0x0000000000010003
2171 * "65535.65535" -> 0x00000000ffffffff
2172 */
2173int strl2llrc_dotted(const char *text, int len, long long *ret)
2174{
2175 const char *end = &text[len];
2176 const char *p;
2177 long long major, minor;
2178
2179 /* Look for dot. */
2180 for (p = text; p < end; p++)
2181 if (*p == '.')
2182 break;
2183
2184 /* Convert major. */
2185 if (strl2llrc(text, p - text, &major) != 0)
2186 return 1;
2187
2188 /* Check major. */
2189 if (major >= 65536)
2190 return 1;
2191
2192 /* Convert minor. */
2193 minor = 0;
2194 if (p < end)
2195 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2196 return 1;
2197
2198 /* Check minor. */
2199 if (minor >= 65536)
2200 return 1;
2201
2202 /* Compose value. */
2203 *ret = (major << 16) | (minor & 0xffff);
2204 return 0;
2205}
2206
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002207/* This function parses a time value optionally followed by a unit suffix among
2208 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2209 * expected by the caller. The computation does its best to avoid overflows.
2210 * The value is returned in <ret> if everything is fine, and a NULL is returned
2211 * by the function. In case of error, a pointer to the error is returned and
2212 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002213 * Values resulting in values larger than or equal to 2^31 after conversion are
2214 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2215 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002216 */
2217const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2218{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002219 unsigned long long imult, idiv;
2220 unsigned long long omult, odiv;
2221 unsigned long long value, result;
Christopher Faulet761d1fb2020-12-11 09:23:07 +01002222 const char *str = text;
2223
2224 if (!isdigit((unsigned char)*text))
2225 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002226
2227 omult = odiv = 1;
2228
2229 switch (unit_flags & TIME_UNIT_MASK) {
2230 case TIME_UNIT_US: omult = 1000000; break;
2231 case TIME_UNIT_MS: omult = 1000; break;
2232 case TIME_UNIT_S: break;
2233 case TIME_UNIT_MIN: odiv = 60; break;
2234 case TIME_UNIT_HOUR: odiv = 3600; break;
2235 case TIME_UNIT_DAY: odiv = 86400; break;
2236 default: break;
2237 }
2238
2239 value = 0;
2240
2241 while (1) {
2242 unsigned int j;
2243
2244 j = *text - '0';
2245 if (j > 9)
2246 break;
2247 text++;
2248 value *= 10;
2249 value += j;
2250 }
2251
2252 imult = idiv = 1;
2253 switch (*text) {
2254 case '\0': /* no unit = default unit */
2255 imult = omult = idiv = odiv = 1;
Christopher Faulet761d1fb2020-12-11 09:23:07 +01002256 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002257 case 's': /* second = unscaled unit */
2258 break;
2259 case 'u': /* microsecond : "us" */
2260 if (text[1] == 's') {
2261 idiv = 1000000;
2262 text++;
Thayne McCombsd5a8cec2021-04-02 14:12:43 -06002263 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002264 }
Christopher Faulet761d1fb2020-12-11 09:23:07 +01002265 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002266 case 'm': /* millisecond : "ms" or minute: "m" */
2267 if (text[1] == 's') {
2268 idiv = 1000;
2269 text++;
2270 } else
2271 imult = 60;
2272 break;
2273 case 'h': /* hour : "h" */
2274 imult = 3600;
2275 break;
2276 case 'd': /* day : "d" */
2277 imult = 86400;
2278 break;
2279 default:
2280 return text;
2281 break;
2282 }
Christopher Faulet761d1fb2020-12-11 09:23:07 +01002283 if (*(++text) != '\0') {
2284 ha_warning("unexpected character '%c' after the timer value '%s', only "
2285 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2286 " This will be reported as an error in next versions.\n", *text, str);
2287 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002288
Christopher Faulet761d1fb2020-12-11 09:23:07 +01002289 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002290 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2291 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2292 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2293 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2294
Willy Tarreau9faebe32019-06-07 19:00:37 +02002295 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2296 if (result >= 0x80000000)
2297 return PARSE_TIME_OVER;
2298 if (!result && value)
2299 return PARSE_TIME_UNDER;
2300 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002301 return NULL;
2302}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002303
Emeric Brun39132b22010-01-04 14:57:24 +01002304/* this function converts the string starting at <text> to an unsigned int
2305 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002306 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002307 */
2308const char *parse_size_err(const char *text, unsigned *ret) {
2309 unsigned value = 0;
2310
Christopher Faulet7f955e62020-12-11 09:30:45 +01002311 if (!isdigit((unsigned char)*text))
2312 return text;
2313
Emeric Brun39132b22010-01-04 14:57:24 +01002314 while (1) {
2315 unsigned int j;
2316
2317 j = *text - '0';
2318 if (j > 9)
2319 break;
2320 if (value > ~0U / 10)
2321 return text;
2322 value *= 10;
2323 if (value > (value + j))
2324 return text;
2325 value += j;
2326 text++;
2327 }
2328
2329 switch (*text) {
2330 case '\0':
2331 break;
2332 case 'K':
2333 case 'k':
2334 if (value > ~0U >> 10)
2335 return text;
2336 value = value << 10;
2337 break;
2338 case 'M':
2339 case 'm':
2340 if (value > ~0U >> 20)
2341 return text;
2342 value = value << 20;
2343 break;
2344 case 'G':
2345 case 'g':
2346 if (value > ~0U >> 30)
2347 return text;
2348 value = value << 30;
2349 break;
2350 default:
2351 return text;
2352 }
2353
Godbach58048a22015-01-28 17:36:16 +08002354 if (*text != '\0' && *++text != '\0')
2355 return text;
2356
Emeric Brun39132b22010-01-04 14:57:24 +01002357 *ret = value;
2358 return NULL;
2359}
2360
Willy Tarreau126d4062013-12-03 17:50:47 +01002361/*
2362 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002363 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002364 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002365 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002366 */
2367int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2368{
2369 int len;
2370 const char *p = source;
2371 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002372 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002373
2374 len = strlen(source);
2375 if (len % 2) {
2376 memprintf(err, "an even number of hex digit is expected");
2377 return 0;
2378 }
2379
2380 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002381
Willy Tarreau126d4062013-12-03 17:50:47 +01002382 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002383 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002384 if (!*binstr) {
2385 memprintf(err, "out of memory while loading string pattern");
2386 return 0;
2387 }
2388 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002389 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002390 else {
2391 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002392 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002393 len, *binstrlen);
2394 return 0;
2395 }
2396 alloc = 0;
2397 }
2398 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002399
2400 i = j = 0;
2401 while (j < len) {
2402 if (!ishex(p[i++]))
2403 goto bad_input;
2404 if (!ishex(p[i++]))
2405 goto bad_input;
2406 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2407 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002408 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002409
2410bad_input:
2411 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Andreas Seltenreich93f91c32016-03-03 20:40:37 +01002412 if (alloc) {
2413 free(*binstr);
2414 *binstr = NULL;
2415 }
Willy Tarreau126d4062013-12-03 17:50:47 +01002416 return 0;
2417}
2418
Willy Tarreau946ba592009-05-10 15:41:18 +02002419/* copies at most <n> characters from <src> and always terminates with '\0' */
2420char *my_strndup(const char *src, int n)
2421{
2422 int len = 0;
2423 char *ret;
2424
2425 while (len < n && src[len])
2426 len++;
2427
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002428 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002429 if (!ret)
2430 return ret;
2431 memcpy(ret, src, len);
2432 ret[len] = '\0';
2433 return ret;
2434}
2435
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002436/*
2437 * search needle in haystack
2438 * returns the pointer if found, returns NULL otherwise
2439 */
2440const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2441{
2442 const void *c = NULL;
2443 unsigned char f;
2444
2445 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2446 return NULL;
2447
2448 f = *(char *)needle;
2449 c = haystack;
2450 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2451 if ((haystacklen - (c - haystack)) < needlelen)
2452 return NULL;
2453
2454 if (memcmp(c, needle, needlelen) == 0)
2455 return c;
2456 ++c;
2457 }
2458 return NULL;
2459}
2460
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002461/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002462size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2463{
2464 size_t ret = 0;
2465
2466 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2467 str++;
2468 ret++;
2469 }
2470 return ret;
2471}
2472
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002473/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002474size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2475{
2476 size_t ret = 0;
2477
2478 while (ret < len) {
2479 if(memchr(reject, *((int *)str), rejectlen))
2480 return ret;
2481 str++;
2482 ret++;
2483 }
2484 return ret;
2485}
2486
Willy Tarreau482b00d2009-10-04 22:48:42 +02002487/* This function returns the first unused key greater than or equal to <key> in
2488 * ID tree <root>. Zero is returned if no place is found.
2489 */
2490unsigned int get_next_id(struct eb_root *root, unsigned int key)
2491{
2492 struct eb32_node *used;
2493
2494 do {
2495 used = eb32_lookup_ge(root, key);
2496 if (!used || used->key > key)
2497 return key; /* key is available */
2498 key++;
2499 } while (key);
2500 return key;
2501}
2502
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002503/* dump the full tree to <file> in DOT format for debugging purposes. Will
2504 * optionally highlight node <subj> if found, depending on operation <op> :
2505 * 0 : nothing
2506 * >0 : insertion, node/leaf are surrounded in red
2507 * <0 : removal, node/leaf are dashed with no background
2508 * Will optionally add "desc" as a label on the graph if set and non-null.
2509 */
2510void 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 +01002511{
2512 struct eb32sc_node *node;
2513 unsigned long scope = -1;
2514
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002515 fprintf(file, "digraph ebtree {\n");
2516
2517 if (desc && *desc) {
2518 fprintf(file,
2519 " fontname=\"fixed\";\n"
2520 " fontsize=8;\n"
2521 " label=\"%s\";\n", desc);
2522 }
2523
Willy Tarreaued3cda02017-11-15 15:04:05 +01002524 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002525 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2526 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002527 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2528 );
2529
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002530 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002531 (long)eb_root_to_node(root),
2532 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002533 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2534
2535 node = eb32sc_first(root, scope);
2536 while (node) {
2537 if (node->node.node_p) {
2538 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002539 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2540 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2541 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002542
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002543 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002544 (long)node,
2545 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002546 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002547
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002548 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002549 (long)node,
2550 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002551 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2552
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002553 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002554 (long)node,
2555 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002556 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2557 }
2558
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002559 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2560 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2561 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002562
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002563 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002564 (long)node,
2565 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002566 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002567 node = eb32sc_next(node, scope);
2568 }
2569 fprintf(file, "}\n");
2570}
2571
Willy Tarreau348238b2010-01-18 15:05:57 +01002572/* This function compares a sample word possibly followed by blanks to another
2573 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2574 * otherwise zero. This intends to be used when checking HTTP headers for some
2575 * values. Note that it validates a word followed only by blanks but does not
2576 * validate a word followed by blanks then other chars.
2577 */
2578int word_match(const char *sample, int slen, const char *word, int wlen)
2579{
2580 if (slen < wlen)
2581 return 0;
2582
2583 while (wlen) {
2584 char c = *sample ^ *word;
2585 if (c && c != ('A' ^ 'a'))
2586 return 0;
2587 sample++;
2588 word++;
2589 slen--;
2590 wlen--;
2591 }
2592
2593 while (slen) {
2594 if (*sample != ' ' && *sample != '\t')
2595 return 0;
2596 sample++;
2597 slen--;
2598 }
2599 return 1;
2600}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002601
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002602/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2603 * is particularly fast because it avoids expensive operations such as
2604 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002605 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002606 */
2607unsigned int inetaddr_host(const char *text)
2608{
2609 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2610 register unsigned int dig100, dig10, dig1;
2611 int s;
2612 const char *p, *d;
2613
2614 dig1 = dig10 = dig100 = ascii_zero;
2615 s = 24;
2616
2617 p = text;
2618 while (1) {
2619 if (((unsigned)(*p - '0')) <= 9) {
2620 p++;
2621 continue;
2622 }
2623
2624 /* here, we have a complete byte between <text> and <p> (exclusive) */
2625 if (p == text)
2626 goto end;
2627
2628 d = p - 1;
2629 dig1 |= (unsigned int)(*d << s);
2630 if (d == text)
2631 goto end;
2632
2633 d--;
2634 dig10 |= (unsigned int)(*d << s);
2635 if (d == text)
2636 goto end;
2637
2638 d--;
2639 dig100 |= (unsigned int)(*d << s);
2640 end:
2641 if (!s || *p != '.')
2642 break;
2643
2644 s -= 8;
2645 text = ++p;
2646 }
2647
2648 dig100 -= ascii_zero;
2649 dig10 -= ascii_zero;
2650 dig1 -= ascii_zero;
2651 return ((dig100 * 10) + dig10) * 10 + dig1;
2652}
2653
2654/*
2655 * Idem except the first unparsed character has to be passed in <stop>.
2656 */
2657unsigned int inetaddr_host_lim(const char *text, const char *stop)
2658{
2659 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2660 register unsigned int dig100, dig10, dig1;
2661 int s;
2662 const char *p, *d;
2663
2664 dig1 = dig10 = dig100 = ascii_zero;
2665 s = 24;
2666
2667 p = text;
2668 while (1) {
2669 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2670 p++;
2671 continue;
2672 }
2673
2674 /* here, we have a complete byte between <text> and <p> (exclusive) */
2675 if (p == text)
2676 goto end;
2677
2678 d = p - 1;
2679 dig1 |= (unsigned int)(*d << s);
2680 if (d == text)
2681 goto end;
2682
2683 d--;
2684 dig10 |= (unsigned int)(*d << s);
2685 if (d == text)
2686 goto end;
2687
2688 d--;
2689 dig100 |= (unsigned int)(*d << s);
2690 end:
2691 if (!s || p == stop || *p != '.')
2692 break;
2693
2694 s -= 8;
2695 text = ++p;
2696 }
2697
2698 dig100 -= ascii_zero;
2699 dig10 -= ascii_zero;
2700 dig1 -= ascii_zero;
2701 return ((dig100 * 10) + dig10) * 10 + dig1;
2702}
2703
2704/*
2705 * Idem except the pointer to first unparsed byte is returned into <ret> which
2706 * must not be NULL.
2707 */
Willy Tarreau74172752010-10-15 23:21:42 +02002708unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002709{
2710 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2711 register unsigned int dig100, dig10, dig1;
2712 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002713 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002714
2715 dig1 = dig10 = dig100 = ascii_zero;
2716 s = 24;
2717
2718 p = text;
2719 while (1) {
2720 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2721 p++;
2722 continue;
2723 }
2724
2725 /* here, we have a complete byte between <text> and <p> (exclusive) */
2726 if (p == text)
2727 goto end;
2728
2729 d = p - 1;
2730 dig1 |= (unsigned int)(*d << s);
2731 if (d == text)
2732 goto end;
2733
2734 d--;
2735 dig10 |= (unsigned int)(*d << s);
2736 if (d == text)
2737 goto end;
2738
2739 d--;
2740 dig100 |= (unsigned int)(*d << s);
2741 end:
2742 if (!s || p == stop || *p != '.')
2743 break;
2744
2745 s -= 8;
2746 text = ++p;
2747 }
2748
2749 *ret = p;
2750 dig100 -= ascii_zero;
2751 dig10 -= ascii_zero;
2752 dig1 -= ascii_zero;
2753 return ((dig100 * 10) + dig10) * 10 + dig1;
2754}
2755
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002756/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2757 * or the number of chars read in case of success. Maybe this could be replaced
2758 * by one of the functions above. Also, apparently this function does not support
2759 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002760 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002761 */
2762int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2763{
2764 const char *addr;
2765 int saw_digit, octets, ch;
2766 u_char tmp[4], *tp;
2767 const char *cp = buf;
2768
2769 saw_digit = 0;
2770 octets = 0;
2771 *(tp = tmp) = 0;
2772
2773 for (addr = buf; addr - buf < len; addr++) {
2774 unsigned char digit = (ch = *addr) - '0';
2775
2776 if (digit > 9 && ch != '.')
2777 break;
2778
2779 if (digit <= 9) {
2780 u_int new = *tp * 10 + digit;
2781
2782 if (new > 255)
2783 return 0;
2784
2785 *tp = new;
2786
2787 if (!saw_digit) {
2788 if (++octets > 4)
2789 return 0;
2790 saw_digit = 1;
2791 }
2792 } else if (ch == '.' && saw_digit) {
2793 if (octets == 4)
2794 return 0;
2795
2796 *++tp = 0;
2797 saw_digit = 0;
2798 } else
2799 return 0;
2800 }
2801
2802 if (octets < 4)
2803 return 0;
2804
2805 memcpy(&dst->s_addr, tmp, 4);
2806 return addr - cp;
2807}
2808
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002809/* This function converts the string in <buf> of the len <len> to
2810 * struct in6_addr <dst> which must be allocated by the caller.
2811 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002812 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002813 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002814int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2815{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002816 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002817 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002818
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002819 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002820 return 0;
2821
2822 memcpy(null_term_ip6, buf, len);
2823 null_term_ip6[len] = '\0';
2824
Willy Tarreau075415a2013-12-12 11:29:39 +01002825 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002826 return 0;
2827
Willy Tarreau075415a2013-12-12 11:29:39 +01002828 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002829 return 1;
2830}
2831
Willy Tarreauacf95772010-06-14 19:09:21 +02002832/* To be used to quote config arg positions. Returns the short string at <ptr>
2833 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2834 * if ptr is NULL or empty. The string is locally allocated.
2835 */
2836const char *quote_arg(const char *ptr)
2837{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002838 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002839 int i;
2840
2841 if (!ptr || !*ptr)
2842 return "end of line";
2843 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002844 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002845 val[i] = *ptr++;
2846 val[i++] = '\'';
2847 val[i] = '\0';
2848 return val;
2849}
2850
Willy Tarreau5b180202010-07-18 10:40:48 +02002851/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2852int get_std_op(const char *str)
2853{
2854 int ret = -1;
2855
2856 if (*str == 'e' && str[1] == 'q')
2857 ret = STD_OP_EQ;
2858 else if (*str == 'n' && str[1] == 'e')
2859 ret = STD_OP_NE;
2860 else if (*str == 'l') {
2861 if (str[1] == 'e') ret = STD_OP_LE;
2862 else if (str[1] == 't') ret = STD_OP_LT;
2863 }
2864 else if (*str == 'g') {
2865 if (str[1] == 'e') ret = STD_OP_GE;
2866 else if (str[1] == 't') ret = STD_OP_GT;
2867 }
2868
2869 if (ret == -1 || str[2] != '\0')
2870 return -1;
2871 return ret;
2872}
2873
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002874/* hash a 32-bit integer to another 32-bit integer */
2875unsigned int full_hash(unsigned int a)
2876{
2877 return __full_hash(a);
2878}
2879
Willy Tarreauf3241112019-02-26 09:56:22 +01002880/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2881 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2882 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2883 * a popcount variant and is described here :
2884 * https://graphics.stanford.edu/~seander/bithacks.html
2885 */
2886unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2887{
2888 unsigned long a, b, c, d;
2889 unsigned int s;
2890 unsigned int t;
2891
2892 a = m - ((m >> 1) & ~0UL/3);
2893 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2894 c = (b + (b >> 4)) & ~0UL/0x11;
2895 d = (c + (c >> 8)) & ~0UL/0x101;
2896
2897 r++; // make r be 1..64
2898
2899 t = 0;
2900 s = LONGBITS;
2901 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002902 unsigned long d2 = (d >> 16) >> 16;
2903 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002904 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2905 }
2906
2907 t = (d >> (s - 16)) & 0xff;
2908 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2909 t = (c >> (s - 8)) & 0xf;
2910 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2911 t = (b >> (s - 4)) & 0x7;
2912 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2913 t = (a >> (s - 2)) & 0x3;
2914 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2915 t = (m >> (s - 1)) & 0x1;
2916 s -= ((t - r) & 256) >> 8;
2917
2918 return s - 1;
2919}
2920
2921/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
2922 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
2923 * using mask_prep_rank_map() below.
2924 */
2925unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
2926 unsigned long a, unsigned long b,
2927 unsigned long c, unsigned long d)
2928{
2929 unsigned int s;
2930 unsigned int t;
2931
2932 r++; // make r be 1..64
2933
2934 t = 0;
2935 s = LONGBITS;
2936 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002937 unsigned long d2 = (d >> 16) >> 16;
2938 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002939 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
2940 }
2941
2942 t = (d >> (s - 16)) & 0xff;
2943 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
2944 t = (c >> (s - 8)) & 0xf;
2945 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
2946 t = (b >> (s - 4)) & 0x7;
2947 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
2948 t = (a >> (s - 2)) & 0x3;
2949 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
2950 t = (m >> (s - 1)) & 0x1;
2951 s -= ((t - r) & 256) >> 8;
2952
2953 return s - 1;
2954}
2955
2956/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
2957 * above.
2958 */
2959void mask_prep_rank_map(unsigned long m,
2960 unsigned long *a, unsigned long *b,
2961 unsigned long *c, unsigned long *d)
2962{
2963 *a = m - ((m >> 1) & ~0UL/3);
2964 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
2965 *c = (*b + (*b >> 4)) & ~0UL/0x11;
2966 *d = (*c + (*c >> 8)) & ~0UL/0x101;
2967}
2968
David du Colombier4f92d322011-03-24 11:09:31 +01002969/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002970 * otherwise zero. Note that <addr> may not necessarily be aligned
2971 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002972 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002973int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002974{
Willy Tarreaueec1d382016-07-13 11:59:39 +02002975 struct in_addr addr_copy;
2976
2977 memcpy(&addr_copy, addr, sizeof(addr_copy));
2978 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01002979}
2980
2981/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02002982 * otherwise zero. Note that <addr> may not necessarily be aligned
2983 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01002984 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02002985int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01002986{
2987 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02002988 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01002989
Willy Tarreaueec1d382016-07-13 11:59:39 +02002990 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01002991 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02002992 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01002993 (((int *)net)[i] & ((int *)mask)[i]))
2994 return 0;
2995 return 1;
2996}
2997
2998/* RFC 4291 prefix */
2999const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3000 0x00, 0x00, 0x00, 0x00,
3001 0x00, 0x00, 0xFF, 0xFF };
3002
Joseph Herlant32b83272018-11-15 11:58:28 -08003003/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003004 * Input and output may overlap.
3005 */
David du Colombier4f92d322011-03-24 11:09:31 +01003006void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3007{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003008 struct in_addr tmp_addr;
3009
3010 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003011 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003012 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003013}
3014
Joseph Herlant32b83272018-11-15 11:58:28 -08003015/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003016 * Return true if conversion is possible and false otherwise.
3017 */
3018int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3019{
3020 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3021 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3022 sizeof(struct in_addr));
3023 return 1;
3024 }
3025
3026 return 0;
3027}
3028
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003029/* compare two struct sockaddr_storage and return:
3030 * 0 (true) if the addr is the same in both
3031 * 1 (false) if the addr is not the same in both
3032 * -1 (unable) if one of the addr is not AF_INET*
3033 */
3034int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3035{
3036 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3037 return -1;
3038
3039 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3040 return -1;
3041
3042 if (ss1->ss_family != ss2->ss_family)
3043 return 1;
3044
3045 switch (ss1->ss_family) {
3046 case AF_INET:
3047 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3048 &((struct sockaddr_in *)ss2)->sin_addr,
3049 sizeof(struct in_addr)) != 0;
3050 case AF_INET6:
3051 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3052 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3053 sizeof(struct in6_addr)) != 0;
3054 }
3055
3056 return 1;
3057}
3058
Baptiste Assmann08396c82016-01-31 00:27:17 +01003059/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003060 * The caller must allocate and clear <dest> before calling.
3061 * The source must be in either AF_INET or AF_INET6 family, or the destination
3062 * address will be undefined. If the destination address used to hold a port,
3063 * it is preserved, so that this function can be used to switch to another
3064 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003065 */
3066struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3067{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003068 int prev_port;
3069
3070 prev_port = get_net_port(dest);
3071 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003072 dest->ss_family = source->ss_family;
3073
3074 /* copy new addr and apply it */
3075 switch (source->ss_family) {
3076 case AF_INET:
3077 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003078 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003079 break;
3080 case AF_INET6:
3081 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 +01003082 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003083 break;
3084 }
3085
3086 return dest;
3087}
3088
William Lallemand421f5b52012-02-06 18:15:57 +01003089char *human_time(int t, short hz_div) {
3090 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3091 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003092 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003093 int cnt=2; // print two numbers
3094
3095 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003096 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003097 return rv;
3098 }
3099
3100 if (unlikely(hz_div > 1))
3101 t /= hz_div;
3102
3103 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003104 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003105 cnt--;
3106 }
3107
3108 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003109 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003110 cnt--;
3111 }
3112
3113 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003114 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003115 cnt--;
3116 }
3117
3118 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003119 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003120
3121 return rv;
3122}
3123
3124const char *monthname[12] = {
3125 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3126 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3127};
3128
3129/* date2str_log: write a date in the format :
3130 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3131 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3132 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3133 *
3134 * without using sprintf. return a pointer to the last char written (\0) or
3135 * NULL if there isn't enough space.
3136 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003137char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003138{
3139
3140 if (size < 25) /* the size is fixed: 24 chars + \0 */
3141 return NULL;
3142
3143 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003144 if (!dst)
3145 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003146 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003147
William Lallemand421f5b52012-02-06 18:15:57 +01003148 memcpy(dst, monthname[tm->tm_mon], 3); // month
3149 dst += 3;
3150 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003151
William Lallemand421f5b52012-02-06 18:15:57 +01003152 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003153 if (!dst)
3154 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003155 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003156
William Lallemand421f5b52012-02-06 18:15:57 +01003157 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003158 if (!dst)
3159 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003160 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003161
William Lallemand421f5b52012-02-06 18:15:57 +01003162 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003163 if (!dst)
3164 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003165 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003166
William Lallemand421f5b52012-02-06 18:15:57 +01003167 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003168 if (!dst)
3169 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003170 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003171
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003172 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003173 if (!dst)
3174 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003175 *dst = '\0';
3176
3177 return dst;
3178}
3179
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003180/* Base year used to compute leap years */
3181#define TM_YEAR_BASE 1900
3182
3183/* Return the difference in seconds between two times (leap seconds are ignored).
3184 * Retrieved from glibc 2.18 source code.
3185 */
3186static int my_tm_diff(const struct tm *a, const struct tm *b)
3187{
3188 /* Compute intervening leap days correctly even if year is negative.
3189 * Take care to avoid int overflow in leap day calculations,
3190 * but it's OK to assume that A and B are close to each other.
3191 */
3192 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3193 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3194 int a100 = a4 / 25 - (a4 % 25 < 0);
3195 int b100 = b4 / 25 - (b4 % 25 < 0);
3196 int a400 = a100 >> 2;
3197 int b400 = b100 >> 2;
3198 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3199 int years = a->tm_year - b->tm_year;
3200 int days = (365 * years + intervening_leap_days
3201 + (a->tm_yday - b->tm_yday));
3202 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3203 + (a->tm_min - b->tm_min))
3204 + (a->tm_sec - b->tm_sec));
3205}
3206
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003207/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003208 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003209 * The string returned has the same format as returned by strftime(... "%z", tm).
3210 * Offsets are kept in an internal cache for better performances.
3211 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003212const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003213{
3214 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003215 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003216
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003217 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003218 struct tm tm_gmt;
3219 int diff;
3220 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003221
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003222 /* Pretend DST not active if its status is unknown */
3223 if (isdst < 0)
3224 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003225
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003226 /* Fetch the offset and initialize it if needed */
3227 gmt_offset = gmt_offsets[isdst & 0x01];
3228 if (unlikely(!*gmt_offset)) {
3229 get_gmtime(t, &tm_gmt);
3230 diff = my_tm_diff(tm, &tm_gmt);
3231 if (diff < 0) {
3232 diff = -diff;
3233 *gmt_offset = '-';
3234 } else {
3235 *gmt_offset = '+';
3236 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003237 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003238 diff /= 60; /* Convert to minutes */
3239 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3240 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003241
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003242 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003243}
3244
William Lallemand421f5b52012-02-06 18:15:57 +01003245/* gmt2str_log: write a date in the format :
3246 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3247 * return a pointer to the last char written (\0) or
3248 * NULL if there isn't enough space.
3249 */
3250char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3251{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003252 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003253 return NULL;
3254
3255 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003256 if (!dst)
3257 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003258 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003259
William Lallemand421f5b52012-02-06 18:15:57 +01003260 memcpy(dst, monthname[tm->tm_mon], 3); // month
3261 dst += 3;
3262 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003263
William Lallemand421f5b52012-02-06 18:15:57 +01003264 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003265 if (!dst)
3266 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003267 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003268
William Lallemand421f5b52012-02-06 18:15:57 +01003269 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003270 if (!dst)
3271 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003272 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003273
William Lallemand421f5b52012-02-06 18:15:57 +01003274 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003275 if (!dst)
3276 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003277 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003278
William Lallemand421f5b52012-02-06 18:15:57 +01003279 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003280 if (!dst)
3281 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003282 *dst++ = ' ';
3283 *dst++ = '+';
3284 *dst++ = '0';
3285 *dst++ = '0';
3286 *dst++ = '0';
3287 *dst++ = '0';
3288 *dst = '\0';
3289
3290 return dst;
3291}
3292
Yuxans Yao4e25b012012-10-19 10:36:09 +08003293/* localdate2str_log: write a date in the format :
3294 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003295 * Both t and tm must represent the same time.
3296 * return a pointer to the last char written (\0) or
3297 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003298 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003299char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003300{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003301 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003302 if (size < 27) /* the size is fixed: 26 chars + \0 */
3303 return NULL;
3304
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003305 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003306
Yuxans Yao4e25b012012-10-19 10:36:09 +08003307 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003308 if (!dst)
3309 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003310 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003311
Yuxans Yao4e25b012012-10-19 10:36:09 +08003312 memcpy(dst, monthname[tm->tm_mon], 3); // month
3313 dst += 3;
3314 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003315
Yuxans Yao4e25b012012-10-19 10:36:09 +08003316 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003317 if (!dst)
3318 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003319 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003320
Yuxans Yao4e25b012012-10-19 10:36:09 +08003321 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003322 if (!dst)
3323 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003324 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003325
Yuxans Yao4e25b012012-10-19 10:36:09 +08003326 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003327 if (!dst)
3328 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003329 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003330
Yuxans Yao4e25b012012-10-19 10:36:09 +08003331 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003332 if (!dst)
3333 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003334 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003335
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003336 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003337 dst += 5;
3338 *dst = '\0';
3339
3340 return dst;
3341}
3342
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003343/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3344 * It is meant as a portable replacement for timegm() for use with valid inputs.
3345 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3346 */
3347time_t my_timegm(const struct tm *tm)
3348{
3349 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3350 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3351 * sum of the extra N days for elapsed months. The sum of all these N
3352 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3353 * in a 5-bit word. This means that with 60 bits we can represent a
3354 * matrix of all these values at once, which is fast and efficient to
3355 * access. The extra February day for leap years is not counted here.
3356 *
3357 * Jan : none = 0 (0)
3358 * Feb : Jan = 3 (3)
3359 * Mar : Jan..Feb = 3 (3 + 0)
3360 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3361 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3362 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3363 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3364 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3365 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3366 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3367 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3368 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3369 */
3370 uint64_t extra =
3371 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3372 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3373 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3374 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3375
3376 unsigned int y = tm->tm_year + 1900;
3377 unsigned int m = tm->tm_mon;
3378 unsigned long days = 0;
3379
3380 /* days since 1/1/1970 for full years */
3381 days += days_since_zero(y) - days_since_zero(1970);
3382
3383 /* days for full months in the current year */
3384 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3385
3386 /* count + 1 after March for leap years. A leap year is a year multiple
3387 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3388 * is leap, 1900 isn't, 1904 is.
3389 */
3390 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3391 days++;
3392
3393 days += tm->tm_mday - 1;
3394 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3395}
3396
Thierry Fournier93127942016-01-20 18:49:45 +01003397/* This function check a char. It returns true and updates
3398 * <date> and <len> pointer to the new position if the
3399 * character is found.
3400 */
3401static inline int parse_expect_char(const char **date, int *len, char c)
3402{
3403 if (*len < 1 || **date != c)
3404 return 0;
3405 (*len)--;
3406 (*date)++;
3407 return 1;
3408}
3409
3410/* This function expects a string <str> of len <l>. It return true and updates.
3411 * <date> and <len> if the string matches, otherwise, it returns false.
3412 */
3413static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3414{
3415 if (*len < l || strncmp(*date, str, l) != 0)
3416 return 0;
3417 (*len) -= l;
3418 (*date) += l;
3419 return 1;
3420}
3421
3422/* This macro converts 3 chars name in integer. */
3423#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3424
3425/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3426 * / %x54.75.65 ; "Tue", case-sensitive
3427 * / %x57.65.64 ; "Wed", case-sensitive
3428 * / %x54.68.75 ; "Thu", case-sensitive
3429 * / %x46.72.69 ; "Fri", case-sensitive
3430 * / %x53.61.74 ; "Sat", case-sensitive
3431 * / %x53.75.6E ; "Sun", case-sensitive
3432 *
3433 * This array must be alphabetically sorted
3434 */
3435static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3436{
3437 if (*len < 3)
3438 return 0;
3439 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3440 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3441 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3442 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3443 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3444 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3445 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3446 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3447 default: return 0;
3448 }
3449 *len -= 3;
3450 *date += 3;
3451 return 1;
3452}
3453
3454/* month = %x4A.61.6E ; "Jan", case-sensitive
3455 * / %x46.65.62 ; "Feb", case-sensitive
3456 * / %x4D.61.72 ; "Mar", case-sensitive
3457 * / %x41.70.72 ; "Apr", case-sensitive
3458 * / %x4D.61.79 ; "May", case-sensitive
3459 * / %x4A.75.6E ; "Jun", case-sensitive
3460 * / %x4A.75.6C ; "Jul", case-sensitive
3461 * / %x41.75.67 ; "Aug", case-sensitive
3462 * / %x53.65.70 ; "Sep", case-sensitive
3463 * / %x4F.63.74 ; "Oct", case-sensitive
3464 * / %x4E.6F.76 ; "Nov", case-sensitive
3465 * / %x44.65.63 ; "Dec", case-sensitive
3466 *
3467 * This array must be alphabetically sorted
3468 */
3469static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3470{
3471 if (*len < 3)
3472 return 0;
3473 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3474 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3475 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3476 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3477 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3478 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3479 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3480 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3481 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3482 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3483 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3484 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3485 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3486 default: return 0;
3487 }
3488 *len -= 3;
3489 *date += 3;
3490 return 1;
3491}
3492
3493/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3494 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3495 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3496 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3497 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3498 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3499 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3500 *
3501 * This array must be alphabetically sorted
3502 */
3503static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3504{
3505 if (*len < 6) /* Minimum length. */
3506 return 0;
3507 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3508 case STR2I3('M','o','n'):
3509 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3510 tm->tm_wday = 1;
3511 return 1;
3512 case STR2I3('T','u','e'):
3513 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3514 tm->tm_wday = 2;
3515 return 1;
3516 case STR2I3('W','e','d'):
3517 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3518 tm->tm_wday = 3;
3519 return 1;
3520 case STR2I3('T','h','u'):
3521 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3522 tm->tm_wday = 4;
3523 return 1;
3524 case STR2I3('F','r','i'):
3525 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3526 tm->tm_wday = 5;
3527 return 1;
3528 case STR2I3('S','a','t'):
3529 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3530 tm->tm_wday = 6;
3531 return 1;
3532 case STR2I3('S','u','n'):
3533 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3534 tm->tm_wday = 7;
3535 return 1;
3536 }
3537 return 0;
3538}
3539
3540/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3541static inline int parse_digit(const char **date, int *len, int *digit)
3542{
3543 if (*len < 1 || **date < '0' || **date > '9')
3544 return 0;
3545 *digit = (**date - '0');
3546 (*date)++;
3547 (*len)--;
3548 return 1;
3549}
3550
3551/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3552static inline int parse_2digit(const char **date, int *len, int *digit)
3553{
3554 int value;
3555
3556 RET0_UNLESS(parse_digit(date, len, &value));
3557 (*digit) = value * 10;
3558 RET0_UNLESS(parse_digit(date, len, &value));
3559 (*digit) += value;
3560
3561 return 1;
3562}
3563
3564/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3565static inline int parse_4digit(const char **date, int *len, int *digit)
3566{
3567 int value;
3568
3569 RET0_UNLESS(parse_digit(date, len, &value));
3570 (*digit) = value * 1000;
3571
3572 RET0_UNLESS(parse_digit(date, len, &value));
3573 (*digit) += value * 100;
3574
3575 RET0_UNLESS(parse_digit(date, len, &value));
3576 (*digit) += value * 10;
3577
3578 RET0_UNLESS(parse_digit(date, len, &value));
3579 (*digit) += value;
3580
3581 return 1;
3582}
3583
3584/* time-of-day = hour ":" minute ":" second
3585 * ; 00:00:00 - 23:59:60 (leap second)
3586 *
3587 * hour = 2DIGIT
3588 * minute = 2DIGIT
3589 * second = 2DIGIT
3590 */
3591static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3592{
3593 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3594 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3595 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3596 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3597 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3598 return 1;
3599}
3600
3601/* From RFC7231
3602 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3603 *
3604 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3605 * ; fixed length/zone/capitalization subset of the format
3606 * ; see Section 3.3 of [RFC5322]
3607 *
3608 *
3609 * date1 = day SP month SP year
3610 * ; e.g., 02 Jun 1982
3611 *
3612 * day = 2DIGIT
3613 * year = 4DIGIT
3614 *
3615 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3616 *
3617 * time-of-day = hour ":" minute ":" second
3618 * ; 00:00:00 - 23:59:60 (leap second)
3619 *
3620 * hour = 2DIGIT
3621 * minute = 2DIGIT
3622 * second = 2DIGIT
3623 *
3624 * DIGIT = decimal 0-9
3625 */
3626int parse_imf_date(const char *date, int len, struct tm *tm)
3627{
David Carlier327298c2016-11-20 10:42:38 +00003628 /* tm_gmtoff, if present, ought to be zero'ed */
3629 memset(tm, 0, sizeof(*tm));
3630
Thierry Fournier93127942016-01-20 18:49:45 +01003631 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3632 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3633 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3634 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3635 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3636 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3637 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3638 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3639 tm->tm_year -= 1900;
3640 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3641 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3642 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3643 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3644 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003645 return 1;
3646}
3647
3648/* From RFC7231
3649 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3650 *
3651 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3652 * date2 = day "-" month "-" 2DIGIT
3653 * ; e.g., 02-Jun-82
3654 *
3655 * day = 2DIGIT
3656 */
3657int parse_rfc850_date(const char *date, int len, struct tm *tm)
3658{
3659 int year;
3660
David Carlier327298c2016-11-20 10:42:38 +00003661 /* tm_gmtoff, if present, ought to be zero'ed */
3662 memset(tm, 0, sizeof(*tm));
3663
Thierry Fournier93127942016-01-20 18:49:45 +01003664 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3665 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3666 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3667 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3668 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3669 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3670 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3671
3672 /* year = 2DIGIT
3673 *
3674 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3675 * two-digit year, MUST interpret a timestamp that appears to be more
3676 * than 50 years in the future as representing the most recent year in
3677 * the past that had the same last two digits.
3678 */
3679 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3680
3681 /* expect SP */
3682 if (!parse_expect_char(&date, &len, ' ')) {
3683 /* Maybe we have the date with 4 digits. */
3684 RET0_UNLESS(parse_2digit(&date, &len, &year));
3685 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3686 /* expect SP */
3687 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3688 } else {
3689 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3690 * tm_year is the number of year since 1900, so for +1900, we
3691 * do nothing, and for +2000, we add 100.
3692 */
3693 if (tm->tm_year <= 60)
3694 tm->tm_year += 100;
3695 }
3696
3697 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3698 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3699 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3700 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003701
3702 return 1;
3703}
3704
3705/* From RFC7231
3706 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3707 *
3708 * asctime-date = day-name SP date3 SP time-of-day SP year
3709 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3710 * ; e.g., Jun 2
3711 *
3712 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3713 * whitespace in an HTTP-date beyond that specifically included as SP in
3714 * the grammar.
3715 */
3716int parse_asctime_date(const char *date, int len, struct tm *tm)
3717{
David Carlier327298c2016-11-20 10:42:38 +00003718 /* tm_gmtoff, if present, ought to be zero'ed */
3719 memset(tm, 0, sizeof(*tm));
3720
Thierry Fournier93127942016-01-20 18:49:45 +01003721 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3722 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3723 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3724 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3725
3726 /* expect SP and 1DIGIT or 2DIGIT */
3727 if (parse_expect_char(&date, &len, ' '))
3728 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3729 else
3730 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3731
3732 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3733 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3734 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3735 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3736 tm->tm_year -= 1900;
3737 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003738 return 1;
3739}
3740
3741/* From RFC7231
3742 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3743 *
3744 * HTTP-date = IMF-fixdate / obs-date
3745 * obs-date = rfc850-date / asctime-date
3746 *
3747 * parses an HTTP date in the RFC format and is accepted
3748 * alternatives. <date> is the strinf containing the date,
3749 * len is the len of the string. <tm> is filled with the
3750 * parsed time. We must considers this time as GMT.
3751 */
3752int parse_http_date(const char *date, int len, struct tm *tm)
3753{
3754 if (parse_imf_date(date, len, tm))
3755 return 1;
3756
3757 if (parse_rfc850_date(date, len, tm))
3758 return 1;
3759
3760 if (parse_asctime_date(date, len, tm))
3761 return 1;
3762
3763 return 0;
3764}
3765
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003766/* Dynamically allocates a string of the proper length to hold the formatted
3767 * output. NULL is returned on error. The caller is responsible for freeing the
3768 * memory area using free(). The resulting string is returned in <out> if the
3769 * pointer is not NULL. A previous version of <out> might be used to build the
3770 * new string, and it will be freed before returning if it is not NULL, which
3771 * makes it possible to build complex strings from iterative calls without
3772 * having to care about freeing intermediate values, as in the example below :
3773 *
3774 * memprintf(&err, "invalid argument: '%s'", arg);
3775 * ...
3776 * memprintf(&err, "parser said : <%s>\n", *err);
3777 * ...
3778 * free(*err);
3779 *
3780 * This means that <err> must be initialized to NULL before first invocation.
3781 * The return value also holds the allocated string, which eases error checking
3782 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003783 * passed instead and it will be ignored. The returned message will then also
3784 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003785 *
3786 * It is also convenient to use it without any free except the last one :
3787 * err = NULL;
3788 * if (!fct1(err)) report(*err);
3789 * if (!fct2(err)) report(*err);
3790 * if (!fct3(err)) report(*err);
3791 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003792 *
3793 * memprintf relies on memvprintf. This last version can be called from any
3794 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003795 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003796char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003797{
3798 va_list args;
3799 char *ret = NULL;
3800 int allocated = 0;
3801 int needed = 0;
3802
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003803 if (!out)
3804 return NULL;
3805
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003806 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003807 char buf1;
3808
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003809 /* vsnprintf() will return the required length even when the
3810 * target buffer is NULL. We do this in a loop just in case
3811 * intermediate evaluations get wrong.
3812 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003813 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003814 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003815 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003816 if (needed < allocated) {
3817 /* Note: on Solaris 8, the first iteration always
3818 * returns -1 if allocated is zero, so we force a
3819 * retry.
3820 */
3821 if (!allocated)
3822 needed = 0;
3823 else
3824 break;
3825 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003826
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003827 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003828 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003829 } while (ret);
3830
3831 if (needed < 0) {
3832 /* an error was encountered */
3833 free(ret);
3834 ret = NULL;
3835 }
3836
3837 if (out) {
3838 free(*out);
3839 *out = ret;
3840 }
3841
3842 return ret;
3843}
William Lallemand421f5b52012-02-06 18:15:57 +01003844
Christopher Faulet93a518f2017-10-24 11:25:33 +02003845char *memprintf(char **out, const char *format, ...)
3846{
3847 va_list args;
3848 char *ret = NULL;
3849
3850 va_start(args, format);
3851 ret = memvprintf(out, format, args);
3852 va_end(args);
3853
3854 return ret;
3855}
3856
Willy Tarreau21c705b2012-09-14 11:40:36 +02003857/* Used to add <level> spaces before each line of <out>, unless there is only one line.
3858 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02003859 * freed by the caller. It also supports being passed a NULL which results in the same
3860 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02003861 * Example of use :
3862 * parse(cmd, &err); (callee: memprintf(&err, ...))
3863 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
3864 * free(err);
3865 */
3866char *indent_msg(char **out, int level)
3867{
3868 char *ret, *in, *p;
3869 int needed = 0;
3870 int lf = 0;
3871 int lastlf = 0;
3872 int len;
3873
Willy Tarreau70eec382012-10-10 08:56:47 +02003874 if (!out || !*out)
3875 return NULL;
3876
Willy Tarreau21c705b2012-09-14 11:40:36 +02003877 in = *out - 1;
3878 while ((in = strchr(in + 1, '\n')) != NULL) {
3879 lastlf = in - *out;
3880 lf++;
3881 }
3882
3883 if (!lf) /* single line, no LF, return it as-is */
3884 return *out;
3885
3886 len = strlen(*out);
3887
3888 if (lf == 1 && lastlf == len - 1) {
3889 /* single line, LF at end, strip it and return as-is */
3890 (*out)[lastlf] = 0;
3891 return *out;
3892 }
3893
3894 /* OK now we have at least one LF, we need to process the whole string
3895 * as a multi-line string. What we'll do :
3896 * - prefix with an LF if there is none
3897 * - add <level> spaces before each line
3898 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
3899 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
3900 */
3901
3902 needed = 1 + level * (lf + 1) + len + 1;
3903 p = ret = malloc(needed);
3904 in = *out;
3905
3906 /* skip initial LFs */
3907 while (*in == '\n')
3908 in++;
3909
3910 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
3911 while (*in) {
3912 *p++ = '\n';
3913 memset(p, ' ', level);
3914 p += level;
3915 do {
3916 *p++ = *in++;
3917 } while (*in && *in != '\n');
3918 if (*in)
3919 in++;
3920 }
3921 *p = 0;
3922
3923 free(*out);
3924 *out = ret;
3925
3926 return ret;
3927}
3928
Willy Tarreaua2c99112019-08-21 13:17:37 +02003929/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
3930 * and end of lines replaced with <eol> if not 0. The first line to indent has
3931 * to be indicated in <first> (starts at zero), so that it is possible to skip
3932 * indenting the first line if it has to be appended after an existing message.
3933 * Empty strings are never indented, and NULL strings are considered empty both
3934 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
3935 * character, non-zero otherwise.
3936 */
3937int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
3938{
3939 int bol, lf;
3940 int pfxlen = pfx ? strlen(pfx) : 0;
3941
3942 if (!in)
3943 return 0;
3944
3945 bol = 1;
3946 lf = 0;
3947 while (*in) {
3948 if (bol && pfxlen) {
3949 if (first > 0)
3950 first--;
3951 else
3952 b_putblk(out, pfx, pfxlen);
3953 bol = 0;
3954 }
3955
3956 lf = (*in == '\n');
3957 bol |= lf;
3958 b_putchr(out, (lf && eol) ? eol : *in);
3959 in++;
3960 }
3961 return lf;
3962}
3963
Willy Tarreau9d22e562019-03-29 18:49:09 +01003964/* removes environment variable <name> from the environment as found in
3965 * environ. This is only provided as an alternative for systems without
3966 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05003967 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01003968 * <name> and to replace the matching pointers with the last pointer of
3969 * the array (since variables are not ordered).
3970 * It always returns 0 (success).
3971 */
3972int my_unsetenv(const char *name)
3973{
3974 extern char **environ;
3975 char **p = environ;
3976 int vars;
3977 int next;
3978 int len;
3979
3980 len = strlen(name);
3981 for (vars = 0; p[vars]; vars++)
3982 ;
3983 next = 0;
3984 while (next < vars) {
3985 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
3986 next++;
3987 continue;
3988 }
3989 if (next < vars - 1)
3990 p[next] = p[vars - 1];
3991 p[--vars] = NULL;
3992 }
3993 return 0;
3994}
3995
Willy Tarreaudad36a32013-03-11 01:20:04 +01003996/* Convert occurrences of environment variables in the input string to their
3997 * corresponding value. A variable is identified as a series of alphanumeric
3998 * characters or underscores following a '$' sign. The <in> string must be
3999 * free()able. NULL returns NULL. The resulting string might be reallocated if
4000 * some expansion is made. Variable names may also be enclosed into braces if
4001 * needed (eg: to concatenate alphanum characters).
4002 */
4003char *env_expand(char *in)
4004{
4005 char *txt_beg;
4006 char *out;
4007 char *txt_end;
4008 char *var_beg;
4009 char *var_end;
4010 char *value;
4011 char *next;
4012 int out_len;
4013 int val_len;
4014
4015 if (!in)
4016 return in;
4017
4018 value = out = NULL;
4019 out_len = 0;
4020
4021 txt_beg = in;
4022 do {
4023 /* look for next '$' sign in <in> */
4024 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4025
4026 if (!*txt_end && !out) /* end and no expansion performed */
4027 return in;
4028
4029 val_len = 0;
4030 next = txt_end;
4031 if (*txt_end == '$') {
4032 char save;
4033
4034 var_beg = txt_end + 1;
4035 if (*var_beg == '{')
4036 var_beg++;
4037
4038 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004039 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004040 var_end++;
4041 }
4042
4043 next = var_end;
4044 if (*var_end == '}' && (var_beg > txt_end + 1))
4045 next++;
4046
4047 /* get value of the variable name at this location */
4048 save = *var_end;
4049 *var_end = '\0';
4050 value = getenv(var_beg);
4051 *var_end = save;
4052 val_len = value ? strlen(value) : 0;
4053 }
4054
Hubert Verstraete831962e2016-06-28 22:44:26 +02004055 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004056 if (txt_end > txt_beg) {
4057 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4058 out_len += txt_end - txt_beg;
4059 }
4060 if (val_len) {
4061 memcpy(out + out_len, value, val_len);
4062 out_len += val_len;
4063 }
4064 out[out_len] = 0;
4065 txt_beg = next;
4066 } while (*txt_beg);
4067
4068 /* here we know that <out> was allocated and that we don't need <in> anymore */
4069 free(in);
4070 return out;
4071}
4072
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004073
4074/* same as strstr() but case-insensitive and with limit length */
4075const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4076{
4077 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004078 unsigned int slen, plen;
4079 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004080
4081 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4082 return NULL;
4083
4084 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4085 return str1;
4086
4087 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4088 return NULL;
4089
4090 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 +02004091 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004092 start++;
4093 slen--;
4094 tmp1++;
4095
4096 if (tmp1 >= len_str1)
4097 return NULL;
4098
4099 /* if pattern longer than string */
4100 if (slen < plen)
4101 return NULL;
4102 }
4103
4104 sptr = start;
4105 pptr = (char *)str2;
4106
4107 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004108 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004109 sptr++;
4110 pptr++;
4111 tmp2++;
4112
4113 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4114 return start;
4115 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4116 return NULL;
4117 }
4118 }
4119 return NULL;
4120}
4121
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004122/* This function read the next valid utf8 char.
4123 * <s> is the byte srray to be decode, <len> is its length.
4124 * The function returns decoded char encoded like this:
4125 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4126 * are the length read. The decoded character is stored in <c>.
4127 */
4128unsigned char utf8_next(const char *s, int len, unsigned int *c)
4129{
4130 const unsigned char *p = (unsigned char *)s;
4131 int dec;
4132 unsigned char code = UTF8_CODE_OK;
4133
4134 if (len < 1)
4135 return UTF8_CODE_OK;
4136
4137 /* Check the type of UTF8 sequence
4138 *
4139 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4140 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4141 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4142 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4143 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4144 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4145 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4146 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4147 */
4148 switch (*p) {
4149 case 0x00 ... 0x7f:
4150 *c = *p;
4151 return UTF8_CODE_OK | 1;
4152
4153 case 0x80 ... 0xbf:
4154 *c = *p;
4155 return UTF8_CODE_BADSEQ | 1;
4156
4157 case 0xc0 ... 0xdf:
4158 if (len < 2) {
4159 *c = *p;
4160 return UTF8_CODE_BADSEQ | 1;
4161 }
4162 *c = *p & 0x1f;
4163 dec = 1;
4164 break;
4165
4166 case 0xe0 ... 0xef:
4167 if (len < 3) {
4168 *c = *p;
4169 return UTF8_CODE_BADSEQ | 1;
4170 }
4171 *c = *p & 0x0f;
4172 dec = 2;
4173 break;
4174
4175 case 0xf0 ... 0xf7:
4176 if (len < 4) {
4177 *c = *p;
4178 return UTF8_CODE_BADSEQ | 1;
4179 }
4180 *c = *p & 0x07;
4181 dec = 3;
4182 break;
4183
4184 case 0xf8 ... 0xfb:
4185 if (len < 5) {
4186 *c = *p;
4187 return UTF8_CODE_BADSEQ | 1;
4188 }
4189 *c = *p & 0x03;
4190 dec = 4;
4191 break;
4192
4193 case 0xfc ... 0xfd:
4194 if (len < 6) {
4195 *c = *p;
4196 return UTF8_CODE_BADSEQ | 1;
4197 }
4198 *c = *p & 0x01;
4199 dec = 5;
4200 break;
4201
4202 case 0xfe ... 0xff:
4203 default:
4204 *c = *p;
4205 return UTF8_CODE_BADSEQ | 1;
4206 }
4207
4208 p++;
4209
4210 while (dec > 0) {
4211
4212 /* need 0x10 for the 2 first bits */
4213 if ( ( *p & 0xc0 ) != 0x80 )
4214 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4215
4216 /* add data at char */
4217 *c = ( *c << 6 ) | ( *p & 0x3f );
4218
4219 dec--;
4220 p++;
4221 }
4222
4223 /* Check ovelong encoding.
4224 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4225 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4226 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4227 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004228 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004229 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4230 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4231 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4232 code |= UTF8_CODE_OVERLONG;
4233
4234 /* Check invalid UTF8 range. */
4235 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4236 (*c >= 0xfffe && *c <= 0xffff))
4237 code |= UTF8_CODE_INVRANGE;
4238
4239 return code | ((p-(unsigned char *)s)&0x0f);
4240}
4241
Maxime de Roucydc887852016-05-13 23:52:54 +02004242/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4243 * On failure : return 0 and <err> filled with an error message.
4244 * The caller is responsible for freeing the <err> and <str> copy
4245 * memory area using free()
4246 */
4247int list_append_word(struct list *li, const char *str, char **err)
4248{
4249 struct wordlist *wl;
4250
4251 wl = calloc(1, sizeof(*wl));
4252 if (!wl) {
4253 memprintf(err, "out of memory");
4254 goto fail_wl;
4255 }
4256
4257 wl->s = strdup(str);
4258 if (!wl->s) {
4259 memprintf(err, "out of memory");
4260 goto fail_wl_s;
4261 }
4262
4263 LIST_ADDQ(li, &wl->list);
4264
4265 return 1;
4266
4267fail_wl_s:
4268 free(wl->s);
4269fail_wl:
4270 free(wl);
4271 return 0;
4272}
4273
Willy Tarreau37101052019-05-20 16:48:20 +02004274/* indicates if a memory location may safely be read or not. The trick consists
4275 * in performing a harmless syscall using this location as an input and letting
4276 * the operating system report whether it's OK or not. For this we have the
4277 * stat() syscall, which will return EFAULT when the memory location supposed
4278 * to contain the file name is not readable. If it is readable it will then
4279 * either return 0 if the area contains an existing file name, or -1 with
4280 * another code. This must not be abused, and some audit systems might detect
4281 * this as abnormal activity. It's used only for unsafe dumps.
4282 */
4283int may_access(const void *ptr)
4284{
4285 struct stat buf;
4286
4287 if (stat(ptr, &buf) == 0)
4288 return 1;
4289 if (errno == EFAULT)
4290 return 0;
4291 return 1;
4292}
4293
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004294/* print a string of text buffer to <out>. The format is :
4295 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4296 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4297 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4298 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004299int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004300{
4301 unsigned char c;
4302 int ptr = 0;
4303
4304 while (buf[ptr] && ptr < bsize) {
4305 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004306 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004307 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004308 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004309 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004310 }
4311 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004312 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004313 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004314 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004315 switch (c) {
4316 case ' ': c = ' '; break;
4317 case '\t': c = 't'; break;
4318 case '\n': c = 'n'; break;
4319 case '\r': c = 'r'; break;
4320 case '\e': c = 'e'; break;
4321 case '\\': c = '\\'; break;
4322 case '=': c = '='; break;
4323 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004324 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004325 }
4326 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004327 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004328 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004329 out->area[out->data++] = '\\';
4330 out->area[out->data++] = 'x';
4331 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4332 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004333 }
4334 ptr++;
4335 }
4336
4337 return ptr;
4338}
4339
4340/* print a buffer in hexa.
4341 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4342 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004343int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004344{
4345 unsigned char c;
4346 int ptr = 0;
4347
4348 while (ptr < bsize) {
4349 c = buf[ptr];
4350
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004351 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004352 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004353 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4354 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004355
4356 ptr++;
4357 }
4358 return ptr;
4359}
4360
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004361/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4362 * prepending each line with prefix <pfx>. The output is *not* initialized.
4363 * The output will not wrap pas the buffer's end so it is more optimal if the
4364 * caller makes sure the buffer is aligned first. A trailing zero will always
4365 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004366 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4367 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004368 */
Willy Tarreau37101052019-05-20 16:48:20 +02004369void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004370{
4371 const unsigned char *d = buf;
4372 int i, j, start;
4373
4374 d = (const unsigned char *)(((unsigned long)buf) & -16);
4375 start = ((unsigned long)buf) & 15;
4376
4377 for (i = 0; i < start + len; i += 16) {
4378 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4379
Willy Tarreau37101052019-05-20 16:48:20 +02004380 // 0: unchecked, 1: checked safe, 2: danger
4381 unsafe = !!unsafe;
4382 if (unsafe && !may_access(d + i))
4383 unsafe = 2;
4384
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004385 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004386 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004387 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004388 else if (unsafe > 1)
4389 chunk_strcat(out, "** ");
4390 else
4391 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004392
4393 if (j == 7)
4394 chunk_strcat(out, "- ");
4395 }
4396 chunk_strcat(out, " ");
4397 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004398 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004399 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004400 else if (unsafe > 1)
4401 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004402 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004403 chunk_appendf(out, "%c", d[i + j]);
4404 else
4405 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004406 }
4407 chunk_strcat(out, "\n");
4408 }
4409}
4410
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004411/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4412 * enclosed in brackets after the address itself, formatted on 14 chars
4413 * including the "0x" prefix. This is meant to be used as a prefix for code
4414 * areas. For example:
4415 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4416 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4417 * is emitted. A NULL <pfx> will be considered empty.
4418 */
4419void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4420{
4421 int ok = 0;
4422 int i;
4423
4424 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4425
4426 for (i = 0; i < n; i++) {
4427 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4428 ok = may_access(addr + i);
4429 if (ok)
4430 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4431 else
4432 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4433 }
4434}
4435
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004436/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4437 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4438 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4439 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4440 * lines are respected within the limit of 70 output chars. Lines that are
4441 * continuation of a previous truncated line begin with "+" instead of " "
4442 * after the offset. The new pointer is returned.
4443 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004444int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004445 int *line, int ptr)
4446{
4447 int end;
4448 unsigned char c;
4449
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004450 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004451 if (end > out->size)
4452 return ptr;
4453
4454 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4455
4456 while (ptr < len && ptr < bsize) {
4457 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004458 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004459 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004460 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004461 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004462 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004463 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004464 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004465 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004466 switch (c) {
4467 case '\t': c = 't'; break;
4468 case '\n': c = 'n'; break;
4469 case '\r': c = 'r'; break;
4470 case '\e': c = 'e'; break;
4471 case '\\': c = '\\'; break;
4472 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004473 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004474 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004475 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004476 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004477 out->area[out->data++] = '\\';
4478 out->area[out->data++] = 'x';
4479 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4480 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004481 }
4482 if (buf[ptr++] == '\n') {
4483 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004484 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004485 *line = ptr;
4486 return ptr;
4487 }
4488 }
4489 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004490 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004491 return ptr;
4492}
4493
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004494/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004495 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4496 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004497 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004498void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4499 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004500{
Willy Tarreau73459792017-04-11 07:58:08 +02004501 unsigned int i;
4502 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004503
4504 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4505 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004506 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004507 for (j = 0; j < 8; j++) {
4508 if (b + j >= 0 && b + j < len)
4509 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4510 else
4511 fprintf(out, " ");
4512 }
4513
4514 if (b + j >= 0 && b + j < len)
4515 fputc('-', out);
4516 else
4517 fputc(' ', out);
4518
4519 for (j = 8; j < 16; j++) {
4520 if (b + j >= 0 && b + j < len)
4521 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4522 else
4523 fprintf(out, " ");
4524 }
4525
4526 fprintf(out, " ");
4527 for (j = 0; j < 16; j++) {
4528 if (b + j >= 0 && b + j < len) {
4529 if (isprint((unsigned char)buf[b + j]))
4530 fputc((unsigned char)buf[b + j], out);
4531 else
4532 fputc('.', out);
4533 }
4534 else
4535 fputc(' ', out);
4536 }
4537 fputc('\n', out);
4538 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004539}
4540
Willy Tarreaubb869862020-04-16 10:52:41 +02004541/* Tries to report the executable path name on platforms supporting this. If
4542 * not found or not possible, returns NULL.
4543 */
4544const char *get_exec_path()
4545{
4546 const char *ret = NULL;
4547
4548#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4549 long execfn = getauxval(AT_EXECFN);
4550
4551 if (execfn && execfn != ENOENT)
4552 ret = (const char *)execfn;
4553#endif
4554 return ret;
4555}
4556
Baruch Siache1651b22020-07-24 07:52:20 +03004557#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004558/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4559 * also returns the symbol size in <size>, otherwise returns 0 there.
4560 */
4561static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4562{
4563 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004564#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004565 const ElfW(Sym) *sym;
4566
4567 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4568 if (ret)
4569 *size = sym ? sym->st_size : 0;
4570#else
4571 ret = dladdr(addr, dli);
4572 *size = 0;
4573#endif
4574 return ret;
4575}
4576#endif
4577
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004578/* Tries to append to buffer <buf> some indications about the symbol at address
4579 * <addr> using the following form:
4580 * lib:+0xoffset (unresolvable address from lib's base)
4581 * main+0xoffset (unresolvable address from main (+/-))
4582 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4583 * name (resolved exact exec address)
4584 * lib:name (resolved exact lib address)
4585 * name+0xoffset/0xsize (resolved address within exec symbol)
4586 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4587 *
4588 * The file name (lib or executable) is limited to what lies between the last
4589 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4590 * 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 +03004591 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004592 *
4593 * The symbol's base address is returned, or NULL when unresolved, in order to
4594 * allow the caller to match it against known ones.
4595 */
Willy Tarreau341fafc2021-01-20 14:37:59 +01004596const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004597{
4598 const struct {
4599 const void *func;
4600 const char *name;
4601 } fcts[] = {
4602 { .func = process_stream, .name = "process_stream" },
4603 { .func = task_run_applet, .name = "task_run_applet" },
4604 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
4605 { .func = conn_fd_handler, .name = "conn_fd_handler" },
4606 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4607 { .func = listener_accept, .name = "listener_accept" },
4608 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4609 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
4610#ifdef USE_LUA
4611 { .func = hlua_process_task, .name = "hlua_process_task" },
4612#endif
4613#if defined(USE_OPENSSL) && (HA_OPENSSL_VERSION_NUMBER >= 0x1010000fL) && !defined(OPENSSL_NO_ASYNC)
4614 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4615 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4616#endif
4617 };
4618
Baruch Siache1651b22020-07-24 07:52:20 +03004619#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004620 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004621 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004622 const char *fname, *p;
4623#endif
4624 int i;
4625
4626 if (pfx)
4627 chunk_appendf(buf, "%s", pfx);
4628
4629 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4630 if (addr == fcts[i].func) {
4631 chunk_appendf(buf, "%s", fcts[i].name);
4632 return addr;
4633 }
4634 }
4635
Baruch Siache1651b22020-07-24 07:52:20 +03004636#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004637 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004638 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004639 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004640
4641 /* 1. prefix the library name if it's not the same object as the one
4642 * that contains the main function. The name is picked between last '/'
4643 * and first following '.'.
4644 */
4645 if (!dladdr(main, &dli_main))
4646 dli_main.dli_fbase = NULL;
4647
4648 if (dli_main.dli_fbase != dli.dli_fbase) {
4649 fname = dli.dli_fname;
4650 p = strrchr(fname, '/');
4651 if (p++)
4652 fname = p;
4653 p = strchr(fname, '.');
4654 if (!p)
4655 p = fname + strlen(fname);
4656
4657 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4658 }
4659
4660 /* 2. symbol name */
4661 if (dli.dli_sname) {
4662 /* known, dump it and return symbol's address (exact or relative) */
4663 chunk_appendf(buf, "%s", dli.dli_sname);
4664 if (addr != dli.dli_saddr) {
4665 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004666 if (size)
4667 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004668 }
4669 return dli.dli_saddr;
4670 }
4671 else if (dli_main.dli_fbase != dli.dli_fbase) {
4672 /* unresolved symbol from a known library, report relative offset */
4673 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4674 return NULL;
4675 }
Baruch Siache1651b22020-07-24 07:52:20 +03004676#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004677 unknown:
4678 /* unresolved symbol from the main file, report relative offset to main */
4679 if ((void*)addr < (void*)main)
4680 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4681 else
4682 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4683 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004684}
4685
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004686/*
4687 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004688 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004689 *
4690 * First, initializes the value with <sz> as address to 0 and initializes the
4691 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4692 * address updating <sz> pointed value to the size of this array.
4693 *
4694 * Returns 1 if succeeded, 0 if not.
4695 */
4696int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4697{
4698 unsigned int *n;
4699 const char *s, *end;
4700
4701 s = str;
4702 *sz = 0;
4703 end = str + strlen(str);
4704 *nums = n = NULL;
4705
4706 while (1) {
4707 unsigned int r;
4708
4709 if (s >= end)
4710 break;
4711
4712 r = read_uint(&s, end);
4713 /* Expected characters after having read an uint: '\0' or '.',
4714 * if '.', must not be terminal.
4715 */
Christopher Faulet9027d3a2021-02-11 10:42:41 +01004716 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4717 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004718 return 0;
Christopher Faulet9027d3a2021-02-11 10:42:41 +01004719 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004720
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004721 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004722 if (!n)
4723 return 0;
4724
4725 n[(*sz)++] = r;
4726 }
4727 *nums = n;
4728
4729 return 1;
4730}
4731
Willy Tarreau4d589e72019-08-23 19:02:26 +02004732
4733/* returns the number of bytes needed to encode <v> as a varint. An inline
4734 * version exists for use with constants (__varint_bytes()).
4735 */
4736int varint_bytes(uint64_t v)
4737{
4738 int len = 1;
4739
4740 if (v >= 240) {
4741 v = (v - 240) >> 4;
4742 while (1) {
4743 len++;
4744 if (v < 128)
4745 break;
4746 v = (v - 128) >> 7;
4747 }
4748 }
4749 return len;
4750}
4751
Willy Tarreau52bf8392020-03-08 00:42:37 +01004752
4753/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004754static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004755
4756/* This is a thread-safe implementation of xoroshiro128** described below:
4757 * http://prng.di.unimi.it/
4758 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4759 * supports fast jumps and passes all common quality tests. It is thread-safe,
4760 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4761 * local lock on other ones.
4762 */
4763uint64_t ha_random64()
4764{
4765 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004766 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4767 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004768
4769#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4770 static HA_SPINLOCK_T rand_lock;
4771
4772 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4773#endif
4774
4775 old[0] = ha_random_state[0];
4776 old[1] = ha_random_state[1];
4777
4778#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4779 do {
4780#endif
4781 result = rotl64(old[0] * 5, 7) * 9;
4782 new[1] = old[0] ^ old[1];
4783 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4784 new[1] = rotl64(new[1], 37); // c
4785
4786#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4787 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4788#else
4789 ha_random_state[0] = new[0];
4790 ha_random_state[1] = new[1];
4791#if defined(USE_THREAD)
4792 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4793#endif
4794#endif
4795 return result;
4796}
4797
4798/* seeds the random state using up to <len> bytes from <seed>, starting with
4799 * the first non-zero byte.
4800 */
4801void ha_random_seed(const unsigned char *seed, size_t len)
4802{
4803 size_t pos;
4804
4805 /* the seed must not be all zeroes, so we pre-fill it with alternating
4806 * bits and overwrite part of them with the block starting at the first
4807 * non-zero byte from the seed.
4808 */
4809 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4810
4811 for (pos = 0; pos < len; pos++)
4812 if (seed[pos] != 0)
4813 break;
4814
4815 if (pos == len)
4816 return;
4817
4818 seed += pos;
4819 len -= pos;
4820
4821 if (len > sizeof(ha_random_state))
4822 len = sizeof(ha_random_state);
4823
4824 memcpy(ha_random_state, seed, len);
4825}
4826
4827/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4828 * and is equivalent to calling ha_random64() as many times. It is used to
4829 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
4830 * different generators (i.e. different processes after a fork). The <dist>
4831 * argument is the distance to jump to and is used in a loop so it rather not
4832 * be too large if the processing time is a concern.
4833 *
4834 * BEWARE: this function is NOT thread-safe and must not be called during
4835 * concurrent accesses to ha_random64().
4836 */
4837void ha_random_jump96(uint32_t dist)
4838{
4839 while (dist--) {
4840 uint64_t s0 = 0;
4841 uint64_t s1 = 0;
4842 int b;
4843
4844 for (b = 0; b < 64; b++) {
4845 if ((0xd2a98b26625eee7bULL >> b) & 1) {
4846 s0 ^= ha_random_state[0];
4847 s1 ^= ha_random_state[1];
4848 }
4849 ha_random64();
4850 }
4851
4852 for (b = 0; b < 64; b++) {
4853 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
4854 s0 ^= ha_random_state[0];
4855 s1 ^= ha_random_state[1];
4856 }
4857 ha_random64();
4858 }
4859 ha_random_state[0] = s0;
4860 ha_random_state[1] = s1;
4861 }
4862}
4863
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01004864/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
4865 * bytes large.
4866 */
4867void ha_generate_uuid(struct buffer *output)
4868{
4869 uint32_t rnd[4];
4870 uint64_t last;
4871
4872 last = ha_random64();
4873 rnd[0] = last;
4874 rnd[1] = last >> 32;
4875
4876 last = ha_random64();
4877 rnd[2] = last;
4878 rnd[3] = last >> 32;
4879
4880 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
4881 rnd[0],
4882 rnd[1] & 0xFFFF,
4883 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
4884 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
4885 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
4886}
4887
4888
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004889/* only used by parse_line() below. It supports writing in place provided that
4890 * <in> is updated to the next location before calling it. In that case, the
4891 * char at <in> may be overwritten.
4892 */
4893#define EMIT_CHAR(x) \
4894 do { \
4895 char __c = (char)(x); \
4896 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
4897 err |= PARSE_ERR_OVERLAP; \
4898 if (outpos >= outmax) \
4899 err |= PARSE_ERR_TOOLARGE; \
4900 if (!err) \
4901 out[outpos] = __c; \
4902 outpos++; \
4903 } while (0)
4904
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004905/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004906 * are put in <args>. If more than <outlen> bytes have to be emitted, the
4907 * extraneous ones are not emitted but <outlen> is updated so that the caller
4908 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
4909 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004910 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
4911 * it is guaranteed that at least one arg will point to the zero. It is safe
4912 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004913 *
4914 * <out> may overlap with <in> provided that it never goes further, in which
4915 * case the parser will accept to perform in-place parsing and unquoting/
4916 * unescaping but only if environment variables do not lead to expansion that
4917 * causes overlapping, otherwise the input string being destroyed, the error
4918 * will not be recoverable. Note that even during out-of-place <in> will
4919 * experience temporary modifications in-place for variable resolution and must
4920 * be writable, and will also receive zeroes to delimit words when using
4921 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
4922 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
4923 * starting point of the first invalid character sequence or unmatched
4924 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
4925 * error reporting might be difficult since zeroes will have been inserted into
4926 * the string. One solution for the caller may consist in replacing all args
4927 * delimiters with spaces in this case.
4928 */
4929uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
4930{
4931 char *quote = NULL;
4932 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02004933 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004934 unsigned char hex1, hex2;
4935 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004936 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004937 size_t outpos = 0;
4938 int squote = 0;
4939 int dquote = 0;
4940 int arg = 0;
4941 uint32_t err = 0;
4942
4943 *nbargs = 0;
4944 *outlen = 0;
4945
Willy Tarreau61dd44b2020-06-25 07:35:42 +02004946 /* argsmax may be -1 here, protecting args[] from any write */
4947 if (arg < argsmax)
4948 args[arg] = out;
4949
Willy Tarreauc8d167b2020-06-16 16:27:26 +02004950 while (1) {
4951 if (*in >= '-' && *in != '\\') {
4952 /* speedup: directly send all regular chars starting
4953 * with '-', '.', '/', alnum etc...
4954 */
4955 EMIT_CHAR(*in++);
4956 continue;
4957 }
4958 else if (*in == '\0' || *in == '\n' || *in == '\r') {
4959 /* end of line */
4960 break;
4961 }
4962 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
4963 /* comment */
4964 break;
4965 }
4966 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
4967 if (dquote) {
4968 dquote = 0;
4969 quote = NULL;
4970 }
4971 else {
4972 dquote = 1;
4973 quote = in;
4974 }
4975 in++;
4976 continue;
4977 }
4978 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
4979 if (squote) {
4980 squote = 0;
4981 quote = NULL;
4982 }
4983 else {
4984 squote = 1;
4985 quote = in;
4986 }
4987 in++;
4988 continue;
4989 }
4990 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
4991 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
4992 * C equivalent value but only when they have a special meaning and within
4993 * double quotes for some of them. Other combinations left unchanged (eg: \1).
4994 */
4995 char tosend = *in;
4996
4997 switch (in[1]) {
4998 case ' ':
4999 case '\\':
5000 tosend = in[1];
5001 in++;
5002 break;
5003
5004 case 't':
5005 tosend = '\t';
5006 in++;
5007 break;
5008
5009 case 'n':
5010 tosend = '\n';
5011 in++;
5012 break;
5013
5014 case 'r':
5015 tosend = '\r';
5016 in++;
5017 break;
5018
5019 case '#':
5020 /* escaping of "#" only if comments are supported */
5021 if (opts & PARSE_OPT_SHARP)
5022 in++;
5023 tosend = *in;
5024 break;
5025
5026 case '\'':
5027 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5028 if (opts & PARSE_OPT_SQUOTE && !squote)
5029 in++;
5030 tosend = *in;
5031 break;
5032
5033 case '"':
5034 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5035 if (opts & PARSE_OPT_DQUOTE && !squote)
5036 in++;
5037 tosend = *in;
5038 break;
5039
5040 case '$':
5041 /* escaping of '$' only inside double quotes and only if env supported */
5042 if (opts & PARSE_OPT_ENV && dquote)
5043 in++;
5044 tosend = *in;
5045 break;
5046
5047 case 'x':
5048 if (!ishex(in[2]) || !ishex(in[3])) {
5049 /* invalid or incomplete hex sequence */
5050 err |= PARSE_ERR_HEX;
5051 if (errptr)
5052 *errptr = in;
5053 goto leave;
5054 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005055 hex1 = toupper((unsigned char)in[2]) - '0';
5056 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005057 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5058 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5059 tosend = (hex1 << 4) + hex2;
5060 in += 3;
5061 break;
5062
5063 default:
5064 /* other combinations are not escape sequences */
5065 break;
5066 }
5067
5068 in++;
5069 EMIT_CHAR(tosend);
5070 }
5071 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5072 /* a non-escaped space is an argument separator */
5073 while (isspace((unsigned char)*in))
5074 in++;
5075 EMIT_CHAR(0);
5076 arg++;
5077 if (arg < argsmax)
5078 args[arg] = out + outpos;
5079 else
5080 err |= PARSE_ERR_TOOMANY;
5081 }
5082 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5083 /* environment variables are evaluated anywhere, or only
5084 * inside double quotes if they are supported.
5085 */
5086 char *var_name;
5087 char save_char;
5088 char *value;
5089
5090 in++;
5091
5092 if (*in == '{')
5093 brace = in++;
5094
5095 if (!isalpha((unsigned char)*in) && *in != '_') {
5096 /* unacceptable character in variable name */
5097 err |= PARSE_ERR_VARNAME;
5098 if (errptr)
5099 *errptr = in;
5100 goto leave;
5101 }
5102
5103 var_name = in;
5104 while (isalnum((unsigned char)*in) || *in == '_')
5105 in++;
5106
5107 save_char = *in;
5108 *in = '\0';
5109 value = getenv(var_name);
5110 *in = save_char;
5111
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005112 /* support for '[*]' sequence to force word expansion,
5113 * only available inside braces */
5114 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5115 word_expand = in++;
5116
5117 if (*in++ != '*' || *in++ != ']') {
5118 err |= PARSE_ERR_WRONG_EXPAND;
5119 if (errptr)
5120 *errptr = word_expand;
5121 goto leave;
5122 }
5123 }
5124
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005125 if (brace) {
5126 if (*in != '}') {
5127 /* unmatched brace */
5128 err |= PARSE_ERR_BRACE;
5129 if (errptr)
5130 *errptr = brace;
5131 goto leave;
5132 }
5133 in++;
5134 brace = NULL;
5135 }
5136
5137 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005138 while (*value) {
5139 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005140 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005141 EMIT_CHAR(0);
5142 ++arg;
5143 if (arg < argsmax)
5144 args[arg] = out + outpos;
5145 else
5146 err |= PARSE_ERR_TOOMANY;
5147
5148 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005149 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005150 ;
5151 } else {
5152 EMIT_CHAR(*value++);
5153 }
5154 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005155 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005156 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005157 }
5158 else {
5159 /* any other regular char */
5160 EMIT_CHAR(*in++);
5161 }
5162 }
5163
5164 /* end of output string */
5165 EMIT_CHAR(0);
5166 arg++;
5167
5168 if (quote) {
5169 /* unmatched quote */
5170 err |= PARSE_ERR_QUOTE;
5171 if (errptr)
5172 *errptr = quote;
5173 goto leave;
5174 }
5175 leave:
5176 *nbargs = arg;
5177 *outlen = outpos;
5178
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005179 /* empty all trailing args by making them point to the trailing zero,
5180 * at least the last one in any case.
5181 */
5182 if (arg > argsmax)
5183 arg = argsmax;
5184
5185 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005186 args[arg++] = out + outpos - 1;
5187
5188 return err;
5189}
5190#undef EMIT_CHAR
5191
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005192/* This is used to sanitize an input line that's about to be used for error reporting.
5193 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5194 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5195 * If non-printable chars are present in the output. It returns the new offset <pos>
5196 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5197 * be at least 6 to support two "..." otherwise the result is undefined. The line
5198 * itself must have at least 7 chars allocated for the same reason.
5199 */
5200size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5201{
5202 size_t shift = 0;
5203 char *out = line;
5204 char *in = line;
5205 char *end = line + width;
5206
5207 if (pos >= width) {
5208 /* if we have to shift, we'll be out of context, so let's
5209 * try to put <pos> at the center of width.
5210 */
5211 shift = pos - width / 2;
5212 in += shift + 3;
5213 end = out + width - 3;
5214 out[0] = out[1] = out[2] = '.';
5215 out += 3;
5216 }
5217
5218 while (out < end && *in) {
5219 if (isspace((unsigned char)*in))
5220 *out++ = ' ';
5221 else if (isprint((unsigned char)*in))
5222 *out++ = *in;
5223 else
5224 *out++ = '?';
5225 in++;
5226 }
5227
5228 if (end < line + width) {
5229 out[0] = out[1] = out[2] = '.';
5230 out += 3;
5231 }
5232
5233 *out++ = 0;
5234 return pos - shift;
5235}
5236
Willy Tarreaubaaee002006-06-26 02:48:02 +02005237/*
5238 * Local variables:
5239 * c-indent-level: 8
5240 * c-basic-offset: 8
5241 * End:
5242 */