blob: 9cb4e89fb2da722bbd6a683f683e7cf9a586d7b4 [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 Tarreauf268ee82020-06-04 17:05:57 +020045#include <haproxy/global.h>
Willy Tarreau86416052020-06-04 09:20:54 +020046#include <haproxy/hlua.h>
Willy Tarreau213e9902020-06-04 14:58:24 +020047#include <haproxy/listener.h>
Willy Tarreau7a00efb2020-06-02 17:02:59 +020048#include <haproxy/namespace.h>
Christopher Faulet9553de72021-02-26 09:12:50 +010049#include <haproxy/net_helper.h>
Willy Tarreau5fc93282020-09-16 18:25:03 +020050#include <haproxy/protocol.h>
Emeric Brunc9437992021-02-12 19:42:55 +010051#include <haproxy/resolvers.h>
Willy Tarreau586f71b2020-12-11 15:54:36 +010052#include <haproxy/sock.h>
Willy Tarreau209108d2020-06-04 20:30:20 +020053#include <haproxy/ssl_sock.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020054#include <haproxy/stream_interface.h>
Willy Tarreaucea0e1b2020-06-04 17:25:40 +020055#include <haproxy/task.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020056#include <haproxy/tools.h>
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +010057
Thierry Fournier93127942016-01-20 18:49:45 +010058/* This macro returns false if the test __x is false. Many
59 * of the following parsing function must be abort the processing
60 * if it returns 0, so this macro is useful for writing light code.
61 */
62#define RET0_UNLESS(__x) do { if (!(__x)) return 0; } while (0)
63
Willy Tarreau56adcf22012-12-23 18:00:29 +010064/* enough to store NB_ITOA_STR integers of :
Willy Tarreau72d759c2007-10-25 12:14:10 +020065 * 2^64-1 = 18446744073709551615 or
66 * -2^63 = -9223372036854775808
Willy Tarreaue7239b52009-03-29 13:41:58 +020067 *
68 * The HTML version needs room for adding the 25 characters
69 * '<span class="rls"></span>' around digits at positions 3N+1 in order
70 * to add spacing at up to 6 positions : 18 446 744 073 709 551 615
Willy Tarreau72d759c2007-10-25 12:14:10 +020071 */
Christopher Faulet99bca652017-11-14 16:47:26 +010072THREAD_LOCAL char itoa_str[NB_ITOA_STR][171];
73THREAD_LOCAL int itoa_idx = 0; /* index of next itoa_str to use */
Willy Tarreaubaaee002006-06-26 02:48:02 +020074
Willy Tarreau588297f2014-06-16 15:16:40 +020075/* sometimes we'll need to quote strings (eg: in stats), and we don't expect
76 * to quote strings larger than a max configuration line.
77 */
Christopher Faulet99bca652017-11-14 16:47:26 +010078THREAD_LOCAL char quoted_str[NB_QSTR][QSTR_SIZE + 1];
79THREAD_LOCAL int quoted_idx = 0;
Willy Tarreau588297f2014-06-16 15:16:40 +020080
Willy Tarreau06e69b52021-03-02 14:01:35 +010081/* thread-local PRNG state. It's modified to start from a different sequence
82 * on all threads upon startup. It must not be used or anything beyond getting
83 * statistical values as it's 100% predictable.
84 */
85THREAD_LOCAL unsigned int statistical_prng_state = 2463534242U;
86
Willy Tarreaubaaee002006-06-26 02:48:02 +020087/*
William Lallemande7340ec2012-01-24 11:15:39 +010088 * unsigned long long ASCII representation
89 *
90 * return the last char '\0' or NULL if no enough
91 * space in dst
92 */
93char *ulltoa(unsigned long long n, char *dst, size_t size)
94{
95 int i = 0;
96 char *res;
97
98 switch(n) {
99 case 1ULL ... 9ULL:
100 i = 0;
101 break;
102
103 case 10ULL ... 99ULL:
104 i = 1;
105 break;
106
107 case 100ULL ... 999ULL:
108 i = 2;
109 break;
110
111 case 1000ULL ... 9999ULL:
112 i = 3;
113 break;
114
115 case 10000ULL ... 99999ULL:
116 i = 4;
117 break;
118
119 case 100000ULL ... 999999ULL:
120 i = 5;
121 break;
122
123 case 1000000ULL ... 9999999ULL:
124 i = 6;
125 break;
126
127 case 10000000ULL ... 99999999ULL:
128 i = 7;
129 break;
130
131 case 100000000ULL ... 999999999ULL:
132 i = 8;
133 break;
134
135 case 1000000000ULL ... 9999999999ULL:
136 i = 9;
137 break;
138
139 case 10000000000ULL ... 99999999999ULL:
140 i = 10;
141 break;
142
143 case 100000000000ULL ... 999999999999ULL:
144 i = 11;
145 break;
146
147 case 1000000000000ULL ... 9999999999999ULL:
148 i = 12;
149 break;
150
151 case 10000000000000ULL ... 99999999999999ULL:
152 i = 13;
153 break;
154
155 case 100000000000000ULL ... 999999999999999ULL:
156 i = 14;
157 break;
158
159 case 1000000000000000ULL ... 9999999999999999ULL:
160 i = 15;
161 break;
162
163 case 10000000000000000ULL ... 99999999999999999ULL:
164 i = 16;
165 break;
166
167 case 100000000000000000ULL ... 999999999999999999ULL:
168 i = 17;
169 break;
170
171 case 1000000000000000000ULL ... 9999999999999999999ULL:
172 i = 18;
173 break;
174
175 case 10000000000000000000ULL ... ULLONG_MAX:
176 i = 19;
177 break;
178 }
179 if (i + 2 > size) // (i + 1) + '\0'
180 return NULL; // too long
181 res = dst + i + 1;
182 *res = '\0';
183 for (; i >= 0; i--) {
184 dst[i] = n % 10ULL + '0';
185 n /= 10ULL;
186 }
187 return res;
188}
189
190/*
191 * unsigned long ASCII representation
192 *
193 * return the last char '\0' or NULL if no enough
194 * space in dst
195 */
196char *ultoa_o(unsigned long n, char *dst, size_t size)
197{
198 int i = 0;
199 char *res;
200
201 switch (n) {
202 case 0U ... 9UL:
203 i = 0;
204 break;
205
206 case 10U ... 99UL:
207 i = 1;
208 break;
209
210 case 100U ... 999UL:
211 i = 2;
212 break;
213
214 case 1000U ... 9999UL:
215 i = 3;
216 break;
217
218 case 10000U ... 99999UL:
219 i = 4;
220 break;
221
222 case 100000U ... 999999UL:
223 i = 5;
224 break;
225
226 case 1000000U ... 9999999UL:
227 i = 6;
228 break;
229
230 case 10000000U ... 99999999UL:
231 i = 7;
232 break;
233
234 case 100000000U ... 999999999UL:
235 i = 8;
236 break;
237#if __WORDSIZE == 32
238
239 case 1000000000ULL ... ULONG_MAX:
240 i = 9;
241 break;
242
243#elif __WORDSIZE == 64
244
245 case 1000000000ULL ... 9999999999UL:
246 i = 9;
247 break;
248
249 case 10000000000ULL ... 99999999999UL:
250 i = 10;
251 break;
252
253 case 100000000000ULL ... 999999999999UL:
254 i = 11;
255 break;
256
257 case 1000000000000ULL ... 9999999999999UL:
258 i = 12;
259 break;
260
261 case 10000000000000ULL ... 99999999999999UL:
262 i = 13;
263 break;
264
265 case 100000000000000ULL ... 999999999999999UL:
266 i = 14;
267 break;
268
269 case 1000000000000000ULL ... 9999999999999999UL:
270 i = 15;
271 break;
272
273 case 10000000000000000ULL ... 99999999999999999UL:
274 i = 16;
275 break;
276
277 case 100000000000000000ULL ... 999999999999999999UL:
278 i = 17;
279 break;
280
281 case 1000000000000000000ULL ... 9999999999999999999UL:
282 i = 18;
283 break;
284
285 case 10000000000000000000ULL ... ULONG_MAX:
286 i = 19;
287 break;
288
289#endif
290 }
291 if (i + 2 > size) // (i + 1) + '\0'
292 return NULL; // too long
293 res = dst + i + 1;
294 *res = '\0';
295 for (; i >= 0; i--) {
296 dst[i] = n % 10U + '0';
297 n /= 10U;
298 }
299 return res;
300}
301
302/*
303 * signed long ASCII representation
304 *
305 * return the last char '\0' or NULL if no enough
306 * space in dst
307 */
308char *ltoa_o(long int n, char *dst, size_t size)
309{
310 char *pos = dst;
311
312 if (n < 0) {
313 if (size < 3)
314 return NULL; // min size is '-' + digit + '\0' but another test in ultoa
315 *pos = '-';
316 pos++;
317 dst = ultoa_o(-n, pos, size - 1);
318 } else {
319 dst = ultoa_o(n, dst, size);
320 }
321 return dst;
322}
323
324/*
325 * signed long long ASCII representation
326 *
327 * return the last char '\0' or NULL if no enough
328 * space in dst
329 */
330char *lltoa(long long n, char *dst, size_t size)
331{
332 char *pos = dst;
333
334 if (n < 0) {
335 if (size < 3)
336 return NULL; // min size is '-' + digit + '\0' but another test in ulltoa
337 *pos = '-';
338 pos++;
339 dst = ulltoa(-n, pos, size - 1);
340 } else {
341 dst = ulltoa(n, dst, size);
342 }
343 return dst;
344}
345
346/*
347 * write a ascii representation of a unsigned into dst,
348 * return a pointer to the last character
349 * Pad the ascii representation with '0', using size.
350 */
351char *utoa_pad(unsigned int n, char *dst, size_t size)
352{
353 int i = 0;
354 char *ret;
355
356 switch(n) {
357 case 0U ... 9U:
358 i = 0;
359 break;
360
361 case 10U ... 99U:
362 i = 1;
363 break;
364
365 case 100U ... 999U:
366 i = 2;
367 break;
368
369 case 1000U ... 9999U:
370 i = 3;
371 break;
372
373 case 10000U ... 99999U:
374 i = 4;
375 break;
376
377 case 100000U ... 999999U:
378 i = 5;
379 break;
380
381 case 1000000U ... 9999999U:
382 i = 6;
383 break;
384
385 case 10000000U ... 99999999U:
386 i = 7;
387 break;
388
389 case 100000000U ... 999999999U:
390 i = 8;
391 break;
392
393 case 1000000000U ... 4294967295U:
394 i = 9;
395 break;
396 }
397 if (i + 2 > size) // (i + 1) + '\0'
398 return NULL; // too long
399 if (i < size)
400 i = size - 2; // padding - '\0'
401
402 ret = dst + i + 1;
403 *ret = '\0';
404 for (; i >= 0; i--) {
405 dst[i] = n % 10U + '0';
406 n /= 10U;
407 }
408 return ret;
409}
410
411/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200412 * copies at most <size-1> chars from <src> to <dst>. Last char is always
413 * set to 0, unless <size> is 0. The number of chars copied is returned
414 * (excluding the terminating zero).
415 * This code has been optimized for size and speed : on x86, it's 45 bytes
416 * long, uses only registers, and consumes only 4 cycles per char.
417 */
418int strlcpy2(char *dst, const char *src, int size)
419{
420 char *orig = dst;
421 if (size) {
422 while (--size && (*dst = *src)) {
423 src++; dst++;
424 }
425 *dst = 0;
426 }
427 return dst - orig;
428}
429
430/*
Willy Tarreau72d759c2007-10-25 12:14:10 +0200431 * This function simply returns a locally allocated string containing
Willy Tarreaubaaee002006-06-26 02:48:02 +0200432 * the ascii representation for number 'n' in decimal.
433 */
Emeric Brun3a7fce52010-01-04 14:54:38 +0100434char *ultoa_r(unsigned long n, char *buffer, int size)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200435{
436 char *pos;
437
Willy Tarreau72d759c2007-10-25 12:14:10 +0200438 pos = buffer + size - 1;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200439 *pos-- = '\0';
440
441 do {
442 *pos-- = '0' + n % 10;
443 n /= 10;
Willy Tarreau72d759c2007-10-25 12:14:10 +0200444 } while (n && pos >= buffer);
Willy Tarreaubaaee002006-06-26 02:48:02 +0200445 return pos + 1;
446}
447
Willy Tarreau91092e52007-10-25 16:58:42 +0200448/*
Willy Tarreaue7239b52009-03-29 13:41:58 +0200449 * This function simply returns a locally allocated string containing
Thierry FOURNIER763a5d82015-07-06 23:09:52 +0200450 * the ascii representation for number 'n' in decimal.
451 */
452char *lltoa_r(long long int in, char *buffer, int size)
453{
454 char *pos;
455 int neg = 0;
456 unsigned long long int n;
457
458 pos = buffer + size - 1;
459 *pos-- = '\0';
460
461 if (in < 0) {
462 neg = 1;
463 n = -in;
464 }
465 else
466 n = in;
467
468 do {
469 *pos-- = '0' + n % 10;
470 n /= 10;
471 } while (n && pos >= buffer);
472 if (neg && pos > buffer)
473 *pos-- = '-';
474 return pos + 1;
475}
476
477/*
478 * This function simply returns a locally allocated string containing
Thierry FOURNIER1480bd82015-06-06 19:14:59 +0200479 * the ascii representation for signed number 'n' in decimal.
480 */
481char *sltoa_r(long n, char *buffer, int size)
482{
483 char *pos;
484
485 if (n >= 0)
486 return ultoa_r(n, buffer, size);
487
488 pos = ultoa_r(-n, buffer + 1, size - 1) - 1;
489 *pos = '-';
490 return pos;
491}
492
493/*
494 * This function simply returns a locally allocated string containing
Willy Tarreaue7239b52009-03-29 13:41:58 +0200495 * the ascii representation for number 'n' in decimal, formatted for
496 * HTML output with tags to create visual grouping by 3 digits. The
497 * output needs to support at least 171 characters.
498 */
499const char *ulltoh_r(unsigned long long n, char *buffer, int size)
500{
501 char *start;
502 int digit = 0;
503
504 start = buffer + size;
505 *--start = '\0';
506
507 do {
508 if (digit == 3 && start >= buffer + 7)
509 memcpy(start -= 7, "</span>", 7);
510
511 if (start >= buffer + 1) {
512 *--start = '0' + n % 10;
513 n /= 10;
514 }
515
516 if (digit == 3 && start >= buffer + 18)
517 memcpy(start -= 18, "<span class=\"rls\">", 18);
518
519 if (digit++ == 3)
520 digit = 1;
521 } while (n && start > buffer);
522 return start;
523}
524
525/*
Willy Tarreau91092e52007-10-25 16:58:42 +0200526 * This function simply returns a locally allocated string containing the ascii
527 * representation for number 'n' in decimal, unless n is 0 in which case it
528 * returns the alternate string (or an empty string if the alternate string is
529 * NULL). It use is intended for limits reported in reports, where it's
530 * desirable not to display anything if there is no limit. Warning! it shares
531 * the same vector as ultoa_r().
532 */
533const char *limit_r(unsigned long n, char *buffer, int size, const char *alt)
534{
535 return (n) ? ultoa_r(n, buffer, size) : (alt ? alt : "");
536}
537
Willy Tarreau588297f2014-06-16 15:16:40 +0200538/* returns a locally allocated string containing the quoted encoding of the
539 * input string. The output may be truncated to QSTR_SIZE chars, but it is
540 * guaranteed that the string will always be properly terminated. Quotes are
541 * encoded by doubling them as is commonly done in CSV files. QSTR_SIZE must
542 * always be at least 4 chars.
543 */
544const char *qstr(const char *str)
545{
546 char *ret = quoted_str[quoted_idx];
547 char *p, *end;
548
549 if (++quoted_idx >= NB_QSTR)
550 quoted_idx = 0;
551
552 p = ret;
553 end = ret + QSTR_SIZE;
554
555 *p++ = '"';
556
557 /* always keep 3 chars to support passing "" and the ending " */
558 while (*str && p < end - 3) {
559 if (*str == '"') {
560 *p++ = '"';
561 *p++ = '"';
562 }
563 else
564 *p++ = *str;
565 str++;
566 }
567 *p++ = '"';
568 return ret;
569}
570
Robert Tsai81ae1952007-12-05 10:47:29 +0100571/*
Willy Tarreaubaaee002006-06-26 02:48:02 +0200572 * Returns non-zero if character <s> is a hex digit (0-9, a-f, A-F), else zero.
573 *
574 * It looks like this one would be a good candidate for inlining, but this is
575 * not interesting because it around 35 bytes long and often called multiple
576 * times within the same function.
577 */
578int ishex(char s)
579{
580 s -= '0';
581 if ((unsigned char)s <= 9)
582 return 1;
583 s -= 'A' - '0';
584 if ((unsigned char)s <= 5)
585 return 1;
586 s -= 'a' - 'A';
587 if ((unsigned char)s <= 5)
588 return 1;
589 return 0;
590}
591
Willy Tarreau3ca1a882015-01-15 18:43:49 +0100592/* rounds <i> down to the closest value having max 2 digits */
593unsigned int round_2dig(unsigned int i)
594{
595 unsigned int mul = 1;
596
597 while (i >= 100) {
598 i /= 10;
599 mul *= 10;
600 }
601 return i * mul;
602}
603
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100604/*
605 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_:.-]. If an
606 * invalid character is found, a pointer to it is returned. If everything is
607 * fine, NULL is returned.
608 */
609const char *invalid_char(const char *name)
610{
611 if (!*name)
612 return name;
613
614 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100615 if (!isalnum((unsigned char)*name) && *name != '.' && *name != ':' &&
Willy Tarreau2e74c3f2007-12-02 18:45:09 +0100616 *name != '_' && *name != '-')
617 return name;
618 name++;
619 }
620 return NULL;
621}
Willy Tarreaubaaee002006-06-26 02:48:02 +0200622
623/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200624 * Checks <name> for invalid characters. Valid chars are [_.-] and those
625 * accepted by <f> function.
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200626 * If an invalid character is found, a pointer to it is returned.
627 * If everything is fine, NULL is returned.
628 */
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200629static inline const char *__invalid_char(const char *name, int (*f)(int)) {
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200630
631 if (!*name)
632 return name;
633
634 while (*name) {
Willy Tarreau90807112020-02-25 08:16:33 +0100635 if (!f((unsigned char)*name) && *name != '.' &&
Krzysztof Piotr Oledzkiefe3b6f2008-05-23 23:49:32 +0200636 *name != '_' && *name != '-')
637 return name;
638
639 name++;
640 }
641
642 return NULL;
643}
644
645/*
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200646 * Checks <name> for invalid characters. Valid chars are [A-Za-z0-9_.-].
647 * If an invalid character is found, a pointer to it is returned.
648 * If everything is fine, NULL is returned.
649 */
650const char *invalid_domainchar(const char *name) {
651 return __invalid_char(name, isalnum);
652}
653
654/*
655 * Checks <name> for invalid characters. Valid chars are [A-Za-z_.-].
656 * If an invalid character is found, a pointer to it is returned.
657 * If everything is fine, NULL is returned.
658 */
659const char *invalid_prefix_char(const char *name) {
Thierry Fournierf7b7c3e2018-03-26 11:54:39 +0200660 return __invalid_char(name, isalnum);
Frédéric Lécailleb82f7422017-04-13 18:24:23 +0200661}
662
663/*
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100664 * converts <str> to a struct sockaddr_storage* provided by the caller. The
Willy Tarreau24709282013-03-10 21:32:12 +0100665 * caller must have zeroed <sa> first, and may have set sa->ss_family to force
666 * parse a specific address format. If the ss_family is 0 or AF_UNSPEC, then
667 * the function tries to guess the address family from the syntax. If the
668 * family is forced and the format doesn't match, an error is returned. The
Willy Tarreaufab5a432011-03-04 15:31:53 +0100669 * string is assumed to contain only an address, no port. The address can be a
670 * dotted IPv4 address, an IPv6 address, a host name, or empty or "*" to
671 * indicate INADDR_ANY. NULL is returned if the host part cannot be resolved.
672 * The return address will only have the address family and the address set,
673 * all other fields remain zero. The string is not supposed to be modified.
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100674 * The IPv6 '::' address is IN6ADDR_ANY. If <resolve> is non-zero, the hostname
675 * is resolved, otherwise only IP addresses are resolved, and anything else
Willy Tarreauecde7df2016-11-02 22:37:03 +0100676 * returns NULL. If the address contains a port, this one is preserved.
Willy Tarreaubaaee002006-06-26 02:48:02 +0200677 */
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100678struct sockaddr_storage *str2ip2(const char *str, struct sockaddr_storage *sa, int resolve)
Willy Tarreaubaaee002006-06-26 02:48:02 +0200679{
Willy Tarreaufab5a432011-03-04 15:31:53 +0100680 struct hostent *he;
mildisff5d5102015-10-26 18:50:08 +0100681 /* max IPv6 length, including brackets and terminating NULL */
682 char tmpip[48];
Willy Tarreauecde7df2016-11-02 22:37:03 +0100683 int port = get_host_port(sa);
mildisff5d5102015-10-26 18:50:08 +0100684
685 /* check IPv6 with square brackets */
686 if (str[0] == '[') {
687 size_t iplength = strlen(str);
688
689 if (iplength < 4) {
690 /* minimal size is 4 when using brackets "[::]" */
691 goto fail;
692 }
693 else if (iplength >= sizeof(tmpip)) {
694 /* IPv6 literal can not be larger than tmpip */
695 goto fail;
696 }
697 else {
698 if (str[iplength - 1] != ']') {
699 /* if address started with bracket, it should end with bracket */
700 goto fail;
701 }
702 else {
703 memcpy(tmpip, str + 1, iplength - 2);
704 tmpip[iplength - 2] = '\0';
705 str = tmpip;
706 }
707 }
708 }
Willy Tarreaufab5a432011-03-04 15:31:53 +0100709
Willy Tarreaufab5a432011-03-04 15:31:53 +0100710 /* Any IPv6 address */
711 if (str[0] == ':' && str[1] == ':' && !str[2]) {
Willy Tarreau24709282013-03-10 21:32:12 +0100712 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
713 sa->ss_family = AF_INET6;
714 else if (sa->ss_family != AF_INET6)
715 goto fail;
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
Willy Tarreau24709282013-03-10 21:32:12 +0100720 /* Any address for the family, defaults to IPv4 */
Willy Tarreaufab5a432011-03-04 15:31:53 +0100721 if (!str[0] || (str[0] == '*' && !str[1])) {
Willy Tarreau24709282013-03-10 21:32:12 +0100722 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
723 sa->ss_family = AF_INET;
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 /* check for IPv6 first */
Willy Tarreau24709282013-03-10 21:32:12 +0100729 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET6) &&
730 inet_pton(AF_INET6, str, &((struct sockaddr_in6 *)sa)->sin6_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100731 sa->ss_family = AF_INET6;
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
736 /* then check for IPv4 */
Willy Tarreau24709282013-03-10 21:32:12 +0100737 if ((!sa->ss_family || sa->ss_family == AF_UNSPEC || sa->ss_family == AF_INET) &&
738 inet_pton(AF_INET, str, &((struct sockaddr_in *)sa)->sin_addr)) {
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100739 sa->ss_family = AF_INET;
Willy Tarreauecde7df2016-11-02 22:37:03 +0100740 set_host_port(sa, port);
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100741 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100742 }
743
Thierry FOURNIER58639a02014-11-25 12:02:25 +0100744 if (!resolve)
745 return NULL;
746
Emeric Brund30e9a12020-12-23 18:49:16 +0100747 if (!resolv_hostname_validation(str, NULL))
Baptiste Assmanna68ca962015-04-14 01:15:08 +0200748 return NULL;
749
David du Colombierd5f43282011-03-17 10:40:16 +0100750#ifdef USE_GETADDRINFO
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200751 if (global.tune.options & GTUNE_USE_GAI) {
David du Colombierd5f43282011-03-17 10:40:16 +0100752 struct addrinfo hints, *result;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100753 int success = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100754
755 memset(&result, 0, sizeof(result));
756 memset(&hints, 0, sizeof(hints));
Willy Tarreau24709282013-03-10 21:32:12 +0100757 hints.ai_family = sa->ss_family ? sa->ss_family : AF_UNSPEC;
David du Colombierd5f43282011-03-17 10:40:16 +0100758 hints.ai_socktype = SOCK_DGRAM;
Dmitry Sivachenkoeab7f392015-10-02 01:01:58 +0200759 hints.ai_flags = 0;
David du Colombierd5f43282011-03-17 10:40:16 +0100760 hints.ai_protocol = 0;
761
762 if (getaddrinfo(str, NULL, &hints, &result) == 0) {
Willy Tarreau24709282013-03-10 21:32:12 +0100763 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
764 sa->ss_family = result->ai_family;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100765 else if (sa->ss_family != result->ai_family) {
766 freeaddrinfo(result);
Willy Tarreau24709282013-03-10 21:32:12 +0100767 goto fail;
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100768 }
Willy Tarreau24709282013-03-10 21:32:12 +0100769
David du Colombierd5f43282011-03-17 10:40:16 +0100770 switch (result->ai_family) {
771 case AF_INET:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100772 memcpy((struct sockaddr_in *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100773 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100774 success = 1;
775 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100776 case AF_INET6:
Willy Tarreauc120c8d2013-03-10 19:27:44 +0100777 memcpy((struct sockaddr_in6 *)sa, result->ai_addr, result->ai_addrlen);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100778 set_host_port(sa, port);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100779 success = 1;
780 break;
David du Colombierd5f43282011-03-17 10:40:16 +0100781 }
782 }
783
Sean Carey58ea0392013-02-15 23:39:18 +0100784 if (result)
785 freeaddrinfo(result);
Tim Duesterhus7d58b4d2018-01-21 22:11:17 +0100786
787 if (success)
788 return sa;
Willy Tarreaufab5a432011-03-04 15:31:53 +0100789 }
David du Colombierd5f43282011-03-17 10:40:16 +0100790#endif
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200791 /* try to resolve an IPv4/IPv6 hostname */
792 he = gethostbyname(str);
793 if (he) {
794 if (!sa->ss_family || sa->ss_family == AF_UNSPEC)
795 sa->ss_family = he->h_addrtype;
796 else if (sa->ss_family != he->h_addrtype)
797 goto fail;
798
799 switch (sa->ss_family) {
800 case AF_INET:
801 ((struct sockaddr_in *)sa)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100802 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200803 return sa;
804 case AF_INET6:
805 ((struct sockaddr_in6 *)sa)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
Willy Tarreauecde7df2016-11-02 22:37:03 +0100806 set_host_port(sa, port);
Nenad Merdanovic88afe032014-04-14 15:56:58 +0200807 return sa;
808 }
809 }
810
David du Colombierd5f43282011-03-17 10:40:16 +0100811 /* unsupported address family */
Willy Tarreau24709282013-03-10 21:32:12 +0100812 fail:
Willy Tarreaufab5a432011-03-04 15:31:53 +0100813 return NULL;
814}
815
816/*
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100817 * Converts <str> to a locally allocated struct sockaddr_storage *, and a port
818 * range or offset consisting in two integers that the caller will have to
819 * check to find the relevant input format. The following format are supported :
820 *
821 * String format | address | port | low | high
822 * addr | <addr> | 0 | 0 | 0
823 * addr: | <addr> | 0 | 0 | 0
824 * addr:port | <addr> | <port> | <port> | <port>
825 * addr:pl-ph | <addr> | <pl> | <pl> | <ph>
826 * addr:+port | <addr> | <port> | 0 | <port>
827 * addr:-port | <addr> |-<port> | <port> | 0
828 *
829 * The detection of a port range or increment by the caller is made by
830 * comparing <low> and <high>. If both are equal, then port 0 means no port
831 * was specified. The caller may pass NULL for <low> and <high> if it is not
832 * interested in retrieving port ranges.
833 *
834 * Note that <addr> above may also be :
835 * - empty ("") => family will be AF_INET and address will be INADDR_ANY
836 * - "*" => family will be AF_INET and address will be INADDR_ANY
837 * - "::" => family will be AF_INET6 and address will be IN6ADDR_ANY
838 * - a host name => family and address will depend on host name resolving.
839 *
Willy Tarreau24709282013-03-10 21:32:12 +0100840 * A prefix may be passed in before the address above to force the family :
841 * - "ipv4@" => force address to resolve as IPv4 and fail if not possible.
842 * - "ipv6@" => force address to resolve as IPv6 and fail if not possible.
843 * - "unix@" => force address to be a path to a UNIX socket even if the
844 * path does not start with a '/'
Willy Tarreauccfccef2014-05-10 01:49:15 +0200845 * - 'abns@' -> force address to belong to the abstract namespace (Linux
846 * only). These sockets are just like Unix sockets but without
847 * the need for an underlying file system. The address is a
848 * string. Technically it's like a Unix socket with a zero in
849 * the first byte of the address.
Willy Tarreau40aa0702013-03-10 23:51:38 +0100850 * - "fd@" => an integer must follow, and is a file descriptor number.
Willy Tarreau24709282013-03-10 21:32:12 +0100851 *
mildisff5d5102015-10-26 18:50:08 +0100852 * IPv6 addresses can be declared with or without square brackets. When using
853 * square brackets for IPv6 addresses, the port separator (colon) is optional.
854 * If not using square brackets, and in order to avoid any ambiguity with
855 * IPv6 addresses, the last colon ':' is mandatory even when no port is specified.
856 * NULL is returned if the address cannot be parsed. The <low> and <high> ports
857 * are always initialized if non-null, even for non-IP families.
Willy Tarreaud393a622013-03-04 18:22:00 +0100858 *
859 * If <pfx> is non-null, it is used as a string prefix before any path-based
860 * address (typically the path to a unix socket).
Willy Tarreau40aa0702013-03-10 23:51:38 +0100861 *
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200862 * if <fqdn> is non-null, it will be filled with :
863 * - a pointer to the FQDN of the server name to resolve if there's one, and
864 * that the caller will have to free(),
865 * - NULL if there was an explicit address that doesn't require resolution.
866 *
Willy Tarreaucd3a55912020-09-04 15:30:46 +0200867 * Hostnames are only resolved if <opts> has PA_O_RESOLVE. Otherwise <fqdn> is
868 * still honored so it is possible for the caller to know whether a resolution
869 * failed by clearing this flag and checking if <fqdn> was filled, indicating
870 * the need for a resolution.
Thierry FOURNIER7fe3be72015-09-26 20:03:36 +0200871 *
Willy Tarreau40aa0702013-03-10 23:51:38 +0100872 * When a file descriptor is passed, its value is put into the s_addr part of
Willy Tarreaua5b325f2020-09-04 16:44:20 +0200873 * the address when cast to sockaddr_in and the address family is
874 * AF_CUST_EXISTING_FD.
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200875 *
Willy Tarreau5fc93282020-09-16 18:25:03 +0200876 * The matching protocol will be set into <proto> if non-null.
877 *
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200878 * Any known file descriptor is also assigned to <fd> if non-null, otherwise it
879 * is forced to -1.
Willy Tarreaufab5a432011-03-04 15:31:53 +0100880 */
Willy Tarreau5fc93282020-09-16 18:25:03 +0200881struct sockaddr_storage *str2sa_range(const char *str, int *port, int *low, int *high, int *fd,
882 struct protocol **proto, char **err,
883 const char *pfx, char **fqdn, unsigned int opts)
Willy Tarreaufab5a432011-03-04 15:31:53 +0100884{
Christopher Faulet1bc04c72017-10-29 20:14:08 +0100885 static THREAD_LOCAL struct sockaddr_storage ss;
David du Colombier6f5ccb12011-03-10 22:26:24 +0100886 struct sockaddr_storage *ret = NULL;
Willy Tarreau5fc93282020-09-16 18:25:03 +0200887 struct protocol *new_proto = NULL;
Willy Tarreau24709282013-03-10 21:32:12 +0100888 char *back, *str2;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100889 char *port1, *port2;
890 int portl, porth, porta;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200891 int abstract = 0;
Willy Tarreaua93e5c72020-09-15 14:01:16 +0200892 int new_fd = -1;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200893 int sock_type, ctrl_type;
Willy Tarreaud4448bc2013-02-20 15:55:15 +0100894
895 portl = porth = porta = 0;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +0200896 if (fqdn)
897 *fqdn = NULL;
Willy Tarreaubaaee002006-06-26 02:48:02 +0200898
Willy Tarreaudad36a32013-03-11 01:20:04 +0100899 str2 = back = env_expand(strdup(str));
Willy Tarreaudf350f12013-03-01 20:22:54 +0100900 if (str2 == NULL) {
901 memprintf(err, "out of memory in '%s'\n", __FUNCTION__);
Willy Tarreaud5191e72010-02-09 20:50:45 +0100902 goto out;
Willy Tarreaudf350f12013-03-01 20:22:54 +0100903 }
Willy Tarreaubaaee002006-06-26 02:48:02 +0200904
Willy Tarreau9f69f462015-09-08 16:01:25 +0200905 if (!*str2) {
906 memprintf(err, "'%s' resolves to an empty address (environment variable missing?)\n", str);
907 goto out;
908 }
909
Willy Tarreau24709282013-03-10 21:32:12 +0100910 memset(&ss, 0, sizeof(ss));
911
Willy Tarreaue835bd82020-09-16 11:35:47 +0200912 /* prepare the default socket types */
Willy Tarreauf23b1bc2021-03-23 18:36:37 +0100913 if ((opts & (PA_O_STREAM|PA_O_DGRAM)) == PA_O_DGRAM ||
914 ((opts & (PA_O_STREAM|PA_O_DGRAM)) == (PA_O_DGRAM|PA_O_STREAM) && (opts & PA_O_DEFAULT_DGRAM)))
Willy Tarreaue835bd82020-09-16 11:35:47 +0200915 sock_type = ctrl_type = SOCK_DGRAM;
916 else
917 sock_type = ctrl_type = SOCK_STREAM;
918
919 if (strncmp(str2, "stream+", 7) == 0) {
920 str2 += 7;
921 sock_type = ctrl_type = SOCK_STREAM;
922 }
923 else if (strncmp(str2, "dgram+", 6) == 0) {
924 str2 += 6;
925 sock_type = ctrl_type = SOCK_DGRAM;
926 }
927
Willy Tarreau24709282013-03-10 21:32:12 +0100928 if (strncmp(str2, "unix@", 5) == 0) {
929 str2 += 5;
Willy Tarreauccfccef2014-05-10 01:49:15 +0200930 abstract = 0;
Willy Tarreau24709282013-03-10 21:32:12 +0100931 ss.ss_family = AF_UNIX;
932 }
Emeric Brunce325c42021-04-02 17:05:09 +0200933 else if (strncmp(str2, "uxdg@", 5) == 0) {
934 str2 += 5;
935 abstract = 0;
936 ss.ss_family = AF_UNIX;
937 sock_type = ctrl_type = SOCK_DGRAM;
938 }
939 else if (strncmp(str2, "uxst@", 5) == 0) {
940 str2 += 5;
941 abstract = 0;
942 ss.ss_family = AF_UNIX;
943 sock_type = ctrl_type = SOCK_STREAM;
944 }
Willy Tarreauccfccef2014-05-10 01:49:15 +0200945 else if (strncmp(str2, "abns@", 5) == 0) {
946 str2 += 5;
947 abstract = 1;
948 ss.ss_family = AF_UNIX;
949 }
Emeric Brunce325c42021-04-02 17:05:09 +0200950 else if (strncmp(str2, "ip@", 3) == 0) {
951 str2 += 3;
952 ss.ss_family = AF_UNSPEC;
953 }
Willy Tarreau24709282013-03-10 21:32:12 +0100954 else if (strncmp(str2, "ipv4@", 5) == 0) {
955 str2 += 5;
956 ss.ss_family = AF_INET;
957 }
958 else if (strncmp(str2, "ipv6@", 5) == 0) {
959 str2 += 5;
960 ss.ss_family = AF_INET6;
961 }
Emeric Brunce325c42021-04-02 17:05:09 +0200962 else if (strncmp(str2, "tcp4@", 5) == 0) {
963 str2 += 5;
964 ss.ss_family = AF_INET;
965 sock_type = ctrl_type = SOCK_STREAM;
966 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200967 else if (strncmp(str2, "udp4@", 5) == 0) {
968 str2 += 5;
969 ss.ss_family = AF_INET;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200970 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200971 }
Emeric Brunce325c42021-04-02 17:05:09 +0200972 else if (strncmp(str2, "tcp6@", 5) == 0) {
973 str2 += 5;
974 ss.ss_family = AF_INET6;
975 sock_type = ctrl_type = SOCK_STREAM;
976 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200977 else if (strncmp(str2, "udp6@", 5) == 0) {
978 str2 += 5;
979 ss.ss_family = AF_INET6;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200980 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200981 }
Emeric Brunce325c42021-04-02 17:05:09 +0200982 else if (strncmp(str2, "tcp@", 4) == 0) {
983 str2 += 4;
984 ss.ss_family = AF_UNSPEC;
985 sock_type = ctrl_type = SOCK_STREAM;
986 }
Emeric Brun3835c0d2020-07-07 09:46:09 +0200987 else if (strncmp(str2, "udp@", 4) == 0) {
988 str2 += 4;
989 ss.ss_family = AF_UNSPEC;
Willy Tarreaue835bd82020-09-16 11:35:47 +0200990 sock_type = ctrl_type = SOCK_DGRAM;
Emeric Brun3835c0d2020-07-07 09:46:09 +0200991 }
Frédéric Lécaille10caf652020-11-23 11:36:57 +0100992 else if (strncmp(str2, "quic4@", 6) == 0) {
993 str2 += 6;
994 ss.ss_family = AF_INET;
995 sock_type = SOCK_DGRAM;
996 ctrl_type = SOCK_STREAM;
997 }
998 else if (strncmp(str2, "quic6@", 6) == 0) {
999 str2 += 6;
1000 ss.ss_family = AF_INET6;
1001 sock_type = SOCK_DGRAM;
1002 ctrl_type = SOCK_STREAM;
1003 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001004 else if (strncmp(str2, "fd@", 3) == 0) {
1005 str2 += 3;
1006 ss.ss_family = AF_CUST_EXISTING_FD;
1007 }
1008 else if (strncmp(str2, "sockpair@", 9) == 0) {
1009 str2 += 9;
1010 ss.ss_family = AF_CUST_SOCKPAIR;
1011 }
Willy Tarreau24709282013-03-10 21:32:12 +01001012 else if (*str2 == '/') {
1013 ss.ss_family = AF_UNIX;
1014 }
1015 else
1016 ss.ss_family = AF_UNSPEC;
1017
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001018 if (ss.ss_family == AF_CUST_SOCKPAIR) {
Willy Tarreaua215be22020-09-16 10:14:16 +02001019 struct sockaddr_storage ss2;
1020 socklen_t addr_len;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001021 char *endptr;
1022
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001023 new_fd = strtol(str2, &endptr, 10);
1024 if (!*str2 || new_fd < 0 || *endptr) {
William Lallemand2fe7dd02018-09-11 16:51:29 +02001025 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
1026 goto out;
1027 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001028
Willy Tarreaua215be22020-09-16 10:14:16 +02001029 /* just verify that it's a socket */
1030 addr_len = sizeof(ss2);
1031 if (getsockname(new_fd, (struct sockaddr *)&ss2, &addr_len) == -1) {
1032 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1033 goto out;
1034 }
1035
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001036 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1037 ((struct sockaddr_in *)&ss)->sin_port = 0;
William Lallemand2fe7dd02018-09-11 16:51:29 +02001038 }
Willy Tarreau5a7beed2020-09-04 16:54:05 +02001039 else if (ss.ss_family == AF_CUST_EXISTING_FD) {
Willy Tarreau40aa0702013-03-10 23:51:38 +01001040 char *endptr;
1041
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001042 new_fd = strtol(str2, &endptr, 10);
1043 if (!*str2 || new_fd < 0 || *endptr) {
Willy Tarreaudad36a32013-03-11 01:20:04 +01001044 memprintf(err, "file descriptor '%s' is not a valid integer in '%s'\n", str2, str);
Willy Tarreau40aa0702013-03-10 23:51:38 +01001045 goto out;
1046 }
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001047
Willy Tarreau6edc7222020-09-15 17:41:56 +02001048 if (opts & PA_O_SOCKET_FD) {
1049 socklen_t addr_len;
1050 int type;
1051
1052 addr_len = sizeof(ss);
1053 if (getsockname(new_fd, (struct sockaddr *)&ss, &addr_len) == -1) {
1054 memprintf(err, "cannot use file descriptor '%d' : %s.\n", new_fd, strerror(errno));
1055 goto out;
1056 }
1057
1058 addr_len = sizeof(type);
1059 if (getsockopt(new_fd, SOL_SOCKET, SO_TYPE, &type, &addr_len) != 0 ||
Willy Tarreaue835bd82020-09-16 11:35:47 +02001060 (type == SOCK_STREAM) != (sock_type == SOCK_STREAM)) {
Willy Tarreau6edc7222020-09-15 17:41:56 +02001061 memprintf(err, "socket on file descriptor '%d' is of the wrong type.\n", new_fd);
1062 goto out;
1063 }
1064
1065 porta = portl = porth = get_host_port(&ss);
1066 } else if (opts & PA_O_RAW_FD) {
1067 ((struct sockaddr_in *)&ss)->sin_addr.s_addr = new_fd;
1068 ((struct sockaddr_in *)&ss)->sin_port = 0;
1069 } else {
1070 memprintf(err, "a file descriptor is not acceptable here in '%s'\n", str);
1071 goto out;
1072 }
Willy Tarreau40aa0702013-03-10 23:51:38 +01001073 }
1074 else if (ss.ss_family == AF_UNIX) {
Willy Tarreau8daa9202019-06-16 18:16:33 +02001075 struct sockaddr_un *un = (struct sockaddr_un *)&ss;
Willy Tarreau15586382013-03-04 19:48:14 +01001076 int prefix_path_len;
1077 int max_path_len;
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001078 int adr_len;
Willy Tarreau15586382013-03-04 19:48:14 +01001079
1080 /* complete unix socket path name during startup or soft-restart is
1081 * <unix_bind_prefix><path>.<pid>.<bak|tmp>
1082 */
Willy Tarreauccfccef2014-05-10 01:49:15 +02001083 prefix_path_len = (pfx && !abstract) ? strlen(pfx) : 0;
Willy Tarreau8daa9202019-06-16 18:16:33 +02001084 max_path_len = (sizeof(un->sun_path) - 1) -
Willy Tarreau327ea5a2020-02-11 06:43:37 +01001085 (abstract ? 0 : prefix_path_len + 1 + 5 + 1 + 3);
Willy Tarreau15586382013-03-04 19:48:14 +01001086
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001087 adr_len = strlen(str2);
1088 if (adr_len > max_path_len) {
Willy Tarreau15586382013-03-04 19:48:14 +01001089 memprintf(err, "socket path '%s' too long (max %d)\n", str, max_path_len);
1090 goto out;
1091 }
1092
Willy Tarreauccfccef2014-05-10 01:49:15 +02001093 /* when abstract==1, we skip the first zero and copy all bytes except the trailing zero */
Willy Tarreau8daa9202019-06-16 18:16:33 +02001094 memset(un->sun_path, 0, sizeof(un->sun_path));
Willy Tarreau94ef3f32014-04-14 14:49:00 +02001095 if (prefix_path_len)
Willy Tarreau8daa9202019-06-16 18:16:33 +02001096 memcpy(un->sun_path, pfx, prefix_path_len);
1097 memcpy(un->sun_path + prefix_path_len + abstract, str2, adr_len + 1 - abstract);
Willy Tarreau15586382013-03-04 19:48:14 +01001098 }
Willy Tarreau24709282013-03-10 21:32:12 +01001099 else { /* IPv4 and IPv6 */
mildisff5d5102015-10-26 18:50:08 +01001100 char *end = str2 + strlen(str2);
1101 char *chr;
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001102
mildisff5d5102015-10-26 18:50:08 +01001103 /* search for : or ] whatever comes first */
1104 for (chr = end-1; chr > str2; chr--) {
1105 if (*chr == ']' || *chr == ':')
1106 break;
1107 }
1108
1109 if (*chr == ':') {
1110 /* Found a colon before a closing-bracket, must be a port separator.
1111 * This guarantee backward compatibility.
1112 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001113 if (!(opts & PA_O_PORT_OK)) {
1114 memprintf(err, "port specification not permitted here in '%s'", str);
1115 goto out;
1116 }
mildisff5d5102015-10-26 18:50:08 +01001117 *chr++ = '\0';
1118 port1 = chr;
1119 }
1120 else {
1121 /* Either no colon and no closing-bracket
1122 * or directly ending with a closing-bracket.
1123 * However, no port.
1124 */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001125 if (opts & PA_O_PORT_MAND) {
1126 memprintf(err, "missing port specification in '%s'", str);
1127 goto out;
1128 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001129 port1 = "";
mildisff5d5102015-10-26 18:50:08 +01001130 }
Willy Tarreaubaaee002006-06-26 02:48:02 +02001131
Willy Tarreau90807112020-02-25 08:16:33 +01001132 if (isdigit((unsigned char)*port1)) { /* single port or range */
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001133 port2 = strchr(port1, '-');
Willy Tarreau7f96a842020-09-15 11:12:44 +02001134 if (port2) {
1135 if (!(opts & PA_O_PORT_RANGE)) {
1136 memprintf(err, "port range not permitted here in '%s'", str);
1137 goto out;
1138 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001139 *port2++ = '\0';
Willy Tarreau7f96a842020-09-15 11:12:44 +02001140 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001141 else
1142 port2 = port1;
1143 portl = atoi(port1);
1144 porth = atoi(port2);
Willy Tarreau7f96a842020-09-15 11:12:44 +02001145
1146 if (portl < !!(opts & PA_O_PORT_MAND) || portl > 65535) {
1147 memprintf(err, "invalid port '%s'", port1);
1148 goto out;
1149 }
1150
1151 if (porth < !!(opts & PA_O_PORT_MAND) || porth > 65535) {
1152 memprintf(err, "invalid port '%s'", port2);
1153 goto out;
1154 }
1155
1156 if (portl > porth) {
1157 memprintf(err, "invalid port range '%d-%d'", portl, porth);
1158 goto out;
1159 }
1160
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001161 porta = portl;
1162 }
1163 else if (*port1 == '-') { /* negative offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001164 if (!(opts & PA_O_PORT_OFS)) {
1165 memprintf(err, "port offset not permitted here in '%s'", str);
1166 goto out;
1167 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001168 portl = atoi(port1 + 1);
1169 porta = -portl;
1170 }
1171 else if (*port1 == '+') { /* positive offset */
Willy Tarreau7f96a842020-09-15 11:12:44 +02001172 if (!(opts & PA_O_PORT_OFS)) {
1173 memprintf(err, "port offset not permitted here in '%s'", str);
1174 goto out;
1175 }
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001176 porth = atoi(port1 + 1);
1177 porta = porth;
1178 }
1179 else if (*port1) { /* other any unexpected char */
Willy Tarreaudad36a32013-03-11 01:20:04 +01001180 memprintf(err, "invalid character '%c' in port number '%s' in '%s'\n", *port1, port1, str);
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001181 goto out;
1182 }
Willy Tarreau7f96a842020-09-15 11:12:44 +02001183 else if (opts & PA_O_PORT_MAND) {
1184 memprintf(err, "missing port specification in '%s'", str);
1185 goto out;
1186 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001187
1188 /* first try to parse the IP without resolving. If it fails, it
1189 * tells us we need to keep a copy of the FQDN to resolve later
1190 * and to enable DNS. In this case we can proceed if <fqdn> is
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001191 * set or if PA_O_RESOLVE is set, otherwise it's an error.
Willy Tarreauceccdd72016-11-02 22:27:10 +01001192 */
1193 if (str2ip2(str2, &ss, 0) == NULL) {
Willy Tarreaucd3a55912020-09-04 15:30:46 +02001194 if ((!(opts & PA_O_RESOLVE) && !fqdn) ||
1195 ((opts & PA_O_RESOLVE) && str2ip2(str2, &ss, 1) == NULL)) {
Willy Tarreauceccdd72016-11-02 22:27:10 +01001196 memprintf(err, "invalid address: '%s' in '%s'\n", str2, str);
1197 goto out;
1198 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001199
Willy Tarreauceccdd72016-11-02 22:27:10 +01001200 if (fqdn) {
1201 if (str2 != back)
1202 memmove(back, str2, strlen(str2) + 1);
1203 *fqdn = back;
1204 back = NULL;
1205 }
Willy Tarreau72b8c1f2015-09-08 15:50:19 +02001206 }
Willy Tarreauceccdd72016-11-02 22:27:10 +01001207 set_host_port(&ss, porta);
Willy Tarreaue4c58c82013-03-06 15:28:17 +01001208 }
Willy Tarreaufab5a432011-03-04 15:31:53 +01001209
Willy Tarreaue835bd82020-09-16 11:35:47 +02001210 if (ctrl_type == SOCK_STREAM && !(opts & PA_O_STREAM)) {
1211 memprintf(err, "stream-type socket not acceptable in '%s'\n", str);
1212 goto out;
1213 }
1214 else if (ctrl_type == SOCK_DGRAM && !(opts & PA_O_DGRAM)) {
1215 memprintf(err, "dgram-type socket not acceptable in '%s'\n", str);
1216 goto out;
1217 }
1218
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001219 if (proto || (opts & PA_O_CONNECT)) {
Willy Tarreau5fc93282020-09-16 18:25:03 +02001220 /* Note: if the caller asks for a proto, we must find one,
1221 * except if we return with an fqdn that will resolve later,
1222 * in which case the address is not known yet (this is only
1223 * for servers actually).
1224 */
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001225 new_proto = protocol_lookup(ss.ss_family,
Willy Tarreauaf9609b2020-09-16 22:04:46 +02001226 sock_type == SOCK_DGRAM,
1227 ctrl_type == SOCK_DGRAM);
Willy Tarreaub2ffc992020-09-16 21:37:31 +02001228
Willy Tarreau5fc93282020-09-16 18:25:03 +02001229 if (!new_proto && (!fqdn || !*fqdn)) {
1230 memprintf(err, "unsupported protocol family %d for address '%s'", ss.ss_family, str);
1231 goto out;
1232 }
Willy Tarreau65ec4e32020-09-16 19:17:08 +02001233
1234 if ((opts & PA_O_CONNECT) && new_proto && !new_proto->connect) {
1235 memprintf(err, "connect() not supported for this protocol family %d used by address '%s'", ss.ss_family, str);
1236 goto out;
1237 }
Willy Tarreau5fc93282020-09-16 18:25:03 +02001238 }
1239
Willy Tarreauc120c8d2013-03-10 19:27:44 +01001240 ret = &ss;
Willy Tarreaud5191e72010-02-09 20:50:45 +01001241 out:
Willy Tarreau48ef4c92017-01-06 18:32:38 +01001242 if (port)
1243 *port = porta;
Willy Tarreaud4448bc2013-02-20 15:55:15 +01001244 if (low)
1245 *low = portl;
1246 if (high)
1247 *high = porth;
Willy Tarreaua93e5c72020-09-15 14:01:16 +02001248 if (fd)
1249 *fd = new_fd;
Willy Tarreau5fc93282020-09-16 18:25:03 +02001250 if (proto)
1251 *proto = new_proto;
Willy Tarreau24709282013-03-10 21:32:12 +01001252 free(back);
Willy Tarreaud5191e72010-02-09 20:50:45 +01001253 return ret;
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001254}
1255
Thayne McCombs92149f92020-11-20 01:28:26 -07001256/* converts <addr> and <port> into a string representation of the address and port. This is sort
1257 * of an inverse of str2sa_range, with some restrictions. The supported families are AF_INET,
1258 * AF_INET6, AF_UNIX, and AF_CUST_SOCKPAIR. If the family is unsopported NULL is returned.
1259 * If map_ports is true, then the sign of the port is included in the output, to indicate it is
1260 * relative to the incoming port. AF_INET and AF_INET6 will be in the form "<addr>:<port>".
1261 * AF_UNIX will either be just the path (if using a pathname) or "abns@<path>" if it is abstract.
1262 * AF_CUST_SOCKPAIR will be of the form "sockpair@<fd>".
1263 *
1264 * The returned char* is allocated, and it is the responsibility of the caller to free it.
1265 */
1266char * sa2str(const struct sockaddr_storage *addr, int port, int map_ports)
1267{
1268 char buffer[INET6_ADDRSTRLEN];
1269 char *out = NULL;
1270 const void *ptr;
1271 const char *path;
1272
1273 switch (addr->ss_family) {
1274 case AF_INET:
1275 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1276 break;
1277 case AF_INET6:
1278 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1279 break;
1280 case AF_UNIX:
1281 path = ((struct sockaddr_un *)addr)->sun_path;
1282 if (path[0] == '\0') {
1283 const int max_length = sizeof(struct sockaddr_un) - offsetof(struct sockaddr_un, sun_path) - 1;
1284 return memprintf(&out, "abns@%.*s", max_length, path+1);
1285 } else {
1286 return strdup(path);
1287 }
1288 case AF_CUST_SOCKPAIR:
1289 return memprintf(&out, "sockpair@%d", ((struct sockaddr_in *)addr)->sin_addr.s_addr);
1290 default:
1291 return NULL;
1292 }
1293 inet_ntop(addr->ss_family, ptr, buffer, get_addr_len(addr));
1294 if (map_ports)
1295 return memprintf(&out, "%s:%+d", buffer, port);
1296 else
1297 return memprintf(&out, "%s:%d", buffer, port);
1298}
1299
1300
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001301/* converts <str> to a struct in_addr containing a network mask. It can be
1302 * passed in dotted form (255.255.255.0) or in CIDR form (24). It returns 1
Jarno Huuskonen577d5ac2017-05-21 17:32:21 +03001303 * if the conversion succeeds otherwise zero.
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001304 */
1305int str2mask(const char *str, struct in_addr *mask)
1306{
1307 if (strchr(str, '.') != NULL) { /* dotted notation */
1308 if (!inet_pton(AF_INET, str, mask))
1309 return 0;
1310 }
1311 else { /* mask length */
1312 char *err;
1313 unsigned long len = strtol(str, &err, 10);
1314
1315 if (!*str || (err && *err) || (unsigned)len > 32)
1316 return 0;
Tim Duesterhus8575f722018-01-25 16:24:48 +01001317
1318 len2mask4(len, mask);
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001319 }
1320 return 1;
1321}
1322
Tim Duesterhus47185172018-01-25 16:24:49 +01001323/* converts <str> to a struct in6_addr containing a network mask. It can be
Tim Duesterhus5e642862018-02-20 17:02:18 +01001324 * passed in quadruplet form (ffff:ffff::) or in CIDR form (64). It returns 1
Tim Duesterhus47185172018-01-25 16:24:49 +01001325 * if the conversion succeeds otherwise zero.
1326 */
1327int str2mask6(const char *str, struct in6_addr *mask)
1328{
1329 if (strchr(str, ':') != NULL) { /* quadruplet notation */
1330 if (!inet_pton(AF_INET6, str, mask))
1331 return 0;
1332 }
1333 else { /* mask length */
1334 char *err;
1335 unsigned long len = strtol(str, &err, 10);
1336
1337 if (!*str || (err && *err) || (unsigned)len > 128)
1338 return 0;
1339
1340 len2mask6(len, mask);
1341 }
1342 return 1;
1343}
1344
Thierry FOURNIERb0504632013-12-14 15:39:02 +01001345/* convert <cidr> to struct in_addr <mask>. It returns 1 if the conversion
1346 * succeeds otherwise zero.
1347 */
1348int cidr2dotted(int cidr, struct in_addr *mask) {
1349
1350 if (cidr < 0 || cidr > 32)
1351 return 0;
1352
1353 mask->s_addr = cidr ? htonl(~0UL << (32 - cidr)) : 0;
1354 return 1;
1355}
1356
Thierry Fournier70473a52016-02-17 17:12:14 +01001357/* Convert mask from bit length form to in_addr form.
1358 * This function never fails.
1359 */
1360void len2mask4(int len, struct in_addr *addr)
1361{
1362 if (len >= 32) {
1363 addr->s_addr = 0xffffffff;
1364 return;
1365 }
1366 if (len <= 0) {
1367 addr->s_addr = 0x00000000;
1368 return;
1369 }
1370 addr->s_addr = 0xffffffff << (32 - len);
1371 addr->s_addr = htonl(addr->s_addr);
1372}
1373
1374/* Convert mask from bit length form to in6_addr form.
1375 * This function never fails.
1376 */
1377void len2mask6(int len, struct in6_addr *addr)
1378{
1379 len2mask4(len, (struct in_addr *)&addr->s6_addr[0]); /* msb */
1380 len -= 32;
1381 len2mask4(len, (struct in_addr *)&addr->s6_addr[4]);
1382 len -= 32;
1383 len2mask4(len, (struct in_addr *)&addr->s6_addr[8]);
1384 len -= 32;
1385 len2mask4(len, (struct in_addr *)&addr->s6_addr[12]); /* lsb */
1386}
1387
Willy Tarreauc6f4ce82009-06-10 11:09:37 +02001388/*
Willy Tarreaud077a8e2007-05-08 18:28:09 +02001389 * converts <str> to two struct in_addr* which must be pre-allocated.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001390 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001391 * is optional and either in the dotted or CIDR notation.
Willy Tarreaubaaee002006-06-26 02:48:02 +02001392 * Note: "addr" can also be a hostname. Returns 1 if OK, 0 if error.
1393 */
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001394int str2net(const char *str, int resolve, struct in_addr *addr, struct in_addr *mask)
Willy Tarreaubaaee002006-06-26 02:48:02 +02001395{
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001396 __label__ out_free, out_err;
1397 char *c, *s;
1398 int ret_val;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001399
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001400 s = strdup(str);
1401 if (!s)
1402 return 0;
1403
Willy Tarreaubaaee002006-06-26 02:48:02 +02001404 memset(mask, 0, sizeof(*mask));
1405 memset(addr, 0, sizeof(*addr));
Willy Tarreaubaaee002006-06-26 02:48:02 +02001406
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001407 if ((c = strrchr(s, '/')) != NULL) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001408 *c++ = '\0';
1409 /* c points to the mask */
Willy Tarreau2937c0d2010-01-26 17:36:17 +01001410 if (!str2mask(c, mask))
1411 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001412 }
1413 else {
Willy Tarreauebd61602006-12-30 11:54:15 +01001414 mask->s_addr = ~0U;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001415 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001416 if (!inet_pton(AF_INET, s, addr)) {
Willy Tarreaubaaee002006-06-26 02:48:02 +02001417 struct hostent *he;
1418
Thierry FOURNIERfc7ac7b2014-02-11 15:23:04 +01001419 if (!resolve)
1420 goto out_err;
1421
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001422 if ((he = gethostbyname(s)) == NULL) {
1423 goto out_err;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001424 }
1425 else
1426 *addr = *(struct in_addr *) *(he->h_addr_list);
1427 }
Willy Tarreau8aeae4a2007-06-17 11:42:08 +02001428
1429 ret_val = 1;
1430 out_free:
1431 free(s);
1432 return ret_val;
1433 out_err:
1434 ret_val = 0;
1435 goto out_free;
Willy Tarreaubaaee002006-06-26 02:48:02 +02001436}
1437
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001438
1439/*
Willy Tarreau6d20e282012-04-27 22:49:47 +02001440 * converts <str> to two struct in6_addr* which must be pre-allocated.
1441 * The format is "addr[/mask]", where "addr" cannot be empty, and mask
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001442 * is an optional number of bits (128 being the default).
Willy Tarreau6d20e282012-04-27 22:49:47 +02001443 * Returns 1 if OK, 0 if error.
1444 */
1445int str62net(const char *str, struct in6_addr *addr, unsigned char *mask)
1446{
1447 char *c, *s;
1448 int ret_val = 0;
1449 char *err;
1450 unsigned long len = 128;
1451
1452 s = strdup(str);
1453 if (!s)
1454 return 0;
1455
1456 memset(mask, 0, sizeof(*mask));
1457 memset(addr, 0, sizeof(*addr));
1458
1459 if ((c = strrchr(s, '/')) != NULL) {
1460 *c++ = '\0'; /* c points to the mask */
1461 if (!*c)
1462 goto out_free;
1463
1464 len = strtoul(c, &err, 10);
1465 if ((err && *err) || (unsigned)len > 128)
1466 goto out_free;
1467 }
1468 *mask = len; /* OK we have a valid mask in <len> */
1469
1470 if (!inet_pton(AF_INET6, s, addr))
1471 goto out_free;
1472
1473 ret_val = 1;
1474 out_free:
1475 free(s);
1476 return ret_val;
1477}
1478
1479
1480/*
Willy Tarreau12e10272021-03-25 11:34:40 +01001481 * Parse IPv4 address found in url. Return the number of bytes parsed. It
1482 * expects exactly 4 numbers between 0 and 255 delimited by dots, and returns
1483 * zero in case of mismatch.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001484 */
David du Colombier6f5ccb12011-03-10 22:26:24 +01001485int url2ipv4(const char *addr, struct in_addr *dst)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001486{
1487 int saw_digit, octets, ch;
1488 u_char tmp[4], *tp;
1489 const char *cp = addr;
1490
1491 saw_digit = 0;
1492 octets = 0;
1493 *(tp = tmp) = 0;
1494
1495 while (*addr) {
Willy Tarreau12e10272021-03-25 11:34:40 +01001496 unsigned char digit = (ch = *addr) - '0';
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001497 if (digit > 9 && ch != '.')
1498 break;
Willy Tarreau12e10272021-03-25 11:34:40 +01001499 addr++;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001500 if (digit <= 9) {
1501 u_int new = *tp * 10 + digit;
1502 if (new > 255)
1503 return 0;
1504 *tp = new;
1505 if (!saw_digit) {
1506 if (++octets > 4)
1507 return 0;
1508 saw_digit = 1;
1509 }
1510 } else if (ch == '.' && saw_digit) {
1511 if (octets == 4)
1512 return 0;
1513 *++tp = 0;
1514 saw_digit = 0;
1515 } else
1516 return 0;
1517 }
1518
1519 if (octets < 4)
1520 return 0;
1521
1522 memcpy(&dst->s_addr, tmp, 4);
Willy Tarreau12e10272021-03-25 11:34:40 +01001523 return addr - cp;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001524}
1525
1526/*
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001527 * Resolve destination server from URL. Convert <str> to a sockaddr_storage.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05001528 * <out> contain the code of the detected scheme, the start and length of
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001529 * the hostname. Actually only http and https are supported. <out> can be NULL.
1530 * This function returns the consumed length. It is useful if you parse complete
1531 * url like http://host:port/path, because the consumed length corresponds to
1532 * the first character of the path. If the conversion fails, it returns -1.
1533 *
1534 * This function tries to resolve the DNS name if haproxy is in starting mode.
1535 * So, this function may be used during the configuration parsing.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001536 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001537int url2sa(const char *url, int ulen, struct sockaddr_storage *addr, struct split_url *out)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001538{
1539 const char *curr = url, *cp = url;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001540 const char *end;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001541 int ret, url_code = 0;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001542 unsigned long long int http_code = 0;
1543 int default_port;
1544 struct hostent *he;
1545 char *p;
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001546
1547 /* Firstly, try to find :// pattern */
1548 while (curr < url+ulen && url_code != 0x3a2f2f) {
1549 url_code = ((url_code & 0xffff) << 8);
1550 url_code += (unsigned char)*curr++;
1551 }
1552
1553 /* Secondly, if :// pattern is found, verify parsed stuff
1554 * before pattern is matching our http pattern.
1555 * If so parse ip address and port in uri.
1556 *
1557 * WARNING: Current code doesn't support dynamic async dns resolver.
1558 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001559 if (url_code != 0x3a2f2f)
1560 return -1;
1561
1562 /* Copy scheme, and utrn to lower case. */
1563 while (cp < curr - 3)
1564 http_code = (http_code << 8) + *cp++;
1565 http_code |= 0x2020202020202020ULL; /* Turn everything to lower case */
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001566
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001567 /* HTTP or HTTPS url matching */
1568 if (http_code == 0x2020202068747470ULL) {
1569 default_port = 80;
1570 if (out)
1571 out->scheme = SCH_HTTP;
1572 }
1573 else if (http_code == 0x2020206874747073ULL) {
1574 default_port = 443;
1575 if (out)
1576 out->scheme = SCH_HTTPS;
1577 }
1578 else
1579 return -1;
1580
1581 /* If the next char is '[', the host address is IPv6. */
1582 if (*curr == '[') {
1583 curr++;
1584
1585 /* Check trash size */
1586 if (trash.size < ulen)
1587 return -1;
1588
1589 /* Look for ']' and copy the address in a trash buffer. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001590 p = trash.area;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001591 for (end = curr;
1592 end < url + ulen && *end != ']';
1593 end++, p++)
1594 *p = *end;
1595 if (*end != ']')
1596 return -1;
1597 *p = '\0';
1598
1599 /* Update out. */
1600 if (out) {
1601 out->host = curr;
1602 out->host_len = end - curr;
1603 }
1604
1605 /* Try IPv6 decoding. */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001606 if (!inet_pton(AF_INET6, trash.area, &((struct sockaddr_in6 *)addr)->sin6_addr))
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001607 return -1;
1608 end++;
1609
1610 /* Decode port. */
1611 if (*end == ':') {
1612 end++;
1613 default_port = read_uint(&end, url + ulen);
1614 }
1615 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1616 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1617 return end - url;
1618 }
1619 else {
1620 /* We are looking for IP address. If you want to parse and
1621 * resolve hostname found in url, you can use str2sa_range(), but
1622 * be warned this can slow down global daemon performances
1623 * while handling lagging dns responses.
1624 */
1625 ret = url2ipv4(curr, &((struct sockaddr_in *)addr)->sin_addr);
1626 if (ret) {
1627 /* Update out. */
1628 if (out) {
1629 out->host = curr;
1630 out->host_len = ret;
1631 }
1632
1633 curr += ret;
1634
1635 /* Decode port. */
1636 if (*curr == ':') {
1637 curr++;
1638 default_port = read_uint(&curr, url + ulen);
1639 }
1640 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1641
1642 /* Set family. */
1643 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1644 return curr - url;
1645 }
1646 else if (global.mode & MODE_STARTING) {
1647 /* The IPv4 and IPv6 decoding fails, maybe the url contain name. Try to execute
1648 * synchronous DNS request only if HAProxy is in the start state.
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001649 */
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001650
1651 /* look for : or / or end */
1652 for (end = curr;
1653 end < url + ulen && *end != '/' && *end != ':';
1654 end++);
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001655 memcpy(trash.area, curr, end - curr);
1656 trash.area[end - curr] = '\0';
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001657
1658 /* try to resolve an IPv4/IPv6 hostname */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001659 he = gethostbyname(trash.area);
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001660 if (!he)
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001661 return -1;
Thierry FOURNIER9f95e402014-03-21 14:51:46 +01001662
1663 /* Update out. */
1664 if (out) {
1665 out->host = curr;
1666 out->host_len = end - curr;
1667 }
1668
1669 /* Decode port. */
1670 if (*end == ':') {
1671 end++;
1672 default_port = read_uint(&end, url + ulen);
1673 }
1674
1675 /* Copy IP address, set port and family. */
1676 switch (he->h_addrtype) {
1677 case AF_INET:
1678 ((struct sockaddr_in *)addr)->sin_addr = *(struct in_addr *) *(he->h_addr_list);
1679 ((struct sockaddr_in *)addr)->sin_port = htons(default_port);
1680 ((struct sockaddr_in *)addr)->sin_family = AF_INET;
1681 return end - url;
1682
1683 case AF_INET6:
1684 ((struct sockaddr_in6 *)addr)->sin6_addr = *(struct in6_addr *) *(he->h_addr_list);
1685 ((struct sockaddr_in6 *)addr)->sin6_port = htons(default_port);
1686 ((struct sockaddr_in6 *)addr)->sin6_family = AF_INET6;
1687 return end - url;
1688 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001689 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001690 }
Alexandre Cassen5eb1a902007-11-29 15:43:32 +01001691 return -1;
1692}
1693
Willy Tarreau631f01c2011-09-05 00:36:48 +02001694/* Tries to convert a sockaddr_storage address to text form. Upon success, the
1695 * address family is returned so that it's easy for the caller to adapt to the
1696 * output format. Zero is returned if the address family is not supported. -1
1697 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1698 * supported.
1699 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001700int addr_to_str(const struct sockaddr_storage *addr, char *str, int size)
Willy Tarreau631f01c2011-09-05 00:36:48 +02001701{
1702
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001703 const void *ptr;
Willy Tarreau631f01c2011-09-05 00:36:48 +02001704
1705 if (size < 5)
1706 return 0;
1707 *str = '\0';
1708
1709 switch (addr->ss_family) {
1710 case AF_INET:
1711 ptr = &((struct sockaddr_in *)addr)->sin_addr;
1712 break;
1713 case AF_INET6:
1714 ptr = &((struct sockaddr_in6 *)addr)->sin6_addr;
1715 break;
1716 case AF_UNIX:
1717 memcpy(str, "unix", 5);
1718 return addr->ss_family;
1719 default:
1720 return 0;
1721 }
1722
1723 if (inet_ntop(addr->ss_family, ptr, str, size))
1724 return addr->ss_family;
1725
1726 /* failed */
1727 return -1;
1728}
1729
Simon Horman75ab8bd2014-06-16 09:39:41 +09001730/* Tries to convert a sockaddr_storage port to text form. Upon success, the
1731 * address family is returned so that it's easy for the caller to adapt to the
1732 * output format. Zero is returned if the address family is not supported. -1
1733 * is returned upon error, with errno set. AF_INET, AF_INET6 and AF_UNIX are
1734 * supported.
1735 */
Willy Tarreaud5ec4bf2019-04-25 17:48:16 +02001736int port_to_str(const struct sockaddr_storage *addr, char *str, int size)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001737{
1738
1739 uint16_t port;
1740
1741
Willy Tarreaud7dad1b2017-01-06 16:46:22 +01001742 if (size < 6)
Simon Horman75ab8bd2014-06-16 09:39:41 +09001743 return 0;
1744 *str = '\0';
1745
1746 switch (addr->ss_family) {
1747 case AF_INET:
1748 port = ((struct sockaddr_in *)addr)->sin_port;
1749 break;
1750 case AF_INET6:
1751 port = ((struct sockaddr_in6 *)addr)->sin6_port;
1752 break;
1753 case AF_UNIX:
1754 memcpy(str, "unix", 5);
1755 return addr->ss_family;
1756 default:
1757 return 0;
1758 }
1759
1760 snprintf(str, size, "%u", ntohs(port));
1761 return addr->ss_family;
1762}
1763
Willy Tarreau16e01562016-08-09 16:46:18 +02001764/* check if the given address is local to the system or not. It will return
1765 * -1 when it's not possible to know, 0 when the address is not local, 1 when
1766 * it is. We don't want to iterate over all interfaces for this (and it is not
1767 * portable). So instead we try to bind in UDP to this address on a free non
1768 * privileged port and to connect to the same address, port 0 (connect doesn't
1769 * care). If it succeeds, we own the address. Note that non-inet addresses are
1770 * considered local since they're most likely AF_UNIX.
1771 */
1772int addr_is_local(const struct netns_entry *ns,
1773 const struct sockaddr_storage *orig)
1774{
1775 struct sockaddr_storage addr;
1776 int result;
1777 int fd;
1778
1779 if (!is_inet_addr(orig))
1780 return 1;
1781
1782 memcpy(&addr, orig, sizeof(addr));
1783 set_host_port(&addr, 0);
1784
1785 fd = my_socketat(ns, addr.ss_family, SOCK_DGRAM, IPPROTO_UDP);
1786 if (fd < 0)
1787 return -1;
1788
1789 result = -1;
1790 if (bind(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == 0) {
1791 if (connect(fd, (struct sockaddr *)&addr, get_addr_len(&addr)) == -1)
1792 result = 0; // fail, non-local address
1793 else
1794 result = 1; // success, local address
1795 }
1796 else {
1797 if (errno == EADDRNOTAVAIL)
1798 result = 0; // definitely not local :-)
1799 }
1800 close(fd);
1801
1802 return result;
1803}
1804
Willy Tarreaubaaee002006-06-26 02:48:02 +02001805/* will try to encode the string <string> replacing all characters tagged in
1806 * <map> with the hexadecimal representation of their ASCII-code (2 digits)
1807 * prefixed by <escape>, and will store the result between <start> (included)
1808 * and <stop> (excluded), and will always terminate the string with a '\0'
1809 * before <stop>. The position of the '\0' is returned if the conversion
1810 * completes. If bytes are missing between <start> and <stop>, then the
1811 * conversion will be incomplete and truncated. If <stop> <= <start>, the '\0'
1812 * cannot even be stored so we return <start> without writing the 0.
1813 * The input string must also be zero-terminated.
1814 */
1815const char hextab[16] = "0123456789ABCDEF";
1816char *encode_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001817 const char escape, const long *map,
Willy Tarreaubaaee002006-06-26 02:48:02 +02001818 const char *string)
1819{
1820 if (start < stop) {
1821 stop--; /* reserve one byte for the final '\0' */
1822 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001823 if (!ha_bit_test((unsigned char)(*string), map))
Willy Tarreaubaaee002006-06-26 02:48:02 +02001824 *start++ = *string;
1825 else {
1826 if (start + 3 >= stop)
1827 break;
1828 *start++ = escape;
1829 *start++ = hextab[(*string >> 4) & 15];
1830 *start++ = hextab[*string & 15];
1831 }
1832 string++;
1833 }
1834 *start = '\0';
1835 }
1836 return start;
1837}
1838
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001839/*
1840 * Same behavior as encode_string() above, except that it encodes chunk
1841 * <chunk> instead of a string.
1842 */
1843char *encode_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001844 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001845 const struct buffer *chunk)
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001846{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001847 char *str = chunk->area;
1848 char *end = chunk->area + chunk->data;
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001849
1850 if (start < stop) {
1851 stop--; /* reserve one byte for the final '\0' */
1852 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001853 if (!ha_bit_test((unsigned char)(*str), map))
Thierry FOURNIERe059ec92014-03-17 12:01:13 +01001854 *start++ = *str;
1855 else {
1856 if (start + 3 >= stop)
1857 break;
1858 *start++ = escape;
1859 *start++ = hextab[(*str >> 4) & 15];
1860 *start++ = hextab[*str & 15];
1861 }
1862 str++;
1863 }
1864 *start = '\0';
1865 }
1866 return start;
1867}
1868
Dragan Dosen0edd1092016-02-12 13:23:02 +01001869/*
1870 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001871 * character. The input <string> must be zero-terminated. The result will
1872 * be stored between <start> (included) and <stop> (excluded). This
1873 * function will always try to terminate the resulting string with a '\0'
1874 * before <stop>, and will return its position if the conversion
1875 * completes.
1876 */
1877char *escape_string(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001878 const char escape, const long *map,
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001879 const char *string)
1880{
1881 if (start < stop) {
1882 stop--; /* reserve one byte for the final '\0' */
1883 while (start < stop && *string != '\0') {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001884 if (!ha_bit_test((unsigned char)(*string), map))
Dragan Dosen1a5d0602016-07-22 16:00:31 +02001885 *start++ = *string;
1886 else {
1887 if (start + 2 >= stop)
1888 break;
1889 *start++ = escape;
1890 *start++ = *string;
1891 }
1892 string++;
1893 }
1894 *start = '\0';
1895 }
1896 return start;
1897}
1898
1899/*
1900 * Tries to prefix characters tagged in the <map> with the <escape>
Dragan Dosen0edd1092016-02-12 13:23:02 +01001901 * character. <chunk> contains the input to be escaped. The result will be
1902 * stored between <start> (included) and <stop> (excluded). The function
1903 * will always try to terminate the resulting string with a '\0' before
1904 * <stop>, and will return its position if the conversion completes.
1905 */
1906char *escape_chunk(char *start, char *stop,
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001907 const char escape, const long *map,
Willy Tarreau83061a82018-07-13 11:56:34 +02001908 const struct buffer *chunk)
Dragan Dosen0edd1092016-02-12 13:23:02 +01001909{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001910 char *str = chunk->area;
1911 char *end = chunk->area + chunk->data;
Dragan Dosen0edd1092016-02-12 13:23:02 +01001912
1913 if (start < stop) {
1914 stop--; /* reserve one byte for the final '\0' */
1915 while (start < stop && str < end) {
Willy Tarreau1bfd6022019-06-07 11:10:07 +02001916 if (!ha_bit_test((unsigned char)(*str), map))
Dragan Dosen0edd1092016-02-12 13:23:02 +01001917 *start++ = *str;
1918 else {
1919 if (start + 2 >= stop)
1920 break;
1921 *start++ = escape;
1922 *start++ = *str;
1923 }
1924 str++;
1925 }
1926 *start = '\0';
1927 }
1928 return start;
1929}
1930
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001931/* Check a string for using it in a CSV output format. If the string contains
1932 * one of the following four char <">, <,>, CR or LF, the string is
1933 * encapsulated between <"> and the <"> are escaped by a <""> sequence.
1934 * <str> is the input string to be escaped. The function assumes that
1935 * the input string is null-terminated.
1936 *
1937 * If <quote> is 0, the result is returned escaped but without double quote.
Willy Tarreau898529b2016-01-06 18:07:04 +01001938 * It is useful if the escaped string is used between double quotes in the
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001939 * format.
1940 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001941 * printf("..., \"%s\", ...\r\n", csv_enc(str, 0, &trash));
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001942 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001943 * If <quote> is 1, the converter puts the quotes only if any reserved character
1944 * is present. If <quote> is 2, the converter always puts the quotes.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001945 *
Willy Tarreau83061a82018-07-13 11:56:34 +02001946 * <output> is a struct buffer used for storing the output string.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001947 *
Willy Tarreau898529b2016-01-06 18:07:04 +01001948 * The function returns the converted string on its output. If an error
1949 * occurs, the function returns an empty string. This type of output is useful
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001950 * for using the function directly as printf() argument.
1951 *
1952 * If the output buffer is too short to contain the input string, the result
1953 * is truncated.
Willy Tarreau898529b2016-01-06 18:07:04 +01001954 *
Willy Tarreaub631c292016-01-08 10:04:08 +01001955 * This function appends the encoding to the existing output chunk, and it
1956 * guarantees that it starts immediately at the first available character of
1957 * the chunk. Please use csv_enc() instead if you want to replace the output
1958 * chunk.
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001959 */
Willy Tarreau83061a82018-07-13 11:56:34 +02001960const char *csv_enc_append(const char *str, int quote, struct buffer *output)
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001961{
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001962 char *end = output->area + output->size;
1963 char *out = output->area + output->data;
Willy Tarreau898529b2016-01-06 18:07:04 +01001964 char *ptr = out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001965
Willy Tarreaub631c292016-01-08 10:04:08 +01001966 if (quote == 1) {
1967 /* automatic quoting: first verify if we'll have to quote the string */
1968 if (!strpbrk(str, "\n\r,\""))
1969 quote = 0;
1970 }
1971
1972 if (quote)
1973 *ptr++ = '"';
1974
Willy Tarreau898529b2016-01-06 18:07:04 +01001975 while (*str && ptr < end - 2) { /* -2 for reserving space for <"> and \0. */
1976 *ptr = *str;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001977 if (*str == '"') {
Willy Tarreau898529b2016-01-06 18:07:04 +01001978 ptr++;
1979 if (ptr >= end - 2) {
1980 ptr--;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001981 break;
1982 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001983 *ptr = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001984 }
Willy Tarreau898529b2016-01-06 18:07:04 +01001985 ptr++;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001986 str++;
1987 }
1988
Willy Tarreaub631c292016-01-08 10:04:08 +01001989 if (quote)
1990 *ptr++ = '"';
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001991
Willy Tarreau898529b2016-01-06 18:07:04 +01001992 *ptr = '\0';
Willy Tarreau843b7cb2018-07-13 10:54:26 +02001993 output->data = ptr - output->area;
Willy Tarreau898529b2016-01-06 18:07:04 +01001994 return out;
Thierry FOURNIERddea6262015-05-28 16:00:28 +02001995}
1996
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02001997/* Decode an URL-encoded string in-place. The resulting string might
1998 * be shorter. If some forbidden characters are found, the conversion is
Thierry FOURNIER5068d962013-10-04 16:27:27 +02001999 * aborted, the string is truncated before the issue and a negative value is
2000 * returned, otherwise the operation returns the length of the decoded string.
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002001 * If the 'in_form' argument is non-nul the string is assumed to be part of
2002 * an "application/x-www-form-urlencoded" encoded string, and the '+' will be
2003 * turned to a space. If it's zero, this will only be done after a question
2004 * mark ('?').
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002005 */
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002006int url_decode(char *string, int in_form)
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002007{
2008 char *in, *out;
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002009 int ret = -1;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002010
2011 in = string;
2012 out = string;
2013 while (*in) {
2014 switch (*in) {
2015 case '+' :
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002016 *out++ = in_form ? ' ' : *in;
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002017 break;
2018 case '%' :
2019 if (!ishex(in[1]) || !ishex(in[2]))
2020 goto end;
2021 *out++ = (hex2i(in[1]) << 4) + hex2i(in[2]);
2022 in += 2;
2023 break;
Willy Tarreau62ba9ba2020-04-23 17:54:47 +02002024 case '?':
2025 in_form = 1;
2026 /* fall through */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002027 default:
2028 *out++ = *in;
2029 break;
2030 }
2031 in++;
2032 }
Thierry FOURNIER5068d962013-10-04 16:27:27 +02002033 ret = out - string; /* success */
Willy Tarreaubf9c2fc2011-05-31 18:06:18 +02002034 end:
2035 *out = 0;
2036 return ret;
2037}
Willy Tarreaubaaee002006-06-26 02:48:02 +02002038
Willy Tarreau6911fa42007-03-04 18:06:08 +01002039unsigned int str2ui(const char *s)
2040{
2041 return __str2ui(s);
2042}
2043
2044unsigned int str2uic(const char *s)
2045{
2046 return __str2uic(s);
2047}
2048
2049unsigned int strl2ui(const char *s, int len)
2050{
2051 return __strl2ui(s, len);
2052}
2053
2054unsigned int strl2uic(const char *s, int len)
2055{
2056 return __strl2uic(s, len);
2057}
2058
Willy Tarreau4ec83cd2010-10-15 23:19:55 +02002059unsigned int read_uint(const char **s, const char *end)
2060{
2061 return __read_uint(s, end);
2062}
2063
Thierry FOURNIER763a5d82015-07-06 23:09:52 +02002064/* This function reads an unsigned integer from the string pointed to by <s> and
2065 * returns it. The <s> pointer is adjusted to point to the first unread char. The
2066 * function automatically stops at <end>. If the number overflows, the 2^64-1
2067 * value is returned.
2068 */
2069unsigned long long int read_uint64(const char **s, const char *end)
2070{
2071 const char *ptr = *s;
2072 unsigned long long int i = 0, tmp;
2073 unsigned int j;
2074
2075 while (ptr < end) {
2076
2077 /* read next char */
2078 j = *ptr - '0';
2079 if (j > 9)
2080 goto read_uint64_end;
2081
2082 /* add char to the number and check overflow. */
2083 tmp = i * 10;
2084 if (tmp / 10 != i) {
2085 i = ULLONG_MAX;
2086 goto read_uint64_eat;
2087 }
2088 if (ULLONG_MAX - tmp < j) {
2089 i = ULLONG_MAX;
2090 goto read_uint64_eat;
2091 }
2092 i = tmp + j;
2093 ptr++;
2094 }
2095read_uint64_eat:
2096 /* eat each numeric char */
2097 while (ptr < end) {
2098 if ((unsigned int)(*ptr - '0') > 9)
2099 break;
2100 ptr++;
2101 }
2102read_uint64_end:
2103 *s = ptr;
2104 return i;
2105}
2106
2107/* This function reads an integer from the string pointed to by <s> and returns
2108 * it. The <s> pointer is adjusted to point to the first unread char. The function
2109 * automatically stops at <end>. Il the number is bigger than 2^63-2, the 2^63-1
2110 * value is returned. If the number is lowest than -2^63-1, the -2^63 value is
2111 * returned.
2112 */
2113long long int read_int64(const char **s, const char *end)
2114{
2115 unsigned long long int i = 0;
2116 int neg = 0;
2117
2118 /* Look for minus char. */
2119 if (**s == '-') {
2120 neg = 1;
2121 (*s)++;
2122 }
2123 else if (**s == '+')
2124 (*s)++;
2125
2126 /* convert as positive number. */
2127 i = read_uint64(s, end);
2128
2129 if (neg) {
2130 if (i > 0x8000000000000000ULL)
2131 return LLONG_MIN;
2132 return -i;
2133 }
2134 if (i > 0x7fffffffffffffffULL)
2135 return LLONG_MAX;
2136 return i;
2137}
2138
Willy Tarreau6911fa42007-03-04 18:06:08 +01002139/* This one is 7 times faster than strtol() on athlon with checks.
2140 * It returns the value of the number composed of all valid digits read,
2141 * and can process negative numbers too.
2142 */
2143int strl2ic(const char *s, int len)
2144{
2145 int i = 0;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002146 int j, k;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002147
2148 if (len > 0) {
2149 if (*s != '-') {
2150 /* positive number */
2151 while (len-- > 0) {
2152 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002153 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002154 if (j > 9)
2155 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002156 i = k + j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002157 }
2158 } else {
2159 /* negative number */
2160 s++;
2161 while (--len > 0) {
2162 j = (*s++) - '0';
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002163 k = i * 10;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002164 if (j > 9)
2165 break;
Willy Tarreau3f0c9762007-10-25 09:42:24 +02002166 i = k - j;
Willy Tarreau6911fa42007-03-04 18:06:08 +01002167 }
2168 }
2169 }
2170 return i;
2171}
2172
2173
2174/* This function reads exactly <len> chars from <s> and converts them to a
2175 * signed integer which it stores into <ret>. It accurately detects any error
2176 * (truncated string, invalid chars, overflows). It is meant to be used in
2177 * applications designed for hostile environments. It returns zero when the
2178 * number has successfully been converted, non-zero otherwise. When an error
2179 * is returned, the <ret> value is left untouched. It is yet 5 to 40 times
2180 * faster than strtol().
2181 */
2182int strl2irc(const char *s, int len, int *ret)
2183{
2184 int i = 0;
2185 int j;
2186
2187 if (!len)
2188 return 1;
2189
2190 if (*s != '-') {
2191 /* positive number */
2192 while (len-- > 0) {
2193 j = (*s++) - '0';
2194 if (j > 9) return 1; /* invalid char */
2195 if (i > INT_MAX / 10) return 1; /* check for multiply overflow */
2196 i = i * 10;
2197 if (i + j < i) return 1; /* check for addition overflow */
2198 i = i + j;
2199 }
2200 } else {
2201 /* negative number */
2202 s++;
2203 while (--len > 0) {
2204 j = (*s++) - '0';
2205 if (j > 9) return 1; /* invalid char */
2206 if (i < INT_MIN / 10) return 1; /* check for multiply overflow */
2207 i = i * 10;
2208 if (i - j > i) return 1; /* check for subtract overflow */
2209 i = i - j;
2210 }
2211 }
2212 *ret = i;
2213 return 0;
2214}
2215
2216
2217/* This function reads exactly <len> chars from <s> and converts them to a
2218 * signed integer which it stores into <ret>. It accurately detects any error
2219 * (truncated string, invalid chars, overflows). It is meant to be used in
2220 * applications designed for hostile environments. It returns zero when the
2221 * number has successfully been converted, non-zero otherwise. When an error
2222 * is returned, the <ret> value is left untouched. It is about 3 times slower
William Dauchy060ffc82021-02-06 20:47:51 +01002223 * than strl2irc().
Willy Tarreau6911fa42007-03-04 18:06:08 +01002224 */
Willy Tarreau6911fa42007-03-04 18:06:08 +01002225
2226int strl2llrc(const char *s, int len, long long *ret)
2227{
2228 long long i = 0;
2229 int j;
2230
2231 if (!len)
2232 return 1;
2233
2234 if (*s != '-') {
2235 /* positive number */
2236 while (len-- > 0) {
2237 j = (*s++) - '0';
2238 if (j > 9) return 1; /* invalid char */
2239 if (i > LLONG_MAX / 10LL) return 1; /* check for multiply overflow */
2240 i = i * 10LL;
2241 if (i + j < i) return 1; /* check for addition overflow */
2242 i = i + j;
2243 }
2244 } else {
2245 /* negative number */
2246 s++;
2247 while (--len > 0) {
2248 j = (*s++) - '0';
2249 if (j > 9) return 1; /* invalid char */
2250 if (i < LLONG_MIN / 10LL) return 1; /* check for multiply overflow */
2251 i = i * 10LL;
2252 if (i - j > i) return 1; /* check for subtract overflow */
2253 i = i - j;
2254 }
2255 }
2256 *ret = i;
2257 return 0;
2258}
2259
Thierry FOURNIER511e9472014-01-23 17:40:34 +01002260/* This function is used with pat_parse_dotted_ver(). It converts a string
2261 * composed by two number separated by a dot. Each part must contain in 16 bits
2262 * because internally they will be represented as a 32-bit quantity stored in
2263 * a 64-bit integer. It returns zero when the number has successfully been
2264 * converted, non-zero otherwise. When an error is returned, the <ret> value
2265 * is left untouched.
2266 *
2267 * "1.3" -> 0x0000000000010003
2268 * "65535.65535" -> 0x00000000ffffffff
2269 */
2270int strl2llrc_dotted(const char *text, int len, long long *ret)
2271{
2272 const char *end = &text[len];
2273 const char *p;
2274 long long major, minor;
2275
2276 /* Look for dot. */
2277 for (p = text; p < end; p++)
2278 if (*p == '.')
2279 break;
2280
2281 /* Convert major. */
2282 if (strl2llrc(text, p - text, &major) != 0)
2283 return 1;
2284
2285 /* Check major. */
2286 if (major >= 65536)
2287 return 1;
2288
2289 /* Convert minor. */
2290 minor = 0;
2291 if (p < end)
2292 if (strl2llrc(p + 1, end - (p + 1), &minor) != 0)
2293 return 1;
2294
2295 /* Check minor. */
2296 if (minor >= 65536)
2297 return 1;
2298
2299 /* Compose value. */
2300 *ret = (major << 16) | (minor & 0xffff);
2301 return 0;
2302}
2303
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002304/* This function parses a time value optionally followed by a unit suffix among
2305 * "d", "h", "m", "s", "ms" or "us". It converts the value into the unit
2306 * expected by the caller. The computation does its best to avoid overflows.
2307 * The value is returned in <ret> if everything is fine, and a NULL is returned
2308 * by the function. In case of error, a pointer to the error is returned and
2309 * <ret> is left untouched. Values are automatically rounded up when needed.
Willy Tarreau9faebe32019-06-07 19:00:37 +02002310 * Values resulting in values larger than or equal to 2^31 after conversion are
2311 * reported as an overflow as value PARSE_TIME_OVER. Non-null values resulting
2312 * in an underflow are reported as an underflow as value PARSE_TIME_UNDER.
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002313 */
2314const char *parse_time_err(const char *text, unsigned *ret, unsigned unit_flags)
2315{
Willy Tarreau9faebe32019-06-07 19:00:37 +02002316 unsigned long long imult, idiv;
2317 unsigned long long omult, odiv;
2318 unsigned long long value, result;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002319 const char *str = text;
2320
2321 if (!isdigit((unsigned char)*text))
2322 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002323
2324 omult = odiv = 1;
2325
2326 switch (unit_flags & TIME_UNIT_MASK) {
2327 case TIME_UNIT_US: omult = 1000000; break;
2328 case TIME_UNIT_MS: omult = 1000; break;
2329 case TIME_UNIT_S: break;
2330 case TIME_UNIT_MIN: odiv = 60; break;
2331 case TIME_UNIT_HOUR: odiv = 3600; break;
2332 case TIME_UNIT_DAY: odiv = 86400; break;
2333 default: break;
2334 }
2335
2336 value = 0;
2337
2338 while (1) {
2339 unsigned int j;
2340
2341 j = *text - '0';
2342 if (j > 9)
2343 break;
2344 text++;
2345 value *= 10;
2346 value += j;
2347 }
2348
2349 imult = idiv = 1;
2350 switch (*text) {
2351 case '\0': /* no unit = default unit */
2352 imult = omult = idiv = odiv = 1;
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002353 goto end;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002354 case 's': /* second = unscaled unit */
2355 break;
2356 case 'u': /* microsecond : "us" */
2357 if (text[1] == 's') {
2358 idiv = 1000000;
2359 text++;
Thayne McCombsa6838052021-04-02 14:12:43 -06002360 break;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002361 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002362 return text;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002363 case 'm': /* millisecond : "ms" or minute: "m" */
2364 if (text[1] == 's') {
2365 idiv = 1000;
2366 text++;
2367 } else
2368 imult = 60;
2369 break;
2370 case 'h': /* hour : "h" */
2371 imult = 3600;
2372 break;
2373 case 'd': /* day : "d" */
2374 imult = 86400;
2375 break;
2376 default:
2377 return text;
2378 break;
2379 }
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002380 if (*(++text) != '\0') {
2381 ha_warning("unexpected character '%c' after the timer value '%s', only "
2382 "(us=microseconds,ms=milliseconds,s=seconds,m=minutes,h=hours,d=days) are supported."
2383 " This will be reported as an error in next versions.\n", *text, str);
2384 }
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002385
Christopher Fauletc20ad0d2020-12-11 09:23:07 +01002386 end:
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002387 if (omult % idiv == 0) { omult /= idiv; idiv = 1; }
2388 if (idiv % omult == 0) { idiv /= omult; omult = 1; }
2389 if (imult % odiv == 0) { imult /= odiv; odiv = 1; }
2390 if (odiv % imult == 0) { odiv /= imult; imult = 1; }
2391
Willy Tarreau9faebe32019-06-07 19:00:37 +02002392 result = (value * (imult * omult) + (idiv * odiv - 1)) / (idiv * odiv);
2393 if (result >= 0x80000000)
2394 return PARSE_TIME_OVER;
2395 if (!result && value)
2396 return PARSE_TIME_UNDER;
2397 *ret = result;
Willy Tarreaua0d37b62007-12-02 22:00:35 +01002398 return NULL;
2399}
Willy Tarreau6911fa42007-03-04 18:06:08 +01002400
Emeric Brun39132b22010-01-04 14:57:24 +01002401/* this function converts the string starting at <text> to an unsigned int
2402 * stored in <ret>. If an error is detected, the pointer to the unexpected
Joseph Herlant32b83272018-11-15 11:58:28 -08002403 * character is returned. If the conversion is successful, NULL is returned.
Emeric Brun39132b22010-01-04 14:57:24 +01002404 */
2405const char *parse_size_err(const char *text, unsigned *ret) {
2406 unsigned value = 0;
2407
Christopher Faulet82635a02020-12-11 09:30:45 +01002408 if (!isdigit((unsigned char)*text))
2409 return text;
2410
Emeric Brun39132b22010-01-04 14:57:24 +01002411 while (1) {
2412 unsigned int j;
2413
2414 j = *text - '0';
2415 if (j > 9)
2416 break;
2417 if (value > ~0U / 10)
2418 return text;
2419 value *= 10;
2420 if (value > (value + j))
2421 return text;
2422 value += j;
2423 text++;
2424 }
2425
2426 switch (*text) {
2427 case '\0':
2428 break;
2429 case 'K':
2430 case 'k':
2431 if (value > ~0U >> 10)
2432 return text;
2433 value = value << 10;
2434 break;
2435 case 'M':
2436 case 'm':
2437 if (value > ~0U >> 20)
2438 return text;
2439 value = value << 20;
2440 break;
2441 case 'G':
2442 case 'g':
2443 if (value > ~0U >> 30)
2444 return text;
2445 value = value << 30;
2446 break;
2447 default:
2448 return text;
2449 }
2450
Godbach58048a22015-01-28 17:36:16 +08002451 if (*text != '\0' && *++text != '\0')
2452 return text;
2453
Emeric Brun39132b22010-01-04 14:57:24 +01002454 *ret = value;
2455 return NULL;
2456}
2457
Willy Tarreau126d4062013-12-03 17:50:47 +01002458/*
2459 * Parse binary string written in hexadecimal (source) and store the decoded
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002460 * result into binstr and set binstrlen to the length of binstr. Memory for
Willy Tarreau126d4062013-12-03 17:50:47 +01002461 * binstr is allocated by the function. In case of error, returns 0 with an
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002462 * error message in err. In success case, it returns the consumed length.
Willy Tarreau126d4062013-12-03 17:50:47 +01002463 */
2464int parse_binary(const char *source, char **binstr, int *binstrlen, char **err)
2465{
2466 int len;
2467 const char *p = source;
2468 int i,j;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002469 int alloc;
Willy Tarreau126d4062013-12-03 17:50:47 +01002470
2471 len = strlen(source);
2472 if (len % 2) {
2473 memprintf(err, "an even number of hex digit is expected");
2474 return 0;
2475 }
2476
2477 len = len >> 1;
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002478
Willy Tarreau126d4062013-12-03 17:50:47 +01002479 if (!*binstr) {
Tim Duesterhuse52b6e52020-09-12 20:26:43 +02002480 *binstr = calloc(len, sizeof(**binstr));
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002481 if (!*binstr) {
2482 memprintf(err, "out of memory while loading string pattern");
2483 return 0;
2484 }
2485 alloc = 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002486 }
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002487 else {
2488 if (*binstrlen < len) {
Joseph Herlant76dbe782018-11-15 12:01:22 -08002489 memprintf(err, "no space available in the buffer. expect %d, provides %d",
Thierry FOURNIER9645d422013-12-06 19:59:28 +01002490 len, *binstrlen);
2491 return 0;
2492 }
2493 alloc = 0;
2494 }
2495 *binstrlen = len;
Willy Tarreau126d4062013-12-03 17:50:47 +01002496
2497 i = j = 0;
2498 while (j < len) {
2499 if (!ishex(p[i++]))
2500 goto bad_input;
2501 if (!ishex(p[i++]))
2502 goto bad_input;
2503 (*binstr)[j++] = (hex2i(p[i-2]) << 4) + hex2i(p[i-1]);
2504 }
Thierry FOURNIERee330af2014-01-21 11:36:14 +01002505 return len << 1;
Willy Tarreau126d4062013-12-03 17:50:47 +01002506
2507bad_input:
2508 memprintf(err, "an hex digit is expected (found '%c')", p[i-1]);
Willy Tarreau61cfdf42021-02-20 10:46:51 +01002509 if (alloc)
2510 ha_free(binstr);
Willy Tarreau126d4062013-12-03 17:50:47 +01002511 return 0;
2512}
2513
Willy Tarreau946ba592009-05-10 15:41:18 +02002514/* copies at most <n> characters from <src> and always terminates with '\0' */
2515char *my_strndup(const char *src, int n)
2516{
2517 int len = 0;
2518 char *ret;
2519
2520 while (len < n && src[len])
2521 len++;
2522
Vincent Bernat3c2f2f22016-04-03 13:48:42 +02002523 ret = malloc(len + 1);
Willy Tarreau946ba592009-05-10 15:41:18 +02002524 if (!ret)
2525 return ret;
2526 memcpy(ret, src, len);
2527 ret[len] = '\0';
2528 return ret;
2529}
2530
Baptiste Assmannbb77c8e2013-10-06 23:24:13 +02002531/*
2532 * search needle in haystack
2533 * returns the pointer if found, returns NULL otherwise
2534 */
2535const void *my_memmem(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen)
2536{
2537 const void *c = NULL;
2538 unsigned char f;
2539
2540 if ((haystack == NULL) || (needle == NULL) || (haystacklen < needlelen))
2541 return NULL;
2542
2543 f = *(char *)needle;
2544 c = haystack;
2545 while ((c = memchr(c, f, haystacklen - (c - haystack))) != NULL) {
2546 if ((haystacklen - (c - haystack)) < needlelen)
2547 return NULL;
2548
2549 if (memcmp(c, needle, needlelen) == 0)
2550 return c;
2551 ++c;
2552 }
2553 return NULL;
2554}
2555
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002556/* get length of the initial segment consisting entirely of bytes in <accept> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002557size_t my_memspn(const void *str, size_t len, const void *accept, size_t acceptlen)
2558{
2559 size_t ret = 0;
2560
2561 while (ret < len && memchr(accept, *((int *)str), acceptlen)) {
2562 str++;
2563 ret++;
2564 }
2565 return ret;
2566}
2567
Ilya Shipitsinc02a23f2020-05-06 00:53:22 +05002568/* get length of the initial segment consisting entirely of bytes not in <rejcet> */
Christopher Faulet5eb96cb2020-04-15 10:23:01 +02002569size_t my_memcspn(const void *str, size_t len, const void *reject, size_t rejectlen)
2570{
2571 size_t ret = 0;
2572
2573 while (ret < len) {
2574 if(memchr(reject, *((int *)str), rejectlen))
2575 return ret;
2576 str++;
2577 ret++;
2578 }
2579 return ret;
2580}
2581
Willy Tarreau482b00d2009-10-04 22:48:42 +02002582/* This function returns the first unused key greater than or equal to <key> in
2583 * ID tree <root>. Zero is returned if no place is found.
2584 */
2585unsigned int get_next_id(struct eb_root *root, unsigned int key)
2586{
2587 struct eb32_node *used;
2588
2589 do {
2590 used = eb32_lookup_ge(root, key);
2591 if (!used || used->key > key)
2592 return key; /* key is available */
2593 key++;
2594 } while (key);
2595 return key;
2596}
2597
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002598/* dump the full tree to <file> in DOT format for debugging purposes. Will
2599 * optionally highlight node <subj> if found, depending on operation <op> :
2600 * 0 : nothing
2601 * >0 : insertion, node/leaf are surrounded in red
2602 * <0 : removal, node/leaf are dashed with no background
2603 * Will optionally add "desc" as a label on the graph if set and non-null.
2604 */
2605void 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 +01002606{
2607 struct eb32sc_node *node;
2608 unsigned long scope = -1;
2609
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002610 fprintf(file, "digraph ebtree {\n");
2611
2612 if (desc && *desc) {
2613 fprintf(file,
2614 " fontname=\"fixed\";\n"
2615 " fontsize=8;\n"
2616 " label=\"%s\";\n", desc);
2617 }
2618
Willy Tarreaued3cda02017-11-15 15:04:05 +01002619 fprintf(file,
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002620 " node [fontname=\"fixed\" fontsize=8 shape=\"box\" style=\"filled\" color=\"black\" fillcolor=\"white\"];\n"
2621 " edge [fontname=\"fixed\" fontsize=8 style=\"solid\" color=\"magenta\" dir=\"forward\"];\n"
Willy Tarreaued3cda02017-11-15 15:04:05 +01002622 " \"%lx_n\" [label=\"root\\n%lx\"]\n", (long)eb_root_to_node(root), (long)root
2623 );
2624
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002625 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002626 (long)eb_root_to_node(root),
2627 (long)eb_root_to_node(eb_clrtag(root->b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002628 eb_gettag(root->b[0]) == EB_LEAF ? 'l' : 'n');
2629
2630 node = eb32sc_first(root, scope);
2631 while (node) {
2632 if (node->node.node_p) {
2633 /* node part is used */
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002634 fprintf(file, " \"%lx_n\" [label=\"%lx\\nkey=%u\\nscope=%lx\\nbit=%d\" fillcolor=\"lightskyblue1\" %s];\n",
2635 (long)node, (long)node, node->key, node->node_s, node->node.bit,
2636 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002637
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002638 fprintf(file, " \"%lx_n\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002639 (long)node,
2640 (long)eb_root_to_node(eb_clrtag(node->node.node_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002641 eb_gettag(node->node.node_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002642
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002643 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"L\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002644 (long)node,
2645 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[0])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002646 eb_gettag(node->node.branches.b[0]) == EB_LEAF ? 'l' : 'n');
2647
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002648 fprintf(file, " \"%lx_n\" -> \"%lx_%c\" [taillabel=\"R\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002649 (long)node,
2650 (long)eb_root_to_node(eb_clrtag(node->node.branches.b[1])),
Willy Tarreaued3cda02017-11-15 15:04:05 +01002651 eb_gettag(node->node.branches.b[1]) == EB_LEAF ? 'l' : 'n');
2652 }
2653
Willy Tarreau9c1e15d2017-11-15 18:51:29 +01002654 fprintf(file, " \"%lx_l\" [label=\"%lx\\nkey=%u\\nscope=%lx\\npfx=%u\" fillcolor=\"yellow\" %s];\n",
2655 (long)node, (long)node, node->key, node->leaf_s, node->node.pfx,
2656 (node == subj) ? (op < 0 ? "color=\"red\" style=\"dashed\"" : op > 0 ? "color=\"red\"" : "") : "");
Willy Tarreaued3cda02017-11-15 15:04:05 +01002657
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002658 fprintf(file, " \"%lx_l\" -> \"%lx_n\" [taillabel=\"%c\"];\n",
Willy Tarreaued3cda02017-11-15 15:04:05 +01002659 (long)node,
2660 (long)eb_root_to_node(eb_clrtag(node->node.leaf_p)),
Willy Tarreau6c7f4de2017-11-15 17:49:54 +01002661 eb_gettag(node->node.leaf_p) ? 'R' : 'L');
Willy Tarreaued3cda02017-11-15 15:04:05 +01002662 node = eb32sc_next(node, scope);
2663 }
2664 fprintf(file, "}\n");
2665}
2666
Willy Tarreau348238b2010-01-18 15:05:57 +01002667/* This function compares a sample word possibly followed by blanks to another
2668 * clean word. The compare is case-insensitive. 1 is returned if both are equal,
2669 * otherwise zero. This intends to be used when checking HTTP headers for some
2670 * values. Note that it validates a word followed only by blanks but does not
2671 * validate a word followed by blanks then other chars.
2672 */
2673int word_match(const char *sample, int slen, const char *word, int wlen)
2674{
2675 if (slen < wlen)
2676 return 0;
2677
2678 while (wlen) {
2679 char c = *sample ^ *word;
2680 if (c && c != ('A' ^ 'a'))
2681 return 0;
2682 sample++;
2683 word++;
2684 slen--;
2685 wlen--;
2686 }
2687
2688 while (slen) {
2689 if (*sample != ' ' && *sample != '\t')
2690 return 0;
2691 sample++;
2692 slen--;
2693 }
2694 return 1;
2695}
Willy Tarreau482b00d2009-10-04 22:48:42 +02002696
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002697/* Converts any text-formatted IPv4 address to a host-order IPv4 address. It
2698 * is particularly fast because it avoids expensive operations such as
2699 * multiplies, which are optimized away at the end. It requires a properly
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05002700 * formatted address though (3 points).
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002701 */
2702unsigned int inetaddr_host(const char *text)
2703{
2704 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2705 register unsigned int dig100, dig10, dig1;
2706 int s;
2707 const char *p, *d;
2708
2709 dig1 = dig10 = dig100 = ascii_zero;
2710 s = 24;
2711
2712 p = text;
2713 while (1) {
2714 if (((unsigned)(*p - '0')) <= 9) {
2715 p++;
2716 continue;
2717 }
2718
2719 /* here, we have a complete byte between <text> and <p> (exclusive) */
2720 if (p == text)
2721 goto end;
2722
2723 d = p - 1;
2724 dig1 |= (unsigned int)(*d << s);
2725 if (d == text)
2726 goto end;
2727
2728 d--;
2729 dig10 |= (unsigned int)(*d << s);
2730 if (d == text)
2731 goto end;
2732
2733 d--;
2734 dig100 |= (unsigned int)(*d << s);
2735 end:
2736 if (!s || *p != '.')
2737 break;
2738
2739 s -= 8;
2740 text = ++p;
2741 }
2742
2743 dig100 -= ascii_zero;
2744 dig10 -= ascii_zero;
2745 dig1 -= ascii_zero;
2746 return ((dig100 * 10) + dig10) * 10 + dig1;
2747}
2748
2749/*
2750 * Idem except the first unparsed character has to be passed in <stop>.
2751 */
2752unsigned int inetaddr_host_lim(const char *text, const char *stop)
2753{
2754 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2755 register unsigned int dig100, dig10, dig1;
2756 int s;
2757 const char *p, *d;
2758
2759 dig1 = dig10 = dig100 = ascii_zero;
2760 s = 24;
2761
2762 p = text;
2763 while (1) {
2764 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2765 p++;
2766 continue;
2767 }
2768
2769 /* here, we have a complete byte between <text> and <p> (exclusive) */
2770 if (p == text)
2771 goto end;
2772
2773 d = p - 1;
2774 dig1 |= (unsigned int)(*d << s);
2775 if (d == text)
2776 goto end;
2777
2778 d--;
2779 dig10 |= (unsigned int)(*d << s);
2780 if (d == text)
2781 goto end;
2782
2783 d--;
2784 dig100 |= (unsigned int)(*d << s);
2785 end:
2786 if (!s || p == stop || *p != '.')
2787 break;
2788
2789 s -= 8;
2790 text = ++p;
2791 }
2792
2793 dig100 -= ascii_zero;
2794 dig10 -= ascii_zero;
2795 dig1 -= ascii_zero;
2796 return ((dig100 * 10) + dig10) * 10 + dig1;
2797}
2798
2799/*
2800 * Idem except the pointer to first unparsed byte is returned into <ret> which
2801 * must not be NULL.
2802 */
Willy Tarreau74172752010-10-15 23:21:42 +02002803unsigned int inetaddr_host_lim_ret(char *text, char *stop, char **ret)
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002804{
2805 const unsigned int ascii_zero = ('0' << 24) | ('0' << 16) | ('0' << 8) | '0';
2806 register unsigned int dig100, dig10, dig1;
2807 int s;
Willy Tarreau74172752010-10-15 23:21:42 +02002808 char *p, *d;
Willy Tarreaud54bbdc2009-09-07 11:00:31 +02002809
2810 dig1 = dig10 = dig100 = ascii_zero;
2811 s = 24;
2812
2813 p = text;
2814 while (1) {
2815 if (((unsigned)(*p - '0')) <= 9 && p < stop) {
2816 p++;
2817 continue;
2818 }
2819
2820 /* here, we have a complete byte between <text> and <p> (exclusive) */
2821 if (p == text)
2822 goto end;
2823
2824 d = p - 1;
2825 dig1 |= (unsigned int)(*d << s);
2826 if (d == text)
2827 goto end;
2828
2829 d--;
2830 dig10 |= (unsigned int)(*d << s);
2831 if (d == text)
2832 goto end;
2833
2834 d--;
2835 dig100 |= (unsigned int)(*d << s);
2836 end:
2837 if (!s || p == stop || *p != '.')
2838 break;
2839
2840 s -= 8;
2841 text = ++p;
2842 }
2843
2844 *ret = p;
2845 dig100 -= ascii_zero;
2846 dig10 -= ascii_zero;
2847 dig1 -= ascii_zero;
2848 return ((dig100 * 10) + dig10) * 10 + dig1;
2849}
2850
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002851/* Convert a fixed-length string to an IP address. Returns 0 in case of error,
2852 * or the number of chars read in case of success. Maybe this could be replaced
2853 * by one of the functions above. Also, apparently this function does not support
2854 * hosts above 255 and requires exactly 4 octets.
Willy Tarreau075415a2013-12-12 11:29:39 +01002855 * The destination is only modified on success.
Willy Tarreauf0b38bf2010-06-06 13:22:23 +02002856 */
2857int buf2ip(const char *buf, size_t len, struct in_addr *dst)
2858{
2859 const char *addr;
2860 int saw_digit, octets, ch;
2861 u_char tmp[4], *tp;
2862 const char *cp = buf;
2863
2864 saw_digit = 0;
2865 octets = 0;
2866 *(tp = tmp) = 0;
2867
2868 for (addr = buf; addr - buf < len; addr++) {
2869 unsigned char digit = (ch = *addr) - '0';
2870
2871 if (digit > 9 && ch != '.')
2872 break;
2873
2874 if (digit <= 9) {
2875 u_int new = *tp * 10 + digit;
2876
2877 if (new > 255)
2878 return 0;
2879
2880 *tp = new;
2881
2882 if (!saw_digit) {
2883 if (++octets > 4)
2884 return 0;
2885 saw_digit = 1;
2886 }
2887 } else if (ch == '.' && saw_digit) {
2888 if (octets == 4)
2889 return 0;
2890
2891 *++tp = 0;
2892 saw_digit = 0;
2893 } else
2894 return 0;
2895 }
2896
2897 if (octets < 4)
2898 return 0;
2899
2900 memcpy(&dst->s_addr, tmp, 4);
2901 return addr - cp;
2902}
2903
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002904/* This function converts the string in <buf> of the len <len> to
2905 * struct in6_addr <dst> which must be allocated by the caller.
2906 * This function returns 1 in success case, otherwise zero.
Willy Tarreau075415a2013-12-12 11:29:39 +01002907 * The destination is only modified on success.
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002908 */
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002909int buf2ip6(const char *buf, size_t len, struct in6_addr *dst)
2910{
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002911 char null_term_ip6[INET6_ADDRSTRLEN + 1];
Willy Tarreau075415a2013-12-12 11:29:39 +01002912 struct in6_addr out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002913
Thierry FOURNIERcd659912013-12-11 12:33:54 +01002914 if (len > INET6_ADDRSTRLEN)
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002915 return 0;
2916
2917 memcpy(null_term_ip6, buf, len);
2918 null_term_ip6[len] = '\0';
2919
Willy Tarreau075415a2013-12-12 11:29:39 +01002920 if (!inet_pton(AF_INET6, null_term_ip6, &out))
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002921 return 0;
2922
Willy Tarreau075415a2013-12-12 11:29:39 +01002923 *dst = out;
Thierry FOURNIERd559dd82013-11-22 16:16:59 +01002924 return 1;
2925}
2926
Willy Tarreauacf95772010-06-14 19:09:21 +02002927/* To be used to quote config arg positions. Returns the short string at <ptr>
2928 * surrounded by simple quotes if <ptr> is valid and non-empty, or "end of line"
2929 * if ptr is NULL or empty. The string is locally allocated.
2930 */
2931const char *quote_arg(const char *ptr)
2932{
Christopher Faulet1bc04c72017-10-29 20:14:08 +01002933 static THREAD_LOCAL char val[32];
Willy Tarreauacf95772010-06-14 19:09:21 +02002934 int i;
2935
2936 if (!ptr || !*ptr)
2937 return "end of line";
2938 val[0] = '\'';
Willy Tarreaude2dd6b2013-01-24 02:14:42 +01002939 for (i = 1; i < sizeof(val) - 2 && *ptr; i++)
Willy Tarreauacf95772010-06-14 19:09:21 +02002940 val[i] = *ptr++;
2941 val[i++] = '\'';
2942 val[i] = '\0';
2943 return val;
2944}
2945
Willy Tarreau5b180202010-07-18 10:40:48 +02002946/* returns an operator among STD_OP_* for string <str> or < 0 if unknown */
2947int get_std_op(const char *str)
2948{
2949 int ret = -1;
2950
2951 if (*str == 'e' && str[1] == 'q')
2952 ret = STD_OP_EQ;
2953 else if (*str == 'n' && str[1] == 'e')
2954 ret = STD_OP_NE;
2955 else if (*str == 'l') {
2956 if (str[1] == 'e') ret = STD_OP_LE;
2957 else if (str[1] == 't') ret = STD_OP_LT;
2958 }
2959 else if (*str == 'g') {
2960 if (str[1] == 'e') ret = STD_OP_GE;
2961 else if (str[1] == 't') ret = STD_OP_GT;
2962 }
2963
2964 if (ret == -1 || str[2] != '\0')
2965 return -1;
2966 return ret;
2967}
2968
Willy Tarreau4c14eaa2010-11-24 14:01:45 +01002969/* hash a 32-bit integer to another 32-bit integer */
2970unsigned int full_hash(unsigned int a)
2971{
2972 return __full_hash(a);
2973}
2974
Willy Tarreauf3241112019-02-26 09:56:22 +01002975/* Return the bit position in mask <m> of the nth bit set of rank <r>, between
2976 * 0 and LONGBITS-1 included, starting from the left. For example ranks 0,1,2,3
2977 * for mask 0x55 will be 6, 4, 2 and 0 respectively. This algorithm is based on
2978 * a popcount variant and is described here :
2979 * https://graphics.stanford.edu/~seander/bithacks.html
2980 */
2981unsigned int mask_find_rank_bit(unsigned int r, unsigned long m)
2982{
2983 unsigned long a, b, c, d;
2984 unsigned int s;
2985 unsigned int t;
2986
2987 a = m - ((m >> 1) & ~0UL/3);
2988 b = (a & ~0UL/5) + ((a >> 2) & ~0UL/5);
2989 c = (b + (b >> 4)) & ~0UL/0x11;
2990 d = (c + (c >> 8)) & ~0UL/0x101;
2991
2992 r++; // make r be 1..64
2993
2994 t = 0;
2995 s = LONGBITS;
2996 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01002997 unsigned long d2 = (d >> 16) >> 16;
2998 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01002999 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3000 }
3001
3002 t = (d >> (s - 16)) & 0xff;
3003 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3004 t = (c >> (s - 8)) & 0xf;
3005 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3006 t = (b >> (s - 4)) & 0x7;
3007 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3008 t = (a >> (s - 2)) & 0x3;
3009 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3010 t = (m >> (s - 1)) & 0x1;
3011 s -= ((t - r) & 256) >> 8;
3012
3013 return s - 1;
3014}
3015
3016/* Same as mask_find_rank_bit() above but makes use of pre-computed bitmaps
3017 * based on <m>, in <a..d>. These ones must be updated whenever <m> changes
3018 * using mask_prep_rank_map() below.
3019 */
3020unsigned int mask_find_rank_bit_fast(unsigned int r, unsigned long m,
3021 unsigned long a, unsigned long b,
3022 unsigned long c, unsigned long d)
3023{
3024 unsigned int s;
3025 unsigned int t;
3026
3027 r++; // make r be 1..64
3028
3029 t = 0;
3030 s = LONGBITS;
3031 if (s > 32) {
Willy Tarreau9b6be3b2019-03-18 16:31:18 +01003032 unsigned long d2 = (d >> 16) >> 16;
3033 t = d2 + (d2 >> 16);
Willy Tarreauf3241112019-02-26 09:56:22 +01003034 s -= ((t - r) & 256) >> 3; r -= (t & ((t - r) >> 8));
3035 }
3036
3037 t = (d >> (s - 16)) & 0xff;
3038 s -= ((t - r) & 256) >> 4; r -= (t & ((t - r) >> 8));
3039 t = (c >> (s - 8)) & 0xf;
3040 s -= ((t - r) & 256) >> 5; r -= (t & ((t - r) >> 8));
3041 t = (b >> (s - 4)) & 0x7;
3042 s -= ((t - r) & 256) >> 6; r -= (t & ((t - r) >> 8));
3043 t = (a >> (s - 2)) & 0x3;
3044 s -= ((t - r) & 256) >> 7; r -= (t & ((t - r) >> 8));
3045 t = (m >> (s - 1)) & 0x1;
3046 s -= ((t - r) & 256) >> 8;
3047
3048 return s - 1;
3049}
3050
3051/* Prepare the bitmaps used by the fast implementation of the find_rank_bit()
3052 * above.
3053 */
3054void mask_prep_rank_map(unsigned long m,
3055 unsigned long *a, unsigned long *b,
3056 unsigned long *c, unsigned long *d)
3057{
3058 *a = m - ((m >> 1) & ~0UL/3);
3059 *b = (*a & ~0UL/5) + ((*a >> 2) & ~0UL/5);
3060 *c = (*b + (*b >> 4)) & ~0UL/0x11;
3061 *d = (*c + (*c >> 8)) & ~0UL/0x101;
3062}
3063
David du Colombier4f92d322011-03-24 11:09:31 +01003064/* Return non-zero if IPv4 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003065 * otherwise zero. Note that <addr> may not necessarily be aligned
3066 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003067 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003068int in_net_ipv4(const void *addr, const struct in_addr *mask, const struct in_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003069{
Willy Tarreaueec1d382016-07-13 11:59:39 +02003070 struct in_addr addr_copy;
3071
3072 memcpy(&addr_copy, addr, sizeof(addr_copy));
3073 return((addr_copy.s_addr & mask->s_addr) == (net->s_addr & mask->s_addr));
David du Colombier4f92d322011-03-24 11:09:31 +01003074}
3075
3076/* Return non-zero if IPv6 address is part of the network,
Willy Tarreaueec1d382016-07-13 11:59:39 +02003077 * otherwise zero. Note that <addr> may not necessarily be aligned
3078 * while the two other ones must.
David du Colombier4f92d322011-03-24 11:09:31 +01003079 */
Willy Tarreaueec1d382016-07-13 11:59:39 +02003080int in_net_ipv6(const void *addr, const struct in6_addr *mask, const struct in6_addr *net)
David du Colombier4f92d322011-03-24 11:09:31 +01003081{
3082 int i;
Willy Tarreaueec1d382016-07-13 11:59:39 +02003083 struct in6_addr addr_copy;
David du Colombier4f92d322011-03-24 11:09:31 +01003084
Willy Tarreaueec1d382016-07-13 11:59:39 +02003085 memcpy(&addr_copy, addr, sizeof(addr_copy));
David du Colombier4f92d322011-03-24 11:09:31 +01003086 for (i = 0; i < sizeof(struct in6_addr) / sizeof(int); i++)
Willy Tarreaueec1d382016-07-13 11:59:39 +02003087 if (((((int *)&addr_copy)[i] & ((int *)mask)[i])) !=
David du Colombier4f92d322011-03-24 11:09:31 +01003088 (((int *)net)[i] & ((int *)mask)[i]))
3089 return 0;
3090 return 1;
3091}
3092
3093/* RFC 4291 prefix */
3094const char rfc4291_pfx[] = { 0x00, 0x00, 0x00, 0x00,
3095 0x00, 0x00, 0x00, 0x00,
3096 0x00, 0x00, 0xFF, 0xFF };
3097
Joseph Herlant32b83272018-11-15 11:58:28 -08003098/* Map IPv4 address on IPv6 address, as specified in RFC 3513.
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003099 * Input and output may overlap.
3100 */
David du Colombier4f92d322011-03-24 11:09:31 +01003101void v4tov6(struct in6_addr *sin6_addr, struct in_addr *sin_addr)
3102{
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003103 struct in_addr tmp_addr;
3104
3105 tmp_addr.s_addr = sin_addr->s_addr;
David du Colombier4f92d322011-03-24 11:09:31 +01003106 memcpy(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx));
Thierry FOURNIER4a04dc32013-11-28 16:33:15 +01003107 memcpy(sin6_addr->s6_addr+12, &tmp_addr.s_addr, 4);
David du Colombier4f92d322011-03-24 11:09:31 +01003108}
3109
Joseph Herlant32b83272018-11-15 11:58:28 -08003110/* Map IPv6 address on IPv4 address, as specified in RFC 3513.
David du Colombier4f92d322011-03-24 11:09:31 +01003111 * Return true if conversion is possible and false otherwise.
3112 */
3113int v6tov4(struct in_addr *sin_addr, struct in6_addr *sin6_addr)
3114{
3115 if (memcmp(sin6_addr->s6_addr, rfc4291_pfx, sizeof(rfc4291_pfx)) == 0) {
3116 memcpy(&(sin_addr->s_addr), &(sin6_addr->s6_addr[12]),
3117 sizeof(struct in_addr));
3118 return 1;
3119 }
3120
3121 return 0;
3122}
3123
Baptiste Assmann08b24cf2016-01-23 23:39:12 +01003124/* compare two struct sockaddr_storage and return:
3125 * 0 (true) if the addr is the same in both
3126 * 1 (false) if the addr is not the same in both
3127 * -1 (unable) if one of the addr is not AF_INET*
3128 */
3129int ipcmp(struct sockaddr_storage *ss1, struct sockaddr_storage *ss2)
3130{
3131 if ((ss1->ss_family != AF_INET) && (ss1->ss_family != AF_INET6))
3132 return -1;
3133
3134 if ((ss2->ss_family != AF_INET) && (ss2->ss_family != AF_INET6))
3135 return -1;
3136
3137 if (ss1->ss_family != ss2->ss_family)
3138 return 1;
3139
3140 switch (ss1->ss_family) {
3141 case AF_INET:
3142 return memcmp(&((struct sockaddr_in *)ss1)->sin_addr,
3143 &((struct sockaddr_in *)ss2)->sin_addr,
3144 sizeof(struct in_addr)) != 0;
3145 case AF_INET6:
3146 return memcmp(&((struct sockaddr_in6 *)ss1)->sin6_addr,
3147 &((struct sockaddr_in6 *)ss2)->sin6_addr,
3148 sizeof(struct in6_addr)) != 0;
3149 }
3150
3151 return 1;
3152}
3153
Christopher Faulet9553de72021-02-26 09:12:50 +01003154/* compare a struct sockaddr_storage to a struct net_addr and return :
3155 * 0 (true) if <addr> is matching <net>
3156 * 1 (false) if <addr> is not matching <net>
3157 * -1 (unable) if <addr> or <net> is not AF_INET*
3158 */
3159int ipcmp2net(const struct sockaddr_storage *addr, const struct net_addr *net)
3160{
3161 if ((addr->ss_family != AF_INET) && (addr->ss_family != AF_INET6))
3162 return -1;
3163
3164 if ((net->family != AF_INET) && (net->family != AF_INET6))
3165 return -1;
3166
3167 if (addr->ss_family != net->family)
3168 return 1;
3169
3170 if (addr->ss_family == AF_INET &&
3171 (((struct sockaddr_in *)addr)->sin_addr.s_addr & net->addr.v4.mask.s_addr) == net->addr.v4.ip.s_addr)
3172 return 0;
3173 else {
3174 const struct in6_addr *addr6 = &(((const struct sockaddr_in6*)addr)->sin6_addr);
3175 const struct in6_addr *nip6 = &net->addr.v6.ip;
3176 const struct in6_addr *nmask6 = &net->addr.v6.mask;
3177
3178 if ((read_u32(&addr6->s6_addr[0]) & read_u32(&nmask6->s6_addr[0])) == read_u32(&nip6->s6_addr[0]) &&
3179 (read_u32(&addr6->s6_addr[4]) & read_u32(&nmask6->s6_addr[4])) == read_u32(&nip6->s6_addr[4]) &&
3180 (read_u32(&addr6->s6_addr[8]) & read_u32(&nmask6->s6_addr[8])) == read_u32(&nip6->s6_addr[8]) &&
3181 (read_u32(&addr6->s6_addr[12]) & read_u32(&nmask6->s6_addr[12])) == read_u32(&nip6->s6_addr[12]))
3182 return 0;
3183 }
3184
3185 return 1;
3186}
3187
Baptiste Assmann08396c82016-01-31 00:27:17 +01003188/* copy IP address from <source> into <dest>
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003189 * The caller must allocate and clear <dest> before calling.
3190 * The source must be in either AF_INET or AF_INET6 family, or the destination
3191 * address will be undefined. If the destination address used to hold a port,
3192 * it is preserved, so that this function can be used to switch to another
3193 * address family with no risk. Returns a pointer to the destination.
Baptiste Assmann08396c82016-01-31 00:27:17 +01003194 */
3195struct sockaddr_storage *ipcpy(struct sockaddr_storage *source, struct sockaddr_storage *dest)
3196{
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003197 int prev_port;
3198
3199 prev_port = get_net_port(dest);
3200 memset(dest, 0, sizeof(*dest));
Baptiste Assmann08396c82016-01-31 00:27:17 +01003201 dest->ss_family = source->ss_family;
3202
3203 /* copy new addr and apply it */
3204 switch (source->ss_family) {
3205 case AF_INET:
3206 ((struct sockaddr_in *)dest)->sin_addr.s_addr = ((struct sockaddr_in *)source)->sin_addr.s_addr;
Willy Tarreaudc3a9e82016-11-04 18:47:01 +01003207 ((struct sockaddr_in *)dest)->sin_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003208 break;
3209 case AF_INET6:
3210 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 +01003211 ((struct sockaddr_in6 *)dest)->sin6_port = prev_port;
Baptiste Assmann08396c82016-01-31 00:27:17 +01003212 break;
3213 }
3214
3215 return dest;
3216}
3217
William Lallemand421f5b52012-02-06 18:15:57 +01003218char *human_time(int t, short hz_div) {
3219 static char rv[sizeof("24855d23h")+1]; // longest of "23h59m" and "59m59s"
3220 char *p = rv;
Willy Tarreau761b3d52014-04-14 14:53:06 +02003221 char *end = rv + sizeof(rv);
William Lallemand421f5b52012-02-06 18:15:57 +01003222 int cnt=2; // print two numbers
3223
3224 if (unlikely(t < 0 || hz_div <= 0)) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003225 snprintf(p, end - p, "?");
William Lallemand421f5b52012-02-06 18:15:57 +01003226 return rv;
3227 }
3228
3229 if (unlikely(hz_div > 1))
3230 t /= hz_div;
3231
3232 if (t >= DAY) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003233 p += snprintf(p, end - p, "%dd", t / DAY);
William Lallemand421f5b52012-02-06 18:15:57 +01003234 cnt--;
3235 }
3236
3237 if (cnt && t % DAY / HOUR) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003238 p += snprintf(p, end - p, "%dh", t % DAY / HOUR);
William Lallemand421f5b52012-02-06 18:15:57 +01003239 cnt--;
3240 }
3241
3242 if (cnt && t % HOUR / MINUTE) {
Willy Tarreau761b3d52014-04-14 14:53:06 +02003243 p += snprintf(p, end - p, "%dm", t % HOUR / MINUTE);
William Lallemand421f5b52012-02-06 18:15:57 +01003244 cnt--;
3245 }
3246
3247 if ((cnt && t % MINUTE) || !t) // also display '0s'
Willy Tarreau761b3d52014-04-14 14:53:06 +02003248 p += snprintf(p, end - p, "%ds", t % MINUTE / SEC);
William Lallemand421f5b52012-02-06 18:15:57 +01003249
3250 return rv;
3251}
3252
3253const char *monthname[12] = {
3254 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
3255 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
3256};
3257
3258/* date2str_log: write a date in the format :
3259 * sprintf(str, "%02d/%s/%04d:%02d:%02d:%02d.%03d",
3260 * tm.tm_mday, monthname[tm.tm_mon], tm.tm_year+1900,
3261 * tm.tm_hour, tm.tm_min, tm.tm_sec, (int)date.tv_usec/1000);
3262 *
3263 * without using sprintf. return a pointer to the last char written (\0) or
3264 * NULL if there isn't enough space.
3265 */
Willy Tarreauf16cb412018-09-04 19:08:48 +02003266char *date2str_log(char *dst, const struct tm *tm, const struct timeval *date, size_t size)
William Lallemand421f5b52012-02-06 18:15:57 +01003267{
3268
3269 if (size < 25) /* the size is fixed: 24 chars + \0 */
3270 return NULL;
3271
3272 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003273 if (!dst)
3274 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003275 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003276
William Lallemand421f5b52012-02-06 18:15:57 +01003277 memcpy(dst, monthname[tm->tm_mon], 3); // month
3278 dst += 3;
3279 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003280
William Lallemand421f5b52012-02-06 18:15:57 +01003281 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003282 if (!dst)
3283 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003284 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003285
William Lallemand421f5b52012-02-06 18:15:57 +01003286 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003287 if (!dst)
3288 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003289 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003290
William Lallemand421f5b52012-02-06 18:15:57 +01003291 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003292 if (!dst)
3293 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003294 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003295
William Lallemand421f5b52012-02-06 18:15:57 +01003296 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003297 if (!dst)
3298 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003299 *dst++ = '.';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003300
Willy Tarreau7d9421d2020-02-29 09:08:02 +01003301 dst = utoa_pad((unsigned int)(date->tv_usec/1000)%1000, dst, 4); // milliseconds
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003302 if (!dst)
3303 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003304 *dst = '\0';
3305
3306 return dst;
3307}
3308
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003309/* Base year used to compute leap years */
3310#define TM_YEAR_BASE 1900
3311
3312/* Return the difference in seconds between two times (leap seconds are ignored).
3313 * Retrieved from glibc 2.18 source code.
3314 */
3315static int my_tm_diff(const struct tm *a, const struct tm *b)
3316{
3317 /* Compute intervening leap days correctly even if year is negative.
3318 * Take care to avoid int overflow in leap day calculations,
3319 * but it's OK to assume that A and B are close to each other.
3320 */
3321 int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
3322 int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
3323 int a100 = a4 / 25 - (a4 % 25 < 0);
3324 int b100 = b4 / 25 - (b4 % 25 < 0);
3325 int a400 = a100 >> 2;
3326 int b400 = b100 >> 2;
3327 int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
3328 int years = a->tm_year - b->tm_year;
3329 int days = (365 * years + intervening_leap_days
3330 + (a->tm_yday - b->tm_yday));
3331 return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
3332 + (a->tm_min - b->tm_min))
3333 + (a->tm_sec - b->tm_sec));
3334}
3335
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003336/* Return the GMT offset for a specific local time.
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003337 * Both t and tm must represent the same time.
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003338 * The string returned has the same format as returned by strftime(... "%z", tm).
3339 * Offsets are kept in an internal cache for better performances.
3340 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003341const char *get_gmt_offset(time_t t, struct tm *tm)
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003342{
3343 /* Cache offsets from GMT (depending on whether DST is active or not) */
Christopher Faulet1bc04c72017-10-29 20:14:08 +01003344 static THREAD_LOCAL char gmt_offsets[2][5+1] = { "", "" };
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003345
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003346 char *gmt_offset;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003347 struct tm tm_gmt;
3348 int diff;
3349 int isdst = tm->tm_isdst;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003350
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003351 /* Pretend DST not active if its status is unknown */
3352 if (isdst < 0)
3353 isdst = 0;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003354
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003355 /* Fetch the offset and initialize it if needed */
3356 gmt_offset = gmt_offsets[isdst & 0x01];
3357 if (unlikely(!*gmt_offset)) {
3358 get_gmtime(t, &tm_gmt);
3359 diff = my_tm_diff(tm, &tm_gmt);
3360 if (diff < 0) {
3361 diff = -diff;
3362 *gmt_offset = '-';
3363 } else {
3364 *gmt_offset = '+';
3365 }
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003366 diff %= 86400U;
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003367 diff /= 60; /* Convert to minutes */
3368 snprintf(gmt_offset+1, 4+1, "%02d%02d", diff/60, diff%60);
3369 }
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003370
Willy Tarreaue112c8a2019-10-29 10:16:11 +01003371 return gmt_offset;
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003372}
3373
William Lallemand421f5b52012-02-06 18:15:57 +01003374/* gmt2str_log: write a date in the format :
3375 * "%02d/%s/%04d:%02d:%02d:%02d +0000" without using snprintf
3376 * return a pointer to the last char written (\0) or
3377 * NULL if there isn't enough space.
3378 */
3379char *gmt2str_log(char *dst, struct tm *tm, size_t size)
3380{
Yuxans Yao4e25b012012-10-19 10:36:09 +08003381 if (size < 27) /* the size is fixed: 26 chars + \0 */
William Lallemand421f5b52012-02-06 18:15:57 +01003382 return NULL;
3383
3384 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003385 if (!dst)
3386 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003387 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003388
William Lallemand421f5b52012-02-06 18:15:57 +01003389 memcpy(dst, monthname[tm->tm_mon], 3); // month
3390 dst += 3;
3391 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003392
William Lallemand421f5b52012-02-06 18:15:57 +01003393 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003394 if (!dst)
3395 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003396 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003397
William Lallemand421f5b52012-02-06 18:15:57 +01003398 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003399 if (!dst)
3400 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003401 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003402
William Lallemand421f5b52012-02-06 18:15:57 +01003403 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003404 if (!dst)
3405 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003406 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003407
William Lallemand421f5b52012-02-06 18:15:57 +01003408 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003409 if (!dst)
3410 return NULL;
William Lallemand421f5b52012-02-06 18:15:57 +01003411 *dst++ = ' ';
3412 *dst++ = '+';
3413 *dst++ = '0';
3414 *dst++ = '0';
3415 *dst++ = '0';
3416 *dst++ = '0';
3417 *dst = '\0';
3418
3419 return dst;
3420}
3421
Yuxans Yao4e25b012012-10-19 10:36:09 +08003422/* localdate2str_log: write a date in the format :
3423 * "%02d/%s/%04d:%02d:%02d:%02d +0000(local timezone)" without using snprintf
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003424 * Both t and tm must represent the same time.
3425 * return a pointer to the last char written (\0) or
3426 * NULL if there isn't enough space.
Yuxans Yao4e25b012012-10-19 10:36:09 +08003427 */
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003428char *localdate2str_log(char *dst, time_t t, struct tm *tm, size_t size)
Yuxans Yao4e25b012012-10-19 10:36:09 +08003429{
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003430 const char *gmt_offset;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003431 if (size < 27) /* the size is fixed: 26 chars + \0 */
3432 return NULL;
3433
Benoit GARNIERe2e5bde2016-03-27 03:04:16 +02003434 gmt_offset = get_gmt_offset(t, tm);
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003435
Yuxans Yao4e25b012012-10-19 10:36:09 +08003436 dst = utoa_pad((unsigned int)tm->tm_mday, dst, 3); // day
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003437 if (!dst)
3438 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003439 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003440
Yuxans Yao4e25b012012-10-19 10:36:09 +08003441 memcpy(dst, monthname[tm->tm_mon], 3); // month
3442 dst += 3;
3443 *dst++ = '/';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003444
Yuxans Yao4e25b012012-10-19 10:36:09 +08003445 dst = utoa_pad((unsigned int)tm->tm_year+1900, dst, 5); // year
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003446 if (!dst)
3447 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003448 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003449
Yuxans Yao4e25b012012-10-19 10:36:09 +08003450 dst = utoa_pad((unsigned int)tm->tm_hour, dst, 3); // hour
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003451 if (!dst)
3452 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003453 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003454
Yuxans Yao4e25b012012-10-19 10:36:09 +08003455 dst = utoa_pad((unsigned int)tm->tm_min, dst, 3); // minutes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003456 if (!dst)
3457 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003458 *dst++ = ':';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003459
Yuxans Yao4e25b012012-10-19 10:36:09 +08003460 dst = utoa_pad((unsigned int)tm->tm_sec, dst, 3); // secondes
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003461 if (!dst)
3462 return NULL;
Yuxans Yao4e25b012012-10-19 10:36:09 +08003463 *dst++ = ' ';
Willy Tarreau4eee38a2019-02-12 11:26:29 +01003464
Benoit GARNIERb413c2a2016-03-27 11:08:03 +02003465 memcpy(dst, gmt_offset, 5); // Offset from local time to GMT
Yuxans Yao4e25b012012-10-19 10:36:09 +08003466 dst += 5;
3467 *dst = '\0';
3468
3469 return dst;
3470}
3471
Willy Tarreaucb1949b2017-07-19 19:05:29 +02003472/* Returns the number of seconds since 01/01/1970 0:0:0 GMT for GMT date <tm>.
3473 * It is meant as a portable replacement for timegm() for use with valid inputs.
3474 * Returns undefined results for invalid dates (eg: months out of range 0..11).
3475 */
3476time_t my_timegm(const struct tm *tm)
3477{
3478 /* Each month has 28, 29, 30 or 31 days, or 28+N. The date in the year
3479 * is thus (current month - 1)*28 + cumulated_N[month] to count the
3480 * sum of the extra N days for elapsed months. The sum of all these N
3481 * days doesn't exceed 30 for a complete year (366-12*28) so it fits
3482 * in a 5-bit word. This means that with 60 bits we can represent a
3483 * matrix of all these values at once, which is fast and efficient to
3484 * access. The extra February day for leap years is not counted here.
3485 *
3486 * Jan : none = 0 (0)
3487 * Feb : Jan = 3 (3)
3488 * Mar : Jan..Feb = 3 (3 + 0)
3489 * Apr : Jan..Mar = 6 (3 + 0 + 3)
3490 * May : Jan..Apr = 8 (3 + 0 + 3 + 2)
3491 * Jun : Jan..May = 11 (3 + 0 + 3 + 2 + 3)
3492 * Jul : Jan..Jun = 13 (3 + 0 + 3 + 2 + 3 + 2)
3493 * Aug : Jan..Jul = 16 (3 + 0 + 3 + 2 + 3 + 2 + 3)
3494 * Sep : Jan..Aug = 19 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3)
3495 * Oct : Jan..Sep = 21 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2)
3496 * Nov : Jan..Oct = 24 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3)
3497 * Dec : Jan..Nov = 26 (3 + 0 + 3 + 2 + 3 + 2 + 3 + 3 + 2 + 3 + 2)
3498 */
3499 uint64_t extra =
3500 ( 0ULL << 0*5) + ( 3ULL << 1*5) + ( 3ULL << 2*5) + /* Jan, Feb, Mar, */
3501 ( 6ULL << 3*5) + ( 8ULL << 4*5) + (11ULL << 5*5) + /* Apr, May, Jun, */
3502 (13ULL << 6*5) + (16ULL << 7*5) + (19ULL << 8*5) + /* Jul, Aug, Sep, */
3503 (21ULL << 9*5) + (24ULL << 10*5) + (26ULL << 11*5); /* Oct, Nov, Dec, */
3504
3505 unsigned int y = tm->tm_year + 1900;
3506 unsigned int m = tm->tm_mon;
3507 unsigned long days = 0;
3508
3509 /* days since 1/1/1970 for full years */
3510 days += days_since_zero(y) - days_since_zero(1970);
3511
3512 /* days for full months in the current year */
3513 days += 28 * m + ((extra >> (m * 5)) & 0x1f);
3514
3515 /* count + 1 after March for leap years. A leap year is a year multiple
3516 * of 4, unless it's multiple of 100 without being multiple of 400. 2000
3517 * is leap, 1900 isn't, 1904 is.
3518 */
3519 if ((m > 1) && !(y & 3) && ((y % 100) || !(y % 400)))
3520 days++;
3521
3522 days += tm->tm_mday - 1;
3523 return days * 86400ULL + tm->tm_hour * 3600 + tm->tm_min * 60 + tm->tm_sec;
3524}
3525
Thierry Fournier93127942016-01-20 18:49:45 +01003526/* This function check a char. It returns true and updates
3527 * <date> and <len> pointer to the new position if the
3528 * character is found.
3529 */
3530static inline int parse_expect_char(const char **date, int *len, char c)
3531{
3532 if (*len < 1 || **date != c)
3533 return 0;
3534 (*len)--;
3535 (*date)++;
3536 return 1;
3537}
3538
3539/* This function expects a string <str> of len <l>. It return true and updates.
3540 * <date> and <len> if the string matches, otherwise, it returns false.
3541 */
3542static inline int parse_strcmp(const char **date, int *len, char *str, int l)
3543{
3544 if (*len < l || strncmp(*date, str, l) != 0)
3545 return 0;
3546 (*len) -= l;
3547 (*date) += l;
3548 return 1;
3549}
3550
3551/* This macro converts 3 chars name in integer. */
3552#define STR2I3(__a, __b, __c) ((__a) * 65536 + (__b) * 256 + (__c))
3553
3554/* day-name = %x4D.6F.6E ; "Mon", case-sensitive
3555 * / %x54.75.65 ; "Tue", case-sensitive
3556 * / %x57.65.64 ; "Wed", case-sensitive
3557 * / %x54.68.75 ; "Thu", case-sensitive
3558 * / %x46.72.69 ; "Fri", case-sensitive
3559 * / %x53.61.74 ; "Sat", case-sensitive
3560 * / %x53.75.6E ; "Sun", case-sensitive
3561 *
3562 * This array must be alphabetically sorted
3563 */
3564static inline int parse_http_dayname(const char **date, int *len, struct tm *tm)
3565{
3566 if (*len < 3)
3567 return 0;
3568 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3569 case STR2I3('M','o','n'): tm->tm_wday = 1; break;
3570 case STR2I3('T','u','e'): tm->tm_wday = 2; break;
3571 case STR2I3('W','e','d'): tm->tm_wday = 3; break;
3572 case STR2I3('T','h','u'): tm->tm_wday = 4; break;
3573 case STR2I3('F','r','i'): tm->tm_wday = 5; break;
3574 case STR2I3('S','a','t'): tm->tm_wday = 6; break;
3575 case STR2I3('S','u','n'): tm->tm_wday = 7; break;
3576 default: return 0;
3577 }
3578 *len -= 3;
3579 *date += 3;
3580 return 1;
3581}
3582
3583/* month = %x4A.61.6E ; "Jan", case-sensitive
3584 * / %x46.65.62 ; "Feb", case-sensitive
3585 * / %x4D.61.72 ; "Mar", case-sensitive
3586 * / %x41.70.72 ; "Apr", case-sensitive
3587 * / %x4D.61.79 ; "May", case-sensitive
3588 * / %x4A.75.6E ; "Jun", case-sensitive
3589 * / %x4A.75.6C ; "Jul", case-sensitive
3590 * / %x41.75.67 ; "Aug", case-sensitive
3591 * / %x53.65.70 ; "Sep", case-sensitive
3592 * / %x4F.63.74 ; "Oct", case-sensitive
3593 * / %x4E.6F.76 ; "Nov", case-sensitive
3594 * / %x44.65.63 ; "Dec", case-sensitive
3595 *
3596 * This array must be alphabetically sorted
3597 */
3598static inline int parse_http_monthname(const char **date, int *len, struct tm *tm)
3599{
3600 if (*len < 3)
3601 return 0;
3602 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3603 case STR2I3('J','a','n'): tm->tm_mon = 0; break;
3604 case STR2I3('F','e','b'): tm->tm_mon = 1; break;
3605 case STR2I3('M','a','r'): tm->tm_mon = 2; break;
3606 case STR2I3('A','p','r'): tm->tm_mon = 3; break;
3607 case STR2I3('M','a','y'): tm->tm_mon = 4; break;
3608 case STR2I3('J','u','n'): tm->tm_mon = 5; break;
3609 case STR2I3('J','u','l'): tm->tm_mon = 6; break;
3610 case STR2I3('A','u','g'): tm->tm_mon = 7; break;
3611 case STR2I3('S','e','p'): tm->tm_mon = 8; break;
3612 case STR2I3('O','c','t'): tm->tm_mon = 9; break;
3613 case STR2I3('N','o','v'): tm->tm_mon = 10; break;
3614 case STR2I3('D','e','c'): tm->tm_mon = 11; break;
3615 default: return 0;
3616 }
3617 *len -= 3;
3618 *date += 3;
3619 return 1;
3620}
3621
3622/* day-name-l = %x4D.6F.6E.64.61.79 ; "Monday", case-sensitive
3623 * / %x54.75.65.73.64.61.79 ; "Tuesday", case-sensitive
3624 * / %x57.65.64.6E.65.73.64.61.79 ; "Wednesday", case-sensitive
3625 * / %x54.68.75.72.73.64.61.79 ; "Thursday", case-sensitive
3626 * / %x46.72.69.64.61.79 ; "Friday", case-sensitive
3627 * / %x53.61.74.75.72.64.61.79 ; "Saturday", case-sensitive
3628 * / %x53.75.6E.64.61.79 ; "Sunday", case-sensitive
3629 *
3630 * This array must be alphabetically sorted
3631 */
3632static inline int parse_http_ldayname(const char **date, int *len, struct tm *tm)
3633{
3634 if (*len < 6) /* Minimum length. */
3635 return 0;
3636 switch (STR2I3((*date)[0], (*date)[1], (*date)[2])) {
3637 case STR2I3('M','o','n'):
3638 RET0_UNLESS(parse_strcmp(date, len, "Monday", 6));
3639 tm->tm_wday = 1;
3640 return 1;
3641 case STR2I3('T','u','e'):
3642 RET0_UNLESS(parse_strcmp(date, len, "Tuesday", 7));
3643 tm->tm_wday = 2;
3644 return 1;
3645 case STR2I3('W','e','d'):
3646 RET0_UNLESS(parse_strcmp(date, len, "Wednesday", 9));
3647 tm->tm_wday = 3;
3648 return 1;
3649 case STR2I3('T','h','u'):
3650 RET0_UNLESS(parse_strcmp(date, len, "Thursday", 8));
3651 tm->tm_wday = 4;
3652 return 1;
3653 case STR2I3('F','r','i'):
3654 RET0_UNLESS(parse_strcmp(date, len, "Friday", 6));
3655 tm->tm_wday = 5;
3656 return 1;
3657 case STR2I3('S','a','t'):
3658 RET0_UNLESS(parse_strcmp(date, len, "Saturday", 8));
3659 tm->tm_wday = 6;
3660 return 1;
3661 case STR2I3('S','u','n'):
3662 RET0_UNLESS(parse_strcmp(date, len, "Sunday", 6));
3663 tm->tm_wday = 7;
3664 return 1;
3665 }
3666 return 0;
3667}
3668
3669/* This function parses exactly 1 digit and returns the numeric value in "digit". */
3670static inline int parse_digit(const char **date, int *len, int *digit)
3671{
3672 if (*len < 1 || **date < '0' || **date > '9')
3673 return 0;
3674 *digit = (**date - '0');
3675 (*date)++;
3676 (*len)--;
3677 return 1;
3678}
3679
3680/* This function parses exactly 2 digits and returns the numeric value in "digit". */
3681static inline int parse_2digit(const char **date, int *len, int *digit)
3682{
3683 int value;
3684
3685 RET0_UNLESS(parse_digit(date, len, &value));
3686 (*digit) = value * 10;
3687 RET0_UNLESS(parse_digit(date, len, &value));
3688 (*digit) += value;
3689
3690 return 1;
3691}
3692
3693/* This function parses exactly 4 digits and returns the numeric value in "digit". */
3694static inline int parse_4digit(const char **date, int *len, int *digit)
3695{
3696 int value;
3697
3698 RET0_UNLESS(parse_digit(date, len, &value));
3699 (*digit) = value * 1000;
3700
3701 RET0_UNLESS(parse_digit(date, len, &value));
3702 (*digit) += value * 100;
3703
3704 RET0_UNLESS(parse_digit(date, len, &value));
3705 (*digit) += value * 10;
3706
3707 RET0_UNLESS(parse_digit(date, len, &value));
3708 (*digit) += value;
3709
3710 return 1;
3711}
3712
3713/* time-of-day = hour ":" minute ":" second
3714 * ; 00:00:00 - 23:59:60 (leap second)
3715 *
3716 * hour = 2DIGIT
3717 * minute = 2DIGIT
3718 * second = 2DIGIT
3719 */
3720static inline int parse_http_time(const char **date, int *len, struct tm *tm)
3721{
3722 RET0_UNLESS(parse_2digit(date, len, &tm->tm_hour)); /* hour 2DIGIT */
3723 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3724 RET0_UNLESS(parse_2digit(date, len, &tm->tm_min)); /* min 2DIGIT */
3725 RET0_UNLESS(parse_expect_char(date, len, ':')); /* expect ":" */
3726 RET0_UNLESS(parse_2digit(date, len, &tm->tm_sec)); /* sec 2DIGIT */
3727 return 1;
3728}
3729
3730/* From RFC7231
3731 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3732 *
3733 * IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT
3734 * ; fixed length/zone/capitalization subset of the format
3735 * ; see Section 3.3 of [RFC5322]
3736 *
3737 *
3738 * date1 = day SP month SP year
3739 * ; e.g., 02 Jun 1982
3740 *
3741 * day = 2DIGIT
3742 * year = 4DIGIT
3743 *
3744 * GMT = %x47.4D.54 ; "GMT", case-sensitive
3745 *
3746 * time-of-day = hour ":" minute ":" second
3747 * ; 00:00:00 - 23:59:60 (leap second)
3748 *
3749 * hour = 2DIGIT
3750 * minute = 2DIGIT
3751 * second = 2DIGIT
3752 *
3753 * DIGIT = decimal 0-9
3754 */
3755int parse_imf_date(const char *date, int len, struct tm *tm)
3756{
David Carlier327298c2016-11-20 10:42:38 +00003757 /* tm_gmtoff, if present, ought to be zero'ed */
3758 memset(tm, 0, sizeof(*tm));
3759
Thierry Fournier93127942016-01-20 18:49:45 +01003760 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3761 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3762 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3763 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3764 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3765 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3766 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3767 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3768 tm->tm_year -= 1900;
3769 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3770 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3771 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3772 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3773 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003774 return 1;
3775}
3776
3777/* From RFC7231
3778 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3779 *
3780 * rfc850-date = day-name-l "," SP date2 SP time-of-day SP GMT
3781 * date2 = day "-" month "-" 2DIGIT
3782 * ; e.g., 02-Jun-82
3783 *
3784 * day = 2DIGIT
3785 */
3786int parse_rfc850_date(const char *date, int len, struct tm *tm)
3787{
3788 int year;
3789
David Carlier327298c2016-11-20 10:42:38 +00003790 /* tm_gmtoff, if present, ought to be zero'ed */
3791 memset(tm, 0, sizeof(*tm));
3792
Thierry Fournier93127942016-01-20 18:49:45 +01003793 RET0_UNLESS(parse_http_ldayname(&date, &len, tm)); /* Read the day name */
3794 RET0_UNLESS(parse_expect_char(&date, &len, ',')); /* expect "," */
3795 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3796 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday)); /* day 2DIGIT */
3797 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3798 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* Month */
3799 RET0_UNLESS(parse_expect_char(&date, &len, '-')); /* expect "-" */
3800
3801 /* year = 2DIGIT
3802 *
3803 * Recipients of a timestamp value in rfc850-(*date) format, which uses a
3804 * two-digit year, MUST interpret a timestamp that appears to be more
3805 * than 50 years in the future as representing the most recent year in
3806 * the past that had the same last two digits.
3807 */
3808 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_year));
3809
3810 /* expect SP */
3811 if (!parse_expect_char(&date, &len, ' ')) {
3812 /* Maybe we have the date with 4 digits. */
3813 RET0_UNLESS(parse_2digit(&date, &len, &year));
3814 tm->tm_year = (tm->tm_year * 100 + year) - 1900;
3815 /* expect SP */
3816 RET0_UNLESS(parse_expect_char(&date, &len, ' '));
3817 } else {
3818 /* I fix 60 as pivot: >60: +1900, <60: +2000. Note that the
3819 * tm_year is the number of year since 1900, so for +1900, we
3820 * do nothing, and for +2000, we add 100.
3821 */
3822 if (tm->tm_year <= 60)
3823 tm->tm_year += 100;
3824 }
3825
3826 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3827 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3828 RET0_UNLESS(parse_strcmp(&date, &len, "GMT", 3)); /* GMT = %x47.4D.54 ; "GMT", case-sensitive */
3829 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003830
3831 return 1;
3832}
3833
3834/* From RFC7231
3835 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3836 *
3837 * asctime-date = day-name SP date3 SP time-of-day SP year
3838 * date3 = month SP ( 2DIGIT / ( SP 1DIGIT ))
3839 * ; e.g., Jun 2
3840 *
3841 * HTTP-date is case sensitive. A sender MUST NOT generate additional
3842 * whitespace in an HTTP-date beyond that specifically included as SP in
3843 * the grammar.
3844 */
3845int parse_asctime_date(const char *date, int len, struct tm *tm)
3846{
David Carlier327298c2016-11-20 10:42:38 +00003847 /* tm_gmtoff, if present, ought to be zero'ed */
3848 memset(tm, 0, sizeof(*tm));
3849
Thierry Fournier93127942016-01-20 18:49:45 +01003850 RET0_UNLESS(parse_http_dayname(&date, &len, tm)); /* day-name */
3851 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3852 RET0_UNLESS(parse_http_monthname(&date, &len, tm)); /* expect month */
3853 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3854
3855 /* expect SP and 1DIGIT or 2DIGIT */
3856 if (parse_expect_char(&date, &len, ' '))
3857 RET0_UNLESS(parse_digit(&date, &len, &tm->tm_mday));
3858 else
3859 RET0_UNLESS(parse_2digit(&date, &len, &tm->tm_mday));
3860
3861 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3862 RET0_UNLESS(parse_http_time(&date, &len, tm)); /* Parse time. */
3863 RET0_UNLESS(parse_expect_char(&date, &len, ' ')); /* expect SP */
3864 RET0_UNLESS(parse_4digit(&date, &len, &tm->tm_year)); /* year = 4DIGIT */
3865 tm->tm_year -= 1900;
3866 tm->tm_isdst = -1;
Thierry Fournier93127942016-01-20 18:49:45 +01003867 return 1;
3868}
3869
3870/* From RFC7231
3871 * https://tools.ietf.org/html/rfc7231#section-7.1.1.1
3872 *
3873 * HTTP-date = IMF-fixdate / obs-date
3874 * obs-date = rfc850-date / asctime-date
3875 *
3876 * parses an HTTP date in the RFC format and is accepted
3877 * alternatives. <date> is the strinf containing the date,
3878 * len is the len of the string. <tm> is filled with the
3879 * parsed time. We must considers this time as GMT.
3880 */
3881int parse_http_date(const char *date, int len, struct tm *tm)
3882{
3883 if (parse_imf_date(date, len, tm))
3884 return 1;
3885
3886 if (parse_rfc850_date(date, len, tm))
3887 return 1;
3888
3889 if (parse_asctime_date(date, len, tm))
3890 return 1;
3891
3892 return 0;
3893}
3894
Willy Tarreau4deeb102021-01-29 10:47:52 +01003895/* print the time <ns> in a short form (exactly 7 chars) at the end of buffer
3896 * <out>. "-" is printed if the value is zero, "inf" if larger than 1000 years.
3897 * It returns the new buffer length, or 0 if it doesn't fit. The value will be
3898 * surrounded by <pfx> and <sfx> respectively if not NULL.
3899 */
3900int print_time_short(struct buffer *out, const char *pfx, uint64_t ns, const char *sfx)
3901{
3902 double val = ns; // 52 bits of mantissa keep ns accuracy over 52 days
3903 const char *unit;
3904
3905 if (!pfx)
3906 pfx = "";
3907 if (!sfx)
3908 sfx = "";
3909
3910 do {
3911 unit = " - "; if (val <= 0.0) break;
3912 unit = "ns"; if (val < 1000.0) break;
3913 unit = "us"; val /= 1000.0; if (val < 1000.0) break;
3914 unit = "ms"; val /= 1000.0; if (val < 1000.0) break;
3915 unit = "s "; val /= 1000.0; if (val < 60.0) break;
3916 unit = "m "; val /= 60.0; if (val < 60.0) break;
3917 unit = "h "; val /= 60.0; if (val < 24.0) break;
3918 unit = "d "; val /= 24.0; if (val < 365.0) break;
3919 unit = "yr"; val /= 365.0; if (val < 1000.0) break;
3920 unit = " inf "; val = 0.0; break;
3921 } while (0);
3922
3923 if (val <= 0.0)
3924 return chunk_appendf(out, "%s%7s%s", pfx, unit, sfx);
3925 else if (val < 10.0)
3926 return chunk_appendf(out, "%s%1.3f%s%s", pfx, val, unit, sfx);
3927 else if (val < 100.0)
3928 return chunk_appendf(out, "%s%2.2f%s%s", pfx, val, unit, sfx);
3929 else
3930 return chunk_appendf(out, "%s%3.1f%s%s", pfx, val, unit, sfx);
3931}
3932
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003933/* Dynamically allocates a string of the proper length to hold the formatted
3934 * output. NULL is returned on error. The caller is responsible for freeing the
3935 * memory area using free(). The resulting string is returned in <out> if the
3936 * pointer is not NULL. A previous version of <out> might be used to build the
3937 * new string, and it will be freed before returning if it is not NULL, which
3938 * makes it possible to build complex strings from iterative calls without
3939 * having to care about freeing intermediate values, as in the example below :
3940 *
3941 * memprintf(&err, "invalid argument: '%s'", arg);
3942 * ...
3943 * memprintf(&err, "parser said : <%s>\n", *err);
3944 * ...
3945 * free(*err);
3946 *
3947 * This means that <err> must be initialized to NULL before first invocation.
3948 * The return value also holds the allocated string, which eases error checking
3949 * and immediate consumption. If the output pointer is not used, NULL must be
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003950 * passed instead and it will be ignored. The returned message will then also
3951 * be NULL so that the caller does not have to bother with freeing anything.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003952 *
3953 * It is also convenient to use it without any free except the last one :
3954 * err = NULL;
3955 * if (!fct1(err)) report(*err);
3956 * if (!fct2(err)) report(*err);
3957 * if (!fct3(err)) report(*err);
3958 * free(*err);
Christopher Faulet93a518f2017-10-24 11:25:33 +02003959 *
3960 * memprintf relies on memvprintf. This last version can be called from any
3961 * function with variadic arguments.
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003962 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003963char *memvprintf(char **out, const char *format, va_list orig_args)
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003964{
3965 va_list args;
3966 char *ret = NULL;
3967 int allocated = 0;
3968 int needed = 0;
3969
Willy Tarreaueb6cead2012-09-20 19:43:14 +02003970 if (!out)
3971 return NULL;
3972
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003973 do {
Willy Tarreaue0609f52019-03-29 19:13:23 +01003974 char buf1;
3975
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003976 /* vsnprintf() will return the required length even when the
3977 * target buffer is NULL. We do this in a loop just in case
3978 * intermediate evaluations get wrong.
3979 */
Christopher Faulet93a518f2017-10-24 11:25:33 +02003980 va_copy(args, orig_args);
Willy Tarreaue0609f52019-03-29 19:13:23 +01003981 needed = vsnprintf(ret ? ret : &buf1, allocated, format, args);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003982 va_end(args);
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003983 if (needed < allocated) {
3984 /* Note: on Solaris 8, the first iteration always
3985 * returns -1 if allocated is zero, so we force a
3986 * retry.
3987 */
3988 if (!allocated)
3989 needed = 0;
3990 else
3991 break;
3992 }
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003993
Willy Tarreau1b2fed62013-04-01 22:48:54 +02003994 allocated = needed + 1;
Hubert Verstraete831962e2016-06-28 22:44:26 +02003995 ret = my_realloc2(ret, allocated);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02003996 } while (ret);
3997
3998 if (needed < 0) {
3999 /* an error was encountered */
Willy Tarreau61cfdf42021-02-20 10:46:51 +01004000 ha_free(&ret);
Willy Tarreau9a7bea52012-04-27 11:16:50 +02004001 }
4002
4003 if (out) {
4004 free(*out);
4005 *out = ret;
4006 }
4007
4008 return ret;
4009}
William Lallemand421f5b52012-02-06 18:15:57 +01004010
Christopher Faulet93a518f2017-10-24 11:25:33 +02004011char *memprintf(char **out, const char *format, ...)
4012{
4013 va_list args;
4014 char *ret = NULL;
4015
4016 va_start(args, format);
4017 ret = memvprintf(out, format, args);
4018 va_end(args);
4019
4020 return ret;
4021}
4022
Willy Tarreau21c705b2012-09-14 11:40:36 +02004023/* Used to add <level> spaces before each line of <out>, unless there is only one line.
4024 * The input argument is automatically freed and reassigned. The result will have to be
Willy Tarreau70eec382012-10-10 08:56:47 +02004025 * freed by the caller. It also supports being passed a NULL which results in the same
4026 * output.
Willy Tarreau21c705b2012-09-14 11:40:36 +02004027 * Example of use :
4028 * parse(cmd, &err); (callee: memprintf(&err, ...))
4029 * fprintf(stderr, "Parser said: %s\n", indent_error(&err));
4030 * free(err);
4031 */
4032char *indent_msg(char **out, int level)
4033{
4034 char *ret, *in, *p;
4035 int needed = 0;
4036 int lf = 0;
4037 int lastlf = 0;
4038 int len;
4039
Willy Tarreau70eec382012-10-10 08:56:47 +02004040 if (!out || !*out)
4041 return NULL;
4042
Willy Tarreau21c705b2012-09-14 11:40:36 +02004043 in = *out - 1;
4044 while ((in = strchr(in + 1, '\n')) != NULL) {
4045 lastlf = in - *out;
4046 lf++;
4047 }
4048
4049 if (!lf) /* single line, no LF, return it as-is */
4050 return *out;
4051
4052 len = strlen(*out);
4053
4054 if (lf == 1 && lastlf == len - 1) {
4055 /* single line, LF at end, strip it and return as-is */
4056 (*out)[lastlf] = 0;
4057 return *out;
4058 }
4059
4060 /* OK now we have at least one LF, we need to process the whole string
4061 * as a multi-line string. What we'll do :
4062 * - prefix with an LF if there is none
4063 * - add <level> spaces before each line
4064 * This means at most ( 1 + level + (len-lf) + lf*<1+level) ) =
4065 * 1 + level + len + lf * level = 1 + level * (lf + 1) + len.
4066 */
4067
4068 needed = 1 + level * (lf + 1) + len + 1;
4069 p = ret = malloc(needed);
4070 in = *out;
4071
4072 /* skip initial LFs */
4073 while (*in == '\n')
4074 in++;
4075
4076 /* copy each line, prefixed with LF and <level> spaces, and without the trailing LF */
4077 while (*in) {
4078 *p++ = '\n';
4079 memset(p, ' ', level);
4080 p += level;
4081 do {
4082 *p++ = *in++;
4083 } while (*in && *in != '\n');
4084 if (*in)
4085 in++;
4086 }
4087 *p = 0;
4088
4089 free(*out);
4090 *out = ret;
4091
4092 return ret;
4093}
4094
Willy Tarreaua2c99112019-08-21 13:17:37 +02004095/* makes a copy of message <in> into <out>, with each line prefixed with <pfx>
4096 * and end of lines replaced with <eol> if not 0. The first line to indent has
4097 * to be indicated in <first> (starts at zero), so that it is possible to skip
4098 * indenting the first line if it has to be appended after an existing message.
4099 * Empty strings are never indented, and NULL strings are considered empty both
4100 * for <in> and <pfx>. It returns non-zero if an EOL was appended as the last
4101 * character, non-zero otherwise.
4102 */
4103int append_prefixed_str(struct buffer *out, const char *in, const char *pfx, char eol, int first)
4104{
4105 int bol, lf;
4106 int pfxlen = pfx ? strlen(pfx) : 0;
4107
4108 if (!in)
4109 return 0;
4110
4111 bol = 1;
4112 lf = 0;
4113 while (*in) {
4114 if (bol && pfxlen) {
4115 if (first > 0)
4116 first--;
4117 else
4118 b_putblk(out, pfx, pfxlen);
4119 bol = 0;
4120 }
4121
4122 lf = (*in == '\n');
4123 bol |= lf;
4124 b_putchr(out, (lf && eol) ? eol : *in);
4125 in++;
4126 }
4127 return lf;
4128}
4129
Willy Tarreau9d22e562019-03-29 18:49:09 +01004130/* removes environment variable <name> from the environment as found in
4131 * environ. This is only provided as an alternative for systems without
4132 * unsetenv() (old Solaris and AIX versions). THIS IS NOT THREAD SAFE.
Ilya Shipitsin856aabc2020-04-16 23:51:34 +05004133 * The principle is to scan environ for each occurrence of variable name
Willy Tarreau9d22e562019-03-29 18:49:09 +01004134 * <name> and to replace the matching pointers with the last pointer of
4135 * the array (since variables are not ordered).
4136 * It always returns 0 (success).
4137 */
4138int my_unsetenv(const char *name)
4139{
4140 extern char **environ;
4141 char **p = environ;
4142 int vars;
4143 int next;
4144 int len;
4145
4146 len = strlen(name);
4147 for (vars = 0; p[vars]; vars++)
4148 ;
4149 next = 0;
4150 while (next < vars) {
4151 if (strncmp(p[next], name, len) != 0 || p[next][len] != '=') {
4152 next++;
4153 continue;
4154 }
4155 if (next < vars - 1)
4156 p[next] = p[vars - 1];
4157 p[--vars] = NULL;
4158 }
4159 return 0;
4160}
4161
Willy Tarreaudad36a32013-03-11 01:20:04 +01004162/* Convert occurrences of environment variables in the input string to their
4163 * corresponding value. A variable is identified as a series of alphanumeric
4164 * characters or underscores following a '$' sign. The <in> string must be
4165 * free()able. NULL returns NULL. The resulting string might be reallocated if
4166 * some expansion is made. Variable names may also be enclosed into braces if
4167 * needed (eg: to concatenate alphanum characters).
4168 */
4169char *env_expand(char *in)
4170{
4171 char *txt_beg;
4172 char *out;
4173 char *txt_end;
4174 char *var_beg;
4175 char *var_end;
4176 char *value;
4177 char *next;
4178 int out_len;
4179 int val_len;
4180
4181 if (!in)
4182 return in;
4183
4184 value = out = NULL;
4185 out_len = 0;
4186
4187 txt_beg = in;
4188 do {
4189 /* look for next '$' sign in <in> */
4190 for (txt_end = txt_beg; *txt_end && *txt_end != '$'; txt_end++);
4191
4192 if (!*txt_end && !out) /* end and no expansion performed */
4193 return in;
4194
4195 val_len = 0;
4196 next = txt_end;
4197 if (*txt_end == '$') {
4198 char save;
4199
4200 var_beg = txt_end + 1;
4201 if (*var_beg == '{')
4202 var_beg++;
4203
4204 var_end = var_beg;
Willy Tarreau90807112020-02-25 08:16:33 +01004205 while (isalnum((unsigned char)*var_end) || *var_end == '_') {
Willy Tarreaudad36a32013-03-11 01:20:04 +01004206 var_end++;
4207 }
4208
4209 next = var_end;
4210 if (*var_end == '}' && (var_beg > txt_end + 1))
4211 next++;
4212
4213 /* get value of the variable name at this location */
4214 save = *var_end;
4215 *var_end = '\0';
4216 value = getenv(var_beg);
4217 *var_end = save;
4218 val_len = value ? strlen(value) : 0;
4219 }
4220
Hubert Verstraete831962e2016-06-28 22:44:26 +02004221 out = my_realloc2(out, out_len + (txt_end - txt_beg) + val_len + 1);
Willy Tarreaudad36a32013-03-11 01:20:04 +01004222 if (txt_end > txt_beg) {
4223 memcpy(out + out_len, txt_beg, txt_end - txt_beg);
4224 out_len += txt_end - txt_beg;
4225 }
4226 if (val_len) {
4227 memcpy(out + out_len, value, val_len);
4228 out_len += val_len;
4229 }
4230 out[out_len] = 0;
4231 txt_beg = next;
4232 } while (*txt_beg);
4233
4234 /* here we know that <out> was allocated and that we don't need <in> anymore */
4235 free(in);
4236 return out;
4237}
4238
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004239
4240/* same as strstr() but case-insensitive and with limit length */
4241const char *strnistr(const char *str1, int len_str1, const char *str2, int len_str2)
4242{
4243 char *pptr, *sptr, *start;
Willy Tarreauc8746532014-05-28 23:05:07 +02004244 unsigned int slen, plen;
4245 unsigned int tmp1, tmp2;
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004246
4247 if (str1 == NULL || len_str1 == 0) // search pattern into an empty string => search is not found
4248 return NULL;
4249
4250 if (str2 == NULL || len_str2 == 0) // pattern is empty => every str1 match
4251 return str1;
4252
4253 if (len_str1 < len_str2) // pattern is longer than string => search is not found
4254 return NULL;
4255
4256 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 +02004257 while (toupper((unsigned char)*start) != toupper((unsigned char)*str2)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004258 start++;
4259 slen--;
4260 tmp1++;
4261
4262 if (tmp1 >= len_str1)
4263 return NULL;
4264
4265 /* if pattern longer than string */
4266 if (slen < plen)
4267 return NULL;
4268 }
4269
4270 sptr = start;
4271 pptr = (char *)str2;
4272
4273 tmp2 = 0;
Willy Tarreauf278eec2020-07-05 21:46:32 +02004274 while (toupper((unsigned char)*sptr) == toupper((unsigned char)*pptr)) {
de Lafond Guillaume88c278f2013-04-15 19:27:10 +02004275 sptr++;
4276 pptr++;
4277 tmp2++;
4278
4279 if (*pptr == '\0' || tmp2 == len_str2) /* end of pattern found */
4280 return start;
4281 if (*sptr == '\0' || tmp2 == len_str1) /* end of string found and the pattern is not fully found */
4282 return NULL;
4283 }
4284 }
4285 return NULL;
4286}
4287
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004288/* This function read the next valid utf8 char.
4289 * <s> is the byte srray to be decode, <len> is its length.
4290 * The function returns decoded char encoded like this:
4291 * The 4 msb are the return code (UTF8_CODE_*), the 4 lsb
4292 * are the length read. The decoded character is stored in <c>.
4293 */
4294unsigned char utf8_next(const char *s, int len, unsigned int *c)
4295{
4296 const unsigned char *p = (unsigned char *)s;
4297 int dec;
4298 unsigned char code = UTF8_CODE_OK;
4299
4300 if (len < 1)
4301 return UTF8_CODE_OK;
4302
4303 /* Check the type of UTF8 sequence
4304 *
4305 * 0... .... 0x00 <= x <= 0x7f : 1 byte: ascii char
4306 * 10.. .... 0x80 <= x <= 0xbf : invalid sequence
4307 * 110. .... 0xc0 <= x <= 0xdf : 2 bytes
4308 * 1110 .... 0xe0 <= x <= 0xef : 3 bytes
4309 * 1111 0... 0xf0 <= x <= 0xf7 : 4 bytes
4310 * 1111 10.. 0xf8 <= x <= 0xfb : 5 bytes
4311 * 1111 110. 0xfc <= x <= 0xfd : 6 bytes
4312 * 1111 111. 0xfe <= x <= 0xff : invalid sequence
4313 */
4314 switch (*p) {
4315 case 0x00 ... 0x7f:
4316 *c = *p;
4317 return UTF8_CODE_OK | 1;
4318
4319 case 0x80 ... 0xbf:
4320 *c = *p;
4321 return UTF8_CODE_BADSEQ | 1;
4322
4323 case 0xc0 ... 0xdf:
4324 if (len < 2) {
4325 *c = *p;
4326 return UTF8_CODE_BADSEQ | 1;
4327 }
4328 *c = *p & 0x1f;
4329 dec = 1;
4330 break;
4331
4332 case 0xe0 ... 0xef:
4333 if (len < 3) {
4334 *c = *p;
4335 return UTF8_CODE_BADSEQ | 1;
4336 }
4337 *c = *p & 0x0f;
4338 dec = 2;
4339 break;
4340
4341 case 0xf0 ... 0xf7:
4342 if (len < 4) {
4343 *c = *p;
4344 return UTF8_CODE_BADSEQ | 1;
4345 }
4346 *c = *p & 0x07;
4347 dec = 3;
4348 break;
4349
4350 case 0xf8 ... 0xfb:
4351 if (len < 5) {
4352 *c = *p;
4353 return UTF8_CODE_BADSEQ | 1;
4354 }
4355 *c = *p & 0x03;
4356 dec = 4;
4357 break;
4358
4359 case 0xfc ... 0xfd:
4360 if (len < 6) {
4361 *c = *p;
4362 return UTF8_CODE_BADSEQ | 1;
4363 }
4364 *c = *p & 0x01;
4365 dec = 5;
4366 break;
4367
4368 case 0xfe ... 0xff:
4369 default:
4370 *c = *p;
4371 return UTF8_CODE_BADSEQ | 1;
4372 }
4373
4374 p++;
4375
4376 while (dec > 0) {
4377
4378 /* need 0x10 for the 2 first bits */
4379 if ( ( *p & 0xc0 ) != 0x80 )
4380 return UTF8_CODE_BADSEQ | ((p-(unsigned char *)s)&0xffff);
4381
4382 /* add data at char */
4383 *c = ( *c << 6 ) | ( *p & 0x3f );
4384
4385 dec--;
4386 p++;
4387 }
4388
4389 /* Check ovelong encoding.
4390 * 1 byte : 5 + 6 : 11 : 0x80 ... 0x7ff
4391 * 2 bytes : 4 + 6 + 6 : 16 : 0x800 ... 0xffff
4392 * 3 bytes : 3 + 6 + 6 + 6 : 21 : 0x10000 ... 0x1fffff
4393 */
Thierry FOURNIER9e7ec082015-03-12 19:32:38 +01004394 if (( *c <= 0x7f && (p-(unsigned char *)s) > 1) ||
Thierry FOURNIER317e1c42014-08-12 10:20:47 +02004395 (*c >= 0x80 && *c <= 0x7ff && (p-(unsigned char *)s) > 2) ||
4396 (*c >= 0x800 && *c <= 0xffff && (p-(unsigned char *)s) > 3) ||
4397 (*c >= 0x10000 && *c <= 0x1fffff && (p-(unsigned char *)s) > 4))
4398 code |= UTF8_CODE_OVERLONG;
4399
4400 /* Check invalid UTF8 range. */
4401 if ((*c >= 0xd800 && *c <= 0xdfff) ||
4402 (*c >= 0xfffe && *c <= 0xffff))
4403 code |= UTF8_CODE_INVRANGE;
4404
4405 return code | ((p-(unsigned char *)s)&0x0f);
4406}
4407
Maxime de Roucydc887852016-05-13 23:52:54 +02004408/* append a copy of string <str> (in a wordlist) at the end of the list <li>
4409 * On failure : return 0 and <err> filled with an error message.
4410 * The caller is responsible for freeing the <err> and <str> copy
4411 * memory area using free()
4412 */
4413int list_append_word(struct list *li, const char *str, char **err)
4414{
4415 struct wordlist *wl;
4416
4417 wl = calloc(1, sizeof(*wl));
4418 if (!wl) {
4419 memprintf(err, "out of memory");
4420 goto fail_wl;
4421 }
4422
4423 wl->s = strdup(str);
4424 if (!wl->s) {
4425 memprintf(err, "out of memory");
4426 goto fail_wl_s;
4427 }
4428
4429 LIST_ADDQ(li, &wl->list);
4430
4431 return 1;
4432
4433fail_wl_s:
4434 free(wl->s);
4435fail_wl:
4436 free(wl);
4437 return 0;
4438}
4439
Willy Tarreau37101052019-05-20 16:48:20 +02004440/* indicates if a memory location may safely be read or not. The trick consists
4441 * in performing a harmless syscall using this location as an input and letting
4442 * the operating system report whether it's OK or not. For this we have the
4443 * stat() syscall, which will return EFAULT when the memory location supposed
4444 * to contain the file name is not readable. If it is readable it will then
4445 * either return 0 if the area contains an existing file name, or -1 with
4446 * another code. This must not be abused, and some audit systems might detect
4447 * this as abnormal activity. It's used only for unsafe dumps.
4448 */
4449int may_access(const void *ptr)
4450{
4451 struct stat buf;
4452
4453 if (stat(ptr, &buf) == 0)
4454 return 1;
4455 if (errno == EFAULT)
4456 return 0;
4457 return 1;
4458}
4459
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004460/* print a string of text buffer to <out>. The format is :
4461 * Non-printable chars \t, \n, \r and \e are * encoded in C format.
4462 * Other non-printable chars are encoded "\xHH". Space, '\', and '=' are also escaped.
4463 * Print stopped if null char or <bsize> is reached, or if no more place in the chunk.
4464 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004465int dump_text(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004466{
4467 unsigned char c;
4468 int ptr = 0;
4469
4470 while (buf[ptr] && ptr < bsize) {
4471 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004472 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\' && c != ' ' && c != '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004473 if (out->data > out->size - 1)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004474 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004475 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004476 }
4477 else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\' || c == ' ' || c == '=') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004478 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004479 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004480 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004481 switch (c) {
4482 case ' ': c = ' '; break;
4483 case '\t': c = 't'; break;
4484 case '\n': c = 'n'; break;
4485 case '\r': c = 'r'; break;
4486 case '\e': c = 'e'; break;
4487 case '\\': c = '\\'; break;
4488 case '=': c = '='; break;
4489 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004490 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004491 }
4492 else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004493 if (out->data > out->size - 4)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004494 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004495 out->area[out->data++] = '\\';
4496 out->area[out->data++] = 'x';
4497 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4498 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004499 }
4500 ptr++;
4501 }
4502
4503 return ptr;
4504}
4505
4506/* print a buffer in hexa.
4507 * Print stopped if <bsize> is reached, or if no more place in the chunk.
4508 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004509int dump_binary(struct buffer *out, const char *buf, int bsize)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004510{
4511 unsigned char c;
4512 int ptr = 0;
4513
4514 while (ptr < bsize) {
4515 c = buf[ptr];
4516
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004517 if (out->data > out->size - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004518 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004519 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4520 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004521
4522 ptr++;
4523 }
4524 return ptr;
4525}
4526
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004527/* Appends into buffer <out> a hex dump of memory area <buf> for <len> bytes,
4528 * prepending each line with prefix <pfx>. The output is *not* initialized.
4529 * The output will not wrap pas the buffer's end so it is more optimal if the
4530 * caller makes sure the buffer is aligned first. A trailing zero will always
4531 * be appended (and not counted) if there is room for it. The caller must make
Willy Tarreau37101052019-05-20 16:48:20 +02004532 * sure that the area is dumpable first. If <unsafe> is non-null, the memory
4533 * locations are checked first for being readable.
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004534 */
Willy Tarreau37101052019-05-20 16:48:20 +02004535void dump_hex(struct buffer *out, const char *pfx, const void *buf, int len, int unsafe)
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004536{
4537 const unsigned char *d = buf;
4538 int i, j, start;
4539
4540 d = (const unsigned char *)(((unsigned long)buf) & -16);
4541 start = ((unsigned long)buf) & 15;
4542
4543 for (i = 0; i < start + len; i += 16) {
4544 chunk_appendf(out, (sizeof(void *) == 4) ? "%s%8p: " : "%s%16p: ", pfx, d + i);
4545
Willy Tarreau37101052019-05-20 16:48:20 +02004546 // 0: unchecked, 1: checked safe, 2: danger
4547 unsafe = !!unsafe;
4548 if (unsafe && !may_access(d + i))
4549 unsafe = 2;
4550
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004551 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004552 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004553 chunk_strcat(out, "'' ");
Willy Tarreau37101052019-05-20 16:48:20 +02004554 else if (unsafe > 1)
4555 chunk_strcat(out, "** ");
4556 else
4557 chunk_appendf(out, "%02x ", d[i + j]);
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004558
4559 if (j == 7)
4560 chunk_strcat(out, "- ");
4561 }
4562 chunk_strcat(out, " ");
4563 for (j = 0; j < 16; j++) {
Willy Tarreau37101052019-05-20 16:48:20 +02004564 if ((i + j < start) || (i + j >= start + len))
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004565 chunk_strcat(out, "'");
Willy Tarreau37101052019-05-20 16:48:20 +02004566 else if (unsafe > 1)
4567 chunk_strcat(out, "*");
Willy Tarreau90807112020-02-25 08:16:33 +01004568 else if (isprint((unsigned char)d[i + j]))
Willy Tarreau37101052019-05-20 16:48:20 +02004569 chunk_appendf(out, "%c", d[i + j]);
4570 else
4571 chunk_strcat(out, ".");
Willy Tarreau9fc5dcb2019-05-20 16:13:40 +02004572 }
4573 chunk_strcat(out, "\n");
4574 }
4575}
4576
Willy Tarreau762fb3e2020-03-03 15:57:10 +01004577/* dumps <pfx> followed by <n> bytes from <addr> in hex form into buffer <buf>
4578 * enclosed in brackets after the address itself, formatted on 14 chars
4579 * including the "0x" prefix. This is meant to be used as a prefix for code
4580 * areas. For example:
4581 * "0x7f10b6557690 [48 c7 c0 0f 00 00 00 0f]"
4582 * It relies on may_access() to know if the bytes are dumpable, otherwise "--"
4583 * is emitted. A NULL <pfx> will be considered empty.
4584 */
4585void dump_addr_and_bytes(struct buffer *buf, const char *pfx, const void *addr, int n)
4586{
4587 int ok = 0;
4588 int i;
4589
4590 chunk_appendf(buf, "%s%#14lx [", pfx ? pfx : "", (long)addr);
4591
4592 for (i = 0; i < n; i++) {
4593 if (i == 0 || (((long)(addr + i) ^ (long)(addr)) & 4096))
4594 ok = may_access(addr + i);
4595 if (ok)
4596 chunk_appendf(buf, "%02x%s", ((uint8_t*)addr)[i], (i<n-1) ? " " : "]");
4597 else
4598 chunk_appendf(buf, "--%s", (i<n-1) ? " " : "]");
4599 }
4600}
4601
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004602/* print a line of text buffer (limited to 70 bytes) to <out>. The format is :
4603 * <2 spaces> <offset=5 digits> <space or plus> <space> <70 chars max> <\n>
4604 * which is 60 chars per line. Non-printable chars \t, \n, \r and \e are
4605 * encoded in C format. Other non-printable chars are encoded "\xHH". Original
4606 * lines are respected within the limit of 70 output chars. Lines that are
4607 * continuation of a previous truncated line begin with "+" instead of " "
4608 * after the offset. The new pointer is returned.
4609 */
Willy Tarreau83061a82018-07-13 11:56:34 +02004610int dump_text_line(struct buffer *out, const char *buf, int bsize, int len,
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004611 int *line, int ptr)
4612{
4613 int end;
4614 unsigned char c;
4615
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004616 end = out->data + 80;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004617 if (end > out->size)
4618 return ptr;
4619
4620 chunk_appendf(out, " %05d%c ", ptr, (ptr == *line) ? ' ' : '+');
4621
4622 while (ptr < len && ptr < bsize) {
4623 c = buf[ptr];
Willy Tarreau90807112020-02-25 08:16:33 +01004624 if (isprint((unsigned char)c) && isascii((unsigned char)c) && c != '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004625 if (out->data > end - 2)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004626 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004627 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004628 } else if (c == '\t' || c == '\n' || c == '\r' || c == '\e' || c == '\\') {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004629 if (out->data > end - 3)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004630 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004631 out->area[out->data++] = '\\';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004632 switch (c) {
4633 case '\t': c = 't'; break;
4634 case '\n': c = 'n'; break;
4635 case '\r': c = 'r'; break;
4636 case '\e': c = 'e'; break;
4637 case '\\': c = '\\'; break;
4638 }
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004639 out->area[out->data++] = c;
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004640 } else {
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004641 if (out->data > end - 5)
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004642 break;
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004643 out->area[out->data++] = '\\';
4644 out->area[out->data++] = 'x';
4645 out->area[out->data++] = hextab[(c >> 4) & 0xF];
4646 out->area[out->data++] = hextab[c & 0xF];
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004647 }
4648 if (buf[ptr++] == '\n') {
4649 /* we had a line break, let's return now */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004650 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004651 *line = ptr;
4652 return ptr;
4653 }
4654 }
4655 /* we have an incomplete line, we return it as-is */
Willy Tarreau843b7cb2018-07-13 10:54:26 +02004656 out->area[out->data++] = '\n';
Willy Tarreau97c2ae12016-11-22 18:00:20 +01004657 return ptr;
4658}
4659
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004660/* displays a <len> long memory block at <buf>, assuming first byte of <buf>
Willy Tarreaued936c52017-04-27 18:03:20 +02004661 * has address <baseaddr>. String <pfx> may be placed as a prefix in front of
4662 * each line. It may be NULL if unused. The output is emitted to file <out>.
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004663 */
Willy Tarreaued936c52017-04-27 18:03:20 +02004664void debug_hexdump(FILE *out, const char *pfx, const char *buf,
4665 unsigned int baseaddr, int len)
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004666{
Willy Tarreau73459792017-04-11 07:58:08 +02004667 unsigned int i;
4668 int b, j;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004669
4670 for (i = 0; i < (len + (baseaddr & 15)); i += 16) {
4671 b = i - (baseaddr & 15);
Willy Tarreaued936c52017-04-27 18:03:20 +02004672 fprintf(out, "%s%08x: ", pfx ? pfx : "", i + (baseaddr & ~15));
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004673 for (j = 0; j < 8; j++) {
4674 if (b + j >= 0 && b + j < len)
4675 fprintf(out, "%02x ", (unsigned char)buf[b + j]);
4676 else
4677 fprintf(out, " ");
4678 }
4679
4680 if (b + j >= 0 && b + j < len)
4681 fputc('-', out);
4682 else
4683 fputc(' ', out);
4684
4685 for (j = 8; j < 16; j++) {
4686 if (b + j >= 0 && b + j < len)
4687 fprintf(out, " %02x", (unsigned char)buf[b + j]);
4688 else
4689 fprintf(out, " ");
4690 }
4691
4692 fprintf(out, " ");
4693 for (j = 0; j < 16; j++) {
4694 if (b + j >= 0 && b + j < len) {
4695 if (isprint((unsigned char)buf[b + j]))
4696 fputc((unsigned char)buf[b + j], out);
4697 else
4698 fputc('.', out);
4699 }
4700 else
4701 fputc(' ', out);
4702 }
4703 fputc('\n', out);
4704 }
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004705}
4706
Willy Tarreaubb869862020-04-16 10:52:41 +02004707/* Tries to report the executable path name on platforms supporting this. If
4708 * not found or not possible, returns NULL.
4709 */
4710const char *get_exec_path()
4711{
4712 const char *ret = NULL;
4713
4714#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 16))
4715 long execfn = getauxval(AT_EXECFN);
4716
4717 if (execfn && execfn != ENOENT)
4718 ret = (const char *)execfn;
4719#endif
4720 return ret;
4721}
4722
Baruch Siache1651b22020-07-24 07:52:20 +03004723#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreau9133e482020-03-04 10:19:36 +01004724/* calls dladdr() or dladdr1() on <addr> and <dli>. If dladdr1 is available,
4725 * also returns the symbol size in <size>, otherwise returns 0 there.
4726 */
4727static int dladdr_and_size(const void *addr, Dl_info *dli, size_t *size)
4728{
4729 int ret;
Willy Tarreau62af9c82020-03-10 07:51:48 +01004730#if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)) // most detailed one
Willy Tarreau9133e482020-03-04 10:19:36 +01004731 const ElfW(Sym) *sym;
4732
4733 ret = dladdr1(addr, dli, (void **)&sym, RTLD_DL_SYMENT);
4734 if (ret)
4735 *size = sym ? sym->st_size : 0;
4736#else
4737 ret = dladdr(addr, dli);
4738 *size = 0;
4739#endif
4740 return ret;
4741}
4742#endif
4743
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004744/* Tries to append to buffer <buf> some indications about the symbol at address
4745 * <addr> using the following form:
4746 * lib:+0xoffset (unresolvable address from lib's base)
4747 * main+0xoffset (unresolvable address from main (+/-))
4748 * lib:main+0xoffset (unresolvable lib address from main (+/-))
4749 * name (resolved exact exec address)
4750 * lib:name (resolved exact lib address)
4751 * name+0xoffset/0xsize (resolved address within exec symbol)
4752 * lib:name+0xoffset/0xsize (resolved address within lib symbol)
4753 *
4754 * The file name (lib or executable) is limited to what lies between the last
4755 * '/' and the first following '.'. An optional prefix <pfx> is prepended before
4756 * 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 +03004757 * that contains the "main" symbol, or when __ELF__ && USE_DL are not set.
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004758 *
4759 * The symbol's base address is returned, or NULL when unresolved, in order to
4760 * allow the caller to match it against known ones.
4761 */
Willy Tarreau45fd1032021-01-20 14:37:59 +01004762const void *resolve_sym_name(struct buffer *buf, const char *pfx, const void *addr)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004763{
4764 const struct {
4765 const void *func;
4766 const char *name;
4767 } fcts[] = {
4768 { .func = process_stream, .name = "process_stream" },
4769 { .func = task_run_applet, .name = "task_run_applet" },
4770 { .func = si_cs_io_cb, .name = "si_cs_io_cb" },
Willy Tarreau586f71b2020-12-11 15:54:36 +01004771 { .func = sock_conn_iocb, .name = "sock_conn_iocb" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004772 { .func = dgram_fd_handler, .name = "dgram_fd_handler" },
4773 { .func = listener_accept, .name = "listener_accept" },
Willy Tarreaud597ec22021-01-29 14:29:06 +01004774 { .func = manage_global_listener_queue, .name = "manage_global_listener_queue" },
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004775 { .func = poller_pipe_io_handler, .name = "poller_pipe_io_handler" },
4776 { .func = mworker_accept_wrapper, .name = "mworker_accept_wrapper" },
Willy Tarreau02922e12021-01-29 12:27:57 +01004777 { .func = session_expire_embryonic, .name = "session_expire_embryonic" },
Willy Tarreaufb5401f2021-01-29 12:25:23 +01004778#ifdef USE_THREAD
4779 { .func = accept_queue_process, .name = "accept_queue_process" },
4780#endif
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004781#ifdef USE_LUA
4782 { .func = hlua_process_task, .name = "hlua_process_task" },
4783#endif
Ilya Shipitsinbdec3ba2020-11-14 01:56:34 +05004784#ifdef SSL_MODE_ASYNC
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004785 { .func = ssl_async_fd_free, .name = "ssl_async_fd_free" },
4786 { .func = ssl_async_fd_handler, .name = "ssl_async_fd_handler" },
4787#endif
4788 };
4789
Baruch Siache1651b22020-07-24 07:52:20 +03004790#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004791 Dl_info dli, dli_main;
Willy Tarreau9133e482020-03-04 10:19:36 +01004792 size_t size;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004793 const char *fname, *p;
4794#endif
4795 int i;
4796
4797 if (pfx)
4798 chunk_appendf(buf, "%s", pfx);
4799
4800 for (i = 0; i < sizeof(fcts) / sizeof(fcts[0]); i++) {
4801 if (addr == fcts[i].func) {
4802 chunk_appendf(buf, "%s", fcts[i].name);
4803 return addr;
4804 }
4805 }
4806
Baruch Siache1651b22020-07-24 07:52:20 +03004807#if (defined(__ELF__) && !defined(__linux__)) || defined(USE_DL)
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004808 /* Now let's try to be smarter */
Willy Tarreau9133e482020-03-04 10:19:36 +01004809 if (!dladdr_and_size(addr, &dli, &size))
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004810 goto unknown;
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004811
4812 /* 1. prefix the library name if it's not the same object as the one
4813 * that contains the main function. The name is picked between last '/'
4814 * and first following '.'.
4815 */
4816 if (!dladdr(main, &dli_main))
4817 dli_main.dli_fbase = NULL;
4818
4819 if (dli_main.dli_fbase != dli.dli_fbase) {
4820 fname = dli.dli_fname;
4821 p = strrchr(fname, '/');
4822 if (p++)
4823 fname = p;
4824 p = strchr(fname, '.');
4825 if (!p)
4826 p = fname + strlen(fname);
4827
4828 chunk_appendf(buf, "%.*s:", (int)(long)(p - fname), fname);
4829 }
4830
4831 /* 2. symbol name */
4832 if (dli.dli_sname) {
4833 /* known, dump it and return symbol's address (exact or relative) */
4834 chunk_appendf(buf, "%s", dli.dli_sname);
4835 if (addr != dli.dli_saddr) {
4836 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_saddr));
Willy Tarreau9133e482020-03-04 10:19:36 +01004837 if (size)
4838 chunk_appendf(buf, "/%#lx", (long)size);
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004839 }
4840 return dli.dli_saddr;
4841 }
4842 else if (dli_main.dli_fbase != dli.dli_fbase) {
4843 /* unresolved symbol from a known library, report relative offset */
4844 chunk_appendf(buf, "+%#lx", (long)(addr - dli.dli_fbase));
4845 return NULL;
4846 }
Baruch Siache1651b22020-07-24 07:52:20 +03004847#endif /* __ELF__ && !__linux__ || USE_DL */
Willy Tarreaueb8b1ca2020-03-03 17:09:08 +01004848 unknown:
4849 /* unresolved symbol from the main file, report relative offset to main */
4850 if ((void*)addr < (void*)main)
4851 chunk_appendf(buf, "main-%#lx", (long)((void*)main - addr));
4852 else
4853 chunk_appendf(buf, "main+%#lx", (long)(addr - (void*)main));
4854 return NULL;
Willy Tarreau0ebb5112016-12-05 00:10:57 +01004855}
4856
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004857/*
4858 * Allocate an array of unsigned int with <nums> as address from <str> string
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05004859 * made of integer separated by dot characters.
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004860 *
4861 * First, initializes the value with <sz> as address to 0 and initializes the
4862 * array with <nums> as address to NULL. Then allocates the array with <nums> as
4863 * address updating <sz> pointed value to the size of this array.
4864 *
4865 * Returns 1 if succeeded, 0 if not.
4866 */
4867int parse_dotted_uints(const char *str, unsigned int **nums, size_t *sz)
4868{
4869 unsigned int *n;
4870 const char *s, *end;
4871
4872 s = str;
4873 *sz = 0;
4874 end = str + strlen(str);
4875 *nums = n = NULL;
4876
4877 while (1) {
4878 unsigned int r;
4879
4880 if (s >= end)
4881 break;
4882
4883 r = read_uint(&s, end);
4884 /* Expected characters after having read an uint: '\0' or '.',
4885 * if '.', must not be terminal.
4886 */
Christopher Faulet4b524122021-02-11 10:42:41 +01004887 if (*s != '\0'&& (*s++ != '.' || s == end)) {
4888 free(n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004889 return 0;
Christopher Faulet4b524122021-02-11 10:42:41 +01004890 }
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004891
Frédéric Lécaille12a71842019-02-26 18:19:48 +01004892 n = my_realloc2(n, (*sz + 1) * sizeof *n);
Frédéric Lécaille3b717162019-02-25 15:04:22 +01004893 if (!n)
4894 return 0;
4895
4896 n[(*sz)++] = r;
4897 }
4898 *nums = n;
4899
4900 return 1;
4901}
4902
Willy Tarreau4d589e72019-08-23 19:02:26 +02004903
4904/* returns the number of bytes needed to encode <v> as a varint. An inline
4905 * version exists for use with constants (__varint_bytes()).
4906 */
4907int varint_bytes(uint64_t v)
4908{
4909 int len = 1;
4910
4911 if (v >= 240) {
4912 v = (v - 240) >> 4;
4913 while (1) {
4914 len++;
4915 if (v < 128)
4916 break;
4917 v = (v - 128) >> 7;
4918 }
4919 }
4920 return len;
4921}
4922
Willy Tarreau52bf8392020-03-08 00:42:37 +01004923
4924/* Random number generator state, see below */
Willy Tarreau1544c142020-03-12 00:31:18 +01004925static uint64_t ha_random_state[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004926
4927/* This is a thread-safe implementation of xoroshiro128** described below:
4928 * http://prng.di.unimi.it/
4929 * It features a 2^128 long sequence, returns 64 high-quality bits on each call,
4930 * supports fast jumps and passes all common quality tests. It is thread-safe,
4931 * uses a double-cas on 64-bit architectures supporting it, and falls back to a
4932 * local lock on other ones.
4933 */
4934uint64_t ha_random64()
4935{
4936 uint64_t result;
Willy Tarreau1544c142020-03-12 00:31:18 +01004937 uint64_t old[2] ALIGNED(2*sizeof(uint64_t));
4938 uint64_t new[2] ALIGNED(2*sizeof(uint64_t));
Willy Tarreau52bf8392020-03-08 00:42:37 +01004939
4940#if defined(USE_THREAD) && (!defined(HA_CAS_IS_8B) || !defined(HA_HAVE_CAS_DW))
4941 static HA_SPINLOCK_T rand_lock;
4942
4943 HA_SPIN_LOCK(OTHER_LOCK, &rand_lock);
4944#endif
4945
4946 old[0] = ha_random_state[0];
4947 old[1] = ha_random_state[1];
4948
4949#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4950 do {
4951#endif
4952 result = rotl64(old[0] * 5, 7) * 9;
4953 new[1] = old[0] ^ old[1];
4954 new[0] = rotl64(old[0], 24) ^ new[1] ^ (new[1] << 16); // a, b
4955 new[1] = rotl64(new[1], 37); // c
4956
4957#if defined(USE_THREAD) && defined(HA_CAS_IS_8B) && defined(HA_HAVE_CAS_DW)
4958 } while (unlikely(!_HA_ATOMIC_DWCAS(ha_random_state, old, new)));
4959#else
4960 ha_random_state[0] = new[0];
4961 ha_random_state[1] = new[1];
4962#if defined(USE_THREAD)
4963 HA_SPIN_UNLOCK(OTHER_LOCK, &rand_lock);
4964#endif
4965#endif
4966 return result;
4967}
4968
4969/* seeds the random state using up to <len> bytes from <seed>, starting with
4970 * the first non-zero byte.
4971 */
4972void ha_random_seed(const unsigned char *seed, size_t len)
4973{
4974 size_t pos;
4975
4976 /* the seed must not be all zeroes, so we pre-fill it with alternating
4977 * bits and overwrite part of them with the block starting at the first
4978 * non-zero byte from the seed.
4979 */
4980 memset(ha_random_state, 0x55, sizeof(ha_random_state));
4981
4982 for (pos = 0; pos < len; pos++)
4983 if (seed[pos] != 0)
4984 break;
4985
4986 if (pos == len)
4987 return;
4988
4989 seed += pos;
4990 len -= pos;
4991
4992 if (len > sizeof(ha_random_state))
4993 len = sizeof(ha_random_state);
4994
4995 memcpy(ha_random_state, seed, len);
4996}
4997
4998/* This causes a jump to (dist * 2^96) places in the pseudo-random sequence,
4999 * and is equivalent to calling ha_random64() as many times. It is used to
5000 * provide non-overlapping sequences of 2^96 numbers (~7*10^28) to up to 2^32
5001 * different generators (i.e. different processes after a fork). The <dist>
5002 * argument is the distance to jump to and is used in a loop so it rather not
5003 * be too large if the processing time is a concern.
5004 *
5005 * BEWARE: this function is NOT thread-safe and must not be called during
5006 * concurrent accesses to ha_random64().
5007 */
5008void ha_random_jump96(uint32_t dist)
5009{
5010 while (dist--) {
5011 uint64_t s0 = 0;
5012 uint64_t s1 = 0;
5013 int b;
5014
5015 for (b = 0; b < 64; b++) {
5016 if ((0xd2a98b26625eee7bULL >> b) & 1) {
5017 s0 ^= ha_random_state[0];
5018 s1 ^= ha_random_state[1];
5019 }
5020 ha_random64();
5021 }
5022
5023 for (b = 0; b < 64; b++) {
5024 if ((0xdddf9b1090aa7ac1ULL >> b) & 1) {
5025 s0 ^= ha_random_state[0];
5026 s1 ^= ha_random_state[1];
5027 }
5028 ha_random64();
5029 }
5030 ha_random_state[0] = s0;
5031 ha_random_state[1] = s1;
5032 }
5033}
5034
Willy Tarreauee3bcdd2020-03-08 17:48:17 +01005035/* Generates an RFC4122 UUID into chunk <output> which must be at least 37
5036 * bytes large.
5037 */
5038void ha_generate_uuid(struct buffer *output)
5039{
5040 uint32_t rnd[4];
5041 uint64_t last;
5042
5043 last = ha_random64();
5044 rnd[0] = last;
5045 rnd[1] = last >> 32;
5046
5047 last = ha_random64();
5048 rnd[2] = last;
5049 rnd[3] = last >> 32;
5050
5051 chunk_printf(output, "%8.8x-%4.4x-%4.4x-%4.4x-%12.12llx",
5052 rnd[0],
5053 rnd[1] & 0xFFFF,
5054 ((rnd[1] >> 16u) & 0xFFF) | 0x4000, // highest 4 bits indicate the uuid version
5055 (rnd[2] & 0x3FFF) | 0x8000, // the highest 2 bits indicate the UUID variant (10),
5056 (long long)((rnd[2] >> 14u) | ((uint64_t) rnd[3] << 18u)) & 0xFFFFFFFFFFFFull);
5057}
5058
5059
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005060/* only used by parse_line() below. It supports writing in place provided that
5061 * <in> is updated to the next location before calling it. In that case, the
5062 * char at <in> may be overwritten.
5063 */
5064#define EMIT_CHAR(x) \
5065 do { \
5066 char __c = (char)(x); \
5067 if ((opts & PARSE_OPT_INPLACE) && out+outpos > in) \
5068 err |= PARSE_ERR_OVERLAP; \
5069 if (outpos >= outmax) \
5070 err |= PARSE_ERR_TOOLARGE; \
5071 if (!err) \
5072 out[outpos] = __c; \
5073 outpos++; \
5074 } while (0)
5075
Ilya Shipitsin46a030c2020-07-05 16:36:08 +05005076/* Parse <in>, copy it into <out> split into isolated words whose pointers
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005077 * are put in <args>. If more than <outlen> bytes have to be emitted, the
5078 * extraneous ones are not emitted but <outlen> is updated so that the caller
5079 * knows how much to realloc. Similarly, <args> are not updated beyond <nbargs>
5080 * but the returned <nbargs> indicates how many were found. All trailing args
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005081 * up to <nbargs> point to the trailing zero, and as long as <nbargs> is > 0,
5082 * it is guaranteed that at least one arg will point to the zero. It is safe
5083 * to call it with a NULL <args> if <nbargs> is 0.
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005084 *
5085 * <out> may overlap with <in> provided that it never goes further, in which
5086 * case the parser will accept to perform in-place parsing and unquoting/
5087 * unescaping but only if environment variables do not lead to expansion that
5088 * causes overlapping, otherwise the input string being destroyed, the error
5089 * will not be recoverable. Note that even during out-of-place <in> will
5090 * experience temporary modifications in-place for variable resolution and must
5091 * be writable, and will also receive zeroes to delimit words when using
5092 * in-place copy. Parsing options <opts> taken from PARSE_OPT_*. Return value
5093 * is zero on success otherwise a bitwise-or of PARSE_ERR_*. Upon error, the
5094 * starting point of the first invalid character sequence or unmatched
5095 * quote/brace is reported in <errptr> if not NULL. When using in-place parsing
5096 * error reporting might be difficult since zeroes will have been inserted into
5097 * the string. One solution for the caller may consist in replacing all args
5098 * delimiters with spaces in this case.
5099 */
5100uint32_t parse_line(char *in, char *out, size_t *outlen, char **args, int *nbargs, uint32_t opts, char **errptr)
5101{
5102 char *quote = NULL;
5103 char *brace = NULL;
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005104 char *word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005105 unsigned char hex1, hex2;
5106 size_t outmax = *outlen;
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005107 int argsmax = *nbargs - 1;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005108 size_t outpos = 0;
5109 int squote = 0;
5110 int dquote = 0;
5111 int arg = 0;
5112 uint32_t err = 0;
5113
5114 *nbargs = 0;
5115 *outlen = 0;
5116
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005117 /* argsmax may be -1 here, protecting args[] from any write */
5118 if (arg < argsmax)
5119 args[arg] = out;
5120
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005121 while (1) {
5122 if (*in >= '-' && *in != '\\') {
5123 /* speedup: directly send all regular chars starting
5124 * with '-', '.', '/', alnum etc...
5125 */
5126 EMIT_CHAR(*in++);
5127 continue;
5128 }
5129 else if (*in == '\0' || *in == '\n' || *in == '\r') {
5130 /* end of line */
5131 break;
5132 }
5133 else if (*in == '#' && (opts & PARSE_OPT_SHARP) && !squote && !dquote) {
5134 /* comment */
5135 break;
5136 }
5137 else if (*in == '"' && !squote && (opts & PARSE_OPT_DQUOTE)) { /* double quote outside single quotes */
5138 if (dquote) {
5139 dquote = 0;
5140 quote = NULL;
5141 }
5142 else {
5143 dquote = 1;
5144 quote = in;
5145 }
5146 in++;
5147 continue;
5148 }
5149 else if (*in == '\'' && !dquote && (opts & PARSE_OPT_SQUOTE)) { /* single quote outside double quotes */
5150 if (squote) {
5151 squote = 0;
5152 quote = NULL;
5153 }
5154 else {
5155 squote = 1;
5156 quote = in;
5157 }
5158 in++;
5159 continue;
5160 }
5161 else if (*in == '\\' && !squote && (opts & PARSE_OPT_BKSLASH)) {
5162 /* first, we'll replace \\, \<space>, \#, \r, \n, \t, \xXX with their
5163 * C equivalent value but only when they have a special meaning and within
5164 * double quotes for some of them. Other combinations left unchanged (eg: \1).
5165 */
5166 char tosend = *in;
5167
5168 switch (in[1]) {
5169 case ' ':
5170 case '\\':
5171 tosend = in[1];
5172 in++;
5173 break;
5174
5175 case 't':
5176 tosend = '\t';
5177 in++;
5178 break;
5179
5180 case 'n':
5181 tosend = '\n';
5182 in++;
5183 break;
5184
5185 case 'r':
5186 tosend = '\r';
5187 in++;
5188 break;
5189
5190 case '#':
5191 /* escaping of "#" only if comments are supported */
5192 if (opts & PARSE_OPT_SHARP)
5193 in++;
5194 tosend = *in;
5195 break;
5196
5197 case '\'':
5198 /* escaping of "'" only outside single quotes and only if single quotes are supported */
5199 if (opts & PARSE_OPT_SQUOTE && !squote)
5200 in++;
5201 tosend = *in;
5202 break;
5203
5204 case '"':
5205 /* escaping of '"' only outside single quotes and only if double quotes are supported */
5206 if (opts & PARSE_OPT_DQUOTE && !squote)
5207 in++;
5208 tosend = *in;
5209 break;
5210
5211 case '$':
5212 /* escaping of '$' only inside double quotes and only if env supported */
5213 if (opts & PARSE_OPT_ENV && dquote)
5214 in++;
5215 tosend = *in;
5216 break;
5217
5218 case 'x':
5219 if (!ishex(in[2]) || !ishex(in[3])) {
5220 /* invalid or incomplete hex sequence */
5221 err |= PARSE_ERR_HEX;
5222 if (errptr)
5223 *errptr = in;
5224 goto leave;
5225 }
Willy Tarreauf278eec2020-07-05 21:46:32 +02005226 hex1 = toupper((unsigned char)in[2]) - '0';
5227 hex2 = toupper((unsigned char)in[3]) - '0';
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005228 if (hex1 > 9) hex1 -= 'A' - '9' - 1;
5229 if (hex2 > 9) hex2 -= 'A' - '9' - 1;
5230 tosend = (hex1 << 4) + hex2;
5231 in += 3;
5232 break;
5233
5234 default:
5235 /* other combinations are not escape sequences */
5236 break;
5237 }
5238
5239 in++;
5240 EMIT_CHAR(tosend);
5241 }
5242 else if (isspace((unsigned char)*in) && !squote && !dquote) {
5243 /* a non-escaped space is an argument separator */
5244 while (isspace((unsigned char)*in))
5245 in++;
5246 EMIT_CHAR(0);
5247 arg++;
5248 if (arg < argsmax)
5249 args[arg] = out + outpos;
5250 else
5251 err |= PARSE_ERR_TOOMANY;
5252 }
5253 else if (*in == '$' && (opts & PARSE_OPT_ENV) && (dquote || !(opts & PARSE_OPT_DQUOTE))) {
5254 /* environment variables are evaluated anywhere, or only
5255 * inside double quotes if they are supported.
5256 */
5257 char *var_name;
5258 char save_char;
5259 char *value;
5260
5261 in++;
5262
5263 if (*in == '{')
5264 brace = in++;
5265
5266 if (!isalpha((unsigned char)*in) && *in != '_') {
5267 /* unacceptable character in variable name */
5268 err |= PARSE_ERR_VARNAME;
5269 if (errptr)
5270 *errptr = in;
5271 goto leave;
5272 }
5273
5274 var_name = in;
5275 while (isalnum((unsigned char)*in) || *in == '_')
5276 in++;
5277
5278 save_char = *in;
5279 *in = '\0';
5280 value = getenv(var_name);
5281 *in = save_char;
5282
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005283 /* support for '[*]' sequence to force word expansion,
5284 * only available inside braces */
5285 if (*in == '[' && brace && (opts & PARSE_OPT_WORD_EXPAND)) {
5286 word_expand = in++;
5287
5288 if (*in++ != '*' || *in++ != ']') {
5289 err |= PARSE_ERR_WRONG_EXPAND;
5290 if (errptr)
5291 *errptr = word_expand;
5292 goto leave;
5293 }
5294 }
5295
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005296 if (brace) {
5297 if (*in != '}') {
5298 /* unmatched brace */
5299 err |= PARSE_ERR_BRACE;
5300 if (errptr)
5301 *errptr = brace;
5302 goto leave;
5303 }
5304 in++;
5305 brace = NULL;
5306 }
5307
5308 if (value) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005309 while (*value) {
5310 /* expand as individual parameters on a space character */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005311 if (word_expand && isspace((unsigned char)*value)) {
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005312 EMIT_CHAR(0);
5313 ++arg;
5314 if (arg < argsmax)
5315 args[arg] = out + outpos;
5316 else
5317 err |= PARSE_ERR_TOOMANY;
5318
5319 /* skip consecutive spaces */
Willy Tarreaufe2cc412020-10-01 18:04:40 +02005320 while (isspace((unsigned char)*++value))
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005321 ;
5322 } else {
5323 EMIT_CHAR(*value++);
5324 }
5325 }
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005326 }
Amaury Denoyellefa41cb62020-10-01 14:32:35 +02005327 word_expand = NULL;
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005328 }
5329 else {
5330 /* any other regular char */
5331 EMIT_CHAR(*in++);
5332 }
5333 }
5334
5335 /* end of output string */
5336 EMIT_CHAR(0);
5337 arg++;
5338
5339 if (quote) {
5340 /* unmatched quote */
5341 err |= PARSE_ERR_QUOTE;
5342 if (errptr)
5343 *errptr = quote;
5344 goto leave;
5345 }
5346 leave:
5347 *nbargs = arg;
5348 *outlen = outpos;
5349
Willy Tarreau61dd44b2020-06-25 07:35:42 +02005350 /* empty all trailing args by making them point to the trailing zero,
5351 * at least the last one in any case.
5352 */
5353 if (arg > argsmax)
5354 arg = argsmax;
5355
5356 while (arg >= 0 && arg <= argsmax)
Willy Tarreauc8d167b2020-06-16 16:27:26 +02005357 args[arg++] = out + outpos - 1;
5358
5359 return err;
5360}
5361#undef EMIT_CHAR
5362
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005363/* This is used to sanitize an input line that's about to be used for error reporting.
5364 * It will adjust <line> to print approximately <width> chars around <pos>, trying to
5365 * preserve the beginning, with leading or trailing "..." when the line is truncated.
5366 * If non-printable chars are present in the output. It returns the new offset <pos>
5367 * in the modified line. Non-printable characters are replaced with '?'. <width> must
5368 * be at least 6 to support two "..." otherwise the result is undefined. The line
5369 * itself must have at least 7 chars allocated for the same reason.
5370 */
5371size_t sanitize_for_printing(char *line, size_t pos, size_t width)
5372{
5373 size_t shift = 0;
5374 char *out = line;
5375 char *in = line;
5376 char *end = line + width;
5377
5378 if (pos >= width) {
5379 /* if we have to shift, we'll be out of context, so let's
5380 * try to put <pos> at the center of width.
5381 */
5382 shift = pos - width / 2;
5383 in += shift + 3;
5384 end = out + width - 3;
5385 out[0] = out[1] = out[2] = '.';
5386 out += 3;
5387 }
5388
5389 while (out < end && *in) {
5390 if (isspace((unsigned char)*in))
5391 *out++ = ' ';
5392 else if (isprint((unsigned char)*in))
5393 *out++ = *in;
5394 else
5395 *out++ = '?';
5396 in++;
5397 }
5398
5399 if (end < line + width) {
5400 out[0] = out[1] = out[2] = '.';
5401 out += 3;
5402 }
5403
5404 *out++ = 0;
5405 return pos - shift;
5406}
Willy Tarreau06e69b52021-03-02 14:01:35 +01005407
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005408/* Update array <fp> with the fingerprint of word <word> by counting the
Willy Tarreauba2c4452021-03-12 09:01:52 +01005409 * transitions between characters. <fp> is a 1024-entries array indexed as
5410 * 32*from+to. Positions for 'from' and 'to' are:
Willy Tarreau9294e882021-03-15 09:34:27 +01005411 * 1..26=letter, 27=digit, 28=other/begin/end.
5412 * Row "from=0" is used to mark the character's presence. Others unused.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005413 */
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005414void update_word_fingerprint(uint8_t *fp, const char *word)
Willy Tarreauba2c4452021-03-12 09:01:52 +01005415{
5416 const char *p;
5417 int from, to;
5418 int c;
5419
Willy Tarreauba2c4452021-03-12 09:01:52 +01005420 from = 28; // begin
5421 for (p = word; *p; p++) {
5422 c = tolower(*p);
5423 switch(c) {
Willy Tarreau9294e882021-03-15 09:34:27 +01005424 case 'a'...'z': to = c - 'a' + 1; break;
5425 case 'A'...'Z': to = tolower(c) - 'a' + 1; break;
5426 case '0'...'9': to = 27; break;
5427 default: to = 28; break;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005428 }
Willy Tarreau9294e882021-03-15 09:34:27 +01005429 fp[to] = 1;
Willy Tarreauba2c4452021-03-12 09:01:52 +01005430 fp[32 * from + to]++;
5431 from = to;
5432 }
5433 to = 28; // end
5434 fp[32 * from + to]++;
5435}
5436
Willy Tarreaue33c4b32021-03-12 18:59:31 +01005437/* Initialize array <fp> with the fingerprint of word <word> by counting the
5438 * transitions between characters. <fp> is a 1024-entries array indexed as
5439 * 32*from+to. Positions for 'from' and 'to' are:
5440 * 0..25=letter, 26=digit, 27=other, 28=begin, 29=end, others unused.
5441 */
5442void make_word_fingerprint(uint8_t *fp, const char *word)
5443{
5444 memset(fp, 0, 1024);
5445 update_word_fingerprint(fp, word);
5446}
5447
Willy Tarreauba2c4452021-03-12 09:01:52 +01005448/* Return the distance between two word fingerprints created by function
5449 * make_word_fingerprint(). It's a positive integer calculated as the sum of
Willy Tarreau714c4c12021-03-15 09:44:53 +01005450 * the differences between each location.
Willy Tarreauba2c4452021-03-12 09:01:52 +01005451 */
5452int word_fingerprint_distance(const uint8_t *fp1, const uint8_t *fp2)
5453{
5454 int i, k, dist = 0;
5455
5456 for (i = 0; i < 1024; i++) {
5457 k = (int)fp1[i] - (int)fp2[i];
Willy Tarreau714c4c12021-03-15 09:44:53 +01005458 dist += abs(k);
Willy Tarreauba2c4452021-03-12 09:01:52 +01005459 }
5460 return dist;
5461}
5462
Willy Tarreau06e69b52021-03-02 14:01:35 +01005463static int init_tools_per_thread()
5464{
5465 /* Let's make each thread start from a different position */
5466 statistical_prng_state += tid * MAX_THREADS;
5467 if (!statistical_prng_state)
5468 statistical_prng_state++;
5469 return 1;
5470}
5471REGISTER_PER_THREAD_INIT(init_tools_per_thread);
Willy Tarreauc54e5ad2020-06-25 09:15:40 +02005472
Willy Tarreaubaaee002006-06-26 02:48:02 +02005473/*
5474 * Local variables:
5475 * c-indent-level: 8
5476 * c-basic-offset: 8
5477 * End:
5478 */